@runtypelabs/persona 3.29.0 → 3.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +55 -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-CxvHw0X6.d.cts → types-B_Qazlm4.d.cts} +6 -0
  5. package/dist/animations/{types-CxvHw0X6.d.ts → types-B_Qazlm4.d.ts} +6 -0
  6. package/dist/animations/wipe.d.cts +1 -1
  7. package/dist/animations/wipe.d.ts +1 -1
  8. package/dist/codegen.cjs +6 -6
  9. package/dist/codegen.js +4 -4
  10. package/dist/index.cjs +47 -47
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +127 -7
  13. package/dist/index.d.ts +127 -7
  14. package/dist/index.global.js +60 -60
  15. package/dist/index.global.js.map +1 -1
  16. package/dist/index.js +47 -47
  17. package/dist/index.js.map +1 -1
  18. package/dist/launcher.global.js +2 -2
  19. package/dist/launcher.global.js.map +1 -1
  20. package/dist/plugin-kit.cjs +1 -0
  21. package/dist/plugin-kit.d.cts +98 -0
  22. package/dist/plugin-kit.d.ts +98 -0
  23. package/dist/plugin-kit.js +1 -0
  24. package/dist/smart-dom-reader.d.cts +113 -4
  25. package/dist/smart-dom-reader.d.ts +113 -4
  26. package/dist/theme-editor.cjs +38 -38
  27. package/dist/theme-editor.d.cts +117 -6
  28. package/dist/theme-editor.d.ts +117 -6
  29. package/dist/theme-editor.js +38 -38
  30. package/dist/theme-reference.cjs +1 -1
  31. package/dist/theme-reference.d.cts +2 -0
  32. package/dist/theme-reference.d.ts +2 -0
  33. package/dist/theme-reference.js +1 -1
  34. package/package.json +8 -2
  35. package/src/client.test.ts +40 -0
  36. package/src/client.ts +18 -4
  37. package/src/components/approval-bubble.test.ts +268 -0
  38. package/src/components/approval-bubble.ts +170 -20
  39. package/src/components/launcher.ts +6 -3
  40. package/src/components/tool-bubble.test.ts +39 -0
  41. package/src/components/tool-bubble.ts +4 -0
  42. package/src/generated/runtype-openapi-contract.ts +12 -0
  43. package/src/index-core.ts +1 -0
  44. package/src/plugin-kit.test.ts +230 -0
  45. package/src/plugin-kit.ts +294 -0
  46. package/src/plugins/types.ts +49 -2
  47. package/src/session.test.ts +99 -0
  48. package/src/session.ts +204 -32
  49. package/src/session.webmcp.test.ts +326 -6
  50. package/src/theme-editor/preview-utils.test.ts +10 -0
  51. package/src/theme-editor/preview-utils.ts +29 -1
  52. package/src/theme-editor/sections.test.ts +17 -0
  53. package/src/theme-editor/sections.ts +31 -0
  54. package/src/theme-reference.ts +1 -1
  55. package/src/types/theme.ts +2 -0
  56. package/src/types.ts +59 -2
  57. package/src/ui.approval-plugin.test.ts +204 -0
  58. package/src/ui.ts +149 -16
  59. package/src/utils/theme.test.ts +6 -2
  60. package/src/utils/theme.ts +0 -8
  61. package/src/utils/tokens.ts +6 -1
  62. package/src/webmcp-bridge.test.ts +66 -0
  63. package/src/webmcp-bridge.ts +49 -0
@@ -1,18 +1,18 @@
1
- var Yp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ts(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];Yp(s)&&Yp(r)?n[o]=Ts(s,r):n[o]=r}return n}var io="min(440px, calc(100vw - 24px))",Ta="440px",St={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:io,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Xp(e,t){if(!(!e&&!t))return e?t?Ts(e,t):e:t}function Qp(e){var t,n,o,r,s,a,i,d,l,p,m,f,u,w,C,M,I,R,H,D,B;return e?{...St,...e,theme:Xp(St.theme,e.theme),darkTheme:Xp(St.darkTheme,e.darkTheme),launcher:{...St.launcher,...e.launcher,dock:{...(t=St.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(o=St.launcher)==null?void 0:o.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...St.copy,...e.copy},sendButton:{...St.sendButton,...e.sendButton},statusIndicator:{...St.statusIndicator,...e.statusIndicator},voiceRecognition:{...St.voiceRecognition,...e.voiceRecognition},features:(()=>{var be,Fe,ve,J,Le,Y,xe,Se;let v=(be=St.features)==null?void 0:be.artifacts,x=(Fe=e.features)==null?void 0:Fe.artifacts,k=(ve=St.features)==null?void 0:ve.scrollToBottom,S=(J=e.features)==null?void 0:J.scrollToBottom,E=(Le=St.features)==null?void 0:Le.streamAnimation,F=(Y=e.features)==null?void 0:Y.streamAnimation,$=(xe=St.features)==null?void 0:xe.askUserQuestion,j=(Se=e.features)==null?void 0:Se.askUserQuestion,me=v===void 0&&x===void 0?void 0:{...v,...x,layout:{...v==null?void 0:v.layout,...x==null?void 0:x.layout}},se=k===void 0&&S===void 0?void 0:{...k,...S},ge=E===void 0&&F===void 0?void 0:{...E,...F},ie=$===void 0&&j===void 0?void 0:{...$,...j,styles:{...$==null?void 0:$.styles,...j==null?void 0:j.styles}};return{...St.features,...e.features,...se!==void 0?{scrollToBottom:se}:{},...me!==void 0?{artifacts:me}:{},...ge!==void 0?{streamAnimation:ge}:{},...ie!==void 0?{askUserQuestion:ie}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:St.suggestionChips,suggestionChipsConfig:{...St.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...St.layout,...e.layout,header:{...(a=St.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=St.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(m=(p=St.layout)==null?void 0:p.messages)==null?void 0:m.avatar,...(u=(f=e.layout)==null?void 0:f.messages)==null?void 0:u.avatar},timestamp:{...(C=(w=St.layout)==null?void 0:w.messages)==null?void 0:C.timestamp,...(I=(M=e.layout)==null?void 0:M.messages)==null?void 0:I.timestamp}},slots:{...(R=St.layout)==null?void 0:R.slots,...(H=e.layout)==null?void 0:H.slots}},markdown:{...St.markdown,...e.markdown,options:{...(D=St.markdown)==null?void 0:D.options,...(B=e.markdown)==null?void 0:B.options}},messageActions:{...St.messageActions,...e.messageActions}}:St}var lg={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},cg={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},dg={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:io,maxWidth:Ta,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Vr(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Vr(e,o):o}function Jp(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let i=`${r}.${s}`;if(typeof a=="string"){let d=Vr(e,a);d!==void 0&&(t[i]={path:i,value:d,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function pg(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function Zp(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=Zp(s,r):n[o]=r}return n}function ug(e,t){return t?Zp(e,t):e}function tn(e,t={}){var r,s,a,i,d,l,p,m,f,u,w,C,M;let n={palette:lg,semantic:cg,components:dg},o={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(f=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(w=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:w.feedback}},spacing:{...n.semantic.spacing,...(C=e==null?void 0:e.semantic)==null?void 0:C.spacing},typography:{...n.semantic.typography,...(M=e==null?void 0:e.semantic)==null?void 0:M.typography}},components:ug(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let I=pg(o);if(!I.valid)throw new Error(`Theme validation failed: ${I.errors.map(R=>R.message).join(", ")}`)}if(t.plugins)for(let I of t.plugins)o=I.transform(o);return o}function eu(e){var C,M,I,R,H,D,B,v,x,k,S,E,F,$,j,me,se,ge,ie,be,Fe,ve,J,Le,Y,xe,Se,de,we,Ue,te,ne,re,nt,ye,le,$e,Be,ce,K,_e,Et,pe,ae,Ln,Nt,ln,Dn,Jn,ze,_,ke,He,De,Ve,dt,ot,At,Vt,q,_t,Qe,Ft,oe,fe,xt,$t,Jt,yn,Tt,wt,ft,bt,zt,et,Fn,Zn,vn,On,ut,wo,Nn,ir,In,Rr,$o,Lo,yt,_n,Vn,xn,It,eo,to,$n,Uo,Io,zo,Un,Wt,wn,no,qo,Ro,jo,Co,zn,po,gt,Kt,Gt,qn,Ko,oo,uo,jn;let t=Jp(e),n={};for(let[T,Kn]of Object.entries(t)){let mo=T.replace(/\./g,"-");n[`--persona-${mo}`]=Kn.value}n["--persona-primary"]=(C=n["--persona-semantic-colors-primary"])!=null?C:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(M=n["--persona-semantic-colors-secondary"])!=null?M:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(I=n["--persona-semantic-colors-accent"])!=null?I:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(R=n["--persona-semantic-colors-surface"])!=null?R:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(H=n["--persona-semantic-colors-background"])!=null?H:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(D=n["--persona-semantic-colors-container"])!=null?D:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(B=n["--persona-semantic-colors-text"])!=null?B:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(v=n["--persona-semantic-colors-text-muted"])!=null?v:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(x=n["--persona-semantic-colors-text-inverse"])!=null?x:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(k=n["--persona-semantic-colors-border"])!=null?k:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(S=n["--persona-semantic-colors-divider"])!=null?S:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(E=n["--persona-components-voice-recording-indicator"])!=null?E:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(F=n["--persona-components-voice-recording-background"])!=null?F:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=($=n["--persona-components-voice-processing-icon"])!=null?$:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(j=n["--persona-components-voice-speaking-icon"])!=null?j:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(me=n["--persona-components-approval-requested-background"])!=null?me:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(se=n["--persona-components-approval-requested-border"])!=null?se:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(ge=n["--persona-components-approval-requested-text"])!=null?ge:n["--persona-palette-colors-gray-900"],n["--persona-approval-approve-bg"]=(ie=n["--persona-components-approval-approve-background"])!=null?ie:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(be=n["--persona-components-approval-deny-background"])!=null?be:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Fe=n["--persona-components-attachment-image-background"])!=null?Fe:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(ve=n["--persona-components-attachment-image-border"])!=null?ve:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(J=n["--persona-semantic-typography-fontFamily"])!=null?J:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(Le=n["--persona-semantic-typography-fontSize"])!=null?Le:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(Y=n["--persona-semantic-typography-fontWeight"])!=null?Y:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(xe=n["--persona-semantic-typography-lineHeight"])!=null?xe:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(Se=n["--persona-palette-radius-sm"])!=null?Se:"0.125rem",n["--persona-radius-md"]=(de=n["--persona-palette-radius-md"])!=null?de:"0.375rem",n["--persona-radius-lg"]=(we=n["--persona-palette-radius-lg"])!=null?we:"0.5rem",n["--persona-radius-xl"]=(Ue=n["--persona-palette-radius-xl"])!=null?Ue:"0.75rem",n["--persona-radius-full"]=(te=n["--persona-palette-radius-full"])!=null?te:"9999px",n["--persona-launcher-radius"]=(re=(ne=n["--persona-components-launcher-borderRadius"])!=null?ne:n["--persona-palette-radius-full"])!=null?re:"9999px",n["--persona-launcher-bg"]=(nt=n["--persona-components-launcher-background"])!=null?nt:n["--persona-primary"],n["--persona-launcher-fg"]=(ye=n["--persona-components-launcher-foreground"])!=null?ye:n["--persona-text-inverse"],n["--persona-launcher-border"]=(le=n["--persona-components-launcher-border"])!=null?le:n["--persona-border"],n["--persona-button-primary-bg"]=($e=n["--persona-components-button-primary-background"])!=null?$e:n["--persona-primary"],n["--persona-button-primary-fg"]=(Be=n["--persona-components-button-primary-foreground"])!=null?Be:n["--persona-text-inverse"],n["--persona-button-radius"]=(K=(ce=n["--persona-components-button-primary-borderRadius"])!=null?ce:n["--persona-palette-radius-full"])!=null?K:"9999px",n["--persona-panel-radius"]=(Et=(_e=n["--persona-components-panel-borderRadius"])!=null?_e:n["--persona-radius-xl"])!=null?Et:"0.75rem",n["--persona-panel-border"]=(pe=n["--persona-components-panel-border"])!=null?pe:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Ln=(ae=n["--persona-components-panel-shadow"])!=null?ae:n["--persona-palette-shadows-xl"])!=null?Ln:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-input-radius"]=(ln=(Nt=n["--persona-components-input-borderRadius"])!=null?Nt:n["--persona-radius-lg"])!=null?ln:"0.5rem",n["--persona-message-user-radius"]=(Jn=(Dn=n["--persona-components-message-user-borderRadius"])!=null?Dn:n["--persona-radius-lg"])!=null?Jn:"0.5rem",n["--persona-message-assistant-radius"]=(_=(ze=n["--persona-components-message-assistant-borderRadius"])!=null?ze:n["--persona-radius-lg"])!=null?_:"0.5rem",n["--persona-header-bg"]=(ke=n["--persona-components-header-background"])!=null?ke:n["--persona-surface"],n["--persona-header-border"]=(He=n["--persona-components-header-border"])!=null?He:n["--persona-divider"],n["--persona-header-icon-bg"]=(De=n["--persona-components-header-iconBackground"])!=null?De:n["--persona-primary"],n["--persona-header-icon-fg"]=(Ve=n["--persona-components-header-iconForeground"])!=null?Ve:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(dt=n["--persona-components-header-titleForeground"])!=null?dt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(ot=n["--persona-components-header-subtitleForeground"])!=null?ot:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(At=n["--persona-components-header-actionIconForeground"])!=null?At:n["--persona-muted"];let o=(Vt=e.components)==null?void 0:Vt.header;o!=null&&o.shadow&&(n["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom);let r=(q=e.components)==null?void 0:q.introCard;n["--persona-intro-card-bg"]=(_t=n["--persona-components-introCard-background"])!=null?_t:n["--persona-surface"],n["--persona-intro-card-radius"]=(Qe=n["--persona-components-introCard-borderRadius"])!=null?Qe:"1rem",n["--persona-intro-card-padding"]=(Ft=n["--persona-components-introCard-padding"])!=null?Ft:"1.5rem",n["--persona-intro-card-shadow"]=(fe=(oe=r==null?void 0:r.shadow)!=null?oe:n["--persona-components-introCard-shadow"])!=null?fe:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(xt=n["--persona-components-input-background"])!=null?xt:n["--persona-surface"],n["--persona-input-placeholder"]=($t=n["--persona-components-input-placeholder"])!=null?$t:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Jt=n["--persona-components-message-user-background"])!=null?Jt:n["--persona-accent"],n["--persona-message-user-text"]=(yn=n["--persona-components-message-user-text"])!=null?yn:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Tt=n["--persona-components-message-user-shadow"])!=null?Tt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(wt=n["--persona-components-message-assistant-background"])!=null?wt:n["--persona-surface"],n["--persona-message-assistant-text"]=(ft=n["--persona-components-message-assistant-text"])!=null?ft:n["--persona-text"],n["--persona-message-assistant-border"]=(bt=n["--persona-components-message-assistant-border"])!=null?bt:n["--persona-border"],n["--persona-message-assistant-shadow"]=(zt=n["--persona-components-message-assistant-shadow"])!=null?zt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(Fn=(et=n["--persona-components-scrollToBottom-background"])!=null?et:n["--persona-button-primary-bg"])!=null?Fn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(vn=(Zn=n["--persona-components-scrollToBottom-foreground"])!=null?Zn:n["--persona-button-primary-fg"])!=null?vn:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(On=n["--persona-components-scrollToBottom-border"])!=null?On:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(ut=n["--persona-components-scrollToBottom-size"])!=null?ut:"40px",n["--persona-scroll-to-bottom-radius"]=(ir=(Nn=(wo=n["--persona-components-scrollToBottom-borderRadius"])!=null?wo:n["--persona-button-radius"])!=null?Nn:n["--persona-radius-full"])!=null?ir:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Rr=(In=n["--persona-components-scrollToBottom-shadow"])!=null?In:n["--persona-palette-shadows-sm"])!=null?Rr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=($o=n["--persona-components-scrollToBottom-padding"])!=null?$o:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Lo=n["--persona-components-scrollToBottom-gap"])!=null?Lo:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(_n=(yt=n["--persona-components-scrollToBottom-fontSize"])!=null?yt:n["--persona-palette-typography-fontSize-sm"])!=null?_n:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Vn=n["--persona-components-scrollToBottom-iconSize"])!=null?Vn:"14px",n["--persona-tool-bubble-shadow"]=(xn=n["--persona-components-toolBubble-shadow"])!=null?xn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(It=n["--persona-components-reasoningBubble-shadow"])!=null?It:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(eo=n["--persona-components-composer-shadow"])!=null?eo:"none",n["--persona-md-inline-code-bg"]=(to=n["--persona-components-markdown-inlineCode-background"])!=null?to:n["--persona-container"],n["--persona-md-inline-code-color"]=($n=n["--persona-components-markdown-inlineCode-foreground"])!=null?$n:n["--persona-text"],n["--persona-md-link-color"]=(Io=(Uo=n["--persona-components-markdown-link-foreground"])!=null?Uo:n["--persona-accent"])!=null?Io:"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let l=n["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(n["--persona-md-prose-font-family"]=l),n["--persona-md-code-block-bg"]=(zo=n["--persona-components-markdown-codeBlock-background"])!=null?zo:n["--persona-container"],n["--persona-md-code-block-border-color"]=(Un=n["--persona-components-markdown-codeBlock-borderColor"])!=null?Un:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Wt=n["--persona-components-markdown-codeBlock-textColor"])!=null?Wt:"inherit",n["--persona-md-table-header-bg"]=(wn=n["--persona-components-markdown-table-headerBackground"])!=null?wn:n["--persona-container"],n["--persona-md-table-border-color"]=(no=n["--persona-components-markdown-table-borderColor"])!=null?no:n["--persona-border"],n["--persona-md-hr-color"]=(qo=n["--persona-components-markdown-hr-color"])!=null?qo:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Ro=n["--persona-components-markdown-blockquote-borderColor"])!=null?Ro:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(jo=n["--persona-components-markdown-blockquote-background"])!=null?jo:"transparent",n["--persona-md-blockquote-text-color"]=(Co=n["--persona-components-markdown-blockquote-textColor"])!=null?Co:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(zn=n["--persona-components-collapsibleWidget-container"])!=null?zn:n["--persona-surface"],n["--cw-surface"]=(po=n["--persona-components-collapsibleWidget-surface"])!=null?po:n["--persona-surface"],n["--cw-border"]=(gt=n["--persona-components-collapsibleWidget-border"])!=null?gt:n["--persona-border"],n["--persona-message-border"]=(Kt=n["--persona-components-message-border"])!=null?Kt:n["--persona-border"];let p=e.components,m=p==null?void 0:p.iconButton;m&&(m.background&&(n["--persona-icon-btn-bg"]=m.background),m.border&&(n["--persona-icon-btn-border"]=m.border),m.color&&(n["--persona-icon-btn-color"]=m.color),m.padding&&(n["--persona-icon-btn-padding"]=m.padding),m.borderRadius&&(n["--persona-icon-btn-radius"]=m.borderRadius),m.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=m.hoverBackground),m.hoverColor&&(n["--persona-icon-btn-hover-color"]=m.hoverColor),m.activeBackground&&(n["--persona-icon-btn-active-bg"]=m.activeBackground),m.activeBorder&&(n["--persona-icon-btn-active-border"]=m.activeBorder));let f=p==null?void 0:p.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let u=p==null?void 0:p.toggleGroup;u&&(u.gap&&(n["--persona-toggle-group-gap"]=u.gap),u.borderRadius&&(n["--persona-toggle-group-radius"]=u.borderRadius));let w=p==null?void 0:p.artifact;if(w!=null&&w.toolbar){let T=w.toolbar;T.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=T.iconHoverColor),T.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=T.iconHoverBackground),T.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=T.iconPadding),T.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=T.iconBorderRadius),T.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=T.iconBorder),T.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=T.toggleGroupGap),T.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=T.toggleBorderRadius),T.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=T.copyBackground),T.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=T.copyBorder),T.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=T.copyColor),T.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=T.copyBorderRadius),T.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=T.copyPadding),T.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=T.copyMenuBackground,n["--persona-dropdown-bg"]=(Gt=n["--persona-dropdown-bg"])!=null?Gt:T.copyMenuBackground),T.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=T.copyMenuBorder,n["--persona-dropdown-border"]=(qn=n["--persona-dropdown-border"])!=null?qn:T.copyMenuBorder),T.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=T.copyMenuShadow,n["--persona-dropdown-shadow"]=(Ko=n["--persona-dropdown-shadow"])!=null?Ko:T.copyMenuShadow),T.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=T.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(oo=n["--persona-dropdown-radius"])!=null?oo:T.copyMenuBorderRadius),T.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=T.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(uo=n["--persona-dropdown-item-hover-bg"])!=null?uo:T.copyMenuItemHoverBackground),T.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=T.iconBackground),T.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=T.toolbarBorder)}if(w!=null&&w.tab){let T=w.tab;T.background&&(n["--persona-artifact-tab-bg"]=T.background),T.activeBackground&&(n["--persona-artifact-tab-active-bg"]=T.activeBackground),T.activeBorder&&(n["--persona-artifact-tab-active-border"]=T.activeBorder),T.borderRadius&&(n["--persona-artifact-tab-radius"]=T.borderRadius),T.textColor&&(n["--persona-artifact-tab-color"]=T.textColor),T.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=T.hoverBackground),T.listBackground&&(n["--persona-artifact-tab-list-bg"]=T.listBackground),T.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=T.listBorderColor),T.listPadding&&(n["--persona-artifact-tab-list-padding"]=T.listPadding)}if(w!=null&&w.pane){let T=w.pane;if(T.toolbarBackground){let Kn=(jn=Vr(e,T.toolbarBackground))!=null?jn:T.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Kn}}return n}var mg={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},tu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},zi=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},gg=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":zi()},fg=e=>gg(e),hg=e=>tn(e),bg=e=>{var n;let t=tn(void 0,{validate:!1});return tn({...e,palette:{...t.palette,colors:{...mg.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},ka=e=>{let t=fg(e),n=tu(e==null?void 0:e.theme),o=tu(e==null?void 0:e.darkTheme);return t==="dark"?bg(Ts(n!=null?n:{},o!=null?o:{})):hg(n)},yg=e=>eu(e),$r=(e,t)=>{var s;let n=ka(t),o=yg(n);for(let[a,i]of Object.entries(o))e.style.setProperty(a,i);let r=(s=t==null?void 0:t.toolCall)==null?void 0:s.shadow;r!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",r.trim()===""?"none":r)},nu=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(zi())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(zi());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};function qi(e,t){let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return o}function xr(e,t,n){var i;let o=t.split(".");if(o.length===1)return{...e,[o[0]]:n};let[r,...s]=o,a=e;return{...a,[r]:xr((i=a==null?void 0:a[r])!=null?i:{},s.join("."),n)}}var ji=class{constructor(t,n,o){this.listeners=[];this.history=[];this.historyIndex=-1;this.suppressHistory=!1;var s;let r=(s=o==null?void 0:o.mergeDefaults)!=null?s:!0;this.config=r?{...St,...n}:n!=null?n:St,this.theme=tn(t,{validate:!1}),this.syncThemeIntoConfig(),this.pushHistorySnapshot(this.exportSnapshot(),!0)}get(t){var n;return t.startsWith("theme.")?qi(this.theme,t.replace("theme.","")):t.startsWith("darkTheme.")?qi((n=this.config.darkTheme)!=null?n:{},t.replace("darkTheme.","")):qi(this.config,t)}getTheme(){return this.theme}getConfig(){return this.config}set(t,n){var o;if(t.startsWith("theme.")){let r=t.replace("theme.","");this.theme=xr(this.theme,r,n),this.syncThemeIntoConfig()}else if(t.startsWith("darkTheme.")){let r=t.replace("darkTheme.",""),s=(o=this.config.darkTheme)!=null?o:tn();this.config={...this.config,darkTheme:xr(s,r,n)}}else this.config=xr(this.config,t,n);this.recordHistory(),this.notifyListeners()}setBatch(t){var s;let n=!1,o=!1,r=!1;for(let[a,i]of Object.entries(t))if(a.startsWith("theme.")){let d=a.replace("theme.","");this.theme=xr(this.theme,d,i),n=!0}else if(a.startsWith("darkTheme.")){let d=a.replace("darkTheme.",""),l=(s=this.config.darkTheme)!=null?s:tn();this.config={...this.config,darkTheme:xr(l,d,i)},o=!0}else this.config=xr(this.config,a,i),r=!0;n&&this.syncThemeIntoConfig(),(n||o||r)&&(this.recordHistory(),this.notifyListeners())}setTheme(t){this.theme=t,this.syncThemeIntoConfig(),this.recordHistory(),this.notifyListeners()}setFullConfig(t,n){this.config={...t},n&&(this.theme=n),this.syncThemeIntoConfig(),this.recordHistory(),this.notifyListeners()}importSnapshot(t){var r,s;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Snapshot must be a JSON object");let n=t;if("config"in n||"theme"in n||n.version===2){let a=(r=n.config)!=null?r:this.config,i=tn((s=n.theme)!=null?s:this.theme,{validate:!1});this.setFullConfig(a,i);return}let o=tn(n,{validate:!1});this.setTheme(o)}resetToDefaults(){this.config={...St},this.theme=tn(),this.syncThemeIntoConfig(),this.history=[],this.historyIndex=-1,this.pushHistorySnapshot(this.exportSnapshot()),this.notifyListeners()}canUndo(){return this.historyIndex>0}canRedo(){return this.historyIndex>=0&&this.historyIndex<this.history.length-1}getHistoryLength(){return this.history.length}getHistoryIndex(){return this.historyIndex}undo(){this.canUndo()&&(this.historyIndex-=1,this.restoreSnapshot(this.history[this.historyIndex]))}redo(){this.canRedo()&&(this.historyIndex+=1,this.restoreSnapshot(this.history[this.historyIndex]))}exportSnapshot(){return{version:2,config:{...this.config,theme:void 0},theme:this.theme}}onChange(t){return this.listeners.push(t),()=>{let n=this.listeners.indexOf(t);n>=0&&this.listeners.splice(n,1)}}syncThemeIntoConfig(){this.config={...this.config,theme:this.theme}}notifyListeners(){for(let t of this.listeners)t(this.config,this.theme)}recordHistory(){this.pushHistorySnapshot(this.exportSnapshot())}pushHistorySnapshot(t,n=!1){if(this.suppressHistory)return;let o=JSON.stringify(t),r=this.historyIndex>=0&&this.history[this.historyIndex]?JSON.stringify(this.history[this.historyIndex]):null;if(n&&this.historyIndex>=0){this.history[this.historyIndex]=t;return}o!==r&&(this.history=this.history.slice(0,this.historyIndex+1),this.history.push(t),this.historyIndex=this.history.length-1)}restoreSnapshot(t){this.suppressHistory=!0,this.config=t.config,this.theme=tn(t.theme,{validate:!1}),this.syncThemeIntoConfig(),this.suppressHistory=!1,this.notifyListeners()}};function Ki(e){let t=e.trim();if(t==="9999px")return{value:100,unit:"px"};let n=t.match(/^([\d.]+)(px|rem)$/);if(!n){let o=parseFloat(t);return{value:isNaN(o)?0:o,unit:"px"}}return{value:parseFloat(n[1]),unit:n[2]}}function Gi(e,t){return t==="rem"?`${e}rem`:`${e}px`}function vg(e,t){return t==="rem"?e*16:e}function xg(e,t){return t==="rem"?e/16:e}function ks(e){if(!e)return"#000000";let t=e.trim().toLowerCase();return t==="transparent"?"transparent":t.startsWith("rgba")||t.startsWith("rgb")?t:t.startsWith("#")?t.length===4?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:t:`#${t}`}function Yi(e){return/^#[0-9A-Fa-f]{6}$/.test(e)}function Xi(e){let t=e.trim().toLowerCase().match(/^rgba?\(([^)]+)\)$/);if(!t)return null;let n=t[1].split(",").map(d=>d.trim());if(n.length<3)return null;let o=d=>{let l=d.endsWith("%"),p=parseFloat(l?d.slice(0,-1):d);return Number.isFinite(p)?Math.max(0,Math.min(255,Math.round(l?p/100*255:p))):NaN},r=o(n[0]),s=o(n[1]),a=o(n[2]);if(!Number.isFinite(r)||!Number.isFinite(s)||!Number.isFinite(a))return null;let i=d=>d.toString(16).padStart(2,"0");return`#${i(r)}${i(s)}${i(a)}`}function Ea(e,t){let n=s=>{var l;let a=ks(s),i=a.startsWith("rgb")?(l=Xi(a))!=null?l:"#000000":a,d=[1,3,5].map(p=>{let m=parseInt(i.slice(p,p+2),16)/255;return m<=.03928?m/12.92:Math.pow((m+.055)/1.055,2.4)});return .2126*d[0]+.7152*d[1]+.0722*d[2]},o=n(e),r=n(t);return(Math.max(o,r)+.05)/(Math.min(o,r)+.05)}function ou(e){var f;let t=ks(e),n=t.startsWith("rgb")?(f=Xi(t))!=null?f:"#000000":t,o=parseInt(n.slice(1,3),16)/255,r=parseInt(n.slice(3,5),16)/255,s=parseInt(n.slice(5,7),16)/255,a=Math.max(o,r,s),i=Math.min(o,r,s),d=(a+i)/2;if(a===i)return{h:0,s:0,l:d};let l=a-i,p=d>.5?l/(2-a-i):l/(a+i),m;switch(a){case o:m=((r-s)/l+(r<s?6:0))/6;break;case r:m=((s-o)/l+2)/6;break;default:m=((o-r)/l+4)/6;break}return{h:m*360,s:p,l:d}}function ru(e,t,n){let o=(e%360+360)%360,r=(1-Math.abs(2*n-1))*t,s=r*(1-Math.abs(o/60%2-1)),a=n-r/2,i,d,l;o<60?[i,d,l]=[r,s,0]:o<120?[i,d,l]=[s,r,0]:o<180?[i,d,l]=[0,r,s]:o<240?[i,d,l]=[0,s,r]:o<300?[i,d,l]=[s,0,r]:[i,d,l]=[r,0,s];let p=m=>{let f=Math.round((m+a)*255).toString(16);return f.length===1?"0"+f:f};return`#${p(i)}${p(d)}${p(l)}`}function Qi(e){let{h:t,s:n,l:o}=ou(e),r={50:.97,100:.94,200:.87,300:.77,400:.64,500:o,600:Math.max(.05,o-.1),700:Math.max(.05,o-.2),800:Math.max(.05,o-.28),900:Math.max(.05,o-.35),950:Math.max(.03,o-.42)},s={50:Math.min(1,n*.85),100:Math.min(1,n*.9),200:Math.min(1,n*.95),300:n,400:n,500:n,600:Math.min(1,n*1.05),700:Math.min(1,n*1.05),800:Math.min(1,n*1),900:Math.min(1,n*.95),950:Math.min(1,n*.9)},a={};for(let[i,d]of Object.entries(r)){let l=s[i];a[i]=ru(t,l,d)}return a}var Ur=["50","100","200","300","400","500","600","700","800","900","950"],Ji=["primary","secondary","accent","gray","success","warning","error","info"];function wg(e,t){return`palette.colors.${e}.${t}`}function su(e,t,n=0){if(n>5)return"#cbd5e1";let o=e(t);return typeof o!="string"?"#cbd5e1":o.startsWith("#")||o.startsWith("rgb")||o==="transparent"?o:o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components.")?su(e,`theme.${o}`,n+1):"#cbd5e1"}function Cg(e){if(!e.startsWith("palette.")&&!e.startsWith("semantic."))return e;let t=e.split(".");if(t[0]==="palette"&&t[1]==="colors"){let n=t[2],o=t[3];return`${n.charAt(0).toUpperCase()+n.slice(1)} ${o}`}return t[0]==="semantic"?t.slice(1).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):t[t.length-1]}var ko=[{id:"solid",label:"Solid"},{id:"soft",label:"Soft"}],Ma=["primary","secondary","accent","gray"],Sg={primary:"Primary",secondary:"Secondary",accent:"Accent",gray:"Neutral"},La={roleId:"role-surfaces",helper:"Page and panel backgrounds",previewZone:"container",intensities:ko,targets:[{path:"semantic.colors.background",kind:"background"},{path:"semantic.colors.surface",kind:"background"},{path:"semantic.colors.container",kind:"background"}]},Ia={roleId:"role-header",helper:"Widget header bar",previewZone:"header",intensities:ko,targets:[{path:"components.header.background",kind:"background"},{path:"components.header.border",kind:"border"},{path:"components.header.iconBackground",kind:"accent"},{path:"components.header.iconForeground",kind:"foreground"},{path:"components.header.titleForeground",kind:"accent"},{path:"components.header.subtitleForeground",kind:"foreground"},{path:"components.header.actionIconForeground",kind:"foreground"}]},Ra={roleId:"role-user-messages",helper:"User chat bubbles",previewZone:"user-message",intensities:ko,targets:[{path:"components.message.user.background",kind:"background"},{path:"components.message.user.text",kind:"foreground"}]},Pa={roleId:"role-assistant-messages",helper:"Assistant chat bubbles",previewZone:"assistant-message",intensities:ko,targets:[{path:"components.message.assistant.background",kind:"background"},{path:"components.message.assistant.text",kind:"foreground"}]},Wa={roleId:"role-primary-actions",helper:"Send button and primary buttons",intensities:ko,targets:[{path:"components.button.primary.background",kind:"background"},{path:"components.button.primary.foreground",kind:"foreground"},{path:"semantic.colors.interactive.default",kind:"accent"},{path:"semantic.colors.interactive.hover",kind:"accent"}]},Ba={roleId:"role-scroll-to-bottom",helper:"Scroll-to-bottom affordances in transcript and event stream",intensities:ko,targets:[{path:"components.scrollToBottom.background",kind:"background"},{path:"components.scrollToBottom.foreground",kind:"foreground"},{path:"components.scrollToBottom.border",kind:"border"}]},Ha={roleId:"role-input",helper:"Message input field",previewZone:"composer",intensities:ko,targets:[{path:"components.input.background",kind:"background"},{path:"components.input.placeholder",kind:"foreground"},{path:"components.input.focus.border",kind:"accent"},{path:"components.input.focus.ring",kind:"accent"}]},Da={roleId:"role-links-focus",helper:"Links, focus rings, and interactive highlights",intensities:ko,targets:[{path:"semantic.colors.accent",kind:"accent"},{path:"semantic.colors.interactive.focus",kind:"accent"},{path:"semantic.colors.interactive.active",kind:"accent"},{path:"components.markdown.link.foreground",kind:"accent"}]},Fa={roleId:"role-borders",helper:"Borders, dividers, and separators",intensities:ko,targets:[{path:"semantic.colors.border",kind:"border"},{path:"semantic.colors.divider",kind:"border"}]},wr=[La,Ia,Ra,Pa,Wa,Ba,Ha,Da,Fa];function Oa(e,t,n){let o={},r=e==="neutral"?"gray":e;for(let s of n.targets){let a=Ag(r,t,s,n.roleId);o[`theme.${s.path}`]=a,o[`darkTheme.${s.path}`]=a}if(n.roleId==="role-primary-actions"){let s=t==="solid"?`palette.colors.${r}.700`:`palette.colors.${r}.200`;o["theme.semantic.colors.interactive.hover"]=s,o["darkTheme.semantic.colors.interactive.hover"]=s}return o}function Ag(e,t,n,o){let r=t==="solid";if(o==="role-header")return Tg(e,r,n);if(o==="role-input")return kg(e,r,n);switch(n.kind){case"background":return r?`palette.colors.${e}.500`:`palette.colors.${e}.${e==="gray"?"50":"100"}`;case"foreground":return r?`palette.colors.${e==="gray"?"gray":e}.50`:`palette.colors.${e==="gray"?"gray":e}.900`;case"border":return r?`palette.colors.${e}.600`:`palette.colors.${e}.200`;case"accent":return r?`palette.colors.${e}.600`:`palette.colors.${e}.400`}}function Tg(e,t,n){let o=n.path;return o.endsWith(".background")?t?`palette.colors.${e}.500`:`palette.colors.${e}.${e==="gray"?"50":"100"}`:o.endsWith(".border")?t?`palette.colors.${e}.600`:`palette.colors.${e}.200`:o.endsWith(".iconBackground")?t?`palette.colors.${e}.${e==="gray"?"700":"600"}`:`palette.colors.${e}.500`:o.endsWith(".iconForeground")?t?`palette.colors.${e}.50`:`palette.colors.${e}.50`:o.endsWith(".titleForeground")?t?`palette.colors.${e}.50`:`palette.colors.${e}.${e==="gray"?"900":"700"}`:o.endsWith(".subtitleForeground")?t?`palette.colors.${e}.200`:`palette.colors.${e}.500`:o.endsWith(".actionIconForeground")?t?`palette.colors.${e}.200`:`palette.colors.${e}.500`:`palette.colors.${e}.500`}function kg(e,t,n){let o=n.path;return o.endsWith(".background")?t?`palette.colors.${e}.${e==="gray"?"100":"50"}`:`palette.colors.${e}.50`:o.endsWith(".placeholder")?`palette.colors.${e}.400`:o.endsWith(".border")||o.endsWith(".ring")?t?`palette.colors.${e}.500`:`palette.colors.${e}.400`:`palette.colors.${e}.500`}var Eg=/^palette\.colors\.(\w+)\.(\d+)$/;function Zi(e,t){var i,d;let n=(i=t.targets.find(l=>l.kind==="background"))!=null?i:t.targets[0];if(!n)return null;let r=String((d=e(n.path))!=null?d:"").match(Eg);if(!r)return null;let s=r[1],a=Ma.includes(s)?s:null;if(!a)return null;for(let l of["solid","soft"]){let p=Oa(a,l,t);if(t.targets.every(f=>{var w;return String((w=e(f.path))!=null?w:"")===p[`theme.${f.path}`]}))return{family:a,intensity:l}}return null}var Mg={id:"theme-mode",title:"Runtime Theme",description:"Controls how the shipped widget picks light or dark mode.",collapsed:!1,fields:[{id:"theme-mode",label:"Runtime Theme",description:"Always Light, Always Dark, or follow the visitor system preference",type:"select",path:"colorScheme",defaultValue:"auto",options:[{value:"light",label:"Light"},{value:"dark",label:"Dark"},{value:"auto",label:"Follow System"}]}]},Lg={id:"brand-colors",title:"Brand Colors",description:"Pick your brand colors. A full shade scale is generated automatically for both light and dark themes.",collapsed:!1,fields:[{id:"brand-primary",label:"Primary",description:"Main brand color for buttons, links, and accents",type:"color",path:"theme.palette.colors.primary.500",defaultValue:"#171717"},{id:"brand-secondary",label:"Secondary",description:"Supporting brand color",type:"color",path:"theme.palette.colors.secondary.500",defaultValue:"#7c3aed"},{id:"brand-accent",label:"Accent",description:"Highlight and decorative color",type:"color",path:"theme.palette.colors.accent.500",defaultValue:"#06b6d4"}]},Ig={id:"chat-colors",title:"Chat Colors",description:"Customize the main colors of the chat interface.",collapsed:!0,fields:[{id:"chat-header-bg",label:"Header Background",type:"token-ref",path:"theme.components.header.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"chat-header-icon-bg",label:"Header Icon Background",type:"token-ref",path:"theme.components.header.iconBackground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-header-icon-fg",label:"Header Icon Color",type:"token-ref",path:"theme.components.header.iconForeground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"chat-header-title-fg",label:"Header Title Color",type:"token-ref",path:"theme.components.header.titleForeground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-header-subtitle-fg",label:"Header Subtitle Color",type:"token-ref",path:"theme.components.header.subtitleForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"chat-header-action-icons-fg",label:"Header Button Icons",type:"token-ref",path:"theme.components.header.actionIconForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"chat-msg-user-bg",label:"User Message Background",type:"token-ref",path:"theme.components.message.user.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-msg-user-text",label:"User Message Text",type:"token-ref",path:"theme.components.message.user.text",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"chat-msg-assistant-bg",label:"Assistant Message Background",type:"token-ref",path:"theme.components.message.assistant.background",defaultValue:"semantic.colors.container",tokenRef:{tokenType:"color"}},{id:"chat-msg-assistant-text",label:"Assistant Message Text",type:"token-ref",path:"theme.components.message.assistant.text",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},Rg={id:"typography",title:"Typography",collapsed:!0,fields:[{id:"typo-font-family",label:"Font Family",type:"select",path:"theme.semantic.typography.fontFamily",defaultValue:"palette.typography.fontFamily.sans",options:[{value:"palette.typography.fontFamily.sans",label:"Sans Serif"},{value:"palette.typography.fontFamily.serif",label:"Serif"},{value:"palette.typography.fontFamily.mono",label:"Monospace"}]},{id:"typo-font-size",label:"Base Font Size",type:"select",path:"theme.semantic.typography.fontSize",defaultValue:"palette.typography.fontSize.base",options:[{value:"palette.typography.fontSize.xs",label:"Extra Small (0.75rem)"},{value:"palette.typography.fontSize.sm",label:"Small (0.875rem)"},{value:"palette.typography.fontSize.base",label:"Base (1rem)"},{value:"palette.typography.fontSize.lg",label:"Large (1.125rem)"},{value:"palette.typography.fontSize.xl",label:"Extra Large (1.25rem)"}]},{id:"typo-font-weight",label:"Font Weight",type:"select",path:"theme.semantic.typography.fontWeight",defaultValue:"palette.typography.fontWeight.normal",options:[{value:"palette.typography.fontWeight.normal",label:"Normal (400)"},{value:"palette.typography.fontWeight.medium",label:"Medium (500)"},{value:"palette.typography.fontWeight.semibold",label:"Semibold (600)"},{value:"palette.typography.fontWeight.bold",label:"Bold (700)"}]},{id:"typo-line-height",label:"Line Height",type:"select",path:"theme.semantic.typography.lineHeight",defaultValue:"palette.typography.lineHeight.normal",options:[{value:"palette.typography.lineHeight.tight",label:"Tight (1.25)"},{value:"palette.typography.lineHeight.normal",label:"Normal (1.5)"},{value:"palette.typography.lineHeight.relaxed",label:"Relaxed (1.625)"}]}]},Pg={id:"launcher-style",title:"Launcher",description:"Control launcher appearance.",collapsed:!0,fields:[{id:"style-launcher-size",label:"Launcher Size",type:"slider",path:"theme.components.launcher.size",defaultValue:"60px",slider:{min:32,max:80,step:2}},{id:"style-launcher-shape",label:"Launcher Shape",type:"select",path:"theme.components.launcher.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Rounded Square"},{value:"palette.radius.lg",label:"Rounded"},{value:"palette.radius.xl",label:"Very Rounded"},{value:"palette.radius.full",label:"Circle"}]},{id:"style-launcher-shadow",label:"Launcher Shadow",type:"select",path:"theme.components.launcher.shadow",defaultValue:"palette.shadows.lg",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},Wg={id:"shape",title:"Shape",description:"Control the corner roundness across the widget.",collapsed:!0,fields:[{id:"radius-sm",label:"Small",type:"slider",path:"theme.palette.radius.sm",defaultValue:"0.125rem",slider:{min:0,max:16,step:1}},{id:"radius-md",label:"Medium",type:"slider",path:"theme.palette.radius.md",defaultValue:"0.375rem",slider:{min:0,max:24,step:1}},{id:"radius-lg",label:"Large",type:"slider",path:"theme.palette.radius.lg",defaultValue:"0.5rem",slider:{min:0,max:32,step:1}},{id:"radius-xl",label:"Extra Large",type:"slider",path:"theme.palette.radius.xl",defaultValue:"0.75rem",slider:{min:0,max:48,step:1}},{id:"radius-full",label:"Full",type:"slider",path:"theme.palette.radius.full",defaultValue:"9999px",slider:{min:0,max:100,step:1,isRadiusFull:!0}}],presets:[{id:"radius-default",label:"Default",values:{"theme.palette.radius.sm":"0.125rem","theme.palette.radius.md":"0.375rem","theme.palette.radius.lg":"0.5rem","theme.palette.radius.xl":"0.75rem","theme.palette.radius.full":"9999px"}},{id:"radius-sharp",label:"Sharp",values:{"theme.palette.radius.sm":"1px","theme.palette.radius.md":"2px","theme.palette.radius.lg":"3px","theme.palette.radius.xl":"4px","theme.palette.radius.full":"4px"}},{id:"radius-rounded",label:"Rounded",values:{"theme.palette.radius.sm":"0.5rem","theme.palette.radius.md":"0.75rem","theme.palette.radius.lg":"1rem","theme.palette.radius.xl":"1.5rem","theme.palette.radius.full":"9999px"}}]},Bg={id:"shadows",title:"Shadows",collapsed:!0,fields:[{id:"shadow-sm",label:"Small",type:"text",path:"theme.palette.shadows.sm",defaultValue:"0 1px 2px 0 rgb(0 0 0 / 0.05)"},{id:"shadow-md",label:"Medium",type:"text",path:"theme.palette.shadows.md",defaultValue:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)"},{id:"shadow-lg",label:"Large",type:"text",path:"theme.palette.shadows.lg",defaultValue:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)"},{id:"shadow-xl",label:"Extra Large",type:"text",path:"theme.palette.shadows.xl",defaultValue:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)"}]},Hg={id:"widget-style",title:"Widget Surface",description:"Adjust the main panel and message bubble treatment.",collapsed:!0,fields:[{id:"style-panel-radius",label:"Panel Corner Radius",type:"select",path:"theme.components.panel.borderRadius",defaultValue:"palette.radius.xl",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"style-panel-shadow",label:"Panel Shadow",type:"select",path:"theme.components.panel.shadow",defaultValue:"palette.shadows.xl",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]},{id:"style-msg-user-radius",label:"User Message Radius",type:"select",path:"theme.components.message.user.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"style-msg-assistant-radius",label:"Assistant Message Radius",type:"select",path:"theme.components.message.assistant.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},zr=[Lg,Ig,Pg,Rg,Mg,Wg,Bg,Hg];function au(){return{id:"brand-palette",title:"Brand Palette",description:"Define your color palette. Edit the base color (500) to auto-generate the full scale.",collapsed:!1,fields:Ji.map(t=>({id:`palette-${t}`,label:`${t.charAt(0).toUpperCase()+t.slice(1)}`,description:`${t} color palette (edit shade 500, auto-generate scale)`,type:"color-scale",path:`theme.palette.colors.${t}`,colorScale:{colorFamily:t}}))}}var iu={id:"semantic-colors",title:"Semantic Colors",description:"Map intents to palette colors.",collapsed:!0,fields:[{id:"sem-primary",label:"Primary",description:"Main brand/action color",type:"token-ref",path:"theme.semantic.colors.primary",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sem-secondary",label:"Secondary",description:"Secondary actions",type:"token-ref",path:"theme.semantic.colors.secondary",defaultValue:"palette.colors.gray.500",tokenRef:{tokenType:"color"}},{id:"sem-accent",label:"Accent",description:"Accent/highlight color",type:"token-ref",path:"theme.semantic.colors.accent",defaultValue:"palette.colors.primary.600",tokenRef:{tokenType:"color"}},{id:"sem-surface",label:"Surface",description:"Primary surface background",type:"token-ref",path:"theme.semantic.colors.surface",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-background",label:"Background",description:"Page/widget background",type:"token-ref",path:"theme.semantic.colors.background",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-container",label:"Container",description:"Container/card background",type:"token-ref",path:"theme.semantic.colors.container",defaultValue:"palette.colors.gray.100",tokenRef:{tokenType:"color"}},{id:"sem-text",label:"Text",description:"Primary text color",type:"token-ref",path:"theme.semantic.colors.text",defaultValue:"palette.colors.gray.900",tokenRef:{tokenType:"color"}},{id:"sem-text-muted",label:"Text Muted",description:"Secondary/muted text",type:"token-ref",path:"theme.semantic.colors.textMuted",defaultValue:"palette.colors.gray.500",tokenRef:{tokenType:"color"}},{id:"sem-text-inverse",label:"Text Inverse",description:"Text on dark backgrounds",type:"token-ref",path:"theme.semantic.colors.textInverse",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-border",label:"Border",description:"Default border color",type:"token-ref",path:"theme.semantic.colors.border",defaultValue:"palette.colors.gray.200",tokenRef:{tokenType:"color"}},{id:"sem-divider",label:"Divider",description:"Divider/separator color",type:"token-ref",path:"theme.semantic.colors.divider",defaultValue:"palette.colors.gray.200",tokenRef:{tokenType:"color"}},{id:"sem-interactive-default",label:"Interactive Default",type:"token-ref",path:"theme.semantic.colors.interactive.default",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sem-interactive-hover",label:"Interactive Hover",type:"token-ref",path:"theme.semantic.colors.interactive.hover",defaultValue:"palette.colors.primary.600",tokenRef:{tokenType:"color"}},{id:"sem-interactive-focus",label:"Interactive Focus",type:"token-ref",path:"theme.semantic.colors.interactive.focus",defaultValue:"palette.colors.primary.700",tokenRef:{tokenType:"color"}},{id:"sem-interactive-active",label:"Interactive Active",type:"token-ref",path:"theme.semantic.colors.interactive.active",defaultValue:"palette.colors.primary.800",tokenRef:{tokenType:"color"}},{id:"sem-interactive-disabled",label:"Interactive Disabled",type:"token-ref",path:"theme.semantic.colors.interactive.disabled",defaultValue:"palette.colors.gray.300",tokenRef:{tokenType:"color"}},{id:"sem-feedback-success",label:"Success",type:"token-ref",path:"theme.semantic.colors.feedback.success",defaultValue:"palette.colors.success.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-warning",label:"Warning",type:"token-ref",path:"theme.semantic.colors.feedback.warning",defaultValue:"palette.colors.warning.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-error",label:"Error",type:"token-ref",path:"theme.semantic.colors.feedback.error",defaultValue:"palette.colors.error.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-info",label:"Info",type:"token-ref",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}}]},Dg=au(),Fg=iu,Og=[au(),iu],Ng={id:"comp-panel",title:"Panel",collapsed:!1,fields:[{id:"panel-width",label:"Width",type:"text",path:"theme.components.panel.width",defaultValue:io},{id:"panel-max-width",label:"Max Width",type:"text",path:"theme.components.panel.maxWidth",defaultValue:Ta},{id:"panel-height",label:"Height",type:"text",path:"theme.components.panel.height",defaultValue:"600px"},{id:"panel-max-height",label:"Max Height",type:"text",path:"theme.components.panel.maxHeight",defaultValue:"calc(100vh - 80px)"},{id:"panel-border-radius",label:"Border Radius",type:"select",path:"theme.components.panel.borderRadius",defaultValue:"palette.radius.xl",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"panel-shadow",label:"Shadow",type:"select",path:"theme.components.panel.shadow",defaultValue:"palette.shadows.xl",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},_g={id:"comp-launcher",title:"Launcher",collapsed:!0,fields:[{id:"launcher-size",label:"Size",type:"slider",path:"theme.components.launcher.size",defaultValue:"60px",slider:{min:32,max:80,step:2}},{id:"launcher-icon-size",label:"Icon Size",type:"slider",path:"theme.components.launcher.iconSize",defaultValue:"28px",slider:{min:16,max:48,step:2}},{id:"launcher-border-radius",label:"Border Radius",type:"select",path:"theme.components.launcher.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"},{value:"palette.radius.full",label:"Full (Circle)"}]},{id:"launcher-shadow",label:"Shadow",type:"select",path:"theme.components.launcher.shadow",defaultValue:"palette.shadows.lg",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},Vg={id:"comp-message-shape",title:"Message Shape",collapsed:!0,fields:[{id:"msg-user-radius",label:"User Bubble Radius",type:"select",path:"theme.components.message.user.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"msg-assistant-radius",label:"Assistant Bubble Radius",type:"select",path:"theme.components.message.assistant.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},$g={id:"comp-input-shape",title:"Input Shape",collapsed:!0,fields:[{id:"input-radius",label:"Border Radius",type:"select",path:"theme.components.input.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},Ug={id:"comp-button-shape",title:"Button Shape",collapsed:!0,fields:[{id:"btn-primary-radius",label:"Primary Radius",type:"select",path:"theme.components.button.primary.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.full",label:"Full"}]}]},zg={id:"comp-header-colors",title:"Header Colors",collapsed:!0,fields:[{id:"header-bg",label:"Background",type:"token-ref",path:"theme.components.header.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"header-icon-bg",label:"Icon background",type:"token-ref",path:"theme.components.header.iconBackground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"header-icon-fg",label:"Icon color",type:"token-ref",path:"theme.components.header.iconForeground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"header-title-fg",label:"Title color",type:"token-ref",path:"theme.components.header.titleForeground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"header-subtitle-fg",label:"Subtitle color",type:"token-ref",path:"theme.components.header.subtitleForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"header-action-icons-fg",label:"Clear / close icons",type:"token-ref",path:"theme.components.header.actionIconForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"header-border",label:"Border",type:"token-ref",path:"theme.components.header.border",defaultValue:"semantic.colors.border",tokenRef:{tokenType:"color"}}]},qg={id:"comp-message-colors",title:"Message Colors",collapsed:!0,fields:[{id:"msg-user-bg",label:"User Bubble Background",type:"token-ref",path:"theme.components.message.user.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"msg-user-text",label:"User Bubble Text",type:"token-ref",path:"theme.components.message.user.text",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"msg-assistant-bg",label:"Assistant Bubble Background",type:"token-ref",path:"theme.components.message.assistant.background",defaultValue:"semantic.colors.container",tokenRef:{tokenType:"color"}},{id:"msg-assistant-text",label:"Assistant Bubble Text",type:"token-ref",path:"theme.components.message.assistant.text",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},jg={id:"comp-input-colors",title:"Input Colors",collapsed:!0,fields:[{id:"input-bg",label:"Background",type:"token-ref",path:"theme.components.input.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"input-placeholder",label:"Placeholder Color",type:"token-ref",path:"theme.components.input.placeholder",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"input-focus-border",label:"Focus Border",type:"token-ref",path:"theme.components.input.focus.border",defaultValue:"semantic.colors.interactive.focus",tokenRef:{tokenType:"color"}},{id:"input-focus-ring",label:"Focus Ring",type:"token-ref",path:"theme.components.input.focus.ring",defaultValue:"semantic.colors.interactive.focus",tokenRef:{tokenType:"color"}}]},Kg={id:"comp-button-colors",title:"Button Colors",collapsed:!0,fields:[{id:"btn-primary-bg",label:"Primary Background",type:"token-ref",path:"theme.components.button.primary.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"btn-primary-fg",label:"Primary Foreground",type:"token-ref",path:"theme.components.button.primary.foreground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"btn-secondary-bg",label:"Secondary Background",type:"token-ref",path:"theme.components.button.secondary.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"btn-secondary-fg",label:"Secondary Foreground",type:"token-ref",path:"theme.components.button.secondary.foreground",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}},{id:"btn-ghost-bg",label:"Ghost Background",type:"color",path:"theme.components.button.ghost.background",defaultValue:"transparent"},{id:"btn-ghost-fg",label:"Ghost Foreground",type:"token-ref",path:"theme.components.button.ghost.foreground",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},Gg={id:"scroll-to-bottom-style",title:"Scroll To Bottom",description:"Style the floating jump-to-latest affordance.",collapsed:!0,fields:[{id:"scroll-bottom-bg",label:"Background",type:"token-ref",path:"theme.components.scrollToBottom.background",defaultValue:"components.button.primary.background",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-fg",label:"Foreground",type:"token-ref",path:"theme.components.scrollToBottom.foreground",defaultValue:"components.button.primary.foreground",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-border",label:"Border",type:"token-ref",path:"theme.components.scrollToBottom.border",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-size",label:"Size",type:"text",path:"theme.components.scrollToBottom.size",defaultValue:"40px"},{id:"scroll-bottom-radius",label:"Border Radius",type:"select",path:"theme.components.scrollToBottom.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"},{value:"palette.radius.full",label:"Full"}]},{id:"scroll-bottom-shadow",label:"Shadow",type:"select",path:"theme.components.scrollToBottom.shadow",defaultValue:"palette.shadows.sm",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]},{id:"scroll-bottom-padding",label:"Padding",type:"text",path:"theme.components.scrollToBottom.padding",defaultValue:"0.5rem 0.875rem"},{id:"scroll-bottom-gap",label:"Gap",type:"text",path:"theme.components.scrollToBottom.gap",defaultValue:"0.5rem"},{id:"scroll-bottom-font-size",label:"Font Size",type:"text",path:"theme.components.scrollToBottom.fontSize",defaultValue:"0.875rem"},{id:"scroll-bottom-icon-size",label:"Icon Size",type:"text",path:"theme.components.scrollToBottom.iconSize",defaultValue:"14px"}]},lu=[Ng,_g,Vg,$g,Ug],cu=[zg,qg,jg,Kg,Gg],du=[...lu,...cu],el=1024*1024,Yg=["What can you help me with?","Tell me about your features","How does this work?"],Es={images:["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],"images-pdf":["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf"],"images-text-pdf":["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf","text/plain","text/markdown","text/csv","application/json"],all:["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"]};function Xg(e){return Number(e)*el}function Qg(e){let t=Number(e);return Number.isFinite(t)?t>1024?String(Math.round(t/el)):String(t):"10"}function Jg(e){var t;return(t=Es[String(e)])!=null?t:Es.images}function Zg(e){let t=Array.isArray(e)?e:Es.images,n=[...new Set(t)].sort();for(let[o,r]of Object.entries(Es)){let s=[...r].sort();if(n.length===s.length&&n.every((a,i)=>a===s[i]))return o}return n.some(o=>o.startsWith("application/vnd")||o==="application/msword")?"all":n.some(o=>o==="text/plain"||o==="text/markdown"||o==="text/csv")?"images-text-pdf":n.includes("application/pdf")?"images-pdf":"images"}var ef={id:"copy",title:"Content & Copy",collapsed:!1,fields:[{id:"copy-show-welcome-card",label:"Show Welcome Card",type:"toggle",path:"copy.showWelcomeCard",defaultValue:!0},{id:"copy-welcome-title",label:"Welcome Title",type:"text",path:"copy.welcomeTitle",defaultValue:"Hello \u{1F44B}"},{id:"copy-welcome-subtitle",label:"Welcome Subtitle",type:"text",path:"copy.welcomeSubtitle",defaultValue:"Ask anything about your account or products."},{id:"copy-placeholder",label:"Input Placeholder",type:"text",path:"copy.inputPlaceholder",defaultValue:"Type your message\u2026"},{id:"copy-send-label",label:"Send Button Label",type:"text",path:"copy.sendButtonLabel",defaultValue:"Send"}]},tf={id:"suggestions",title:"Suggestion Chips",description:"Configure chip content and styling.",collapsed:!0,fields:[{id:"suggestions-list",label:"Suggestions",description:"Add, edit, and remove chips directly.",type:"chip-list",path:"suggestionChips",defaultValue:Yg}]},nf={id:"general-layout",title:"Layout Basics",collapsed:!0,fields:[{id:"layout-show-header",label:"Show Header",type:"toggle",path:"layout.showHeader",defaultValue:!0},{id:"layout-show-footer",label:"Show Footer",type:"toggle",path:"layout.showFooter",defaultValue:!0},{id:"layout-content-max-width",label:"Content Max Width",description:"Max width for messages + composer",type:"text",path:"layout.contentMaxWidth",defaultValue:""}]},of={id:"header-layout",title:"Header",collapsed:!0,fields:[{id:"layout-header",label:"Header Layout",type:"select",path:"layout.header.layout",defaultValue:"default",options:[{value:"default",label:"Default"},{value:"minimal",label:"Minimal"}]},{id:"layout-show-icon",label:"Show Header Icon",type:"toggle",path:"layout.header.showIcon",defaultValue:!0},{id:"layout-show-title",label:"Show Header Title",type:"toggle",path:"layout.header.showTitle",defaultValue:!0},{id:"layout-show-subtitle",label:"Show Header Subtitle",type:"toggle",path:"layout.header.showSubtitle",defaultValue:!0},{id:"layout-show-close",label:"Show Close Button",type:"toggle",path:"layout.header.showCloseButton",defaultValue:!0},{id:"layout-show-clear",label:"Show Clear Chat",type:"toggle",path:"layout.header.showClearChat",defaultValue:!0}]},rf={id:"messages-layout",title:"Messages",collapsed:!0,fields:[{id:"layout-messages",label:"Messages Layout",type:"select",path:"layout.messages.layout",defaultValue:"bubble",options:[{value:"bubble",label:"Bubble"},{value:"flat",label:"Flat"},{value:"minimal",label:"Minimal"}]},{id:"layout-group",label:"Group Consecutive",type:"toggle",path:"layout.messages.groupConsecutive",defaultValue:!1},{id:"layout-avatar-show",label:"Show Avatars",type:"toggle",path:"layout.messages.avatar.show",defaultValue:!1},{id:"layout-avatar-pos",label:"Avatar Position",type:"select",path:"layout.messages.avatar.position",defaultValue:"left",options:[{value:"left",label:"Left"},{value:"right",label:"Right"}]},{id:"layout-avatar-user",label:"User Avatar URL",type:"text",path:"layout.messages.avatar.userAvatar",defaultValue:""},{id:"layout-avatar-assistant",label:"Assistant Avatar URL",type:"text",path:"layout.messages.avatar.assistantAvatar",defaultValue:""},{id:"layout-timestamp-show",label:"Show Timestamps",type:"toggle",path:"layout.messages.timestamp.show",defaultValue:!1},{id:"layout-timestamp-pos",label:"Timestamp Position",type:"select",path:"layout.messages.timestamp.position",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"below",label:"Below"}]}]},sf={id:"message-actions",title:"Message Actions",collapsed:!0,fields:[{id:"msg-actions-enabled",label:"Enabled",type:"toggle",path:"messageActions.enabled",defaultValue:!0},{id:"msg-actions-copy",label:"Show Copy",type:"toggle",path:"messageActions.showCopy",defaultValue:!0},{id:"msg-actions-upvote",label:"Show Upvote",type:"toggle",path:"messageActions.showUpvote",defaultValue:!0},{id:"msg-actions-downvote",label:"Show Downvote",type:"toggle",path:"messageActions.showDownvote",defaultValue:!0},{id:"msg-actions-visibility",label:"Visibility",type:"select",path:"messageActions.visibility",defaultValue:"hover",options:[{value:"hover",label:"On Hover"},{value:"always",label:"Always Visible"}]},{id:"msg-actions-align",label:"Alignment",type:"select",path:"messageActions.align",defaultValue:"right",options:[{value:"left",label:"Left"},{value:"right",label:"Right"}]},{id:"msg-actions-layout",label:"Layout",type:"select",path:"messageActions.layout",defaultValue:"pill-inside",options:[{value:"pill-inside",label:"Pill"},{value:"row-inside",label:"Row"}]}]},af={id:"launcher-basics",title:"Launcher",collapsed:!0,fields:[{id:"launch-enabled",label:"Enabled",type:"toggle",path:"launcher.enabled",defaultValue:!0},{id:"launch-mount-mode",label:"Mount Mode",type:"select",path:"launcher.mountMode",defaultValue:"floating",options:[{value:"floating",label:"Floating"},{value:"docked",label:"Docked"}]},{id:"launch-position",label:"Position",type:"select",path:"launcher.position",defaultValue:"bottom-right",options:[{value:"bottom-right",label:"Bottom Right"},{value:"bottom-left",label:"Bottom Left"},{value:"top-right",label:"Top Right"},{value:"top-left",label:"Top Left"}]},{id:"launch-width",label:"Width",type:"text",path:"launcher.width",defaultValue:io},{id:"launch-auto-expand",label:"Auto Expand",type:"toggle",path:"launcher.autoExpand",defaultValue:!1},{id:"launch-title",label:"Title",type:"text",path:"launcher.title",defaultValue:"Chat Assistant"},{id:"launch-subtitle",label:"Subtitle",type:"text",path:"launcher.subtitle",defaultValue:"Here to help you get answers fast"}]},lf={id:"launcher-advanced",title:"Launcher Advanced",collapsed:!0,fields:[{id:"launch-dock-side",label:"Dock Side",type:"select",path:"launcher.dock.side",defaultValue:"right",options:[{value:"right",label:"Right"},{value:"left",label:"Left"}]},{id:"launch-dock-width",label:"Dock Width",type:"text",path:"launcher.dock.width",defaultValue:"420px"},{id:"launch-dock-animate",label:"Dock Animate",type:"toggle",path:"launcher.dock.animate",defaultValue:!0},{id:"launch-dock-reveal",label:"Dock Reveal",type:"select",path:"launcher.dock.reveal",defaultValue:"resize",options:[{value:"resize",label:"Resize"},{value:"overlay",label:"Overlay"},{value:"push",label:"Push"},{value:"emerge",label:"Emerge"}]},{id:"launch-text-hidden",label:"Hide Text",type:"toggle",path:"launcher.textHidden",defaultValue:!1},{id:"launch-icon-text",label:"Agent Icon Text",type:"text",path:"launcher.agentIconText",defaultValue:"\u{1F4AC}"},{id:"launch-icon-name",label:"Agent Icon Name (Lucide)",type:"text",path:"launcher.agentIconName",defaultValue:"bot"},{id:"launch-icon-hidden",label:"Hide Agent Icon",type:"toggle",path:"launcher.agentIconHidden",defaultValue:!1},{id:"launch-icon-size",label:"Agent Icon Size",type:"slider",path:"launcher.agentIconSize",defaultValue:"40px",slider:{min:16,max:72,step:2}},{id:"launch-icon-url",label:"Icon Image URL",description:"Custom image URL (overrides emoji/lucide)",type:"text",path:"launcher.iconUrl",defaultValue:""},{id:"launch-header-icon-name",label:"Header Icon Name (Lucide)",type:"text",path:"launcher.headerIconName",defaultValue:"bot"},{id:"launch-header-icon-size",label:"Header Icon Size",type:"slider",path:"launcher.headerIconSize",defaultValue:"48px",slider:{min:24,max:80,step:2}},{id:"launch-header-icon-hidden",label:"Hide Header Icon",type:"toggle",path:"launcher.headerIconHidden",defaultValue:!1},{id:"launch-full-height",label:"Full Height",type:"toggle",path:"launcher.fullHeight",defaultValue:!1},{id:"launch-sidebar",label:"Sidebar Mode",type:"toggle",path:"launcher.sidebarMode",defaultValue:!1},{id:"launch-sidebar-width",label:"Sidebar Width",type:"text",path:"launcher.sidebarWidth",defaultValue:"420px"},{id:"launch-mobile-fullscreen",label:"Mobile Fullscreen",description:"Fullscreen on mobile devices",type:"toggle",path:"launcher.mobileFullscreen",defaultValue:!0},{id:"launch-mobile-breakpoint",label:"Mobile Breakpoint (px)",type:"text",path:"launcher.mobileBreakpoint",defaultValue:640,formatValue:e=>String(e!=null?e:640),parseValue:e=>Number(e)},{id:"launch-height-offset",label:"Height Offset (px)",type:"text",path:"launcher.heightOffset",defaultValue:0,formatValue:e=>String(e!=null?e:0),parseValue:e=>Number(e)},{id:"launch-collapsed-max-width",label:"Collapsed Max Width",description:"Max width of launcher pill when closed",type:"text",path:"launcher.collapsedMaxWidth",defaultValue:""},{id:"launch-cta-text",label:"CTA Icon Text",type:"text",path:"launcher.callToActionIconText",defaultValue:"\u2197"},{id:"launch-cta-name",label:"CTA Icon Name",type:"text",path:"launcher.callToActionIconName",defaultValue:""},{id:"launch-cta-hidden",label:"Hide CTA Icon",type:"toggle",path:"launcher.callToActionIconHidden",defaultValue:!1},{id:"launch-cta-size",label:"CTA Icon Size",type:"slider",path:"launcher.callToActionIconSize",defaultValue:"32px",slider:{min:16,max:64,step:2}},{id:"launch-cta-padding",label:"CTA Icon Padding",type:"slider",path:"launcher.callToActionIconPadding",defaultValue:"5px",slider:{min:0,max:24,step:1}},{id:"launch-cta-bg",label:"CTA Icon Background",type:"color",path:"launcher.callToActionIconBackgroundColor",defaultValue:""}]},cf={id:"send-button",title:"Send Button",collapsed:!0,fields:[{id:"send-use-icon",label:"Use Icon",type:"toggle",path:"sendButton.useIcon",defaultValue:!1},{id:"send-icon-text",label:"Icon Text",type:"text",path:"sendButton.iconText",defaultValue:"\u2191"},{id:"send-icon-name",label:"Icon Name (Lucide)",type:"text",path:"sendButton.iconName",defaultValue:""},{id:"send-size",label:"Size",type:"slider",path:"sendButton.size",defaultValue:"40px",slider:{min:24,max:64,step:2}},{id:"send-border-width",label:"Border Width",type:"slider",path:"sendButton.borderWidth",defaultValue:"0px",slider:{min:0,max:10,step:1}},{id:"send-padding-x",label:"Padding X",type:"slider",path:"sendButton.paddingX",defaultValue:"10px",slider:{min:0,max:32,step:1}},{id:"send-padding-y",label:"Padding Y",type:"slider",path:"sendButton.paddingY",defaultValue:"6px",slider:{min:0,max:32,step:1}},{id:"send-show-tooltip",label:"Show Tooltip",type:"toggle",path:"sendButton.showTooltip",defaultValue:!1},{id:"send-tooltip-text",label:"Tooltip Text",type:"text",path:"sendButton.tooltipText",defaultValue:"Send message"}]},df={id:"close-button",title:"Close Button",collapsed:!0,fields:[{id:"close-size",label:"Size",type:"slider",path:"launcher.closeButtonSize",defaultValue:"32px",slider:{min:16,max:64,step:1}},{id:"close-placement",label:"Placement",type:"select",path:"launcher.closeButtonPlacement",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"top-right",label:"Top Right"}]},{id:"close-border-width",label:"Border Width",type:"slider",path:"launcher.closeButtonBorderWidth",defaultValue:"0px",slider:{min:0,max:8,step:1}},{id:"close-border-radius",label:"Border Radius",type:"slider",path:"launcher.closeButtonBorderRadius",defaultValue:"50%",slider:{min:0,max:100,step:1,isRadiusFull:!0}},{id:"close-icon-name",label:"Icon Name",type:"text",path:"launcher.closeButtonIconName",defaultValue:"x"},{id:"close-icon-text",label:"Icon Text",type:"text",path:"launcher.closeButtonIconText",defaultValue:"\xD7"},{id:"close-show-tooltip",label:"Show Tooltip",type:"toggle",path:"launcher.closeButtonShowTooltip",defaultValue:!0},{id:"close-tooltip-text",label:"Tooltip Text",type:"text",path:"launcher.closeButtonTooltipText",defaultValue:"Close chat"}]},pf={id:"clear-chat",title:"Clear Chat Button",collapsed:!0,fields:[{id:"clear-enabled",label:"Enabled",type:"toggle",path:"launcher.clearChat.enabled",defaultValue:!0},{id:"clear-placement",label:"Placement",type:"select",path:"launcher.clearChat.placement",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"top-right",label:"Top Right"}]},{id:"clear-icon-name",label:"Icon Name",type:"text",path:"launcher.clearChat.iconName",defaultValue:"refresh-cw"},{id:"clear-size",label:"Size",type:"slider",path:"launcher.clearChat.size",defaultValue:"32px",slider:{min:16,max:64,step:1}},{id:"clear-show-tooltip",label:"Show Tooltip",type:"toggle",path:"launcher.clearChat.showTooltip",defaultValue:!0},{id:"clear-tooltip-text",label:"Tooltip Text",type:"text",path:"launcher.clearChat.tooltipText",defaultValue:"Clear chat"}]},uf={id:"status-indicator",title:"Status Indicator",collapsed:!0,fields:[{id:"status-visible",label:"Visible",type:"toggle",path:"statusIndicator.visible",defaultValue:!0},{id:"status-align",label:"Alignment",type:"select",path:"statusIndicator.align",defaultValue:"right",options:[{value:"left",label:"Left"},{value:"center",label:"Center"},{value:"right",label:"Right"}]},{id:"status-idle-text",label:"Idle Text",type:"text",path:"statusIndicator.idleText",defaultValue:"Online"},{id:"status-connecting-text",label:"Connecting Text",type:"text",path:"statusIndicator.connectingText",defaultValue:"Connecting\u2026"},{id:"status-connected-text",label:"Connected Text",type:"text",path:"statusIndicator.connectedText",defaultValue:"Streaming\u2026"},{id:"status-error-text",label:"Error Text",type:"text",path:"statusIndicator.errorText",defaultValue:"Offline"}]},mf={id:"features",title:"Features",collapsed:!0,fields:[{id:"feat-voice",label:"Voice Recognition",description:"Enable voice input",type:"toggle",path:"voiceRecognition.enabled",defaultValue:!1},{id:"feat-auto-focus",label:"Auto Focus Input",description:"Focus input after panel opens",type:"toggle",path:"autoFocusInput",defaultValue:!1},{id:"feat-scroll-bottom-enabled",label:"Scroll To Bottom",description:"Show a jump-to-latest affordance when the user scrolls away from new content",type:"toggle",path:"features.scrollToBottom.enabled",defaultValue:!0},{id:"feat-scroll-bottom-icon",label:"Scroll To Bottom Icon",type:"text",path:"features.scrollToBottom.iconName",defaultValue:"arrow-down"},{id:"feat-scroll-bottom-label",label:"Scroll To Bottom Label",description:"Leave empty for icon-only mode",type:"text",path:"features.scrollToBottom.label",defaultValue:""}]},gf={id:"stream-animation",title:"Stream Animation",description:"Control how assistant text appears while streaming.",collapsed:!0,fields:[{id:"stream-anim-type",label:"Animation",description:"Reveal effect applied to each assistant reply as it streams.",type:"select",path:"features.streamAnimation.type",defaultValue:"none",options:[{value:"none",label:"None"},{value:"typewriter",label:"Typewriter"},{value:"word-fade",label:"Word fade"},{value:"letter-rise",label:"Letter rise"},{value:"glyph-cycle",label:"Glyph cycle"},{value:"wipe",label:"Wipe"},{value:"pop-bubble",label:"Pop bubble"}]},{id:"stream-anim-placeholder",label:"Pre-first-token Placeholder",description:"What to show before the first token arrives.",type:"select",path:"features.streamAnimation.placeholder",defaultValue:"none",options:[{value:"none",label:"Typing indicator (default)"},{value:"skeleton",label:"Skeleton shimmer"}]},{id:"stream-anim-buffer",label:"Content Buffering",description:"Trim in-progress units so only complete words/lines reveal.",type:"select",path:"features.streamAnimation.buffer",defaultValue:"none",options:[{value:"none",label:"None \u2014 stream every character"},{value:"word",label:"Word \u2014 hold until whitespace"},{value:"line",label:"Line \u2014 hold until newline"}]},{id:"stream-anim-speed",label:"Per-unit Duration (ms)",description:"Animation length for each character or word.",type:"select",path:"features.streamAnimation.speed",defaultValue:120,options:[{value:"40",label:"40ms \u2014 snappy"},{value:"80",label:"80ms"},{value:"120",label:"120ms (default)"},{value:"200",label:"200ms"},{value:"320",label:"320ms"},{value:"480",label:"480ms \u2014 slow"}],formatValue:e=>String(e!=null?e:120),parseValue:e=>Number(e)},{id:"stream-anim-duration",label:"Container Duration (ms)",description:"Length of container-level effects (pop-bubble, custom plugins).",type:"select",path:"features.streamAnimation.duration",defaultValue:1800,options:[{value:"600",label:"600ms"},{value:"1200",label:"1200ms"},{value:"1800",label:"1800ms (default)"},{value:"2400",label:"2400ms"},{value:"3600",label:"3600ms \u2014 slow"}],formatValue:e=>String(e!=null?e:1800),parseValue:e=>Number(e)}]},ff={id:"attachments-config",title:"Attachments",collapsed:!0,fields:[{id:"attach-enabled",label:"Enabled",type:"toggle",path:"attachments.enabled",defaultValue:!1},{id:"attach-max-files",label:"Max Files",type:"select",path:"attachments.maxFiles",defaultValue:4,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"4",label:"4"},{value:"6",label:"6"},{value:"8",label:"8"},{value:"10",label:"10"}],formatValue:e=>String(e!=null?e:4),parseValue:e=>Number(e)},{id:"attach-max-size",label:"Max File Size (MB)",type:"select",path:"attachments.maxFileSize",defaultValue:10*el,options:[{value:"1",label:"1 MB"},{value:"5",label:"5 MB"},{value:"10",label:"10 MB"},{value:"25",label:"25 MB"},{value:"50",label:"50 MB"}],formatValue:Qg,parseValue:Xg},{id:"attach-types",label:"Allowed File Types",type:"select",path:"attachments.allowedTypes",defaultValue:Es.images,options:[{value:"images",label:"Images only"},{value:"images-pdf",label:"Images + PDF"},{value:"images-text-pdf",label:"Images + text + PDF"},{value:"all",label:"All supported types"}],formatValue:Zg,parseValue:Jg}]},hf={id:"artifacts-config",title:"Artifacts",collapsed:!0,fields:[{id:"art-enabled",label:"Enabled",description:"Show artifact sidebar for documents and components",type:"toggle",path:"features.artifacts.enabled",defaultValue:!1},{id:"art-appearance",label:"Pane Appearance",type:"select",path:"features.artifacts.layout.paneAppearance",defaultValue:"panel",options:[{value:"panel",label:"Panel (bordered)"},{value:"seamless",label:"Seamless"}]}]},bf={id:"artifacts-customization",title:"Artifact Customization",collapsed:!0,fields:[{id:"art-toolbar",label:"Toolbar Preset",type:"select",path:"features.artifacts.layout.toolbarPreset",defaultValue:"default",options:[{value:"default",label:"Default"},{value:"document",label:"Document"}]},{id:"art-pane-width",label:"Pane Width",description:"CSS width (e.g. 40%, 28rem)",type:"text",path:"features.artifacts.layout.paneWidth",defaultValue:"40%"},{id:"art-pane-max-width",label:"Pane Max Width",type:"text",path:"features.artifacts.layout.paneMaxWidth",defaultValue:"28rem"},{id:"art-split-gap",label:"Split Gap",type:"text",path:"features.artifacts.layout.splitGap",defaultValue:"0.5rem"},{id:"art-pane-bg",label:"Pane Background",type:"color",path:"features.artifacts.layout.paneBackground",defaultValue:""},{id:"art-unified",label:"Unified Split Chrome",description:"Wrap chat and artifact in a single container",type:"toggle",path:"features.artifacts.layout.unifiedSplitChrome",defaultValue:!1},{id:"art-resizable",label:"Resizable",description:"Allow dragging the pane divider",type:"toggle",path:"features.artifacts.layout.resizable",defaultValue:!1},{id:"art-expand-panel",label:"Expand Panel When Open",description:"Widen the launcher panel to fit artifacts",type:"toggle",path:"features.artifacts.layout.expandLauncherPanelWhenOpen",defaultValue:!0}]},yf={id:"api-integration",title:"API & Integration",description:"Runtime and integration options.",collapsed:!0,fields:[{id:"dev-api-url",label:"API URL",type:"text",path:"apiUrl",defaultValue:""},{id:"dev-flow",label:"Flow ID",type:"text",path:"flowId",defaultValue:""},{id:"dev-parser",label:"Stream Parser",type:"select",path:"parserType",defaultValue:"plain",options:[{value:"plain",label:"Plain Text"},{value:"json",label:"JSON"},{value:"regex-json",label:"Regex JSON"},{value:"xml",label:"XML"}]}]},vf={id:"debug-inspection",title:"Debug & Inspection",collapsed:!0,fields:[{id:"dev-reasoning",label:"Show Reasoning",description:"Display AI reasoning steps",type:"toggle",path:"features.showReasoning",defaultValue:!1},{id:"dev-tool-calls",label:"Show Tool Calls",description:"Display tool call details",type:"toggle",path:"features.showToolCalls",defaultValue:!1},{id:"dev-tool-collapsed-mode",label:"Tool Call Summary",description:"Choose what collapsed tool rows show by default",type:"select",path:"features.toolCallDisplay.collapsedMode",defaultValue:"tool-call",options:[{value:"tool-call",label:"Tool Call"},{value:"tool-name",label:"Tool Name"},{value:"tool-preview",label:"Tool Preview"}]},{id:"dev-tool-active-preview",label:"Tool Preview While Active",description:"Show a lightweight preview in collapsed active tool rows",type:"toggle",path:"features.toolCallDisplay.activePreview",defaultValue:!1},{id:"dev-tool-preview-lines",label:"Tool Preview Lines",type:"select",path:"features.toolCallDisplay.previewMaxLines",defaultValue:3,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"3",label:"3"},{value:"4",label:"4"},{value:"5",label:"5"}],formatValue:e=>String(e!=null?e:3),parseValue:e=>Number(e)},{id:"dev-tool-active-min-height",label:"Tool Active Min Height",description:"CSS min-height for collapsed active tool rows (e.g. 5rem)",type:"text",path:"features.toolCallDisplay.activeMinHeight",defaultValue:""},{id:"dev-tool-expandable",label:"Tool Calls Expandable",description:"Allow expanding tool call rows to see full details",type:"toggle",path:"features.toolCallDisplay.expandable",defaultValue:!0},{id:"dev-tool-grouped",label:"Group Sequential Tool Calls",description:"Render consecutive tool rows inside a grouped container",type:"toggle",path:"features.toolCallDisplay.grouped",defaultValue:!1},{id:"dev-reasoning-expandable",label:"Reasoning Expandable",description:"Allow expanding reasoning rows to see full details",type:"toggle",path:"features.reasoningDisplay.expandable",defaultValue:!0},{id:"dev-reasoning-active-preview",label:"Reasoning Preview While Active",description:"Show a lightweight preview in collapsed active reasoning rows",type:"toggle",path:"features.reasoningDisplay.activePreview",defaultValue:!1},{id:"dev-reasoning-preview-lines",label:"Reasoning Preview Lines",type:"select",path:"features.reasoningDisplay.previewMaxLines",defaultValue:3,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"3",label:"3"},{value:"4",label:"4"},{value:"5",label:"5"}],formatValue:e=>String(e!=null?e:3),parseValue:e=>Number(e)},{id:"dev-reasoning-active-min-height",label:"Reasoning Active Min Height",description:"CSS min-height for collapsed active reasoning rows (e.g. 5rem)",type:"text",path:"features.reasoningDisplay.activeMinHeight",defaultValue:""},{id:"dev-debug",label:"Debug Mode",description:"Show debug information",type:"toggle",path:"debug",defaultValue:!1}]},xf={id:"markdown",title:"Markdown Options",collapsed:!0,fields:[{id:"md-gfm",label:"GitHub Flavored Markdown",type:"toggle",path:"markdown.options.gfm",defaultValue:!0},{id:"md-breaks",label:"Line Breaks",type:"toggle",path:"markdown.options.breaks",defaultValue:!0},{id:"md-header-ids",label:"Header IDs",type:"toggle",path:"markdown.options.headerIds",defaultValue:!1},{id:"md-pedantic",label:"Pedantic Mode",type:"toggle",path:"markdown.options.pedantic",defaultValue:!1},{id:"md-silent",label:"Silent",type:"toggle",path:"markdown.options.silent",defaultValue:!1},{id:"md-disable-styles",label:"Disable Default Styles",type:"toggle",path:"markdown.disableDefaultStyles",defaultValue:!1}]},Na=[{label:"Content",sections:[ef,tf]},{label:"Layout",sections:[nf,of,rf,sf]},{label:"Widget",sections:[af,lf,cf,df,pf,uf]},{label:"Features",sections:[mf,gf,ff,hf,bf]},{label:"Developer",collapsedByDefault:!0,sections:[yf,vf,xf]}],pu=Na.flatMap(e=>e.sections),uu={id:"theme-mode-v2",title:"Theme",description:"Choose how the interface adapts across light and dark mode.",collapsed:!1,fields:[{id:"color-mode",label:"Color Mode",type:"select",path:"colorScheme",defaultValue:"auto",options:[{value:"auto",label:"Auto"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}]}]},mu={id:"brand-palette-v2",title:"Brand Palette",description:"Set your brand, accent, and neutral colors. These are used to generate the interface theme.",collapsed:!1,fields:[{id:"bp-primary",label:"Primary",description:"Main brand color",type:"color",path:"theme.palette.colors.primary.500",defaultValue:"#171717"},{id:"bp-secondary",label:"Secondary",description:"Supporting brand color",type:"color",path:"theme.palette.colors.secondary.500",defaultValue:"#8b5cf6"},{id:"bp-accent",label:"Accent",description:"Highlight and decorative color",type:"color",path:"theme.palette.colors.accent.500",defaultValue:"#06b6d4"},{id:"bp-neutral",label:"Neutral",description:"Backgrounds, text, and borders",type:"color",path:"theme.palette.colors.gray.500",defaultValue:"#6b7280"}]},gu={id:"status-palette",title:"Status Palette",description:"Colors for system feedback states.",collapsed:!0,fields:[{id:"sp-success",label:"Success",type:"color",path:"theme.palette.colors.success.500",defaultValue:"#22c55e"},{id:"sp-warning",label:"Warning",type:"color",path:"theme.palette.colors.warning.500",defaultValue:"#eab308"},{id:"sp-error",label:"Error",type:"color",path:"theme.palette.colors.error.500",defaultValue:"#ef4444"},{id:"sp-notice",label:"Notice",description:"Info and notice states",type:"color",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500"}]},fu={id:"interface-roles",title:"Interface Roles",description:"Control where brand and neutral colors appear across the interface.",collapsed:!1,fields:[{id:"role-surfaces",label:"Background Surfaces",type:"role-assignment",path:"theme.semantic.colors.background",roleAssignment:La},{id:"role-header",label:"Header",type:"role-assignment",path:"theme.components.header.background",roleAssignment:Ia},{id:"role-user-messages",label:"User Messages",type:"role-assignment",path:"theme.components.message.user.background",roleAssignment:Ra},{id:"role-assistant-messages",label:"Assistant Messages",type:"role-assignment",path:"theme.components.message.assistant.background",roleAssignment:Pa},{id:"role-primary-actions",label:"Primary Actions",type:"role-assignment",path:"theme.components.button.primary.background",roleAssignment:Wa},{id:"role-scroll-to-bottom",label:"Scroll To Bottom",type:"role-assignment",path:"theme.components.scrollToBottom.background",roleAssignment:Ba},{id:"role-input",label:"Input Field",type:"role-assignment",path:"theme.components.input.background",roleAssignment:Ha},{id:"role-links-focus",label:"Links & Focus",type:"role-assignment",path:"theme.semantic.colors.accent",roleAssignment:Da},{id:"role-borders",label:"Borders & Dividers",type:"role-assignment",path:"theme.semantic.colors.border",roleAssignment:Fa}]},hu={id:"status-colors",title:"Status Colors",description:"Used for system states like success, warning, notice, and error.",collapsed:!0,fields:[{id:"sc-notice",label:"Notice",type:"token-ref",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sc-success",label:"Success",type:"token-ref",path:"theme.semantic.colors.feedback.success",defaultValue:"palette.colors.success.500",tokenRef:{tokenType:"color"}},{id:"sc-warning",label:"Warning",type:"token-ref",path:"theme.semantic.colors.feedback.warning",defaultValue:"palette.colors.warning.500",tokenRef:{tokenType:"color"}},{id:"sc-error",label:"Error",type:"token-ref",path:"theme.semantic.colors.feedback.error",defaultValue:"palette.colors.error.500",tokenRef:{tokenType:"color"}}]},bu={id:"advanced-tokens",title:"Advanced Tokens",description:"Override individual semantic and component values when you need precise control.",collapsed:!0,fields:[]},wf=[uu,mu,gu,fu,hu,bu],tl=[{id:"style",label:"Style",sections:zr},{id:"design-system",label:"Design System",sections:du},{id:"configure",label:"Configure",sections:pu}];function yu(e,t){return e.startsWith("theme.")?e.replace(/^theme\./,`${t}.`):e}function Cf(e,t,n){return{...e,id:`${n}-${e.id}`,path:yu(e.path,t)}}function Sf(e,t){let n=e.find(o=>o.id===t);if(!n)throw new Error(`Section "${t}" not found in definitions`);return n}function Af(e,t,n,o=e.collapsed){var a;let r=n==="light"?"Light":"Dark",s=n==="light"?"Applies when the widget is in light mode.":"Applies when the widget is in dark mode.";return{...e,id:`${n}-${e.id}`,title:`${r} ${e.title}`,description:e.description?`${s} ${e.description}`:s,collapsed:o,fields:e.fields.map(i=>Cf(i,t,n)),presets:(a=e.presets)==null?void 0:a.map(i=>({...i,id:`${n}-${i.id}`,values:Object.fromEntries(Object.entries(i.values).map(([d,l])=>[yu(d,t),l]))}))}}var vu=[{id:"default-light",name:"Default Light",description:"Clean monochrome light theme",theme:{components:{artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}}},preview:{primary:"#171717",surface:"#ffffff",accent:"#0f0f0f"},tags:["light"]},{id:"default-dark",name:"Default Dark",description:"Monochrome dark theme",theme:{palette:{colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},semantic:{colors:{primary:"palette.colors.primary.400",secondary:"palette.colors.gray.400",accent:"palette.colors.primary.500",surface:"palette.colors.gray.800",background:"palette.colors.gray.900",container:"palette.colors.gray.800",text:"palette.colors.gray.100",textMuted:"palette.colors.gray.400",textInverse:"palette.colors.gray.900",border:"palette.colors.gray.700",divider:"palette.colors.gray.700",interactive:{default:"palette.colors.primary.400",hover:"palette.colors.primary.300",focus:"palette.colors.primary.500",active:"palette.colors.primary.600",disabled:"palette.colors.gray.600"},feedback:{success:"palette.colors.success.400",warning:"palette.colors.warning.400",error:"palette.colors.error.400",info:"palette.colors.primary.400"}}}},preview:{primary:"#171717",surface:"#1f2937",accent:"#0f0f0f"},tags:["dark"]},{id:"high-contrast",name:"High Contrast",description:"Maximum contrast for accessibility",theme:{semantic:{colors:{primary:"palette.colors.primary.700",secondary:"palette.colors.gray.700",accent:"palette.colors.primary.800",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.200",text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.400",divider:"palette.colors.gray.400",interactive:{default:"palette.colors.primary.700",hover:"palette.colors.primary.800",focus:"palette.colors.primary.900",active:"palette.colors.primary.950",disabled:"palette.colors.gray.400"},feedback:{success:"palette.colors.success.700",warning:"palette.colors.warning.700",error:"palette.colors.error.700",info:"palette.colors.primary.700"}}}},preview:{primary:"#0a0a0a",surface:"#f9fafb",accent:"#050505"},tags:["light","high-contrast","accessibility"]}],Ms=[...vu];function nl(e){return Ms.find(t=>t.id===e)}import{Marked as Tf}from"marked";var kf=e=>{if(e)return e},ol=e=>{var r,s;let t=e==null?void 0:e.markedOptions,n=new Tf({gfm:(r=t==null?void 0:t.gfm)!=null?r:!0,breaks:(s=t==null?void 0:t.breaks)!=null?s:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),o=kf(e==null?void 0:e.renderer);return o&&n.use({renderer:o}),a=>n.parse(a)},_a=e=>e?ol({markedOptions:e.options,renderer:e.renderer}):ol(),Jx=ol();var Ls=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");import Ef from"dompurify";var Mf={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},Lf=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,If=()=>{let e=Ef(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(t,n)=>{if(n.attrName==="src"||n.attrName==="href"){let o=n.attrValue;o.toLowerCase().startsWith("data:")&&!Lf.test(o)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,Mf)},Va=e=>e===!1?null:typeof e=="function"?e:If();var rl="webmcp:",$a={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function wu(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var o,r;return[n.name,(o=n.description)!=null?o:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(r=n.origin)!=null?r:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${Rf(t.join(""))}`}function xu(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function Rf(e){let t=xu(e,0).toString(36),n=xu(e,2654435761).toString(36);return`${t}.${n}`}var Ua=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return $a.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",r),[]}let o=typeof location!="undefined"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=Bf(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return vo("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let u=typeof document!="undefined"&&!!document.modelContext;return vo(u?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=Pf(t),a;try{a=await r.getTools()}catch(u){let w=u instanceof Error?u.message:String(u);return vo(`Failed to read WebMCP registry: ${w}`)}let i=a.find(u=>u.name===s);if(!i)return vo(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return vo(`WebMCP tool not allowed by client allowlist: ${s}`);if(o!=null&&o.aborted)return vo("Aborted by cancel()");let d={toolName:s,args:n,description:i.description,reason:"gate"};if(!await this.requestConfirm(d))return vo("User declined the tool call.");if(o!=null&&o.aborted)return vo("Aborted by cancel()");let l=new AbortController,p=!1,m=setTimeout(()=>{p=!0,l.abort()},this.timeoutMs),f=()=>l.abort();o&&(o.aborted?l.abort():o.addEventListener("abort",f,{once:!0}));try{let u=await r.executeTool(i,Of(n),{signal:l.signal});return Hf(u)}catch(u){if(p)return vo(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return vo("Aborted by cancel()");let w=u instanceof Error?u.message:String(u);return vo(w)}finally{clearTimeout(m),o&&o.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){$a.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,$a.warn("document.modelContext is present but does not expose getTools()/executeTool() \u2014 WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var o;let n=(o=this.confirmHandler)!=null?o:Df;try{return await n(t)}catch(r){return $a.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,r),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>Wf(t,o))}},Pf=e=>e.startsWith(rl)?e.slice(rl.length):e,sl=e=>e.startsWith(rl),Wf=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Bf=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Hf=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:Nf(t)}]}},vo=e=>({isError:!0,content:[{type:"text",text:e}]}),Df=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Ff(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
1
+ var nu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ps(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];nu(s)&&nu(r)?n[o]=Ps(s,r):n[o]=r}return n}var go="min(440px, calc(100vw - 24px))",La="440px",It={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:go,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function ou(e,t){if(!(!e&&!t))return e?t?Ps(e,t):e:t}function ru(e){var t,n,o,r,s,a,i,d,l,m,p,f,u,C,v,E,L,I,P,H,W;return e?{...It,...e,theme:ou(It.theme,e.theme),darkTheme:ou(It.darkTheme,e.darkTheme),launcher:{...It.launcher,...e.launcher,dock:{...(t=It.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(o=It.launcher)==null?void 0:o.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...It.copy,...e.copy},sendButton:{...It.sendButton,...e.sendButton},statusIndicator:{...It.statusIndicator,...e.statusIndicator},voiceRecognition:{...It.voiceRecognition,...e.voiceRecognition},features:(()=>{var be,Fe,xe,j,de,K,ye,le;let x=(be=It.features)==null?void 0:be.artifacts,w=(Fe=e.features)==null?void 0:Fe.artifacts,k=(xe=It.features)==null?void 0:xe.scrollToBottom,S=(j=e.features)==null?void 0:j.scrollToBottom,A=(de=It.features)==null?void 0:de.streamAnimation,N=(K=e.features)==null?void 0:K.streamAnimation,$=(ye=It.features)==null?void 0:ye.askUserQuestion,G=(le=e.features)==null?void 0:le.askUserQuestion,fe=x===void 0&&w===void 0?void 0:{...x,...w,layout:{...x==null?void 0:x.layout,...w==null?void 0:w.layout}},ge=k===void 0&&S===void 0?void 0:{...k,...S},se=A===void 0&&N===void 0?void 0:{...A,...N},ke=$===void 0&&G===void 0?void 0:{...$,...G,styles:{...$==null?void 0:$.styles,...G==null?void 0:G.styles}};return{...It.features,...e.features,...ge!==void 0?{scrollToBottom:ge}:{},...fe!==void 0?{artifacts:fe}:{},...se!==void 0?{streamAnimation:se}:{},...ke!==void 0?{askUserQuestion:ke}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:It.suggestionChips,suggestionChipsConfig:{...It.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...It.layout,...e.layout,header:{...(a=It.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=It.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(p=(m=It.layout)==null?void 0:m.messages)==null?void 0:p.avatar,...(u=(f=e.layout)==null?void 0:f.messages)==null?void 0:u.avatar},timestamp:{...(v=(C=It.layout)==null?void 0:C.messages)==null?void 0:v.timestamp,...(L=(E=e.layout)==null?void 0:E.messages)==null?void 0:L.timestamp}},slots:{...(I=It.layout)==null?void 0:I.slots,...(P=e.layout)==null?void 0:P.slots}},markdown:{...It.markdown,...e.markdown,options:{...(H=It.markdown)==null?void 0:H.options,...(W=e.markdown)==null?void 0:W.options}},messageActions:{...It.messageActions,...e.messageActions}}:It}var Sg={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},Ag={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},Tg={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:go,maxWidth:La,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function jr(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?jr(e,o):o}function su(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let i=`${r}.${s}`;if(typeof a=="string"){let d=jr(e,a);d!==void 0&&(t[i]={path:i,value:d,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function kg(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function au(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=au(s,r):n[o]=r}return n}function Eg(e,t){return t?au(e,t):e}function sn(e,t={}){var r,s,a,i,d,l,m,p,f,u,C,v,E;let n={palette:Sg,semantic:Ag,components:Tg},o={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(m=e==null?void 0:e.semantic)==null?void 0:m.colors,interactive:{...n.semantic.colors.interactive,...(f=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(C=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:C.feedback}},spacing:{...n.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...n.semantic.typography,...(E=e==null?void 0:e.semantic)==null?void 0:E.typography}},components:Eg(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let L=kg(o);if(!L.valid)throw new Error(`Theme validation failed: ${L.errors.map(I=>I.message).join(", ")}`)}if(t.plugins)for(let L of t.plugins)o=L.transform(o);return o}function iu(e){var v,E,L,I,P,H,W,x,w,k,S,A,N,$,G,fe,ge,se,ke,be,Fe,xe,j,de,K,ye,le,te,Ce,Ue,ee,oe,ae,rt,Ae,pe,$e,We,ue,X,Ne,Bt,he,ce,Rn,$t,mn,Dn,eo,ze,_,Me,Be,He,_e,ut,st,Rt,qt,q,Ut,Je,_t,re,we,Tt,jt,en,Sn,Pt,Et,xt,Ct,Kt,nt,Fn,to,An,On,ht,Eo,Nn,dr,Pn,Hr,qo,Bo,St,_n,Vn,Tn,Mt,no,oo,$n,jo,Ho,Ko,Un,Dt,kn,ro,Go,Do,Yo,Mo,zn,bo,yt,Yt,Xt,qn,Xo,so,yo,jn,V,ao;let t=su(e),n={};for(let[ve,Kn]of Object.entries(t)){let io=ve.replace(/\./g,"-");n[`--persona-${io}`]=Kn.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(E=n["--persona-semantic-colors-secondary"])!=null?E:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(L=n["--persona-semantic-colors-accent"])!=null?L:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(I=n["--persona-semantic-colors-surface"])!=null?I:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(P=n["--persona-semantic-colors-background"])!=null?P:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(H=n["--persona-semantic-colors-container"])!=null?H:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(W=n["--persona-semantic-colors-text"])!=null?W:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(x=n["--persona-semantic-colors-text-muted"])!=null?x:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(w=n["--persona-semantic-colors-text-inverse"])!=null?w:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(k=n["--persona-semantic-colors-border"])!=null?k:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(S=n["--persona-semantic-colors-divider"])!=null?S:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(A=n["--persona-components-voice-recording-indicator"])!=null?A:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(N=n["--persona-components-voice-recording-background"])!=null?N:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=($=n["--persona-components-voice-processing-icon"])!=null?$:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(G=n["--persona-components-voice-speaking-icon"])!=null?G:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(fe=n["--persona-components-approval-requested-background"])!=null?fe:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(ge=n["--persona-components-approval-requested-border"])!=null?ge:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(se=n["--persona-components-approval-requested-text"])!=null?se:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(ke=n["--persona-components-approval-requested-shadow"])!=null?ke:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-approval-approve-bg"]=(be=n["--persona-components-approval-approve-background"])!=null?be:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(Fe=n["--persona-components-approval-deny-background"])!=null?Fe:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(xe=n["--persona-components-attachment-image-background"])!=null?xe:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(j=n["--persona-components-attachment-image-border"])!=null?j:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(de=n["--persona-semantic-typography-fontFamily"])!=null?de:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(K=n["--persona-semantic-typography-fontSize"])!=null?K:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(ye=n["--persona-semantic-typography-fontWeight"])!=null?ye:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(le=n["--persona-semantic-typography-lineHeight"])!=null?le:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(te=n["--persona-palette-radius-sm"])!=null?te:"0.125rem",n["--persona-radius-md"]=(Ce=n["--persona-palette-radius-md"])!=null?Ce:"0.375rem",n["--persona-radius-lg"]=(Ue=n["--persona-palette-radius-lg"])!=null?Ue:"0.5rem",n["--persona-radius-xl"]=(ee=n["--persona-palette-radius-xl"])!=null?ee:"0.75rem",n["--persona-radius-full"]=(oe=n["--persona-palette-radius-full"])!=null?oe:"9999px",n["--persona-launcher-radius"]=(rt=(ae=n["--persona-components-launcher-borderRadius"])!=null?ae:n["--persona-palette-radius-full"])!=null?rt:"9999px",n["--persona-launcher-bg"]=(Ae=n["--persona-components-launcher-background"])!=null?Ae:n["--persona-primary"],n["--persona-launcher-fg"]=(pe=n["--persona-components-launcher-foreground"])!=null?pe:n["--persona-text-inverse"],n["--persona-launcher-border"]=($e=n["--persona-components-launcher-border"])!=null?$e:n["--persona-border"],n["--persona-button-primary-bg"]=(We=n["--persona-components-button-primary-background"])!=null?We:n["--persona-primary"],n["--persona-button-primary-fg"]=(ue=n["--persona-components-button-primary-foreground"])!=null?ue:n["--persona-text-inverse"],n["--persona-button-radius"]=(Ne=(X=n["--persona-components-button-primary-borderRadius"])!=null?X:n["--persona-palette-radius-full"])!=null?Ne:"9999px",n["--persona-panel-radius"]=(he=(Bt=n["--persona-components-panel-borderRadius"])!=null?Bt:n["--persona-radius-xl"])!=null?he:"0.75rem",n["--persona-panel-border"]=(ce=n["--persona-components-panel-border"])!=null?ce:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=($t=(Rn=n["--persona-components-panel-shadow"])!=null?Rn:n["--persona-palette-shadows-xl"])!=null?$t:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(mn=n["--persona-components-launcher-shadow"])!=null?mn:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(eo=(Dn=n["--persona-components-input-borderRadius"])!=null?Dn:n["--persona-radius-lg"])!=null?eo:"0.5rem",n["--persona-message-user-radius"]=(_=(ze=n["--persona-components-message-user-borderRadius"])!=null?ze:n["--persona-radius-lg"])!=null?_:"0.5rem",n["--persona-message-assistant-radius"]=(Be=(Me=n["--persona-components-message-assistant-borderRadius"])!=null?Me:n["--persona-radius-lg"])!=null?Be:"0.5rem",n["--persona-header-bg"]=(He=n["--persona-components-header-background"])!=null?He:n["--persona-surface"],n["--persona-header-border"]=(_e=n["--persona-components-header-border"])!=null?_e:n["--persona-divider"],n["--persona-header-icon-bg"]=(ut=n["--persona-components-header-iconBackground"])!=null?ut:n["--persona-primary"],n["--persona-header-icon-fg"]=(st=n["--persona-components-header-iconForeground"])!=null?st:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(Rt=n["--persona-components-header-titleForeground"])!=null?Rt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(qt=n["--persona-components-header-subtitleForeground"])!=null?qt:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(q=n["--persona-components-header-actionIconForeground"])!=null?q:n["--persona-muted"];let o=(Ut=e.components)==null?void 0:Ut.header;o!=null&&o.shadow&&(n["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom);let r=(Je=e.components)==null?void 0:Je.introCard;n["--persona-intro-card-bg"]=(_t=n["--persona-components-introCard-background"])!=null?_t:n["--persona-surface"],n["--persona-intro-card-radius"]=(re=n["--persona-components-introCard-borderRadius"])!=null?re:"1rem",n["--persona-intro-card-padding"]=(we=n["--persona-components-introCard-padding"])!=null?we:"1.5rem",n["--persona-intro-card-shadow"]=(jt=(Tt=r==null?void 0:r.shadow)!=null?Tt:n["--persona-components-introCard-shadow"])!=null?jt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(en=n["--persona-components-input-background"])!=null?en:n["--persona-surface"],n["--persona-input-placeholder"]=(Sn=n["--persona-components-input-placeholder"])!=null?Sn:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Pt=n["--persona-components-message-user-background"])!=null?Pt:n["--persona-accent"],n["--persona-message-user-text"]=(Et=n["--persona-components-message-user-text"])!=null?Et:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(xt=n["--persona-components-message-user-shadow"])!=null?xt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Ct=n["--persona-components-message-assistant-background"])!=null?Ct:n["--persona-surface"],n["--persona-message-assistant-text"]=(Kt=n["--persona-components-message-assistant-text"])!=null?Kt:n["--persona-text"],n["--persona-message-assistant-border"]=(nt=n["--persona-components-message-assistant-border"])!=null?nt:n["--persona-border"],n["--persona-message-assistant-shadow"]=(Fn=n["--persona-components-message-assistant-shadow"])!=null?Fn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(An=(to=n["--persona-components-scrollToBottom-background"])!=null?to:n["--persona-button-primary-bg"])!=null?An:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(ht=(On=n["--persona-components-scrollToBottom-foreground"])!=null?On:n["--persona-button-primary-fg"])!=null?ht:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Eo=n["--persona-components-scrollToBottom-border"])!=null?Eo:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(Nn=n["--persona-components-scrollToBottom-size"])!=null?Nn:"40px",n["--persona-scroll-to-bottom-radius"]=(Hr=(Pn=(dr=n["--persona-components-scrollToBottom-borderRadius"])!=null?dr:n["--persona-button-radius"])!=null?Pn:n["--persona-radius-full"])!=null?Hr:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Bo=(qo=n["--persona-components-scrollToBottom-shadow"])!=null?qo:n["--persona-palette-shadows-sm"])!=null?Bo:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(St=n["--persona-components-scrollToBottom-padding"])!=null?St:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(_n=n["--persona-components-scrollToBottom-gap"])!=null?_n:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Tn=(Vn=n["--persona-components-scrollToBottom-fontSize"])!=null?Vn:n["--persona-palette-typography-fontSize-sm"])!=null?Tn:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Mt=n["--persona-components-scrollToBottom-iconSize"])!=null?Mt:"14px",n["--persona-tool-bubble-shadow"]=(no=n["--persona-components-toolBubble-shadow"])!=null?no:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(oo=n["--persona-components-reasoningBubble-shadow"])!=null?oo:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=($n=n["--persona-components-composer-shadow"])!=null?$n:"none",n["--persona-md-inline-code-bg"]=(jo=n["--persona-components-markdown-inlineCode-background"])!=null?jo:n["--persona-container"],n["--persona-md-inline-code-color"]=(Ho=n["--persona-components-markdown-inlineCode-foreground"])!=null?Ho:n["--persona-text"],n["--persona-md-link-color"]=(Un=(Ko=n["--persona-components-markdown-link-foreground"])!=null?Ko:n["--persona-accent"])!=null?Un:"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let l=n["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(n["--persona-md-prose-font-family"]=l),n["--persona-md-code-block-bg"]=(Dt=n["--persona-components-markdown-codeBlock-background"])!=null?Dt:n["--persona-container"],n["--persona-md-code-block-border-color"]=(kn=n["--persona-components-markdown-codeBlock-borderColor"])!=null?kn:n["--persona-border"],n["--persona-md-code-block-text-color"]=(ro=n["--persona-components-markdown-codeBlock-textColor"])!=null?ro:"inherit",n["--persona-md-table-header-bg"]=(Go=n["--persona-components-markdown-table-headerBackground"])!=null?Go:n["--persona-container"],n["--persona-md-table-border-color"]=(Do=n["--persona-components-markdown-table-borderColor"])!=null?Do:n["--persona-border"],n["--persona-md-hr-color"]=(Yo=n["--persona-components-markdown-hr-color"])!=null?Yo:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Mo=n["--persona-components-markdown-blockquote-borderColor"])!=null?Mo:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(zn=n["--persona-components-markdown-blockquote-background"])!=null?zn:"transparent",n["--persona-md-blockquote-text-color"]=(bo=n["--persona-components-markdown-blockquote-textColor"])!=null?bo:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(yt=n["--persona-components-collapsibleWidget-container"])!=null?yt:n["--persona-surface"],n["--cw-surface"]=(Yt=n["--persona-components-collapsibleWidget-surface"])!=null?Yt:n["--persona-surface"],n["--cw-border"]=(Xt=n["--persona-components-collapsibleWidget-border"])!=null?Xt:n["--persona-border"],n["--persona-message-border"]=(qn=n["--persona-components-message-border"])!=null?qn:n["--persona-border"];let m=e.components,p=m==null?void 0:m.iconButton;p&&(p.background&&(n["--persona-icon-btn-bg"]=p.background),p.border&&(n["--persona-icon-btn-border"]=p.border),p.color&&(n["--persona-icon-btn-color"]=p.color),p.padding&&(n["--persona-icon-btn-padding"]=p.padding),p.borderRadius&&(n["--persona-icon-btn-radius"]=p.borderRadius),p.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=p.hoverBackground),p.hoverColor&&(n["--persona-icon-btn-hover-color"]=p.hoverColor),p.activeBackground&&(n["--persona-icon-btn-active-bg"]=p.activeBackground),p.activeBorder&&(n["--persona-icon-btn-active-border"]=p.activeBorder));let f=m==null?void 0:m.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let u=m==null?void 0:m.toggleGroup;u&&(u.gap&&(n["--persona-toggle-group-gap"]=u.gap),u.borderRadius&&(n["--persona-toggle-group-radius"]=u.borderRadius));let C=m==null?void 0:m.artifact;if(C!=null&&C.toolbar){let ve=C.toolbar;ve.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=ve.iconHoverColor),ve.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=ve.iconHoverBackground),ve.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=ve.iconPadding),ve.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=ve.iconBorderRadius),ve.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=ve.iconBorder),ve.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=ve.toggleGroupGap),ve.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=ve.toggleBorderRadius),ve.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=ve.copyBackground),ve.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=ve.copyBorder),ve.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=ve.copyColor),ve.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=ve.copyBorderRadius),ve.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=ve.copyPadding),ve.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=ve.copyMenuBackground,n["--persona-dropdown-bg"]=(Xo=n["--persona-dropdown-bg"])!=null?Xo:ve.copyMenuBackground),ve.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=ve.copyMenuBorder,n["--persona-dropdown-border"]=(so=n["--persona-dropdown-border"])!=null?so:ve.copyMenuBorder),ve.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=ve.copyMenuShadow,n["--persona-dropdown-shadow"]=(yo=n["--persona-dropdown-shadow"])!=null?yo:ve.copyMenuShadow),ve.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=ve.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(jn=n["--persona-dropdown-radius"])!=null?jn:ve.copyMenuBorderRadius),ve.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ve.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(V=n["--persona-dropdown-item-hover-bg"])!=null?V:ve.copyMenuItemHoverBackground),ve.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=ve.iconBackground),ve.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=ve.toolbarBorder)}if(C!=null&&C.tab){let ve=C.tab;ve.background&&(n["--persona-artifact-tab-bg"]=ve.background),ve.activeBackground&&(n["--persona-artifact-tab-active-bg"]=ve.activeBackground),ve.activeBorder&&(n["--persona-artifact-tab-active-border"]=ve.activeBorder),ve.borderRadius&&(n["--persona-artifact-tab-radius"]=ve.borderRadius),ve.textColor&&(n["--persona-artifact-tab-color"]=ve.textColor),ve.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=ve.hoverBackground),ve.listBackground&&(n["--persona-artifact-tab-list-bg"]=ve.listBackground),ve.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=ve.listBorderColor),ve.listPadding&&(n["--persona-artifact-tab-list-padding"]=ve.listPadding)}if(C!=null&&C.pane){let ve=C.pane;if(ve.toolbarBackground){let Kn=(ao=jr(e,ve.toolbarBackground))!=null?ao:ve.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Kn}}return n}var Mg={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},lu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Xi=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Lg=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Xi()},Ig=e=>Lg(e),Rg=e=>sn(e),Pg=e=>{var n;let t=sn(void 0,{validate:!1});return sn({...e,palette:{...t.palette,colors:{...Mg.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Ia=e=>{let t=Ig(e),n=lu(e==null?void 0:e.theme),o=lu(e==null?void 0:e.darkTheme);return t==="dark"?Pg(Ps(n!=null?n:{},o!=null?o:{})):Rg(n)},Wg=e=>iu(e),Kr=(e,t)=>{let n=Ia(t),o=Wg(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s)},cu=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Xi())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(Xi());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};function Qi(e,t){let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return o}function Sr(e,t,n){var i;let o=t.split(".");if(o.length===1)return{...e,[o[0]]:n};let[r,...s]=o,a=e;return{...a,[r]:Sr((i=a==null?void 0:a[r])!=null?i:{},s.join("."),n)}}var Ji=class{constructor(t,n,o){this.listeners=[];this.history=[];this.historyIndex=-1;this.suppressHistory=!1;var s;let r=(s=o==null?void 0:o.mergeDefaults)!=null?s:!0;this.config=r?{...It,...n}:n!=null?n:It,this.theme=sn(t,{validate:!1}),this.syncThemeIntoConfig(),this.pushHistorySnapshot(this.exportSnapshot(),!0)}get(t){var n;return t.startsWith("theme.")?Qi(this.theme,t.replace("theme.","")):t.startsWith("darkTheme.")?Qi((n=this.config.darkTheme)!=null?n:{},t.replace("darkTheme.","")):Qi(this.config,t)}getTheme(){return this.theme}getConfig(){return this.config}set(t,n){var o;if(t.startsWith("theme.")){let r=t.replace("theme.","");this.theme=Sr(this.theme,r,n),this.syncThemeIntoConfig()}else if(t.startsWith("darkTheme.")){let r=t.replace("darkTheme.",""),s=(o=this.config.darkTheme)!=null?o:sn();this.config={...this.config,darkTheme:Sr(s,r,n)}}else this.config=Sr(this.config,t,n);this.recordHistory(),this.notifyListeners()}setBatch(t){var s;let n=!1,o=!1,r=!1;for(let[a,i]of Object.entries(t))if(a.startsWith("theme.")){let d=a.replace("theme.","");this.theme=Sr(this.theme,d,i),n=!0}else if(a.startsWith("darkTheme.")){let d=a.replace("darkTheme.",""),l=(s=this.config.darkTheme)!=null?s:sn();this.config={...this.config,darkTheme:Sr(l,d,i)},o=!0}else this.config=Sr(this.config,a,i),r=!0;n&&this.syncThemeIntoConfig(),(n||o||r)&&(this.recordHistory(),this.notifyListeners())}setTheme(t){this.theme=t,this.syncThemeIntoConfig(),this.recordHistory(),this.notifyListeners()}setFullConfig(t,n){this.config={...t},n&&(this.theme=n),this.syncThemeIntoConfig(),this.recordHistory(),this.notifyListeners()}importSnapshot(t){var r,s;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Snapshot must be a JSON object");let n=t;if("config"in n||"theme"in n||n.version===2){let a=(r=n.config)!=null?r:this.config,i=sn((s=n.theme)!=null?s:this.theme,{validate:!1});this.setFullConfig(a,i);return}let o=sn(n,{validate:!1});this.setTheme(o)}resetToDefaults(){this.config={...It},this.theme=sn(),this.syncThemeIntoConfig(),this.history=[],this.historyIndex=-1,this.pushHistorySnapshot(this.exportSnapshot()),this.notifyListeners()}canUndo(){return this.historyIndex>0}canRedo(){return this.historyIndex>=0&&this.historyIndex<this.history.length-1}getHistoryLength(){return this.history.length}getHistoryIndex(){return this.historyIndex}undo(){this.canUndo()&&(this.historyIndex-=1,this.restoreSnapshot(this.history[this.historyIndex]))}redo(){this.canRedo()&&(this.historyIndex+=1,this.restoreSnapshot(this.history[this.historyIndex]))}exportSnapshot(){return{version:2,config:{...this.config,theme:void 0},theme:this.theme}}onChange(t){return this.listeners.push(t),()=>{let n=this.listeners.indexOf(t);n>=0&&this.listeners.splice(n,1)}}syncThemeIntoConfig(){this.config={...this.config,theme:this.theme}}notifyListeners(){for(let t of this.listeners)t(this.config,this.theme)}recordHistory(){this.pushHistorySnapshot(this.exportSnapshot())}pushHistorySnapshot(t,n=!1){if(this.suppressHistory)return;let o=JSON.stringify(t),r=this.historyIndex>=0&&this.history[this.historyIndex]?JSON.stringify(this.history[this.historyIndex]):null;if(n&&this.historyIndex>=0){this.history[this.historyIndex]=t;return}o!==r&&(this.history=this.history.slice(0,this.historyIndex+1),this.history.push(t),this.historyIndex=this.history.length-1)}restoreSnapshot(t){this.suppressHistory=!0,this.config=t.config,this.theme=sn(t.theme,{validate:!1}),this.syncThemeIntoConfig(),this.suppressHistory=!1,this.notifyListeners()}};function Zi(e){let t=e.trim();if(t==="9999px")return{value:100,unit:"px"};let n=t.match(/^([\d.]+)(px|rem)$/);if(!n){let o=parseFloat(t);return{value:isNaN(o)?0:o,unit:"px"}}return{value:parseFloat(n[1]),unit:n[2]}}function el(e,t){return t==="rem"?`${e}rem`:`${e}px`}function Bg(e,t){return t==="rem"?e*16:e}function Hg(e,t){return t==="rem"?e/16:e}function Ws(e){if(!e)return"#000000";let t=e.trim().toLowerCase();return t==="transparent"?"transparent":t.startsWith("rgba")||t.startsWith("rgb")?t:t.startsWith("#")?t.length===4?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:t:`#${t}`}function tl(e){return/^#[0-9A-Fa-f]{6}$/.test(e)}function nl(e){let t=e.trim().toLowerCase().match(/^rgba?\(([^)]+)\)$/);if(!t)return null;let n=t[1].split(",").map(d=>d.trim());if(n.length<3)return null;let o=d=>{let l=d.endsWith("%"),m=parseFloat(l?d.slice(0,-1):d);return Number.isFinite(m)?Math.max(0,Math.min(255,Math.round(l?m/100*255:m))):NaN},r=o(n[0]),s=o(n[1]),a=o(n[2]);if(!Number.isFinite(r)||!Number.isFinite(s)||!Number.isFinite(a))return null;let i=d=>d.toString(16).padStart(2,"0");return`#${i(r)}${i(s)}${i(a)}`}function Ra(e,t){let n=s=>{var l;let a=Ws(s),i=a.startsWith("rgb")?(l=nl(a))!=null?l:"#000000":a,d=[1,3,5].map(m=>{let p=parseInt(i.slice(m,m+2),16)/255;return p<=.03928?p/12.92:Math.pow((p+.055)/1.055,2.4)});return .2126*d[0]+.7152*d[1]+.0722*d[2]},o=n(e),r=n(t);return(Math.max(o,r)+.05)/(Math.min(o,r)+.05)}function du(e){var f;let t=Ws(e),n=t.startsWith("rgb")?(f=nl(t))!=null?f:"#000000":t,o=parseInt(n.slice(1,3),16)/255,r=parseInt(n.slice(3,5),16)/255,s=parseInt(n.slice(5,7),16)/255,a=Math.max(o,r,s),i=Math.min(o,r,s),d=(a+i)/2;if(a===i)return{h:0,s:0,l:d};let l=a-i,m=d>.5?l/(2-a-i):l/(a+i),p;switch(a){case o:p=((r-s)/l+(r<s?6:0))/6;break;case r:p=((s-o)/l+2)/6;break;default:p=((o-r)/l+4)/6;break}return{h:p*360,s:m,l:d}}function pu(e,t,n){let o=(e%360+360)%360,r=(1-Math.abs(2*n-1))*t,s=r*(1-Math.abs(o/60%2-1)),a=n-r/2,i,d,l;o<60?[i,d,l]=[r,s,0]:o<120?[i,d,l]=[s,r,0]:o<180?[i,d,l]=[0,r,s]:o<240?[i,d,l]=[0,s,r]:o<300?[i,d,l]=[s,0,r]:[i,d,l]=[r,0,s];let m=p=>{let f=Math.round((p+a)*255).toString(16);return f.length===1?"0"+f:f};return`#${m(i)}${m(d)}${m(l)}`}function ol(e){let{h:t,s:n,l:o}=du(e),r={50:.97,100:.94,200:.87,300:.77,400:.64,500:o,600:Math.max(.05,o-.1),700:Math.max(.05,o-.2),800:Math.max(.05,o-.28),900:Math.max(.05,o-.35),950:Math.max(.03,o-.42)},s={50:Math.min(1,n*.85),100:Math.min(1,n*.9),200:Math.min(1,n*.95),300:n,400:n,500:n,600:Math.min(1,n*1.05),700:Math.min(1,n*1.05),800:Math.min(1,n*1),900:Math.min(1,n*.95),950:Math.min(1,n*.9)},a={};for(let[i,d]of Object.entries(r)){let l=s[i];a[i]=pu(t,l,d)}return a}var Gr=["50","100","200","300","400","500","600","700","800","900","950"],rl=["primary","secondary","accent","gray","success","warning","error","info"];function Dg(e,t){return`palette.colors.${e}.${t}`}function uu(e,t,n=0){if(n>5)return"#cbd5e1";let o=e(t);return typeof o!="string"?"#cbd5e1":o.startsWith("#")||o.startsWith("rgb")||o==="transparent"?o:o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components.")?uu(e,`theme.${o}`,n+1):"#cbd5e1"}function Fg(e){if(!e.startsWith("palette.")&&!e.startsWith("semantic."))return e;let t=e.split(".");if(t[0]==="palette"&&t[1]==="colors"){let n=t[2],o=t[3];return`${n.charAt(0).toUpperCase()+n.slice(1)} ${o}`}return t[0]==="semantic"?t.slice(1).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):t[t.length-1]}var Ro=[{id:"solid",label:"Solid"},{id:"soft",label:"Soft"}],Pa=["primary","secondary","accent","gray"],Og={primary:"Primary",secondary:"Secondary",accent:"Accent",gray:"Neutral"},Wa={roleId:"role-surfaces",helper:"Page and panel backgrounds",previewZone:"container",intensities:Ro,targets:[{path:"semantic.colors.background",kind:"background"},{path:"semantic.colors.surface",kind:"background"},{path:"semantic.colors.container",kind:"background"}]},Ba={roleId:"role-header",helper:"Widget header bar",previewZone:"header",intensities:Ro,targets:[{path:"components.header.background",kind:"background"},{path:"components.header.border",kind:"border"},{path:"components.header.iconBackground",kind:"accent"},{path:"components.header.iconForeground",kind:"foreground"},{path:"components.header.titleForeground",kind:"accent"},{path:"components.header.subtitleForeground",kind:"foreground"},{path:"components.header.actionIconForeground",kind:"foreground"}]},Ha={roleId:"role-user-messages",helper:"User chat bubbles",previewZone:"user-message",intensities:Ro,targets:[{path:"components.message.user.background",kind:"background"},{path:"components.message.user.text",kind:"foreground"}]},Da={roleId:"role-assistant-messages",helper:"Assistant chat bubbles",previewZone:"assistant-message",intensities:Ro,targets:[{path:"components.message.assistant.background",kind:"background"},{path:"components.message.assistant.text",kind:"foreground"}]},Fa={roleId:"role-primary-actions",helper:"Send button and primary buttons",intensities:Ro,targets:[{path:"components.button.primary.background",kind:"background"},{path:"components.button.primary.foreground",kind:"foreground"},{path:"semantic.colors.interactive.default",kind:"accent"},{path:"semantic.colors.interactive.hover",kind:"accent"}]},Oa={roleId:"role-scroll-to-bottom",helper:"Scroll-to-bottom affordances in transcript and event stream",intensities:Ro,targets:[{path:"components.scrollToBottom.background",kind:"background"},{path:"components.scrollToBottom.foreground",kind:"foreground"},{path:"components.scrollToBottom.border",kind:"border"}]},Na={roleId:"role-input",helper:"Message input field",previewZone:"composer",intensities:Ro,targets:[{path:"components.input.background",kind:"background"},{path:"components.input.placeholder",kind:"foreground"},{path:"components.input.focus.border",kind:"accent"},{path:"components.input.focus.ring",kind:"accent"}]},_a={roleId:"role-links-focus",helper:"Links, focus rings, and interactive highlights",intensities:Ro,targets:[{path:"semantic.colors.accent",kind:"accent"},{path:"semantic.colors.interactive.focus",kind:"accent"},{path:"semantic.colors.interactive.active",kind:"accent"},{path:"components.markdown.link.foreground",kind:"accent"}]},Va={roleId:"role-borders",helper:"Borders, dividers, and separators",intensities:Ro,targets:[{path:"semantic.colors.border",kind:"border"},{path:"semantic.colors.divider",kind:"border"}]},Ar=[Wa,Ba,Ha,Da,Fa,Oa,Na,_a,Va];function $a(e,t,n){let o={},r=e==="neutral"?"gray":e;for(let s of n.targets){let a=Ng(r,t,s,n.roleId);o[`theme.${s.path}`]=a,o[`darkTheme.${s.path}`]=a}if(n.roleId==="role-primary-actions"){let s=t==="solid"?`palette.colors.${r}.700`:`palette.colors.${r}.200`;o["theme.semantic.colors.interactive.hover"]=s,o["darkTheme.semantic.colors.interactive.hover"]=s}return o}function Ng(e,t,n,o){let r=t==="solid";if(o==="role-header")return _g(e,r,n);if(o==="role-input")return Vg(e,r,n);switch(n.kind){case"background":return r?`palette.colors.${e}.500`:`palette.colors.${e}.${e==="gray"?"50":"100"}`;case"foreground":return r?`palette.colors.${e==="gray"?"gray":e}.50`:`palette.colors.${e==="gray"?"gray":e}.900`;case"border":return r?`palette.colors.${e}.600`:`palette.colors.${e}.200`;case"accent":return r?`palette.colors.${e}.600`:`palette.colors.${e}.400`}}function _g(e,t,n){let o=n.path;return o.endsWith(".background")?t?`palette.colors.${e}.500`:`palette.colors.${e}.${e==="gray"?"50":"100"}`:o.endsWith(".border")?t?`palette.colors.${e}.600`:`palette.colors.${e}.200`:o.endsWith(".iconBackground")?t?`palette.colors.${e}.${e==="gray"?"700":"600"}`:`palette.colors.${e}.500`:o.endsWith(".iconForeground")?t?`palette.colors.${e}.50`:`palette.colors.${e}.50`:o.endsWith(".titleForeground")?t?`palette.colors.${e}.50`:`palette.colors.${e}.${e==="gray"?"900":"700"}`:o.endsWith(".subtitleForeground")?t?`palette.colors.${e}.200`:`palette.colors.${e}.500`:o.endsWith(".actionIconForeground")?t?`palette.colors.${e}.200`:`palette.colors.${e}.500`:`palette.colors.${e}.500`}function Vg(e,t,n){let o=n.path;return o.endsWith(".background")?t?`palette.colors.${e}.${e==="gray"?"100":"50"}`:`palette.colors.${e}.50`:o.endsWith(".placeholder")?`palette.colors.${e}.400`:o.endsWith(".border")||o.endsWith(".ring")?t?`palette.colors.${e}.500`:`palette.colors.${e}.400`:`palette.colors.${e}.500`}var $g=/^palette\.colors\.(\w+)\.(\d+)$/;function sl(e,t){var i,d;let n=(i=t.targets.find(l=>l.kind==="background"))!=null?i:t.targets[0];if(!n)return null;let r=String((d=e(n.path))!=null?d:"").match($g);if(!r)return null;let s=r[1],a=Pa.includes(s)?s:null;if(!a)return null;for(let l of["solid","soft"]){let m=$a(a,l,t);if(t.targets.every(f=>{var C;return String((C=e(f.path))!=null?C:"")===m[`theme.${f.path}`]}))return{family:a,intensity:l}}return null}var Ug={id:"theme-mode",title:"Runtime Theme",description:"Controls how the shipped widget picks light or dark mode.",collapsed:!1,fields:[{id:"theme-mode",label:"Runtime Theme",description:"Always Light, Always Dark, or follow the visitor system preference",type:"select",path:"colorScheme",defaultValue:"auto",options:[{value:"light",label:"Light"},{value:"dark",label:"Dark"},{value:"auto",label:"Follow System"}]}]},zg={id:"brand-colors",title:"Brand Colors",description:"Pick your brand colors. A full shade scale is generated automatically for both light and dark themes.",collapsed:!1,fields:[{id:"brand-primary",label:"Primary",description:"Main brand color for buttons, links, and accents",type:"color",path:"theme.palette.colors.primary.500",defaultValue:"#171717"},{id:"brand-secondary",label:"Secondary",description:"Supporting brand color",type:"color",path:"theme.palette.colors.secondary.500",defaultValue:"#7c3aed"},{id:"brand-accent",label:"Accent",description:"Highlight and decorative color",type:"color",path:"theme.palette.colors.accent.500",defaultValue:"#06b6d4"}]},qg={id:"chat-colors",title:"Chat Colors",description:"Customize the main colors of the chat interface.",collapsed:!0,fields:[{id:"chat-header-bg",label:"Header Background",type:"token-ref",path:"theme.components.header.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"chat-header-icon-bg",label:"Header Icon Background",type:"token-ref",path:"theme.components.header.iconBackground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-header-icon-fg",label:"Header Icon Color",type:"token-ref",path:"theme.components.header.iconForeground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"chat-header-title-fg",label:"Header Title Color",type:"token-ref",path:"theme.components.header.titleForeground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-header-subtitle-fg",label:"Header Subtitle Color",type:"token-ref",path:"theme.components.header.subtitleForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"chat-header-action-icons-fg",label:"Header Button Icons",type:"token-ref",path:"theme.components.header.actionIconForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"chat-msg-user-bg",label:"User Message Background",type:"token-ref",path:"theme.components.message.user.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-msg-user-text",label:"User Message Text",type:"token-ref",path:"theme.components.message.user.text",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"chat-msg-assistant-bg",label:"Assistant Message Background",type:"token-ref",path:"theme.components.message.assistant.background",defaultValue:"semantic.colors.container",tokenRef:{tokenType:"color"}},{id:"chat-msg-assistant-text",label:"Assistant Message Text",type:"token-ref",path:"theme.components.message.assistant.text",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},jg={id:"typography",title:"Typography",collapsed:!0,fields:[{id:"typo-font-family",label:"Font Family",type:"select",path:"theme.semantic.typography.fontFamily",defaultValue:"palette.typography.fontFamily.sans",options:[{value:"palette.typography.fontFamily.sans",label:"Sans Serif"},{value:"palette.typography.fontFamily.serif",label:"Serif"},{value:"palette.typography.fontFamily.mono",label:"Monospace"}]},{id:"typo-font-size",label:"Base Font Size",type:"select",path:"theme.semantic.typography.fontSize",defaultValue:"palette.typography.fontSize.base",options:[{value:"palette.typography.fontSize.xs",label:"Extra Small (0.75rem)"},{value:"palette.typography.fontSize.sm",label:"Small (0.875rem)"},{value:"palette.typography.fontSize.base",label:"Base (1rem)"},{value:"palette.typography.fontSize.lg",label:"Large (1.125rem)"},{value:"palette.typography.fontSize.xl",label:"Extra Large (1.25rem)"}]},{id:"typo-font-weight",label:"Font Weight",type:"select",path:"theme.semantic.typography.fontWeight",defaultValue:"palette.typography.fontWeight.normal",options:[{value:"palette.typography.fontWeight.normal",label:"Normal (400)"},{value:"palette.typography.fontWeight.medium",label:"Medium (500)"},{value:"palette.typography.fontWeight.semibold",label:"Semibold (600)"},{value:"palette.typography.fontWeight.bold",label:"Bold (700)"}]},{id:"typo-line-height",label:"Line Height",type:"select",path:"theme.semantic.typography.lineHeight",defaultValue:"palette.typography.lineHeight.normal",options:[{value:"palette.typography.lineHeight.tight",label:"Tight (1.25)"},{value:"palette.typography.lineHeight.normal",label:"Normal (1.5)"},{value:"palette.typography.lineHeight.relaxed",label:"Relaxed (1.625)"}]}]},Kg={id:"launcher-style",title:"Launcher",description:"Control launcher appearance.",collapsed:!0,fields:[{id:"style-launcher-size",label:"Launcher Size",type:"slider",path:"theme.components.launcher.size",defaultValue:"60px",slider:{min:32,max:80,step:2}},{id:"style-launcher-shape",label:"Launcher Shape",type:"select",path:"theme.components.launcher.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Rounded Square"},{value:"palette.radius.lg",label:"Rounded"},{value:"palette.radius.xl",label:"Very Rounded"},{value:"palette.radius.full",label:"Circle"}]},{id:"style-launcher-shadow",label:"Launcher Shadow",type:"select",path:"theme.components.launcher.shadow",defaultValue:"palette.shadows.lg",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},Gg={id:"shape",title:"Shape",description:"Control the corner roundness across the widget.",collapsed:!0,fields:[{id:"radius-sm",label:"Small",type:"slider",path:"theme.palette.radius.sm",defaultValue:"0.125rem",slider:{min:0,max:16,step:1}},{id:"radius-md",label:"Medium",type:"slider",path:"theme.palette.radius.md",defaultValue:"0.375rem",slider:{min:0,max:24,step:1}},{id:"radius-lg",label:"Large",type:"slider",path:"theme.palette.radius.lg",defaultValue:"0.5rem",slider:{min:0,max:32,step:1}},{id:"radius-xl",label:"Extra Large",type:"slider",path:"theme.palette.radius.xl",defaultValue:"0.75rem",slider:{min:0,max:48,step:1}},{id:"radius-full",label:"Full",type:"slider",path:"theme.palette.radius.full",defaultValue:"9999px",slider:{min:0,max:100,step:1,isRadiusFull:!0}}],presets:[{id:"radius-default",label:"Default",values:{"theme.palette.radius.sm":"0.125rem","theme.palette.radius.md":"0.375rem","theme.palette.radius.lg":"0.5rem","theme.palette.radius.xl":"0.75rem","theme.palette.radius.full":"9999px"}},{id:"radius-sharp",label:"Sharp",values:{"theme.palette.radius.sm":"1px","theme.palette.radius.md":"2px","theme.palette.radius.lg":"3px","theme.palette.radius.xl":"4px","theme.palette.radius.full":"4px"}},{id:"radius-rounded",label:"Rounded",values:{"theme.palette.radius.sm":"0.5rem","theme.palette.radius.md":"0.75rem","theme.palette.radius.lg":"1rem","theme.palette.radius.xl":"1.5rem","theme.palette.radius.full":"9999px"}}]},Yg={id:"shadows",title:"Shadows",collapsed:!0,fields:[{id:"shadow-sm",label:"Small",type:"text",path:"theme.palette.shadows.sm",defaultValue:"0 1px 2px 0 rgb(0 0 0 / 0.05)"},{id:"shadow-md",label:"Medium",type:"text",path:"theme.palette.shadows.md",defaultValue:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)"},{id:"shadow-lg",label:"Large",type:"text",path:"theme.palette.shadows.lg",defaultValue:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)"},{id:"shadow-xl",label:"Extra Large",type:"text",path:"theme.palette.shadows.xl",defaultValue:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)"}]},Xg={id:"widget-style",title:"Widget Surface",description:"Adjust the main panel and message bubble treatment.",collapsed:!0,fields:[{id:"style-panel-radius",label:"Panel Corner Radius",type:"select",path:"theme.components.panel.borderRadius",defaultValue:"palette.radius.xl",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"style-panel-shadow",label:"Panel Shadow",type:"select",path:"theme.components.panel.shadow",defaultValue:"palette.shadows.xl",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]},{id:"style-msg-user-radius",label:"User Message Radius",type:"select",path:"theme.components.message.user.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"style-msg-assistant-radius",label:"Assistant Message Radius",type:"select",path:"theme.components.message.assistant.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},Xr=[zg,qg,Kg,jg,Ug,Gg,Yg,Xg];function gu(){return{id:"brand-palette",title:"Brand Palette",description:"Define your color palette. Edit the base color (500) to auto-generate the full scale.",collapsed:!1,fields:rl.map(t=>({id:`palette-${t}`,label:`${t.charAt(0).toUpperCase()+t.slice(1)}`,description:`${t} color palette (edit shade 500, auto-generate scale)`,type:"color-scale",path:`theme.palette.colors.${t}`,colorScale:{colorFamily:t}}))}}var fu={id:"semantic-colors",title:"Semantic Colors",description:"Map intents to palette colors.",collapsed:!0,fields:[{id:"sem-primary",label:"Primary",description:"Main brand/action color",type:"token-ref",path:"theme.semantic.colors.primary",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sem-secondary",label:"Secondary",description:"Secondary actions",type:"token-ref",path:"theme.semantic.colors.secondary",defaultValue:"palette.colors.gray.500",tokenRef:{tokenType:"color"}},{id:"sem-accent",label:"Accent",description:"Accent/highlight color",type:"token-ref",path:"theme.semantic.colors.accent",defaultValue:"palette.colors.primary.600",tokenRef:{tokenType:"color"}},{id:"sem-surface",label:"Surface",description:"Primary surface background",type:"token-ref",path:"theme.semantic.colors.surface",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-background",label:"Background",description:"Page/widget background",type:"token-ref",path:"theme.semantic.colors.background",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-container",label:"Container",description:"Container/card background",type:"token-ref",path:"theme.semantic.colors.container",defaultValue:"palette.colors.gray.100",tokenRef:{tokenType:"color"}},{id:"sem-text",label:"Text",description:"Primary text color",type:"token-ref",path:"theme.semantic.colors.text",defaultValue:"palette.colors.gray.900",tokenRef:{tokenType:"color"}},{id:"sem-text-muted",label:"Text Muted",description:"Secondary/muted text",type:"token-ref",path:"theme.semantic.colors.textMuted",defaultValue:"palette.colors.gray.500",tokenRef:{tokenType:"color"}},{id:"sem-text-inverse",label:"Text Inverse",description:"Text on dark backgrounds",type:"token-ref",path:"theme.semantic.colors.textInverse",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-border",label:"Border",description:"Default border color",type:"token-ref",path:"theme.semantic.colors.border",defaultValue:"palette.colors.gray.200",tokenRef:{tokenType:"color"}},{id:"sem-divider",label:"Divider",description:"Divider/separator color",type:"token-ref",path:"theme.semantic.colors.divider",defaultValue:"palette.colors.gray.200",tokenRef:{tokenType:"color"}},{id:"sem-interactive-default",label:"Interactive Default",type:"token-ref",path:"theme.semantic.colors.interactive.default",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sem-interactive-hover",label:"Interactive Hover",type:"token-ref",path:"theme.semantic.colors.interactive.hover",defaultValue:"palette.colors.primary.600",tokenRef:{tokenType:"color"}},{id:"sem-interactive-focus",label:"Interactive Focus",type:"token-ref",path:"theme.semantic.colors.interactive.focus",defaultValue:"palette.colors.primary.700",tokenRef:{tokenType:"color"}},{id:"sem-interactive-active",label:"Interactive Active",type:"token-ref",path:"theme.semantic.colors.interactive.active",defaultValue:"palette.colors.primary.800",tokenRef:{tokenType:"color"}},{id:"sem-interactive-disabled",label:"Interactive Disabled",type:"token-ref",path:"theme.semantic.colors.interactive.disabled",defaultValue:"palette.colors.gray.300",tokenRef:{tokenType:"color"}},{id:"sem-feedback-success",label:"Success",type:"token-ref",path:"theme.semantic.colors.feedback.success",defaultValue:"palette.colors.success.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-warning",label:"Warning",type:"token-ref",path:"theme.semantic.colors.feedback.warning",defaultValue:"palette.colors.warning.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-error",label:"Error",type:"token-ref",path:"theme.semantic.colors.feedback.error",defaultValue:"palette.colors.error.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-info",label:"Info",type:"token-ref",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}}]},Qg=gu(),Jg=fu,Zg=[gu(),fu],ef={id:"comp-panel",title:"Panel",collapsed:!1,fields:[{id:"panel-width",label:"Width",type:"text",path:"theme.components.panel.width",defaultValue:go},{id:"panel-max-width",label:"Max Width",type:"text",path:"theme.components.panel.maxWidth",defaultValue:La},{id:"panel-height",label:"Height",type:"text",path:"theme.components.panel.height",defaultValue:"600px"},{id:"panel-max-height",label:"Max Height",type:"text",path:"theme.components.panel.maxHeight",defaultValue:"calc(100vh - 80px)"},{id:"panel-border-radius",label:"Border Radius",type:"select",path:"theme.components.panel.borderRadius",defaultValue:"palette.radius.xl",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"panel-shadow",label:"Shadow",type:"select",path:"theme.components.panel.shadow",defaultValue:"palette.shadows.xl",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},tf={id:"comp-launcher",title:"Launcher",collapsed:!0,fields:[{id:"launcher-size",label:"Size",type:"slider",path:"theme.components.launcher.size",defaultValue:"60px",slider:{min:32,max:80,step:2}},{id:"launcher-icon-size",label:"Icon Size",type:"slider",path:"theme.components.launcher.iconSize",defaultValue:"28px",slider:{min:16,max:48,step:2}},{id:"launcher-border-radius",label:"Border Radius",type:"select",path:"theme.components.launcher.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"},{value:"palette.radius.full",label:"Full (Circle)"}]},{id:"launcher-shadow",label:"Shadow",type:"select",path:"theme.components.launcher.shadow",defaultValue:"palette.shadows.lg",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},nf={id:"comp-message-shape",title:"Message Shape",collapsed:!0,fields:[{id:"msg-user-radius",label:"User Bubble Radius",type:"select",path:"theme.components.message.user.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"msg-assistant-radius",label:"Assistant Bubble Radius",type:"select",path:"theme.components.message.assistant.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},of={id:"comp-input-shape",title:"Input Shape",collapsed:!0,fields:[{id:"input-radius",label:"Border Radius",type:"select",path:"theme.components.input.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},rf={id:"comp-button-shape",title:"Button Shape",collapsed:!0,fields:[{id:"btn-primary-radius",label:"Primary Radius",type:"select",path:"theme.components.button.primary.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.full",label:"Full"}]}]},sf={id:"comp-header-colors",title:"Header Colors",collapsed:!0,fields:[{id:"header-bg",label:"Background",type:"token-ref",path:"theme.components.header.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"header-icon-bg",label:"Icon background",type:"token-ref",path:"theme.components.header.iconBackground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"header-icon-fg",label:"Icon color",type:"token-ref",path:"theme.components.header.iconForeground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"header-title-fg",label:"Title color",type:"token-ref",path:"theme.components.header.titleForeground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"header-subtitle-fg",label:"Subtitle color",type:"token-ref",path:"theme.components.header.subtitleForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"header-action-icons-fg",label:"Clear / close icons",type:"token-ref",path:"theme.components.header.actionIconForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"header-border",label:"Border",type:"token-ref",path:"theme.components.header.border",defaultValue:"semantic.colors.border",tokenRef:{tokenType:"color"}}]},af={id:"comp-message-colors",title:"Message Colors",collapsed:!0,fields:[{id:"msg-user-bg",label:"User Bubble Background",type:"token-ref",path:"theme.components.message.user.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"msg-user-text",label:"User Bubble Text",type:"token-ref",path:"theme.components.message.user.text",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"msg-assistant-bg",label:"Assistant Bubble Background",type:"token-ref",path:"theme.components.message.assistant.background",defaultValue:"semantic.colors.container",tokenRef:{tokenType:"color"}},{id:"msg-assistant-text",label:"Assistant Bubble Text",type:"token-ref",path:"theme.components.message.assistant.text",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},lf={id:"comp-input-colors",title:"Input Colors",collapsed:!0,fields:[{id:"input-bg",label:"Background",type:"token-ref",path:"theme.components.input.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"input-placeholder",label:"Placeholder Color",type:"token-ref",path:"theme.components.input.placeholder",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"input-focus-border",label:"Focus Border",type:"token-ref",path:"theme.components.input.focus.border",defaultValue:"semantic.colors.interactive.focus",tokenRef:{tokenType:"color"}},{id:"input-focus-ring",label:"Focus Ring",type:"token-ref",path:"theme.components.input.focus.ring",defaultValue:"semantic.colors.interactive.focus",tokenRef:{tokenType:"color"}}]},cf={id:"comp-button-colors",title:"Button Colors",collapsed:!0,fields:[{id:"btn-primary-bg",label:"Primary Background",type:"token-ref",path:"theme.components.button.primary.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"btn-primary-fg",label:"Primary Foreground",type:"token-ref",path:"theme.components.button.primary.foreground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"btn-secondary-bg",label:"Secondary Background",type:"token-ref",path:"theme.components.button.secondary.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"btn-secondary-fg",label:"Secondary Foreground",type:"token-ref",path:"theme.components.button.secondary.foreground",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}},{id:"btn-ghost-bg",label:"Ghost Background",type:"color",path:"theme.components.button.ghost.background",defaultValue:"transparent"},{id:"btn-ghost-fg",label:"Ghost Foreground",type:"token-ref",path:"theme.components.button.ghost.foreground",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},df={id:"scroll-to-bottom-style",title:"Scroll To Bottom",description:"Style the floating jump-to-latest affordance.",collapsed:!0,fields:[{id:"scroll-bottom-bg",label:"Background",type:"token-ref",path:"theme.components.scrollToBottom.background",defaultValue:"components.button.primary.background",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-fg",label:"Foreground",type:"token-ref",path:"theme.components.scrollToBottom.foreground",defaultValue:"components.button.primary.foreground",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-border",label:"Border",type:"token-ref",path:"theme.components.scrollToBottom.border",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-size",label:"Size",type:"text",path:"theme.components.scrollToBottom.size",defaultValue:"40px"},{id:"scroll-bottom-radius",label:"Border Radius",type:"select",path:"theme.components.scrollToBottom.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"},{value:"palette.radius.full",label:"Full"}]},{id:"scroll-bottom-shadow",label:"Shadow",type:"select",path:"theme.components.scrollToBottom.shadow",defaultValue:"palette.shadows.sm",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]},{id:"scroll-bottom-padding",label:"Padding",type:"text",path:"theme.components.scrollToBottom.padding",defaultValue:"0.5rem 0.875rem"},{id:"scroll-bottom-gap",label:"Gap",type:"text",path:"theme.components.scrollToBottom.gap",defaultValue:"0.5rem"},{id:"scroll-bottom-font-size",label:"Font Size",type:"text",path:"theme.components.scrollToBottom.fontSize",defaultValue:"0.875rem"},{id:"scroll-bottom-icon-size",label:"Icon Size",type:"text",path:"theme.components.scrollToBottom.iconSize",defaultValue:"14px"}]},Yr=[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}],al="0 5px 15px rgba(15, 23, 42, 0.08)",mu=[{value:al,label:"Default"},...Yr],pf={id:"comp-shadows",title:"Component Shadows",description:"Box-shadow for chat bubbles and surfaces.",collapsed:!0,fields:[{id:"shadow-msg-user",label:"User Message",type:"select",path:"theme.components.message.user.shadow",defaultValue:"palette.shadows.sm",options:Yr},{id:"shadow-msg-assistant",label:"Assistant Message",type:"select",path:"theme.components.message.assistant.shadow",defaultValue:"palette.shadows.sm",options:Yr},{id:"shadow-tool-bubble",label:"Tool Call Bubble",type:"select",path:"theme.components.toolBubble.shadow",defaultValue:"palette.shadows.sm",options:Yr},{id:"shadow-reasoning-bubble",label:"Reasoning Bubble",type:"select",path:"theme.components.reasoningBubble.shadow",defaultValue:"palette.shadows.sm",options:Yr},{id:"shadow-approval",label:"Approval Bubble",type:"select",path:"theme.components.approval.requested.shadow",defaultValue:al,options:mu},{id:"shadow-intro-card",label:"Intro Card",type:"select",path:"theme.components.introCard.shadow",defaultValue:al,options:mu},{id:"shadow-composer",label:"Composer",type:"select",path:"theme.components.composer.shadow",defaultValue:"palette.shadows.none",options:Yr}]},hu=[ef,tf,nf,of,rf,pf],bu=[sf,af,lf,cf,df],yu=[...hu,...bu],il=1024*1024,uf=["What can you help me with?","Tell me about your features","How does this work?"],Bs={images:["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],"images-pdf":["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf"],"images-text-pdf":["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf","text/plain","text/markdown","text/csv","application/json"],all:["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"]};function mf(e){return Number(e)*il}function gf(e){let t=Number(e);return Number.isFinite(t)?t>1024?String(Math.round(t/il)):String(t):"10"}function ff(e){var t;return(t=Bs[String(e)])!=null?t:Bs.images}function hf(e){let t=Array.isArray(e)?e:Bs.images,n=[...new Set(t)].sort();for(let[o,r]of Object.entries(Bs)){let s=[...r].sort();if(n.length===s.length&&n.every((a,i)=>a===s[i]))return o}return n.some(o=>o.startsWith("application/vnd")||o==="application/msword")?"all":n.some(o=>o==="text/plain"||o==="text/markdown"||o==="text/csv")?"images-text-pdf":n.includes("application/pdf")?"images-pdf":"images"}var bf={id:"copy",title:"Content & Copy",collapsed:!1,fields:[{id:"copy-show-welcome-card",label:"Show Welcome Card",type:"toggle",path:"copy.showWelcomeCard",defaultValue:!0},{id:"copy-welcome-title",label:"Welcome Title",type:"text",path:"copy.welcomeTitle",defaultValue:"Hello \u{1F44B}"},{id:"copy-welcome-subtitle",label:"Welcome Subtitle",type:"text",path:"copy.welcomeSubtitle",defaultValue:"Ask anything about your account or products."},{id:"copy-placeholder",label:"Input Placeholder",type:"text",path:"copy.inputPlaceholder",defaultValue:"Type your message\u2026"},{id:"copy-send-label",label:"Send Button Label",type:"text",path:"copy.sendButtonLabel",defaultValue:"Send"}]},yf={id:"suggestions",title:"Suggestion Chips",description:"Configure chip content and styling.",collapsed:!0,fields:[{id:"suggestions-list",label:"Suggestions",description:"Add, edit, and remove chips directly.",type:"chip-list",path:"suggestionChips",defaultValue:uf}]},vf={id:"general-layout",title:"Layout Basics",collapsed:!0,fields:[{id:"layout-show-header",label:"Show Header",type:"toggle",path:"layout.showHeader",defaultValue:!0},{id:"layout-show-footer",label:"Show Footer",type:"toggle",path:"layout.showFooter",defaultValue:!0},{id:"layout-content-max-width",label:"Content Max Width",description:"Max width for messages + composer",type:"text",path:"layout.contentMaxWidth",defaultValue:""}]},xf={id:"header-layout",title:"Header",collapsed:!0,fields:[{id:"layout-header",label:"Header Layout",type:"select",path:"layout.header.layout",defaultValue:"default",options:[{value:"default",label:"Default"},{value:"minimal",label:"Minimal"}]},{id:"layout-show-icon",label:"Show Header Icon",type:"toggle",path:"layout.header.showIcon",defaultValue:!0},{id:"layout-show-title",label:"Show Header Title",type:"toggle",path:"layout.header.showTitle",defaultValue:!0},{id:"layout-show-subtitle",label:"Show Header Subtitle",type:"toggle",path:"layout.header.showSubtitle",defaultValue:!0},{id:"layout-show-close",label:"Show Close Button",type:"toggle",path:"layout.header.showCloseButton",defaultValue:!0},{id:"layout-show-clear",label:"Show Clear Chat",type:"toggle",path:"layout.header.showClearChat",defaultValue:!0}]},wf={id:"messages-layout",title:"Messages",collapsed:!0,fields:[{id:"layout-messages",label:"Messages Layout",type:"select",path:"layout.messages.layout",defaultValue:"bubble",options:[{value:"bubble",label:"Bubble"},{value:"flat",label:"Flat"},{value:"minimal",label:"Minimal"}]},{id:"layout-group",label:"Group Consecutive",type:"toggle",path:"layout.messages.groupConsecutive",defaultValue:!1},{id:"layout-avatar-show",label:"Show Avatars",type:"toggle",path:"layout.messages.avatar.show",defaultValue:!1},{id:"layout-avatar-pos",label:"Avatar Position",type:"select",path:"layout.messages.avatar.position",defaultValue:"left",options:[{value:"left",label:"Left"},{value:"right",label:"Right"}]},{id:"layout-avatar-user",label:"User Avatar URL",type:"text",path:"layout.messages.avatar.userAvatar",defaultValue:""},{id:"layout-avatar-assistant",label:"Assistant Avatar URL",type:"text",path:"layout.messages.avatar.assistantAvatar",defaultValue:""},{id:"layout-timestamp-show",label:"Show Timestamps",type:"toggle",path:"layout.messages.timestamp.show",defaultValue:!1},{id:"layout-timestamp-pos",label:"Timestamp Position",type:"select",path:"layout.messages.timestamp.position",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"below",label:"Below"}]}]},Cf={id:"message-actions",title:"Message Actions",collapsed:!0,fields:[{id:"msg-actions-enabled",label:"Enabled",type:"toggle",path:"messageActions.enabled",defaultValue:!0},{id:"msg-actions-copy",label:"Show Copy",type:"toggle",path:"messageActions.showCopy",defaultValue:!0},{id:"msg-actions-upvote",label:"Show Upvote",type:"toggle",path:"messageActions.showUpvote",defaultValue:!0},{id:"msg-actions-downvote",label:"Show Downvote",type:"toggle",path:"messageActions.showDownvote",defaultValue:!0},{id:"msg-actions-visibility",label:"Visibility",type:"select",path:"messageActions.visibility",defaultValue:"hover",options:[{value:"hover",label:"On Hover"},{value:"always",label:"Always Visible"}]},{id:"msg-actions-align",label:"Alignment",type:"select",path:"messageActions.align",defaultValue:"right",options:[{value:"left",label:"Left"},{value:"right",label:"Right"}]},{id:"msg-actions-layout",label:"Layout",type:"select",path:"messageActions.layout",defaultValue:"pill-inside",options:[{value:"pill-inside",label:"Pill"},{value:"row-inside",label:"Row"}]}]},Sf={id:"launcher-basics",title:"Launcher",collapsed:!0,fields:[{id:"launch-enabled",label:"Enabled",type:"toggle",path:"launcher.enabled",defaultValue:!0},{id:"launch-mount-mode",label:"Mount Mode",type:"select",path:"launcher.mountMode",defaultValue:"floating",options:[{value:"floating",label:"Floating"},{value:"docked",label:"Docked"}]},{id:"launch-position",label:"Position",type:"select",path:"launcher.position",defaultValue:"bottom-right",options:[{value:"bottom-right",label:"Bottom Right"},{value:"bottom-left",label:"Bottom Left"},{value:"top-right",label:"Top Right"},{value:"top-left",label:"Top Left"}]},{id:"launch-width",label:"Width",type:"text",path:"launcher.width",defaultValue:go},{id:"launch-auto-expand",label:"Auto Expand",type:"toggle",path:"launcher.autoExpand",defaultValue:!1},{id:"launch-title",label:"Title",type:"text",path:"launcher.title",defaultValue:"Chat Assistant"},{id:"launch-subtitle",label:"Subtitle",type:"text",path:"launcher.subtitle",defaultValue:"Here to help you get answers fast"}]},Af={id:"launcher-advanced",title:"Launcher Advanced",collapsed:!0,fields:[{id:"launch-dock-side",label:"Dock Side",type:"select",path:"launcher.dock.side",defaultValue:"right",options:[{value:"right",label:"Right"},{value:"left",label:"Left"}]},{id:"launch-dock-width",label:"Dock Width",type:"text",path:"launcher.dock.width",defaultValue:"420px"},{id:"launch-dock-animate",label:"Dock Animate",type:"toggle",path:"launcher.dock.animate",defaultValue:!0},{id:"launch-dock-reveal",label:"Dock Reveal",type:"select",path:"launcher.dock.reveal",defaultValue:"resize",options:[{value:"resize",label:"Resize"},{value:"overlay",label:"Overlay"},{value:"push",label:"Push"},{value:"emerge",label:"Emerge"}]},{id:"launch-text-hidden",label:"Hide Text",type:"toggle",path:"launcher.textHidden",defaultValue:!1},{id:"launch-icon-text",label:"Agent Icon Text",type:"text",path:"launcher.agentIconText",defaultValue:"\u{1F4AC}"},{id:"launch-icon-name",label:"Agent Icon Name (Lucide)",type:"text",path:"launcher.agentIconName",defaultValue:"bot"},{id:"launch-icon-hidden",label:"Hide Agent Icon",type:"toggle",path:"launcher.agentIconHidden",defaultValue:!1},{id:"launch-icon-size",label:"Agent Icon Size",type:"slider",path:"launcher.agentIconSize",defaultValue:"40px",slider:{min:16,max:72,step:2}},{id:"launch-icon-url",label:"Icon Image URL",description:"Custom image URL (overrides emoji/lucide)",type:"text",path:"launcher.iconUrl",defaultValue:""},{id:"launch-header-icon-name",label:"Header Icon Name (Lucide)",type:"text",path:"launcher.headerIconName",defaultValue:"bot"},{id:"launch-header-icon-size",label:"Header Icon Size",type:"slider",path:"launcher.headerIconSize",defaultValue:"48px",slider:{min:24,max:80,step:2}},{id:"launch-header-icon-hidden",label:"Hide Header Icon",type:"toggle",path:"launcher.headerIconHidden",defaultValue:!1},{id:"launch-full-height",label:"Full Height",type:"toggle",path:"launcher.fullHeight",defaultValue:!1},{id:"launch-sidebar",label:"Sidebar Mode",type:"toggle",path:"launcher.sidebarMode",defaultValue:!1},{id:"launch-sidebar-width",label:"Sidebar Width",type:"text",path:"launcher.sidebarWidth",defaultValue:"420px"},{id:"launch-mobile-fullscreen",label:"Mobile Fullscreen",description:"Fullscreen on mobile devices",type:"toggle",path:"launcher.mobileFullscreen",defaultValue:!0},{id:"launch-mobile-breakpoint",label:"Mobile Breakpoint (px)",type:"text",path:"launcher.mobileBreakpoint",defaultValue:640,formatValue:e=>String(e!=null?e:640),parseValue:e=>Number(e)},{id:"launch-height-offset",label:"Height Offset (px)",type:"text",path:"launcher.heightOffset",defaultValue:0,formatValue:e=>String(e!=null?e:0),parseValue:e=>Number(e)},{id:"launch-collapsed-max-width",label:"Collapsed Max Width",description:"Max width of launcher pill when closed",type:"text",path:"launcher.collapsedMaxWidth",defaultValue:""},{id:"launch-cta-text",label:"CTA Icon Text",type:"text",path:"launcher.callToActionIconText",defaultValue:"\u2197"},{id:"launch-cta-name",label:"CTA Icon Name",type:"text",path:"launcher.callToActionIconName",defaultValue:""},{id:"launch-cta-hidden",label:"Hide CTA Icon",type:"toggle",path:"launcher.callToActionIconHidden",defaultValue:!1},{id:"launch-cta-size",label:"CTA Icon Size",type:"slider",path:"launcher.callToActionIconSize",defaultValue:"32px",slider:{min:16,max:64,step:2}},{id:"launch-cta-padding",label:"CTA Icon Padding",type:"slider",path:"launcher.callToActionIconPadding",defaultValue:"5px",slider:{min:0,max:24,step:1}},{id:"launch-cta-bg",label:"CTA Icon Background",type:"color",path:"launcher.callToActionIconBackgroundColor",defaultValue:""}]},Tf={id:"send-button",title:"Send Button",collapsed:!0,fields:[{id:"send-use-icon",label:"Use Icon",type:"toggle",path:"sendButton.useIcon",defaultValue:!1},{id:"send-icon-text",label:"Icon Text",type:"text",path:"sendButton.iconText",defaultValue:"\u2191"},{id:"send-icon-name",label:"Icon Name (Lucide)",type:"text",path:"sendButton.iconName",defaultValue:""},{id:"send-size",label:"Size",type:"slider",path:"sendButton.size",defaultValue:"40px",slider:{min:24,max:64,step:2}},{id:"send-border-width",label:"Border Width",type:"slider",path:"sendButton.borderWidth",defaultValue:"0px",slider:{min:0,max:10,step:1}},{id:"send-padding-x",label:"Padding X",type:"slider",path:"sendButton.paddingX",defaultValue:"10px",slider:{min:0,max:32,step:1}},{id:"send-padding-y",label:"Padding Y",type:"slider",path:"sendButton.paddingY",defaultValue:"6px",slider:{min:0,max:32,step:1}},{id:"send-show-tooltip",label:"Show Tooltip",type:"toggle",path:"sendButton.showTooltip",defaultValue:!1},{id:"send-tooltip-text",label:"Tooltip Text",type:"text",path:"sendButton.tooltipText",defaultValue:"Send message"}]},kf={id:"close-button",title:"Close Button",collapsed:!0,fields:[{id:"close-size",label:"Size",type:"slider",path:"launcher.closeButtonSize",defaultValue:"32px",slider:{min:16,max:64,step:1}},{id:"close-placement",label:"Placement",type:"select",path:"launcher.closeButtonPlacement",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"top-right",label:"Top Right"}]},{id:"close-border-width",label:"Border Width",type:"slider",path:"launcher.closeButtonBorderWidth",defaultValue:"0px",slider:{min:0,max:8,step:1}},{id:"close-border-radius",label:"Border Radius",type:"slider",path:"launcher.closeButtonBorderRadius",defaultValue:"50%",slider:{min:0,max:100,step:1,isRadiusFull:!0}},{id:"close-icon-name",label:"Icon Name",type:"text",path:"launcher.closeButtonIconName",defaultValue:"x"},{id:"close-icon-text",label:"Icon Text",type:"text",path:"launcher.closeButtonIconText",defaultValue:"\xD7"},{id:"close-show-tooltip",label:"Show Tooltip",type:"toggle",path:"launcher.closeButtonShowTooltip",defaultValue:!0},{id:"close-tooltip-text",label:"Tooltip Text",type:"text",path:"launcher.closeButtonTooltipText",defaultValue:"Close chat"}]},Ef={id:"clear-chat",title:"Clear Chat Button",collapsed:!0,fields:[{id:"clear-enabled",label:"Enabled",type:"toggle",path:"launcher.clearChat.enabled",defaultValue:!0},{id:"clear-placement",label:"Placement",type:"select",path:"launcher.clearChat.placement",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"top-right",label:"Top Right"}]},{id:"clear-icon-name",label:"Icon Name",type:"text",path:"launcher.clearChat.iconName",defaultValue:"refresh-cw"},{id:"clear-size",label:"Size",type:"slider",path:"launcher.clearChat.size",defaultValue:"32px",slider:{min:16,max:64,step:1}},{id:"clear-show-tooltip",label:"Show Tooltip",type:"toggle",path:"launcher.clearChat.showTooltip",defaultValue:!0},{id:"clear-tooltip-text",label:"Tooltip Text",type:"text",path:"launcher.clearChat.tooltipText",defaultValue:"Clear chat"}]},Mf={id:"status-indicator",title:"Status Indicator",collapsed:!0,fields:[{id:"status-visible",label:"Visible",type:"toggle",path:"statusIndicator.visible",defaultValue:!0},{id:"status-align",label:"Alignment",type:"select",path:"statusIndicator.align",defaultValue:"right",options:[{value:"left",label:"Left"},{value:"center",label:"Center"},{value:"right",label:"Right"}]},{id:"status-idle-text",label:"Idle Text",type:"text",path:"statusIndicator.idleText",defaultValue:"Online"},{id:"status-connecting-text",label:"Connecting Text",type:"text",path:"statusIndicator.connectingText",defaultValue:"Connecting\u2026"},{id:"status-connected-text",label:"Connected Text",type:"text",path:"statusIndicator.connectedText",defaultValue:"Streaming\u2026"},{id:"status-error-text",label:"Error Text",type:"text",path:"statusIndicator.errorText",defaultValue:"Offline"}]},Lf={id:"features",title:"Features",collapsed:!0,fields:[{id:"feat-voice",label:"Voice Recognition",description:"Enable voice input",type:"toggle",path:"voiceRecognition.enabled",defaultValue:!1},{id:"feat-auto-focus",label:"Auto Focus Input",description:"Focus input after panel opens",type:"toggle",path:"autoFocusInput",defaultValue:!1},{id:"feat-scroll-bottom-enabled",label:"Scroll To Bottom",description:"Show a jump-to-latest affordance when the user scrolls away from new content",type:"toggle",path:"features.scrollToBottom.enabled",defaultValue:!0},{id:"feat-scroll-bottom-icon",label:"Scroll To Bottom Icon",type:"text",path:"features.scrollToBottom.iconName",defaultValue:"arrow-down"},{id:"feat-scroll-bottom-label",label:"Scroll To Bottom Label",description:"Leave empty for icon-only mode",type:"text",path:"features.scrollToBottom.label",defaultValue:""}]},If={id:"stream-animation",title:"Stream Animation",description:"Control how assistant text appears while streaming.",collapsed:!0,fields:[{id:"stream-anim-type",label:"Animation",description:"Reveal effect applied to each assistant reply as it streams.",type:"select",path:"features.streamAnimation.type",defaultValue:"none",options:[{value:"none",label:"None"},{value:"typewriter",label:"Typewriter"},{value:"word-fade",label:"Word fade"},{value:"letter-rise",label:"Letter rise"},{value:"glyph-cycle",label:"Glyph cycle"},{value:"wipe",label:"Wipe"},{value:"pop-bubble",label:"Pop bubble"}]},{id:"stream-anim-placeholder",label:"Pre-first-token Placeholder",description:"What to show before the first token arrives.",type:"select",path:"features.streamAnimation.placeholder",defaultValue:"none",options:[{value:"none",label:"Typing indicator (default)"},{value:"skeleton",label:"Skeleton shimmer"}]},{id:"stream-anim-buffer",label:"Content Buffering",description:"Trim in-progress units so only complete words/lines reveal.",type:"select",path:"features.streamAnimation.buffer",defaultValue:"none",options:[{value:"none",label:"None \u2014 stream every character"},{value:"word",label:"Word \u2014 hold until whitespace"},{value:"line",label:"Line \u2014 hold until newline"}]},{id:"stream-anim-speed",label:"Per-unit Duration (ms)",description:"Animation length for each character or word.",type:"select",path:"features.streamAnimation.speed",defaultValue:120,options:[{value:"40",label:"40ms \u2014 snappy"},{value:"80",label:"80ms"},{value:"120",label:"120ms (default)"},{value:"200",label:"200ms"},{value:"320",label:"320ms"},{value:"480",label:"480ms \u2014 slow"}],formatValue:e=>String(e!=null?e:120),parseValue:e=>Number(e)},{id:"stream-anim-duration",label:"Container Duration (ms)",description:"Length of container-level effects (pop-bubble, custom plugins).",type:"select",path:"features.streamAnimation.duration",defaultValue:1800,options:[{value:"600",label:"600ms"},{value:"1200",label:"1200ms"},{value:"1800",label:"1800ms (default)"},{value:"2400",label:"2400ms"},{value:"3600",label:"3600ms \u2014 slow"}],formatValue:e=>String(e!=null?e:1800),parseValue:e=>Number(e)}]},Rf={id:"attachments-config",title:"Attachments",collapsed:!0,fields:[{id:"attach-enabled",label:"Enabled",type:"toggle",path:"attachments.enabled",defaultValue:!1},{id:"attach-max-files",label:"Max Files",type:"select",path:"attachments.maxFiles",defaultValue:4,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"4",label:"4"},{value:"6",label:"6"},{value:"8",label:"8"},{value:"10",label:"10"}],formatValue:e=>String(e!=null?e:4),parseValue:e=>Number(e)},{id:"attach-max-size",label:"Max File Size (MB)",type:"select",path:"attachments.maxFileSize",defaultValue:10*il,options:[{value:"1",label:"1 MB"},{value:"5",label:"5 MB"},{value:"10",label:"10 MB"},{value:"25",label:"25 MB"},{value:"50",label:"50 MB"}],formatValue:gf,parseValue:mf},{id:"attach-types",label:"Allowed File Types",type:"select",path:"attachments.allowedTypes",defaultValue:Bs.images,options:[{value:"images",label:"Images only"},{value:"images-pdf",label:"Images + PDF"},{value:"images-text-pdf",label:"Images + text + PDF"},{value:"all",label:"All supported types"}],formatValue:hf,parseValue:ff}]},Pf={id:"artifacts-config",title:"Artifacts",collapsed:!0,fields:[{id:"art-enabled",label:"Enabled",description:"Show artifact sidebar for documents and components",type:"toggle",path:"features.artifacts.enabled",defaultValue:!1},{id:"art-appearance",label:"Pane Appearance",type:"select",path:"features.artifacts.layout.paneAppearance",defaultValue:"panel",options:[{value:"panel",label:"Panel (bordered)"},{value:"seamless",label:"Seamless"}]}]},Wf={id:"artifacts-customization",title:"Artifact Customization",collapsed:!0,fields:[{id:"art-toolbar",label:"Toolbar Preset",type:"select",path:"features.artifacts.layout.toolbarPreset",defaultValue:"default",options:[{value:"default",label:"Default"},{value:"document",label:"Document"}]},{id:"art-pane-width",label:"Pane Width",description:"CSS width (e.g. 40%, 28rem)",type:"text",path:"features.artifacts.layout.paneWidth",defaultValue:"40%"},{id:"art-pane-max-width",label:"Pane Max Width",type:"text",path:"features.artifacts.layout.paneMaxWidth",defaultValue:"28rem"},{id:"art-split-gap",label:"Split Gap",type:"text",path:"features.artifacts.layout.splitGap",defaultValue:"0.5rem"},{id:"art-pane-bg",label:"Pane Background",type:"color",path:"features.artifacts.layout.paneBackground",defaultValue:""},{id:"art-unified",label:"Unified Split Chrome",description:"Wrap chat and artifact in a single container",type:"toggle",path:"features.artifacts.layout.unifiedSplitChrome",defaultValue:!1},{id:"art-resizable",label:"Resizable",description:"Allow dragging the pane divider",type:"toggle",path:"features.artifacts.layout.resizable",defaultValue:!1},{id:"art-expand-panel",label:"Expand Panel When Open",description:"Widen the launcher panel to fit artifacts",type:"toggle",path:"features.artifacts.layout.expandLauncherPanelWhenOpen",defaultValue:!0}]},Bf={id:"api-integration",title:"API & Integration",description:"Runtime and integration options.",collapsed:!0,fields:[{id:"dev-api-url",label:"API URL",type:"text",path:"apiUrl",defaultValue:""},{id:"dev-flow",label:"Flow ID",type:"text",path:"flowId",defaultValue:""},{id:"dev-parser",label:"Stream Parser",type:"select",path:"parserType",defaultValue:"plain",options:[{value:"plain",label:"Plain Text"},{value:"json",label:"JSON"},{value:"regex-json",label:"Regex JSON"},{value:"xml",label:"XML"}]}]},Hf={id:"debug-inspection",title:"Debug & Inspection",collapsed:!0,fields:[{id:"dev-reasoning",label:"Show Reasoning",description:"Display AI reasoning steps",type:"toggle",path:"features.showReasoning",defaultValue:!1},{id:"dev-tool-calls",label:"Show Tool Calls",description:"Display tool call details",type:"toggle",path:"features.showToolCalls",defaultValue:!1},{id:"dev-tool-collapsed-mode",label:"Tool Call Summary",description:"Choose what collapsed tool rows show by default",type:"select",path:"features.toolCallDisplay.collapsedMode",defaultValue:"tool-call",options:[{value:"tool-call",label:"Tool Call"},{value:"tool-name",label:"Tool Name"},{value:"tool-preview",label:"Tool Preview"}]},{id:"dev-tool-active-preview",label:"Tool Preview While Active",description:"Show a lightweight preview in collapsed active tool rows",type:"toggle",path:"features.toolCallDisplay.activePreview",defaultValue:!1},{id:"dev-tool-preview-lines",label:"Tool Preview Lines",type:"select",path:"features.toolCallDisplay.previewMaxLines",defaultValue:3,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"3",label:"3"},{value:"4",label:"4"},{value:"5",label:"5"}],formatValue:e=>String(e!=null?e:3),parseValue:e=>Number(e)},{id:"dev-tool-active-min-height",label:"Tool Active Min Height",description:"CSS min-height for collapsed active tool rows (e.g. 5rem)",type:"text",path:"features.toolCallDisplay.activeMinHeight",defaultValue:""},{id:"dev-tool-expandable",label:"Tool Calls Expandable",description:"Allow expanding tool call rows to see full details",type:"toggle",path:"features.toolCallDisplay.expandable",defaultValue:!0},{id:"dev-tool-grouped",label:"Group Sequential Tool Calls",description:"Render consecutive tool rows inside a grouped container",type:"toggle",path:"features.toolCallDisplay.grouped",defaultValue:!1},{id:"dev-reasoning-expandable",label:"Reasoning Expandable",description:"Allow expanding reasoning rows to see full details",type:"toggle",path:"features.reasoningDisplay.expandable",defaultValue:!0},{id:"dev-reasoning-active-preview",label:"Reasoning Preview While Active",description:"Show a lightweight preview in collapsed active reasoning rows",type:"toggle",path:"features.reasoningDisplay.activePreview",defaultValue:!1},{id:"dev-reasoning-preview-lines",label:"Reasoning Preview Lines",type:"select",path:"features.reasoningDisplay.previewMaxLines",defaultValue:3,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"3",label:"3"},{value:"4",label:"4"},{value:"5",label:"5"}],formatValue:e=>String(e!=null?e:3),parseValue:e=>Number(e)},{id:"dev-reasoning-active-min-height",label:"Reasoning Active Min Height",description:"CSS min-height for collapsed active reasoning rows (e.g. 5rem)",type:"text",path:"features.reasoningDisplay.activeMinHeight",defaultValue:""},{id:"dev-debug",label:"Debug Mode",description:"Show debug information",type:"toggle",path:"debug",defaultValue:!1}]},Df={id:"markdown",title:"Markdown Options",collapsed:!0,fields:[{id:"md-gfm",label:"GitHub Flavored Markdown",type:"toggle",path:"markdown.options.gfm",defaultValue:!0},{id:"md-breaks",label:"Line Breaks",type:"toggle",path:"markdown.options.breaks",defaultValue:!0},{id:"md-header-ids",label:"Header IDs",type:"toggle",path:"markdown.options.headerIds",defaultValue:!1},{id:"md-pedantic",label:"Pedantic Mode",type:"toggle",path:"markdown.options.pedantic",defaultValue:!1},{id:"md-silent",label:"Silent",type:"toggle",path:"markdown.options.silent",defaultValue:!1},{id:"md-disable-styles",label:"Disable Default Styles",type:"toggle",path:"markdown.disableDefaultStyles",defaultValue:!1}]},Ua=[{label:"Content",sections:[bf,yf]},{label:"Layout",sections:[vf,xf,wf,Cf]},{label:"Widget",sections:[Sf,Af,Tf,kf,Ef,Mf]},{label:"Features",sections:[Lf,If,Rf,Pf,Wf]},{label:"Developer",collapsedByDefault:!0,sections:[Bf,Hf,Df]}],vu=Ua.flatMap(e=>e.sections),xu={id:"theme-mode-v2",title:"Theme",description:"Choose how the interface adapts across light and dark mode.",collapsed:!1,fields:[{id:"color-mode",label:"Color Mode",type:"select",path:"colorScheme",defaultValue:"auto",options:[{value:"auto",label:"Auto"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}]}]},wu={id:"brand-palette-v2",title:"Brand Palette",description:"Set your brand, accent, and neutral colors. These are used to generate the interface theme.",collapsed:!1,fields:[{id:"bp-primary",label:"Primary",description:"Main brand color",type:"color",path:"theme.palette.colors.primary.500",defaultValue:"#171717"},{id:"bp-secondary",label:"Secondary",description:"Supporting brand color",type:"color",path:"theme.palette.colors.secondary.500",defaultValue:"#8b5cf6"},{id:"bp-accent",label:"Accent",description:"Highlight and decorative color",type:"color",path:"theme.palette.colors.accent.500",defaultValue:"#06b6d4"},{id:"bp-neutral",label:"Neutral",description:"Backgrounds, text, and borders",type:"color",path:"theme.palette.colors.gray.500",defaultValue:"#6b7280"}]},Cu={id:"status-palette",title:"Status Palette",description:"Colors for system feedback states.",collapsed:!0,fields:[{id:"sp-success",label:"Success",type:"color",path:"theme.palette.colors.success.500",defaultValue:"#22c55e"},{id:"sp-warning",label:"Warning",type:"color",path:"theme.palette.colors.warning.500",defaultValue:"#eab308"},{id:"sp-error",label:"Error",type:"color",path:"theme.palette.colors.error.500",defaultValue:"#ef4444"},{id:"sp-notice",label:"Notice",description:"Info and notice states",type:"color",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500"}]},Su={id:"interface-roles",title:"Interface Roles",description:"Control where brand and neutral colors appear across the interface.",collapsed:!1,fields:[{id:"role-surfaces",label:"Background Surfaces",type:"role-assignment",path:"theme.semantic.colors.background",roleAssignment:Wa},{id:"role-header",label:"Header",type:"role-assignment",path:"theme.components.header.background",roleAssignment:Ba},{id:"role-user-messages",label:"User Messages",type:"role-assignment",path:"theme.components.message.user.background",roleAssignment:Ha},{id:"role-assistant-messages",label:"Assistant Messages",type:"role-assignment",path:"theme.components.message.assistant.background",roleAssignment:Da},{id:"role-primary-actions",label:"Primary Actions",type:"role-assignment",path:"theme.components.button.primary.background",roleAssignment:Fa},{id:"role-scroll-to-bottom",label:"Scroll To Bottom",type:"role-assignment",path:"theme.components.scrollToBottom.background",roleAssignment:Oa},{id:"role-input",label:"Input Field",type:"role-assignment",path:"theme.components.input.background",roleAssignment:Na},{id:"role-links-focus",label:"Links & Focus",type:"role-assignment",path:"theme.semantic.colors.accent",roleAssignment:_a},{id:"role-borders",label:"Borders & Dividers",type:"role-assignment",path:"theme.semantic.colors.border",roleAssignment:Va}]},Au={id:"status-colors",title:"Status Colors",description:"Used for system states like success, warning, notice, and error.",collapsed:!0,fields:[{id:"sc-notice",label:"Notice",type:"token-ref",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sc-success",label:"Success",type:"token-ref",path:"theme.semantic.colors.feedback.success",defaultValue:"palette.colors.success.500",tokenRef:{tokenType:"color"}},{id:"sc-warning",label:"Warning",type:"token-ref",path:"theme.semantic.colors.feedback.warning",defaultValue:"palette.colors.warning.500",tokenRef:{tokenType:"color"}},{id:"sc-error",label:"Error",type:"token-ref",path:"theme.semantic.colors.feedback.error",defaultValue:"palette.colors.error.500",tokenRef:{tokenType:"color"}}]},Tu={id:"advanced-tokens",title:"Advanced Tokens",description:"Override individual semantic and component values when you need precise control.",collapsed:!0,fields:[]},Ff=[xu,wu,Cu,Su,Au,Tu],ll=[{id:"style",label:"Style",sections:Xr},{id:"design-system",label:"Design System",sections:yu},{id:"configure",label:"Configure",sections:vu}];function ku(e,t){return e.startsWith("theme.")?e.replace(/^theme\./,`${t}.`):e}function Of(e,t,n){return{...e,id:`${n}-${e.id}`,path:ku(e.path,t)}}function Nf(e,t){let n=e.find(o=>o.id===t);if(!n)throw new Error(`Section "${t}" not found in definitions`);return n}function _f(e,t,n,o=e.collapsed){var a;let r=n==="light"?"Light":"Dark",s=n==="light"?"Applies when the widget is in light mode.":"Applies when the widget is in dark mode.";return{...e,id:`${n}-${e.id}`,title:`${r} ${e.title}`,description:e.description?`${s} ${e.description}`:s,collapsed:o,fields:e.fields.map(i=>Of(i,t,n)),presets:(a=e.presets)==null?void 0:a.map(i=>({...i,id:`${n}-${i.id}`,values:Object.fromEntries(Object.entries(i.values).map(([d,l])=>[ku(d,t),l]))}))}}var Eu=[{id:"default-light",name:"Default Light",description:"Clean monochrome light theme",theme:{components:{artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}}},preview:{primary:"#171717",surface:"#ffffff",accent:"#0f0f0f"},tags:["light"]},{id:"default-dark",name:"Default Dark",description:"Monochrome dark theme",theme:{palette:{colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},semantic:{colors:{primary:"palette.colors.primary.400",secondary:"palette.colors.gray.400",accent:"palette.colors.primary.500",surface:"palette.colors.gray.800",background:"palette.colors.gray.900",container:"palette.colors.gray.800",text:"palette.colors.gray.100",textMuted:"palette.colors.gray.400",textInverse:"palette.colors.gray.900",border:"palette.colors.gray.700",divider:"palette.colors.gray.700",interactive:{default:"palette.colors.primary.400",hover:"palette.colors.primary.300",focus:"palette.colors.primary.500",active:"palette.colors.primary.600",disabled:"palette.colors.gray.600"},feedback:{success:"palette.colors.success.400",warning:"palette.colors.warning.400",error:"palette.colors.error.400",info:"palette.colors.primary.400"}}}},preview:{primary:"#171717",surface:"#1f2937",accent:"#0f0f0f"},tags:["dark"]},{id:"high-contrast",name:"High Contrast",description:"Maximum contrast for accessibility",theme:{semantic:{colors:{primary:"palette.colors.primary.700",secondary:"palette.colors.gray.700",accent:"palette.colors.primary.800",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.200",text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.400",divider:"palette.colors.gray.400",interactive:{default:"palette.colors.primary.700",hover:"palette.colors.primary.800",focus:"palette.colors.primary.900",active:"palette.colors.primary.950",disabled:"palette.colors.gray.400"},feedback:{success:"palette.colors.success.700",warning:"palette.colors.warning.700",error:"palette.colors.error.700",info:"palette.colors.primary.700"}}}},preview:{primary:"#0a0a0a",surface:"#f9fafb",accent:"#050505"},tags:["light","high-contrast","accessibility"]}],Hs=[...Eu];function cl(e){return Hs.find(t=>t.id===e)}import{Marked as Vf}from"marked";var $f=e=>{if(e)return e},dl=e=>{var r,s;let t=e==null?void 0:e.markedOptions,n=new Vf({gfm:(r=t==null?void 0:t.gfm)!=null?r:!0,breaks:(s=t==null?void 0:t.breaks)!=null?s:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),o=$f(e==null?void 0:e.renderer);return o&&n.use({renderer:o}),a=>n.parse(a)},za=e=>e?dl({markedOptions:e.options,renderer:e.renderer}):dl(),gw=dl();var Ds=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");import Uf from"dompurify";var zf={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},qf=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,jf=()=>{let e=Uf(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(t,n)=>{if(n.attrName==="src"||n.attrName==="href"){let o=n.attrValue;o.toLowerCase().startsWith("data:")&&!qf.test(o)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,zf)},qa=e=>e===!1?null:typeof e=="function"?e:jf();var Tr="webmcp:",pl=new Map,Mu=e=>{var t;pl.clear();for(let n of e){let o=(t=n.title)==null?void 0:t.trim();o&&pl.set(n.name,o)}},ul=e=>pl.get(Ru(e)),ja={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function Iu(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var o,r;return[n.name,(o=n.description)!=null?o:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(r=n.origin)!=null?r:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${Kf(t.join(""))}`}function Lu(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function Kf(e){let t=Lu(e,0).toString(36),n=Lu(e,2654435761).toString(36);return`${t}.${n}`}var Ka=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return ja.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",r),[]}Mu(n);let o=typeof location!="undefined"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=Yf(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return To("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let C=typeof document!="undefined"&&!!document.modelContext;return To(C?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=Ru(t),a;try{a=await r.getTools()}catch(C){let v=C instanceof Error?C.message:String(C);return To(`Failed to read WebMCP registry: ${v}`)}Mu(a);let i=a.find(C=>C.name===s);if(!i)return To(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return To(`WebMCP tool not allowed by client allowlist: ${s}`);if(o!=null&&o.aborted)return To("Aborted by cancel()");let d=ul(s),l={toolName:s,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(l))return To("User declined the tool call.");if(o!=null&&o.aborted)return To("Aborted by cancel()");let m=new AbortController,p=!1,f=setTimeout(()=>{p=!0,m.abort()},this.timeoutMs),u=()=>m.abort();o&&(o.aborted?m.abort():o.addEventListener("abort",u,{once:!0}));try{let C=await r.executeTool(i,Zf(n),{signal:m.signal});return Xf(C)}catch(C){if(p)return To(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return To("Aborted by cancel()");let v=C instanceof Error?C.message:String(C);return To(v)}finally{clearTimeout(f),o&&o.removeEventListener("abort",u)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){ja.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,ja.warn("document.modelContext is present but does not expose getTools()/executeTool() \u2014 WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var o;let n=(o=this.confirmHandler)!=null?o:Qf;try{return await n(t)}catch(r){return ja.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,r),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>Gf(t,o))}},Ru=e=>e.startsWith(Tr)?e.slice(Tr.length):e,Qr=e=>e.startsWith(Tr),Gf=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Yf=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Xf=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:eh(t)}]}},To=e=>({isError:!0,content:[{type:"text",text:e}]}),Qf=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Jf(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
2
2
 
3
3
  Arguments:
4
4
  ${t}`:"")+(e.description?`
5
5
 
6
- ${e.description}`:"");return window.confirm(n)},Ff=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},Of=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Nf=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};import{parse as _f,STR as Vf,OBJ as $f}from"partial-json";var Cu=e=>e.replace(/\\n/g,`
7
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),qr=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Uf=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Su=e=>e.status==="complete"?Uf(e):e.status==="pending"?"Waiting":"",zf=e=>{var r,s,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((a=(s=e.startedAt)!=null?s:e.completedAt)!=null?a:Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var Au=e=>e.status==="complete"?zf(e):"Using tool...",za=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Rs=e=>{var n,o,r;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((r=(o=e.startedAt)!=null?o:e.completedAt)!=null?r:Date.now()));return za(t)},qa=e=>{var n,o,r;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((r=(o=e.startedAt)!=null?o:e.completedAt)!=null?r:Date.now()));return za(t)},al=(e,t,n)=>{var s;if(!t)return n;let o=((s=e.name)==null?void 0:s.trim())||"tool",r=Rs(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},ja=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Is(o,n.slice(s,a.index),[]),a[1]!==void 0?Is(o,a[1],["bold"]):a[2]!==void 0?Is(o,a[2],["italic"]):a[3]!==void 0&&Is(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Is(o,n.slice(s),[]),o},Is=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},qf=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
6
+ ${e.description}`:"");return window.confirm(n)},Jf=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},Zf=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},eh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};import{parse as th,STR as nh,OBJ as oh}from"partial-json";var Pu=e=>e.replace(/\\n/g,`
7
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Jr=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},rh=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Wu=e=>e.status==="complete"?rh(e):e.status==="pending"?"Waiting":"",sh=e=>{var r,s,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((a=(s=e.startedAt)!=null?s:e.completedAt)!=null?a:Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var Bu=e=>e.status==="complete"?sh(e):"Using tool...",Ga=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Os=e=>{var n,o,r;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((r=(o=e.startedAt)!=null?o:e.completedAt)!=null?r:Date.now()));return Ga(t)},Ya=e=>{var n,o,r;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((r=(o=e.startedAt)!=null?o:e.completedAt)!=null?r:Date.now()));return Ga(t)},ml=(e,t,n)=>{var s;if(!t)return n;let o=((s=e.name)==null?void 0:s.trim())||"tool",r=Os(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},Xa=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Fs(o,n.slice(s,a.index),[]),a[1]!==void 0?Fs(o,a[1],["bold"]):a[2]!==void 0?Fs(o,a[2],["italic"]):a[3]!==void 0&&Fs(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Fs(o,n.slice(s),[]),o},Fs=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},ah=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
8
8
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=o.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
9
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Cr=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Tu=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ku=()=>{var t;let e=qf();return{processChunk:async n=>{let o=n.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},Eu=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=_f(n,Vf|$f);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Cu(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Cu(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var Mu=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Ka=class{constructor(t,n=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=n}push(t,n){var s,a,i;let o=(i=(s=n==null?void 0:n.seq)!=null?s:n==null?void 0:n.sequenceIndex)!=null?i:(a=n==null?void 0:n.agentContext)==null?void 0:a.seq;if(o==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,n);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),o===this.nextExpectedSeq){this.emitter(t,n),this.nextExpectedSeq=o+1,this.drainConsecutive();return}if(o<this.nextExpectedSeq){this.emitter(t,n);return}let r=this.buffer.get(o);r!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${o} (${r.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(r.payloadType,r.payload)),this.buffer.set(o,{payloadType:t,payload:n,seq:o}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((n,o)=>n[0]-o[0]);for(let[n,o]of t)this.buffer.delete(n),this.emitter(o.payloadType,o.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var jf="https://api.runtype.com/v1/dispatch",Ga="https://api.runtype.com";function Kf(e){var s,a;let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let i=(a=(s=t.slice(r+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var il=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Gf(e){switch(e){case"json":return Eu;case"regex-json":return ku;case"xml":return Mu;default:return Tu}}var Lu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Yf(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=Lu(n);if(!Lu(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Cr(e);return Cr(t)!==null&&a===null?t:e}var Ps=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,o,r,s;this.apiUrl=(n=t.apiUrl)!=null?n:jf,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:Gf(t.parserType),this.contextProviders=(r=t.contextProviders)!=null?r:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new Ua(t.webmcp):null}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ga}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let o=await this.sessionInitPromise;return this.clientSession=o,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,o),o}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let t=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},o=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){let i=await o.json().catch(()=>({error:"Session initialization failed"}));throw o.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):o.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let r=await o.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(r.sessionId),{sessionId:r.sessionId,expiresAt:new Date(r.expiresAt),flow:r.flow,config:{welcomeMessage:r.config.welcomeMessage,placeholder:r.config.placeholder,theme:r.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ga}/v1/client/feedback`}async sendFeedback(t){var s,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var r,s,a,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(r=this.config).onSessionExpired)==null||s.call(r);let D=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:D}),D}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([D])=>D!=="sessionId"&&D!=="session_id")):void 0,m={sessionId:d.sessionId,messages:t.messages.filter(il).map(D=>{var B,v,x;return{id:D.id,role:D.role,content:(x=(v=(B=D.contentParts)!=null?B:D.llmContent)!=null?v:D.rawContent)!=null?x:D.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},f=l.clientTools,u=!!(f&&f.length>0),w=u?wu(f):void 0,C=this.clientToolsFingerprintSessionId===d.sessionId,M=u&&C&&this.lastSentClientToolsFingerprint===w,I=!1,R=null,H;for(let D=0;;D++){let v={...m,...u&&(I||!M)&&f?{clientTools:f}:{},...w?{clientToolsFingerprint:w}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",v),H=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v),signal:o.signal}),H.status===409&&D===0&&u){let x=await H.json().catch(()=>null);if((x==null?void 0:x.error)==="client_tools_resend_required"){I=!0,this.lastSentClientToolsFingerprint=null;continue}R=x!=null?x:{error:"Chat request failed"}}break}if(!H.ok){let D=R!=null?R:await H.json().catch(()=>({error:"Chat request failed"}));if(H.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let v=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:v}),v}if(H.status===429){let v=new Error(D.hint||"Message limit reached for this session.");throw n({type:"error",error:v}),v}let B=new Error(D.error||"Failed to send message");throw n({type:"error",error:B}),B}if(!H.body){let D=new Error("No response body received");throw n({type:"error",error:D}),D}this.lastSentClientToolsFingerprint=w!=null?w:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(H.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let r=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ga}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,o){var l,p;let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Ga}/resume`,a;r&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=o==null?void 0:o.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var s;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(il).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),o={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},r=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(r&&r.length>0&&(o.clientTools=r),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(o.context=a)}return o}async buildPayload(t){var s;let o={messages:t.slice().filter(il).sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},r=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(r&&r.length>0&&(o.clientTools=r),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(o.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...o},config:this.config});if(a&&typeof a=="object"){let i=a;return o.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=o.clientTools),i}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return o}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return o.current=m,r(m),m},l=p=>o.current?o.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,r(p)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o){var ln,Dn,Jn,ze;let r=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=_=>{let ke=_.reasoning?{..._.reasoning,chunks:[..._.reasoning.chunks]}:void 0,He=_.toolCall?{..._.toolCall,chunks:_.toolCall.chunks?[..._.toolCall.chunks]:void 0}:void 0,De=_.tools?_.tools.map(Ve=>({...Ve,chunks:Ve.chunks?[...Ve.chunks]:void 0})):void 0;return{..._,reasoning:ke,toolCall:He,tools:De}},m=_=>{if(_.role!=="assistant"||_.variant)return!0;let ke=Array.isArray(_.contentParts)&&_.contentParts.length>0,He=typeof _.rawContent=="string"&&_.rawContent.trim()!=="";return typeof _.content=="string"&&_.content.trim()!==""||ke||He||!!_.stopReason},f=_=>{m(_)&&n({type:"message",message:p(_)})},u=null,w=null,C={current:null},M={current:null},I=!1,R=new Map,H=new Map,D=new Map,B=new Map,v={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},k=(_,ke,He="")=>`${_}::${ke}::${He}`,S=(_,ke)=>`${_}::${ke}::`,E=(_,ke,He,De)=>{let Ve=k(_,ke,He),dt=D.get(Ve);if(dt)return dt;let ot=He?`-${He}`:"",At={id:`nested-${_}-${ke}${ot}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...He?{partId:He}:{},agentMetadata:{executionId:De,parentToolId:_,parentStepId:ke}};return D.set(Ve,At),f(At),At},F=_=>{if(_==null)return null;try{return String(_)}catch{return null}},$=_=>{var ke,He,De,Ve,dt;return F((dt=(Ve=(De=(He=(ke=_.stepId)!=null?ke:_.step_id)!=null?He:_.step)!=null?De:_.parentId)!=null?Ve:_.flowStepId)!=null?dt:_.flow_step_id)},j=_=>{var ke,He,De,Ve,dt,ot,At;return F((At=(ot=(dt=(Ve=(De=(He=(ke=_.callId)!=null?ke:_.call_id)!=null?He:_.requestId)!=null?De:_.request_id)!=null?Ve:_.toolCallId)!=null?dt:_.tool_call_id)!=null?ot:_.stepId)!=null?At:_.step_id)},me=o,se=!1,ge=()=>{if(u)return u;let _;return!se&&me?(_=me,se=!0):me&&M.current?_=`${me}_${M.current}`:_=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,u={id:_,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(u),u},ie=(_,ke)=>{v.lastId=ke,_&&v.byStep.set(_,ke)},be=(_,ke)=>{var dt;let He=(dt=_.reasoningId)!=null?dt:_.id,De=$(_);if(He){let ot=String(He);return ie(De,ot),ot}if(De){let ot=v.byStep.get(De);if(ot)return v.lastId=ot,ot}if(v.lastId&&!ke)return v.lastId;if(!ke)return null;let Ve=`reason-${l()}`;return ie(De,Ve),Ve},Fe=_=>{let ke=R.get(_);if(ke)return ke;let He={id:`reason-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:_,status:"streaming",chunks:[]}};return R.set(_,He),f(He),He},ve=(_,ke)=>{x.lastId=ke,_&&x.byCall.set(_,ke)},J=new Set,Le=new Map,Y=new Set,xe=new Map,Se=_=>{if(!_)return!1;let ke=_.replace(/_+/g,"_").replace(/^_|_$/g,"");return ke==="emit_artifact_markdown"||ke==="emit_artifact_component"},de=(_,ke)=>{var dt;let He=(dt=_.toolId)!=null?dt:_.id,De=j(_);if(He){let ot=String(He);return ve(De,ot),ot}if(De){let ot=x.byCall.get(De);if(ot)return x.lastId=ot,ot}if(x.lastId&&!ke)return x.lastId;if(!ke)return null;let Ve=`tool-${l()}`;return ve(De,Ve),Ve},we=_=>{let ke=H.get(_);if(ke)return ke;let He={id:`tool-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:_,status:"pending"}};return H.set(_,He),f(He),He},Ue=_=>{if(typeof _=="number"&&Number.isFinite(_))return _;if(typeof _=="string"){let ke=Number(_);if(!Number.isNaN(ke)&&Number.isFinite(ke))return ke;let He=Date.parse(_);if(!Number.isNaN(He))return He}return Date.now()},te=_=>{if(typeof _=="string")return _;if(_==null)return"";try{return JSON.stringify(_)}catch{return String(_)}},ne=new Map,re=new Map,nt=new Map,ye=new Map,le=null,$e=(_,ke,He)=>{var At;let De=nt.get(_);De||(De=[],nt.set(_,De));let Ve=0,dt=De.length;for(;Ve<dt;){let Vt=Ve+dt>>>1;De[Vt].seq<ke?Ve=Vt+1:dt=Vt}((At=De[Ve])==null?void 0:At.seq)===ke?De[Ve]={seq:ke,text:He}:De.splice(Ve,0,{seq:ke,text:He});let ot="";for(let Vt=0;Vt<De.length;Vt++)ot+=De[Vt].text;return ot},Be=(_,ke)=>{let He=te(ke),De=re.get(_.id),Ve=Yf(De,He);_.rawContent=Ve;let dt=ne.get(_.id),ot=Qe=>{var oe;let Ft=(oe=_.content)!=null?oe:"";Qe.trim()!==""&&(Ft.trim().length===0||Qe.startsWith(Ft)||Qe.trimStart().startsWith(Ft.trim()))&&(_.content=Qe)},At=()=>{var Qe;if(dt){let Ft=(Qe=dt.close)==null?void 0:Qe.call(dt);Ft instanceof Promise&&Ft.catch(()=>{})}ne.delete(_.id),re.delete(_.id),_.streaming=!1,f(_)};if(!dt){ot(He),At();return}let Vt=Cr(Ve);if(Vt!==null&&Vt.trim()!==""){ot(Vt),At();return}let q=Qe=>{var fe;let Ft=typeof Qe=="string"?Qe:(fe=Qe==null?void 0:Qe.text)!=null?fe:null;if(Ft!==null&&Ft.trim()!=="")return Ft;let oe=dt.getExtractedText();return oe!==null&&oe.trim()!==""?oe:He},_t;try{_t=dt.processChunk(Ve)}catch{ot(He),At();return}if(_t instanceof Promise){_t.then(Qe=>{ot(q(Qe)),At()}).catch(()=>{ot(He),At()});return}ot(q(_t)),At()},ce=[],K=!1,_e,Et=()=>{K||(K=!0,queueMicrotask(()=>{K=!1,_e()}))},pe=new Ka((_,ke)=>{ce.push({payloadType:_,payload:ke}),Et()}),ae=null,Ln=new Map,Nt=(ln=this.config.iterationDisplay)!=null?ln:"separate";for(_e=()=>{var _,ke,He,De,Ve,dt,ot,At,Vt,q,_t,Qe,Ft,oe,fe,xt,$t,Jt,yn,Tt,wt,ft,bt,zt,et,Fn,Zn,vn,On,ut,wo,Nn,ir,In,Rr,$o,Lo,yt,_n,Vn,xn,It,eo,to,$n,Uo,Io,zo,Un,Wt,wn,no,qo,Ro,jo,Co,zn,po,gt,Kt,Gt,qn,Ko,oo,uo,jn,T,Kn,mo,Po,So,ss,go,fo,ho,Wo,lr,ra,as,sa,Pr,mt,is,ro,Rn,aa,ia,Wr,Bo,la,cr,ls,Ho,cs,Go,Yo,ca,da,$i,dr,Xo,pa,ds,Qo,ua,ps,Jo,us,ma,Do,ga,Zo,Bt,Br,Hr,ms,Ao,fa,gs,fs,ha,Dr,Fr,pr,ba,ya,hs,bs,ys,vs,Cn,Gn,Fo,rt,xs,ur,bo,va;for(let er=0;er<ce.length;er++){let je=ce[er].payloadType,A=ce[er].payload;if(je==="reason_start"){let U=(_=be(A,!0))!=null?_:`reason-${l()}`,W=Fe(U);W.reasoning=(ke=W.reasoning)!=null?ke:{id:U,status:"streaming",chunks:[]},W.reasoning.startedAt=(De=W.reasoning.startedAt)!=null?De:Ue((He=A.startedAt)!=null?He:A.timestamp),W.reasoning.completedAt=void 0,W.reasoning.durationMs=void 0,W.streaming=!0,W.reasoning.status="streaming",f(W)}else if(je==="reason_delta"||je==="reason_chunk"){let U=(dt=(Ve=be(A,!1))!=null?Ve:be(A,!0))!=null?dt:`reason-${l()}`,W=Fe(U);W.reasoning=(ot=W.reasoning)!=null?ot:{id:U,status:"streaming",chunks:[]},W.reasoning.startedAt=(Vt=W.reasoning.startedAt)!=null?Vt:Ue((At=A.startedAt)!=null?At:A.timestamp);let Z=(Qe=(_t=(q=A.reasoningText)!=null?q:A.text)!=null?_t:A.delta)!=null?Qe:"";if(Z&&A.hidden!==!0){let G=typeof A.sequenceIndex=="number"?A.sequenceIndex:void 0;if(G!==void 0){let X=$e(U,G,String(Z));W.reasoning.chunks=[X]}else W.reasoning.chunks.push(String(Z))}if(W.reasoning.status=A.done?"complete":"streaming",A.done){W.reasoning.completedAt=Ue((Ft=A.completedAt)!=null?Ft:A.timestamp);let G=(oe=W.reasoning.startedAt)!=null?oe:Date.now();W.reasoning.durationMs=Math.max(0,((fe=W.reasoning.completedAt)!=null?fe:Date.now())-G)}W.streaming=W.reasoning.status!=="complete",f(W)}else if(je==="reason_complete"){let U=($t=(xt=be(A,!1))!=null?xt:be(A,!0))!=null?$t:`reason-${l()}`,W=R.get(U);if(W!=null&&W.reasoning){W.reasoning.status="complete",W.reasoning.completedAt=Ue((Jt=A.completedAt)!=null?Jt:A.timestamp);let G=(yn=W.reasoning.startedAt)!=null?yn:Date.now();W.reasoning.durationMs=Math.max(0,((Tt=W.reasoning.completedAt)!=null?Tt:Date.now())-G),W.streaming=!1,f(W)}let Z=$(A);Z&&v.byStep.delete(Z)}else if(je==="tool_start"){let U=(wt=de(A,!0))!=null?wt:`tool-${l()}`,W=(ft=A.toolName)!=null?ft:A.name;if(Se(W)){J.add(U);continue}let Z=we(U),G=(bt=Z.toolCall)!=null?bt:{id:U,status:"pending"};G.name=W!=null?W:G.name,G.status="running",A.args!==void 0?G.args=A.args:A.parameters!==void 0&&(G.args=A.parameters),G.startedAt=(et=G.startedAt)!=null?et:Ue((zt=A.startedAt)!=null?zt:A.timestamp),G.completedAt=void 0,G.durationMs=void 0,Z.toolCall=G,Z.streaming=!0;let X=A.agentContext;(X||A.executionId)&&(Z.agentMetadata={executionId:(Fn=X==null?void 0:X.executionId)!=null?Fn:A.executionId,iteration:(Zn=X==null?void 0:X.iteration)!=null?Zn:A.iteration}),f(Z)}else if(je==="tool_chunk"||je==="tool_delta"){let U=(On=(vn=de(A,!1))!=null?vn:de(A,!0))!=null?On:`tool-${l()}`;if(J.has(U))continue;let W=we(U),Z=(ut=W.toolCall)!=null?ut:{id:U,status:"running"};Z.startedAt=(Nn=Z.startedAt)!=null?Nn:Ue((wo=A.startedAt)!=null?wo:A.timestamp);let G=(Rr=(In=(ir=A.text)!=null?ir:A.delta)!=null?In:A.message)!=null?Rr:"";G&&(Z.chunks=($o=Z.chunks)!=null?$o:[],Z.chunks.push(String(G))),Z.status="running",W.toolCall=Z,W.streaming=!0;let X=A.agentContext;(X||A.executionId)&&(W.agentMetadata=(_n=W.agentMetadata)!=null?_n:{executionId:(Lo=X==null?void 0:X.executionId)!=null?Lo:A.executionId,iteration:(yt=X==null?void 0:X.iteration)!=null?yt:A.iteration}),f(W)}else if(je==="tool_complete"){let U=(xn=(Vn=de(A,!1))!=null?Vn:de(A,!0))!=null?xn:`tool-${l()}`;if(J.has(U)){J.delete(U);continue}let W=we(U),Z=(It=W.toolCall)!=null?It:{id:U,status:"running"};Z.status="complete",A.result!==void 0&&(Z.result=A.result),typeof A.duration=="number"&&(Z.duration=A.duration),Z.completedAt=Ue((eo=A.completedAt)!=null?eo:A.timestamp);let G=(to=A.duration)!=null?to:A.executionTime;if(typeof G=="number")Z.durationMs=G;else{let Ne=($n=Z.startedAt)!=null?$n:Date.now();Z.durationMs=Math.max(0,((Uo=Z.completedAt)!=null?Uo:Date.now())-Ne)}W.toolCall=Z,W.streaming=!1;let X=A.agentContext;(X||A.executionId)&&(W.agentMetadata=(Un=W.agentMetadata)!=null?Un:{executionId:(Io=X==null?void 0:X.executionId)!=null?Io:A.executionId,iteration:(zo=X==null?void 0:X.iteration)!=null?zo:A.iteration}),f(W);let Xe=j(A);Xe&&x.byCall.delete(Xe)}else if(je==="step_await"&&A.awaitReason==="local_tool_required"&&A.toolName){let U=typeof A.toolCallId=="string"&&A.toolCallId.length>0?A.toolCallId:void 0,W=(Wt=U!=null?U:A.toolId)!=null?Wt:`local-${l()}`,Z=we(W),G=(wn=Z.toolCall)!=null?wn:{id:W,status:"pending"};G.name=A.toolName,G.args=A.parameters,G.status="complete",G.chunks=(no=G.chunks)!=null?no:[],G.startedAt=(Ro=G.startedAt)!=null?Ro:Ue((qo=A.startedAt)!=null?qo:A.timestamp),G.completedAt=(jo=G.completedAt)!=null?jo:G.startedAt,Z.toolCall=G,Z.streaming=!1,Z.agentMetadata={...Z.agentMetadata,executionId:(zn=A.executionId)!=null?zn:(Co=Z.agentMetadata)==null?void 0:Co.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},f(Z)}else if(je==="text_start"){if((po=A.toolContext)!=null&&po.toolId)continue;let U=A.partId;if(U!==void 0&&M.current!==null&&U!==M.current){let W=u;W&&(W.streaming=!1,f(W),le=W,u=null,I=!0)}U!==void 0&&(M.current=U)}else if(je==="text_end"){if((gt=A.toolContext)!=null&&gt.toolId)continue;let U=u;U&&(U.streaming=!1,f(U),le=U,u=null,I=!0)}else if(je==="step_chunk"||je==="step_delta"){let U=A.stepType,W=A.executionType;if(U==="tool"||W==="context")continue;let Z=A.toolContext;if(Z!=null&&Z.toolId){let Ne=String((Gt=(Kt=A.id)!=null?Kt:Z.stepId)!=null?Gt:`step-${l()}`),Ze=A.partId!==void 0&&A.partId!==null?String(A.partId):"",Ie=`${Z.toolId}::${Ne}`,Ge=B.get(Ie);if(Ze!==""&&Ge!==void 0&&Ge!==""&&Ge!==Ze){let Ct=D.get(k(Z.toolId,Ne,Ge));Ct&&Ct.streaming!==!1&&(Ct.streaming=!1,f(Ct))}Ze!==""&&B.set(Ie,Ze);let Rt=E(Z.toolId,Ne,Ze,Z.executionId),nn=(uo=(oo=(Ko=(qn=A.text)!=null?qn:A.delta)!=null?Ko:A.content)!=null?oo:A.chunk)!=null?uo:"";nn&&(Rt.content+=String(nn),Rt.streaming=!0,f(Rt)),A.isComplete&&(Rt.streaming=!1,f(Rt));continue}let G=A.partId;if(G!==void 0&&M.current!==null&&G!==M.current){let Ne=u;Ne&&(Ne.streaming=!1,f(Ne),le=Ne,u=null,I=!0)}G!==void 0&&(M.current=G);let X=G!==void 0&&(jn=ye.get(G))!=null?jn:ge();G!==void 0&&(X.partId||(X.partId=G),ye.set(G,X));let Xe=(Po=(mo=(Kn=(T=A.text)!=null?T:A.delta)!=null?Kn:A.content)!=null?mo:A.chunk)!=null?Po:"";if(Xe){let Ne=typeof A.seq=="number"?A.seq:void 0,Ze=G!=null?G:X.id,Ie=Ne!==void 0?$e(Ze,Ne,String(Xe)):((So=re.get(X.id))!=null?So:"")+Xe;X.rawContent=Ie,ne.has(X.id)||ne.set(X.id,this.createStreamParser());let Ge=ne.get(X.id),Rt=Ie.trim().startsWith("{")||Ie.trim().startsWith("[");if(Rt&&re.set(X.id,Ie),Ge.__isPlainTextParser===!0){X.content=Ne!==void 0?Ie:X.content+Xe,re.delete(X.id),ne.delete(X.id),X.rawContent=void 0,f(X);continue}let Ct=Ge.processChunk(Ie);if(Ct instanceof Promise)Ct.then(Mt=>{var un;let on=typeof Mt=="string"?Mt:(un=Mt==null?void 0:Mt.text)!=null?un:null;if(on!==null&&on.trim()!=="")X.content=on,f(X);else if(!Rt&&!Ie.trim().startsWith("<")){let Sn=u,Yt=Sn&&Sn.id===X.id?Sn:X;Yt.id===X.id&&(Yt.content=Ne!==void 0?Ie:Yt.content+Xe,re.delete(Yt.id),ne.delete(Yt.id),Yt.rawContent=void 0,f(Yt))}}).catch(()=>{X.content=Ne!==void 0?Ie:X.content+Xe,re.delete(X.id),ne.delete(X.id),X.rawContent=void 0,f(X)});else{let Mt=typeof Ct=="string"?Ct:(ss=Ct==null?void 0:Ct.text)!=null?ss:null;Mt!==null&&Mt.trim()!==""?(X.content=Mt,f(X)):!Rt&&!Ie.trim().startsWith("<")&&(X.content=Ne!==void 0?Ie:X.content+Xe,re.delete(X.id),ne.delete(X.id),X.rawContent=void 0,f(X))}}if(A.isComplete){let Ne=(fo=(go=A.result)==null?void 0:go.response)!=null?fo:X.content;if(Ne){let Ze=re.get(X.id),Ie=Ze!=null?Ze:te(Ne);X.rawContent=Ie;let Ge=ne.get(X.id),Rt=null,nn=!1;if(Ge&&(Rt=Ge.getExtractedText(),Rt===null&&(Rt=Cr(Ie)),Rt===null)){let Ct=Ge.processChunk(Ie);Ct instanceof Promise?(nn=!0,Ct.then(Mt=>{var un;let on=typeof Mt=="string"?Mt:(un=Mt==null?void 0:Mt.text)!=null?un:null;if(on!==null){let Sn=u;Sn&&Sn.id===X.id&&(Sn.content=on,Sn.streaming=!1,ne.delete(Sn.id),re.delete(Sn.id),f(Sn))}})):Rt=typeof Ct=="string"?Ct:(ho=Ct==null?void 0:Ct.text)!=null?ho:null}if(!nn){Rt!==null&&Rt.trim()!==""?X.content=Rt:re.has(X.id)||(X.content=te(Ne));let Ct=ne.get(X.id);if(Ct){let Mt=(Wo=Ct.close)==null?void 0:Wo.call(Ct);Mt instanceof Promise&&Mt.catch(()=>{}),ne.delete(X.id)}re.delete(X.id),X.streaming=!1,f(X)}}}}else if(je==="step_complete"){let U=A.stepType,W=A.executionType;if(U==="tool"||W==="context")continue;let Z=A.toolContext;if(Z!=null&&Z.toolId){let Ne=String((ra=(lr=A.id)!=null?lr:Z.stepId)!=null?ra:"");if(Ne){let Ze=S(Z.toolId,Ne);for(let[Ie,Ge]of D)Ie.startsWith(Ze)&&Ge.streaming!==!1&&(Ge.streaming=!1,f(Ge));B.delete(`${Z.toolId}::${Ne}`)}continue}let G=A.stopReason;if(I){if(u!==null){let Ie=u;G&&(Ie.stopReason=G),ne.delete(Ie.id),re.delete(Ie.id),Ie.streaming!==!1&&(Ie.streaming=!1,f(Ie))}let Ne=(as=A.result)==null?void 0:as.response,Ze=le;Ze&&(G&&(Ze.stopReason=G),Ne!=null?Be(Ze,Ne):(ne.delete(Ze.id),re.delete(Ze.id))),le=null;continue}let X=(sa=A.result)==null?void 0:sa.response,Xe=ge();if(G&&(Xe.stopReason=G),X!=null){let Ne=ne.get(Xe.id),Ze=!1,Ie=!1;if(Ne){let Ge=Ne.getExtractedText(),Rt=re.get(Xe.id),nn=Rt!=null?Rt:te(X);if(Xe.rawContent=nn,Ge!==null&&Ge.trim()!=="")Xe.content=Ge,Ze=!0;else{let Ct=Cr(nn);if(Ct!==null)Xe.content=Ct,Ze=!0;else{let Mt=Ne.processChunk(nn);if(Mt instanceof Promise)Ie=!0,Mt.then(on=>{var Sn;let un=typeof on=="string"?on:(Sn=on==null?void 0:on.text)!=null?Sn:null;if(un!==null&&un.trim()!==""){let Yt=u;Yt&&Yt.id===Xe.id&&(Yt.content=un,Yt.streaming=!1,ne.delete(Yt.id),re.delete(Yt.id),f(Yt))}else{let Yt=Ne.getExtractedText(),so=u;so&&so.id===Xe.id&&(Yt!==null&&Yt.trim()!==""?so.content=Yt:re.has(so.id)||(so.content=te(X)),so.streaming=!1,ne.delete(so.id),re.delete(so.id),f(so))}});else{let on=typeof Mt=="string"?Mt:(Pr=Mt==null?void 0:Mt.text)!=null?Pr:null;if(on!==null&&on.trim()!=="")Xe.content=on,Ze=!0;else{let un=Ne.getExtractedText();un!==null&&un.trim()!==""&&(Xe.content=un,Ze=!0)}}}}}if(!Ie){if(!Xe.rawContent){let Ge=re.get(Xe.id);Xe.rawContent=Ge!=null?Ge:te(X)}if(!Ze&&!re.has(Xe.id)&&(Xe.content=te(X)),Ne){let Ge=(mt=Ne.close)==null?void 0:mt.call(Ne);Ge instanceof Promise&&Ge.catch(()=>{})}ne.delete(Xe.id),re.delete(Xe.id),Xe.streaming=!1,f(Xe)}}else ne.delete(Xe.id),re.delete(Xe.id),Xe.streaming=!1,f(Xe)}else if(je==="flow_complete"){let U=(is=A.result)==null?void 0:is.response;if(I){if(u!==null){let W=u;ne.delete(W.id),re.delete(W.id),W.streaming!==!1&&(W.streaming=!1,f(W))}}else if(U!=null){let W=ge(),Z=re.get(W.id),G=Z!=null?Z:te(U);W.rawContent=G;let X=te(U),Xe=ne.get(W.id);if(Xe){let Ie=Cr(G);if(Ie!==null)X=Ie;else{let Ge=Xe.processChunk(G);Ge instanceof Promise&&Ge.then(nn=>{var Mt;let Ct=typeof nn=="string"?nn:(Mt=nn==null?void 0:nn.text)!=null?Mt:null;Ct!==null&&(W.content=Ct,W.streaming=!1,f(W))});let Rt=Xe.getExtractedText();Rt!==null&&(X=Rt)}}ne.delete(W.id),re.delete(W.id);let Ne=X!==W.content,Ze=W.streaming!==!1;Ne&&(W.content=X),W.streaming=!1,(Ne||Ze)&&f(W)}else if(u!==null){let W=u;ne.delete(W.id),re.delete(W.id),W.streaming!==!1&&(W.streaming=!1,f(W))}n({type:"status",status:"idle"})}else if(je==="agent_start")ae={executionId:A.executionId,agentId:(ro=A.agentId)!=null?ro:"virtual",agentName:(Rn=A.agentName)!=null?Rn:"",status:"running",currentIteration:0,maxTurns:(aa=A.maxTurns)!=null?aa:1,startedAt:Ue(A.startedAt)};else if(je==="agent_iteration_start"){if(ae&&(ae.currentIteration=A.iteration),Nt==="separate"&&A.iteration>1){let U=u;U&&(U.streaming=!1,f(U),Ln.set(A.iteration-1,U),u=null)}}else if(je==="agent_turn_start")w=null;else if(je==="agent_turn_delta"){if(A.contentType==="text"){let U=ge();U.content+=(ia=A.delta)!=null?ia:"",U.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId,agentName:ae==null?void 0:ae.agentName},w=U,f(U)}else if(A.contentType==="thinking"){let U=(Wr=A.turnId)!=null?Wr:`agent-think-${A.iteration}`,W=Fe(U);W.reasoning=(Bo=W.reasoning)!=null?Bo:{id:U,status:"streaming",chunks:[]},W.reasoning.chunks.push((la=A.delta)!=null?la:""),W.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId},f(W)}else if(A.contentType==="tool_input"){let U=(cr=A.toolCallId)!=null?cr:x.lastId;if(U){let W=H.get(U);W!=null&&W.toolCall&&(W.toolCall.chunks=(ls=W.toolCall.chunks)!=null?ls:[],W.toolCall.chunks.push((Ho=A.delta)!=null?Ho:""),f(W))}}}else if(je==="agent_turn_complete"){let U=A.turnId;if(U){let G=R.get(U);if(G!=null&&G.reasoning){G.reasoning.status="complete",G.reasoning.completedAt=Ue(A.completedAt);let X=(cs=G.reasoning.startedAt)!=null?cs:Date.now();G.reasoning.durationMs=Math.max(0,((Go=G.reasoning.completedAt)!=null?Go:Date.now())-X),G.streaming=!1,f(G)}}let W=A.stopReason,Z=u!=null?u:w;if(W&&Z!==null){let G=A.turnId;(!G||((Yo=Z.agentMetadata)==null?void 0:Yo.turnId)===G)&&(Z.stopReason=W,f(Z))}}else if(je==="agent_tool_start"){u&&(u.streaming=!1,f(u),u=null);let U=(ca=A.toolCallId)!=null?ca:`agent-tool-${l()}`;ve(j(A),U);let W=we(U),Z=(da=W.toolCall)!=null?da:{id:U,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};Z.name=(dr=($i=A.toolName)!=null?$i:A.name)!=null?dr:Z.name,Z.status="running",A.parameters!==void 0&&(Z.args=A.parameters),Z.startedAt=Ue((Xo=A.startedAt)!=null?Xo:A.timestamp),W.toolCall=Z,W.streaming=!0,W.agentMetadata={executionId:A.executionId,iteration:A.iteration},f(W)}else if(je==="agent_tool_delta"){let U=(pa=A.toolCallId)!=null?pa:x.lastId;if(U){let W=(ds=H.get(U))!=null?ds:we(U);W.toolCall&&(W.toolCall.chunks=(Qo=W.toolCall.chunks)!=null?Qo:[],W.toolCall.chunks.push((ua=A.delta)!=null?ua:""),W.toolCall.status="running",W.streaming=!0,f(W))}}else if(je==="agent_tool_complete"){let U=(ps=A.toolCallId)!=null?ps:x.lastId;if(U){let W=(Jo=H.get(U))!=null?Jo:we(U);if(W.toolCall){W.toolCall.status="complete",A.result!==void 0&&(W.toolCall.result=A.result),typeof A.executionTime=="number"&&(W.toolCall.durationMs=A.executionTime),W.toolCall.completedAt=Ue((us=A.completedAt)!=null?us:A.timestamp),W.streaming=!1,f(W);let Z=j(A);Z&&x.byCall.delete(Z)}}}else if(je==="agent_media"){let U=Array.isArray(A.media)?A.media:[],W=[];for(let Z of U){if(!Z||typeof Z!="object")continue;let G=Z,X=typeof G.type=="string"?G.type:void 0,Xe=typeof G.mediaType=="string"?G.mediaType.toLowerCase():"",Ne=null,Ze="";if(X==="media"){let Ie=typeof G.data=="string"?G.data:void 0;if(!Ie)continue;Ze=Xe.length>0?Xe:"application/octet-stream",Ne=`data:${Ze};base64,${Ie}`}else if(X==="image-url"){let Ie=typeof G.url=="string"?G.url:void 0;if(!Ie)continue;Ze=Xe,Ne=Ie}else if(X==="file-url"){let Ie=typeof G.url=="string"?G.url:void 0;if(!Ie)continue;Ze=Xe,Ne=Ie}else continue;if(Ne)if(X==="image-url"||Ze.startsWith("image/"))W.push({type:"image",image:Ne,...Ze?{mimeType:Ze}:{}});else if(Ze.startsWith("audio/"))W.push({type:"audio",audio:Ne,mimeType:Ze});else if(Ze.startsWith("video/"))W.push({type:"video",video:Ne,mimeType:Ze});else{let Ie=Ze||"application/octet-stream";W.push({type:"file",data:Ne,mimeType:Ie,filename:Kf(Ie)})}}if(W.length>0){let Z=l(),G=A.toolCallId,Xe={id:`agent-media-${typeof G=="string"&&G.length>0?`${G}-${Z}`:String(Z)}`,role:"assistant",content:"",contentParts:W,createdAt:new Date().toISOString(),streaming:!1,sequence:Z,agentMetadata:{executionId:A.executionId,iteration:A.iteration}};f(Xe);let Ne=u;Ne&&(Ne.streaming=!1,f(Ne)),u=null,C.current=null}}else if(je!=="agent_iteration_complete"){if(je==="agent_reflection"||je==="agent_reflect"){let U=`agent-reflection-${A.executionId}-${A.iteration}`,W={id:U,role:"assistant",content:(ma=A.reflection)!=null?ma:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:U,status:"complete",chunks:[(Do=A.reflection)!=null?Do:""]},agentMetadata:{executionId:A.executionId,iteration:A.iteration}};f(W)}else if(je==="agent_complete"){ae&&(ae.status=A.success?"complete":"error",ae.completedAt=Ue(A.completedAt),ae.stopReason=A.stopReason);let U=u;U&&(U.streaming=!1,f(U)),n({type:"status",status:"idle"})}else if(je==="agent_error"){let U=typeof A.error=="string"?A.error:(Zo=(ga=A.error)==null?void 0:ga.message)!=null?Zo:"Agent execution error";A.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",U):n({type:"error",error:new Error(U)})}else if(je!=="agent_ping"){if(je==="agent_approval_start"){let U=(Bt=A.approvalId)!=null?Bt:`approval-${l()}`,W={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(Br=ae==null?void 0:ae.agentId)!=null?Br:"virtual",executionId:(ms=(Hr=A.executionId)!=null?Hr:ae==null?void 0:ae.executionId)!=null?ms:"",toolName:(Ao=A.toolName)!=null?Ao:"",toolType:A.toolType,description:(gs=A.description)!=null?gs:`Execute ${(fa=A.toolName)!=null?fa:"tool"}`,parameters:A.parameters}};f(W)}else if(je==="step_await"&&A.awaitReason==="approval_required"){let U=(fs=A.approvalId)!=null?fs:`approval-${l()}`,W={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(ha=ae==null?void 0:ae.agentId)!=null?ha:"virtual",executionId:(Fr=(Dr=A.executionId)!=null?Dr:ae==null?void 0:ae.executionId)!=null?Fr:"",toolName:(pr=A.toolName)!=null?pr:"",toolType:A.toolType,description:(ya=A.description)!=null?ya:`Execute ${(ba=A.toolName)!=null?ba:"tool"}`,parameters:A.parameters}};f(W)}else if(je==="agent_approval_complete"){let U=A.approvalId;if(U){let Z={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:(hs=A.decision)!=null?hs:"approved",agentId:(bs=ae==null?void 0:ae.agentId)!=null?bs:"virtual",executionId:(vs=(ys=A.executionId)!=null?ys:ae==null?void 0:ae.executionId)!=null?vs:"",toolName:(Cn=A.toolName)!=null?Cn:"",description:(Gn=A.description)!=null?Gn:"",resolvedAt:Date.now()}};f(Z)}}else if(je==="artifact_start"||je==="artifact_delta"||je==="artifact_update"||je==="artifact_complete"){if(je==="artifact_start"){let U=A.artifactType,W=String(A.id),Z=typeof A.title=="string"?A.title:void 0;if(n({type:"artifact_start",id:W,artifactType:U,title:Z,component:typeof A.component=="string"?A.component:void 0}),xe.set(W,{markdown:"",title:Z}),!Y.has(W)){Y.add(W);let G={id:`artifact-ref-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:W,title:Z,artifactType:U,status:"streaming"}})};Le.set(W,G),f(G)}}else if(je==="artifact_delta"){let U=String(A.id),W=typeof A.delta=="string"?A.delta:String((Fo=A.delta)!=null?Fo:"");n({type:"artifact_delta",id:U,artDelta:W});let Z=xe.get(U);Z&&(Z.markdown+=W)}else if(je==="artifact_update"){let U=A.props&&typeof A.props=="object"&&!Array.isArray(A.props)?A.props:{};n({type:"artifact_update",id:String(A.id),props:U,component:typeof A.component=="string"?A.component:void 0})}else if(je==="artifact_complete"){let U=String(A.id);n({type:"artifact_complete",id:U});let W=Le.get(U);if(W){W.streaming=!1;try{let Z=JSON.parse((rt=W.rawContent)!=null?rt:"{}");if(Z.props){Z.props.status="complete";let G=xe.get(U);G!=null&&G.markdown&&(Z.props.markdown=G.markdown)}W.rawContent=JSON.stringify(Z)}catch{}xe.delete(U),f(W),Le.delete(U)}}}else if(je==="transcript_insert"){let U=A.message;if(!U||typeof U!="object")continue;let W=String((xs=U.id)!=null?xs:`msg-${l()}`),Z=U.role,X={id:W,role:Z==="user"?"user":Z==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:l()};if(f(X),X.rawContent)try{let Xe=JSON.parse(X.rawContent),Ne=(ur=Xe==null?void 0:Xe.props)==null?void 0:ur.artifactId;typeof Ne=="string"&&Y.add(Ne)}catch{}u=null,C.current=null,ne.delete(W),re.delete(W)}else if(je==="error"||je==="step_error"||je==="dispatch_error"||je==="flow_error"){let U=null;if(A.error instanceof Error)U=A.error;else if(je==="dispatch_error"){let W=(bo=A.message)!=null?bo:A.error;W!=null&&W!==""&&(U=new Error(String(W)))}else if(je==="step_error"||je==="flow_error"){let W=A.error;typeof W=="string"&&W!==""?U=new Error(W):W!=null&&typeof W=="object"&&"message"in W&&(U=new Error(String((va=W.message)!=null?va:W)))}else je==="error"&&A.error!=null&&A.error!==""&&(U=new Error(String(A.error)));if(U){n({type:"error",error:U});let W=u;W&&W.streaming&&(W.streaming=!1,f(W)),n({type:"status",status:"idle"})}}}}}ce.length=0};;){let{done:_,value:ke}=await r.read();if(_)break;a+=s.decode(ke,{stream:!0});let He=a.split(`
9
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},kr=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Hu=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Du=()=>{var t;let e=ah();return{processChunk:async n=>{let o=n.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},Fu=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=th(n,nh|oh);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Pu(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Pu(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var Ou=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Qa=class{constructor(t,n=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=n}push(t,n){var s,a,i;let o=(i=(s=n==null?void 0:n.seq)!=null?s:n==null?void 0:n.sequenceIndex)!=null?i:(a=n==null?void 0:n.agentContext)==null?void 0:a.seq;if(o==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,n);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),o===this.nextExpectedSeq){this.emitter(t,n),this.nextExpectedSeq=o+1,this.drainConsecutive();return}if(o<this.nextExpectedSeq){this.emitter(t,n);return}let r=this.buffer.get(o);r!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${o} (${r.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(r.payloadType,r.payload)),this.buffer.set(o,{payloadType:t,payload:n,seq:o}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((n,o)=>n[0]-o[0]);for(let[n,o]of t)this.buffer.delete(n),this.emitter(o.payloadType,o.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var ih="https://api.runtype.com/v1/dispatch",Ja="https://api.runtype.com";function lh(e){var s,a;let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let i=(a=(s=t.slice(r+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var gl=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function ch(e){switch(e){case"json":return Fu;case"regex-json":return Du;case"xml":return Ou;default:return Hu}}var Nu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function dh(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=Nu(n);if(!Nu(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=kr(e);return kr(t)!==null&&a===null?t:e}var Ns=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,o,r,s;this.apiUrl=(n=t.apiUrl)!=null?n:ih,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:ch(t.parserType),this.contextProviders=(r=t.contextProviders)!=null?r:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new Ka(t.webmcp):null}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ja}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let o=await this.sessionInitPromise;return this.clientSession=o,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,o),o}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let t=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},o=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){let i=await o.json().catch(()=>({error:"Session initialization failed"}));throw o.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):o.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let r=await o.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(r.sessionId),{sessionId:r.sessionId,expiresAt:new Date(r.expiresAt),flow:r.flow,config:{welcomeMessage:r.config.welcomeMessage,placeholder:r.config.placeholder,theme:r.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ja}/v1/client/feedback`}async sendFeedback(t){var s,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var r,s,a,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(r=this.config).onSessionExpired)==null||s.call(r);let H=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:H}),H}let l=await this.buildPayload(t.messages),m=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([H])=>H!=="sessionId"&&H!=="session_id")):void 0,p={sessionId:d.sessionId,messages:t.messages.filter(gl).map(H=>{var W,x,w;return{id:H.id,role:H.role,content:(w=(x=(W=H.contentParts)!=null?W:H.llmContent)!=null?x:H.rawContent)!=null?w:H.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...m&&Object.keys(m).length>0&&{metadata:m},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},f=l.clientTools,u=!!(f&&f.length>0),C=u?Iu(f):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,E=u&&v&&this.lastSentClientToolsFingerprint===C,L=!1,I=null,P;for(let H=0;;H++){let x={...p,...u&&(L||!E)&&f?{clientTools:f}:{},...C?{clientToolsFingerprint:C}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",x),P=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(x),signal:o.signal}),P.status===409&&H===0&&u){let w=await P.json().catch(()=>null);if((w==null?void 0:w.error)==="client_tools_resend_required"){L=!0,this.lastSentClientToolsFingerprint=null;continue}I=w!=null?w:{error:"Chat request failed"}}break}if(!P.ok){let H=I!=null?I:await P.json().catch(()=>({error:"Chat request failed"}));if(P.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let x=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:x}),x}if(P.status===429){let x=new Error(H.hint||"Message limit reached for this session.");throw n({type:"error",error:x}),x}let W=new Error(H.error||"Failed to send message");throw n({type:"error",error:W}),W}if(!P.body){let H=new Error("No response body received");throw n({type:"error",error:H}),H}this.lastSentClientToolsFingerprint=C!=null?C:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(P.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let r=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ja}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,o){var l,m;let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Ja}/resume`,a;r&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(m=o==null?void 0:o.streamResponse)!=null?m:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var s;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(gl).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),o={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},r=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(r&&r.length>0&&(o.clientTools=r),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(o.context=a)}return o}async buildPayload(t){var s;let o={messages:t.slice().filter(gl).sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},r=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(r&&r.length>0&&(o.clientTools=r),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(o.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...o},config:this.config});if(a&&typeof a=="object"){let i=a;return o.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=o.clientTools),i}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return o}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=m=>{let p={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...m!==void 0&&{partId:m}};return o.current=p,r(p),p},l=m=>o.current?o.current:d(m);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let m=l(i.partId);i.partId!==void 0&&!m.partId&&(m.partId=i.partId),m.content+=i.text,r(m)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o){var mn,Dn,eo,ze;let r=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,m=_=>{let Me=_.reasoning?{..._.reasoning,chunks:[..._.reasoning.chunks]}:void 0,Be=_.toolCall?{..._.toolCall,chunks:_.toolCall.chunks?[..._.toolCall.chunks]:void 0}:void 0,He=_.tools?_.tools.map(_e=>({..._e,chunks:_e.chunks?[..._e.chunks]:void 0})):void 0;return{..._,reasoning:Me,toolCall:Be,tools:He}},p=_=>{if(_.role!=="assistant"||_.variant)return!0;let Me=Array.isArray(_.contentParts)&&_.contentParts.length>0,Be=typeof _.rawContent=="string"&&_.rawContent.trim()!=="";return typeof _.content=="string"&&_.content.trim()!==""||Me||Be||!!_.stopReason},f=_=>{p(_)&&n({type:"message",message:m(_)})},u=null,C=null,v={current:null},E={current:null},L=!1,I=new Map,P=new Map,H=new Map,W=new Map,x={lastId:null,byStep:new Map},w={lastId:null,byCall:new Map},k=(_,Me,Be="")=>`${_}::${Me}::${Be}`,S=(_,Me)=>`${_}::${Me}::`,A=(_,Me,Be,He)=>{let _e=k(_,Me,Be),ut=H.get(_e);if(ut)return ut;let st=Be?`-${Be}`:"",Rt={id:`nested-${_}-${Me}${st}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Be?{partId:Be}:{},agentMetadata:{executionId:He,parentToolId:_,parentStepId:Me}};return H.set(_e,Rt),f(Rt),Rt},N=_=>{if(_==null)return null;try{return String(_)}catch{return null}},$=_=>{var Me,Be,He,_e,ut;return N((ut=(_e=(He=(Be=(Me=_.stepId)!=null?Me:_.step_id)!=null?Be:_.step)!=null?He:_.parentId)!=null?_e:_.flowStepId)!=null?ut:_.flow_step_id)},G=_=>{var Me,Be,He,_e,ut,st,Rt;return N((Rt=(st=(ut=(_e=(He=(Be=(Me=_.callId)!=null?Me:_.call_id)!=null?Be:_.requestId)!=null?He:_.request_id)!=null?_e:_.toolCallId)!=null?ut:_.tool_call_id)!=null?st:_.stepId)!=null?Rt:_.step_id)},fe=o,ge=!1,se=()=>{if(u)return u;let _;return!ge&&fe?(_=fe,ge=!0):fe&&E.current?_=`${fe}_${E.current}`:_=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,u={id:_,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(u),u},ke=(_,Me)=>{x.lastId=Me,_&&x.byStep.set(_,Me)},be=(_,Me)=>{var ut;let Be=(ut=_.reasoningId)!=null?ut:_.id,He=$(_);if(Be){let st=String(Be);return ke(He,st),st}if(He){let st=x.byStep.get(He);if(st)return x.lastId=st,st}if(x.lastId&&!Me)return x.lastId;if(!Me)return null;let _e=`reason-${l()}`;return ke(He,_e),_e},Fe=_=>{let Me=I.get(_);if(Me)return Me;let Be={id:`reason-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:_,status:"streaming",chunks:[]}};return I.set(_,Be),f(Be),Be},xe=(_,Me)=>{w.lastId=Me,_&&w.byCall.set(_,Me)},j=new Set,de=new Map,K=new Set,ye=new Map,le=_=>{if(!_)return!1;let Me=_.replace(/_+/g,"_").replace(/^_|_$/g,"");return Me==="emit_artifact_markdown"||Me==="emit_artifact_component"},te=(_,Me)=>{var ut;let Be=(ut=_.toolId)!=null?ut:_.id,He=G(_);if(Be){let st=String(Be);return xe(He,st),st}if(He){let st=w.byCall.get(He);if(st)return w.lastId=st,st}if(w.lastId&&!Me)return w.lastId;if(!Me)return null;let _e=`tool-${l()}`;return xe(He,_e),_e},Ce=_=>{let Me=P.get(_);if(Me)return Me;let Be={id:`tool-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:_,status:"pending"}};return P.set(_,Be),f(Be),Be},Ue=_=>{if(typeof _=="number"&&Number.isFinite(_))return _;if(typeof _=="string"){let Me=Number(_);if(!Number.isNaN(Me)&&Number.isFinite(Me))return Me;let Be=Date.parse(_);if(!Number.isNaN(Be))return Be}return Date.now()},ee=_=>{if(typeof _=="string")return _;if(_==null)return"";try{return JSON.stringify(_)}catch{return String(_)}},oe=new Map,ae=new Map,rt=new Map,Ae=new Map,pe=null,$e=(_,Me,Be)=>{var Rt;let He=rt.get(_);He||(He=[],rt.set(_,He));let _e=0,ut=He.length;for(;_e<ut;){let qt=_e+ut>>>1;He[qt].seq<Me?_e=qt+1:ut=qt}((Rt=He[_e])==null?void 0:Rt.seq)===Me?He[_e]={seq:Me,text:Be}:He.splice(_e,0,{seq:Me,text:Be});let st="";for(let qt=0;qt<He.length;qt++)st+=He[qt].text;return st},We=(_,Me)=>{let Be=ee(Me),He=ae.get(_.id),_e=dh(He,Be);_.rawContent=_e;let ut=oe.get(_.id),st=Je=>{var re;let _t=(re=_.content)!=null?re:"";Je.trim()!==""&&(_t.trim().length===0||Je.startsWith(_t)||Je.trimStart().startsWith(_t.trim()))&&(_.content=Je)},Rt=()=>{var Je;if(ut){let _t=(Je=ut.close)==null?void 0:Je.call(ut);_t instanceof Promise&&_t.catch(()=>{})}oe.delete(_.id),ae.delete(_.id),_.streaming=!1,f(_)};if(!ut){st(Be),Rt();return}let qt=kr(_e);if(qt!==null&&qt.trim()!==""){st(qt),Rt();return}let q=Je=>{var we;let _t=typeof Je=="string"?Je:(we=Je==null?void 0:Je.text)!=null?we:null;if(_t!==null&&_t.trim()!=="")return _t;let re=ut.getExtractedText();return re!==null&&re.trim()!==""?re:Be},Ut;try{Ut=ut.processChunk(_e)}catch{st(Be),Rt();return}if(Ut instanceof Promise){Ut.then(Je=>{st(q(Je)),Rt()}).catch(()=>{st(Be),Rt()});return}st(q(Ut)),Rt()},ue=[],X=!1,Ne,Bt=()=>{X||(X=!0,queueMicrotask(()=>{X=!1,Ne()}))},he=new Qa((_,Me)=>{ue.push({payloadType:_,payload:Me}),Bt()}),ce=null,Rn=new Map,$t=(mn=this.config.iterationDisplay)!=null?mn:"separate";for(Ne=()=>{var _,Me,Be,He,_e,ut,st,Rt,qt,q,Ut,Je,_t,re,we,Tt,jt,en,Sn,Pt,Et,xt,Ct,Kt,nt,Fn,to,An,On,ht,Eo,Nn,dr,Pn,Hr,qo,Bo,St,_n,Vn,Tn,Mt,no,oo,$n,jo,Ho,Ko,Un,Dt,kn,ro,Go,Do,Yo,Mo,zn,bo,yt,Yt,Xt,qn,Xo,so,yo,jn,V,ao,ve,Kn,io,vo,us,xo,wo,Co,Fo,pr,ua,ms,ma,Dr,bt,gs,lo,Wn,ga,fa,Fr,Oo,ha,ur,fs,No,hs,Qo,Jo,ba,ya,Gi,mr,Zo,va,bs,er,xa,ys,tr,vs,wa,_o,Ca,nr,Ft,Or,Nr,xs,Lo,Sa,ws,Cs,Aa,_r,Vr,gr,Ta,ka,Ss,As,Ts,ks,En,Gn,Vo,lt,Es,fr,So;for(let $r=0;$r<ue.length;$r++){let Ge=ue[$r].payloadType,T=ue[$r].payload;if(Ge==="reason_start"){let U=(_=be(T,!0))!=null?_:`reason-${l()}`,R=Fe(U);R.reasoning=(Me=R.reasoning)!=null?Me:{id:U,status:"streaming",chunks:[]},R.reasoning.startedAt=(He=R.reasoning.startedAt)!=null?He:Ue((Be=T.startedAt)!=null?Be:T.timestamp),R.reasoning.completedAt=void 0,R.reasoning.durationMs=void 0,R.streaming=!0,R.reasoning.status="streaming",f(R)}else if(Ge==="reason_delta"||Ge==="reason_chunk"){let U=(ut=(_e=be(T,!1))!=null?_e:be(T,!0))!=null?ut:`reason-${l()}`,R=Fe(U);R.reasoning=(st=R.reasoning)!=null?st:{id:U,status:"streaming",chunks:[]},R.reasoning.startedAt=(qt=R.reasoning.startedAt)!=null?qt:Ue((Rt=T.startedAt)!=null?Rt:T.timestamp);let J=(Je=(Ut=(q=T.reasoningText)!=null?q:T.text)!=null?Ut:T.delta)!=null?Je:"";if(J&&T.hidden!==!0){let ie=typeof T.sequenceIndex=="number"?T.sequenceIndex:void 0;if(ie!==void 0){let Y=$e(U,ie,String(J));R.reasoning.chunks=[Y]}else R.reasoning.chunks.push(String(J))}if(R.reasoning.status=T.done?"complete":"streaming",T.done){R.reasoning.completedAt=Ue((_t=T.completedAt)!=null?_t:T.timestamp);let ie=(re=R.reasoning.startedAt)!=null?re:Date.now();R.reasoning.durationMs=Math.max(0,((we=R.reasoning.completedAt)!=null?we:Date.now())-ie)}R.streaming=R.reasoning.status!=="complete",f(R)}else if(Ge==="reason_complete"){let U=(jt=(Tt=be(T,!1))!=null?Tt:be(T,!0))!=null?jt:`reason-${l()}`,R=I.get(U);if(R!=null&&R.reasoning){R.reasoning.status="complete",R.reasoning.completedAt=Ue((en=T.completedAt)!=null?en:T.timestamp);let ie=(Sn=R.reasoning.startedAt)!=null?Sn:Date.now();R.reasoning.durationMs=Math.max(0,((Pt=R.reasoning.completedAt)!=null?Pt:Date.now())-ie),R.streaming=!1,f(R)}let J=$(T);J&&x.byStep.delete(J)}else if(Ge==="tool_start"){let U=(Et=te(T,!0))!=null?Et:`tool-${l()}`,R=(xt=T.toolName)!=null?xt:T.name;if(le(R)){j.add(U);continue}let J=Ce(U),ie=(Ct=J.toolCall)!=null?Ct:{id:U,status:"pending"};ie.name=R!=null?R:ie.name,ie.status="running",T.args!==void 0?ie.args=T.args:T.parameters!==void 0&&(ie.args=T.parameters),ie.startedAt=(nt=ie.startedAt)!=null?nt:Ue((Kt=T.startedAt)!=null?Kt:T.timestamp),ie.completedAt=void 0,ie.durationMs=void 0,J.toolCall=ie,J.streaming=!0;let Y=T.agentContext;(Y||T.executionId)&&(J.agentMetadata={executionId:(Fn=Y==null?void 0:Y.executionId)!=null?Fn:T.executionId,iteration:(to=Y==null?void 0:Y.iteration)!=null?to:T.iteration}),f(J)}else if(Ge==="tool_chunk"||Ge==="tool_delta"){let U=(On=(An=te(T,!1))!=null?An:te(T,!0))!=null?On:`tool-${l()}`;if(j.has(U))continue;let R=Ce(U),J=(ht=R.toolCall)!=null?ht:{id:U,status:"running"};J.startedAt=(Nn=J.startedAt)!=null?Nn:Ue((Eo=T.startedAt)!=null?Eo:T.timestamp);let ie=(Hr=(Pn=(dr=T.text)!=null?dr:T.delta)!=null?Pn:T.message)!=null?Hr:"";ie&&(J.chunks=(qo=J.chunks)!=null?qo:[],J.chunks.push(String(ie))),J.status="running",R.toolCall=J,R.streaming=!0;let Y=T.agentContext;(Y||T.executionId)&&(R.agentMetadata=(_n=R.agentMetadata)!=null?_n:{executionId:(Bo=Y==null?void 0:Y.executionId)!=null?Bo:T.executionId,iteration:(St=Y==null?void 0:Y.iteration)!=null?St:T.iteration}),f(R)}else if(Ge==="tool_complete"){let U=(Tn=(Vn=te(T,!1))!=null?Vn:te(T,!0))!=null?Tn:`tool-${l()}`;if(j.has(U)){j.delete(U);continue}let R=Ce(U),J=(Mt=R.toolCall)!=null?Mt:{id:U,status:"running"};J.status="complete",T.result!==void 0&&(J.result=T.result),typeof T.duration=="number"&&(J.duration=T.duration),J.completedAt=Ue((no=T.completedAt)!=null?no:T.timestamp);let ie=(oo=T.duration)!=null?oo:T.executionTime;if(typeof ie=="number")J.durationMs=ie;else{let Oe=($n=J.startedAt)!=null?$n:Date.now();J.durationMs=Math.max(0,((jo=J.completedAt)!=null?jo:Date.now())-Oe)}R.toolCall=J,R.streaming=!1;let Y=T.agentContext;(Y||T.executionId)&&(R.agentMetadata=(Un=R.agentMetadata)!=null?Un:{executionId:(Ho=Y==null?void 0:Y.executionId)!=null?Ho:T.executionId,iteration:(Ko=Y==null?void 0:Y.iteration)!=null?Ko:T.iteration}),f(R);let Ie=G(T);Ie&&w.byCall.delete(Ie)}else if(Ge==="step_await"&&T.awaitReason==="local_tool_required"&&T.toolName){let U=typeof T.toolCallId=="string"&&T.toolCallId.length>0?T.toolCallId:void 0,R=(Dt=U!=null?U:T.toolId)!=null?Dt:`local-${l()}`,J=Ce(R),ie=T.toolName,Y=Qr(ie),Ie=(kn=J.toolCall)!=null?kn:{id:R,status:"pending"};Ie.name=ie,Ie.args=T.parameters,Ie.status=Y?"running":"complete",Ie.chunks=(ro=Ie.chunks)!=null?ro:[],Ie.startedAt=(Do=Ie.startedAt)!=null?Do:Ue((Go=T.startedAt)!=null?Go:T.timestamp),Y?(Ie.completedAt=void 0,Ie.duration=void 0,Ie.durationMs=void 0):Ie.completedAt=(Yo=Ie.completedAt)!=null?Yo:Ie.startedAt,J.toolCall=Ie,J.streaming=!1,J.agentMetadata={...J.agentMetadata,executionId:(zn=T.executionId)!=null?zn:(Mo=J.agentMetadata)==null?void 0:Mo.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},f(J)}else if(Ge==="text_start"){if((bo=T.toolContext)!=null&&bo.toolId)continue;let U=T.partId;if(U!==void 0&&E.current!==null&&U!==E.current){let R=u;R&&(R.streaming=!1,f(R),pe=R,u=null,L=!0)}U!==void 0&&(E.current=U)}else if(Ge==="text_end"){if((yt=T.toolContext)!=null&&yt.toolId)continue;let U=u;U&&(U.streaming=!1,f(U),pe=U,u=null,L=!0)}else if(Ge==="step_chunk"||Ge==="step_delta"){let U=T.stepType,R=T.executionType;if(U==="tool"||R==="context")continue;let J=T.toolContext;if(J!=null&&J.toolId){let Oe=String((Xt=(Yt=T.id)!=null?Yt:J.stepId)!=null?Xt:`step-${l()}`),ct=T.partId!==void 0&&T.partId!==null?String(T.partId):"",Ye=`${J.toolId}::${Oe}`,Xe=W.get(Ye);if(ct!==""&&Xe!==void 0&&Xe!==""&&Xe!==ct){let Lt=H.get(k(J.toolId,Oe,Xe));Lt&&Lt.streaming!==!1&&(Lt.streaming=!1,f(Lt))}ct!==""&&W.set(Ye,ct);let Ze=A(J.toolId,Oe,ct,J.executionId),Qt=(yo=(so=(Xo=(qn=T.text)!=null?qn:T.delta)!=null?Xo:T.content)!=null?so:T.chunk)!=null?yo:"";Qt&&(Ze.content+=String(Qt),Ze.streaming=!0,f(Ze)),T.isComplete&&(Ze.streaming=!1,f(Ze));continue}let ie=T.partId;if(ie!==void 0&&E.current!==null&&ie!==E.current){let Oe=u;Oe&&(Oe.streaming=!1,f(Oe),pe=Oe,u=null,L=!0)}ie!==void 0&&(E.current=ie);let Y=ie!==void 0&&(jn=Ae.get(ie))!=null?jn:se();ie!==void 0&&(Y.partId||(Y.partId=ie),Ae.set(ie,Y));let Ie=(Kn=(ve=(ao=(V=T.text)!=null?V:T.delta)!=null?ao:T.content)!=null?ve:T.chunk)!=null?Kn:"";if(Ie){let Oe=typeof T.seq=="number"?T.seq:void 0,ct=ie!=null?ie:Y.id,Ye=Oe!==void 0?$e(ct,Oe,String(Ie)):((io=ae.get(Y.id))!=null?io:"")+Ie;Y.rawContent=Ye,oe.has(Y.id)||oe.set(Y.id,this.createStreamParser());let Xe=oe.get(Y.id),Ze=Ye.trim().startsWith("{")||Ye.trim().startsWith("[");if(Ze&&ae.set(Y.id,Ye),Xe.__isPlainTextParser===!0){Y.content=Oe!==void 0?Ye:Y.content+Ie,ae.delete(Y.id),oe.delete(Y.id),Y.rawContent=void 0,f(Y);continue}let Lt=Xe.processChunk(Ye);if(Lt instanceof Promise)Lt.then(Ht=>{var bn;let an=typeof Ht=="string"?Ht:(bn=Ht==null?void 0:Ht.text)!=null?bn:null;if(an!==null&&an.trim()!=="")Y.content=an,f(Y);else if(!Ze&&!Ye.trim().startsWith("<")){let fn=u,tn=fn&&fn.id===Y.id?fn:Y;tn.id===Y.id&&(tn.content=Oe!==void 0?Ye:tn.content+Ie,ae.delete(tn.id),oe.delete(tn.id),tn.rawContent=void 0,f(tn))}}).catch(()=>{Y.content=Oe!==void 0?Ye:Y.content+Ie,ae.delete(Y.id),oe.delete(Y.id),Y.rawContent=void 0,f(Y)});else{let Ht=typeof Lt=="string"?Lt:(vo=Lt==null?void 0:Lt.text)!=null?vo:null;Ht!==null&&Ht.trim()!==""?(Y.content=Ht,f(Y)):!Ze&&!Ye.trim().startsWith("<")&&(Y.content=Oe!==void 0?Ye:Y.content+Ie,ae.delete(Y.id),oe.delete(Y.id),Y.rawContent=void 0,f(Y))}}if(T.isComplete){let Oe=(xo=(us=T.result)==null?void 0:us.response)!=null?xo:Y.content;if(Oe){let ct=ae.get(Y.id),Ye=ct!=null?ct:ee(Oe);Y.rawContent=Ye;let Xe=oe.get(Y.id),Ze=null,Qt=!1;if(Xe&&(Ze=Xe.getExtractedText(),Ze===null&&(Ze=kr(Ye)),Ze===null)){let Lt=Xe.processChunk(Ye);Lt instanceof Promise?(Qt=!0,Lt.then(Ht=>{var bn;let an=typeof Ht=="string"?Ht:(bn=Ht==null?void 0:Ht.text)!=null?bn:null;if(an!==null){let fn=u;fn&&fn.id===Y.id&&(fn.content=an,fn.streaming=!1,oe.delete(fn.id),ae.delete(fn.id),f(fn))}})):Ze=typeof Lt=="string"?Lt:(wo=Lt==null?void 0:Lt.text)!=null?wo:null}if(!Qt){Ze!==null&&Ze.trim()!==""?Y.content=Ze:ae.has(Y.id)||(Y.content=ee(Oe));let Lt=oe.get(Y.id);if(Lt){let Ht=(Co=Lt.close)==null?void 0:Co.call(Lt);Ht instanceof Promise&&Ht.catch(()=>{}),oe.delete(Y.id)}ae.delete(Y.id),Y.streaming=!1,f(Y)}}}}else if(Ge==="step_complete"){let U=T.stepType,R=T.executionType;if(U==="tool"||R==="context")continue;let J=T.toolContext;if(J!=null&&J.toolId){let Oe=String((pr=(Fo=T.id)!=null?Fo:J.stepId)!=null?pr:"");if(Oe){let ct=S(J.toolId,Oe);for(let[Ye,Xe]of H)Ye.startsWith(ct)&&Xe.streaming!==!1&&(Xe.streaming=!1,f(Xe));W.delete(`${J.toolId}::${Oe}`)}continue}let ie=T.stopReason;if(L){if(u!==null){let Ye=u;ie&&(Ye.stopReason=ie),oe.delete(Ye.id),ae.delete(Ye.id),Ye.streaming!==!1&&(Ye.streaming=!1,f(Ye))}let Oe=(ua=T.result)==null?void 0:ua.response,ct=pe;ct&&(ie&&(ct.stopReason=ie),Oe!=null?We(ct,Oe):(oe.delete(ct.id),ae.delete(ct.id))),pe=null;continue}let Y=(ms=T.result)==null?void 0:ms.response,Ie=se();if(ie&&(Ie.stopReason=ie),Y!=null){let Oe=oe.get(Ie.id),ct=!1,Ye=!1;if(Oe){let Xe=Oe.getExtractedText(),Ze=ae.get(Ie.id),Qt=Ze!=null?Ze:ee(Y);if(Ie.rawContent=Qt,Xe!==null&&Xe.trim()!=="")Ie.content=Xe,ct=!0;else{let Lt=kr(Qt);if(Lt!==null)Ie.content=Lt,ct=!0;else{let Ht=Oe.processChunk(Qt);if(Ht instanceof Promise)Ye=!0,Ht.then(an=>{var fn;let bn=typeof an=="string"?an:(fn=an==null?void 0:an.text)!=null?fn:null;if(bn!==null&&bn.trim()!==""){let tn=u;tn&&tn.id===Ie.id&&(tn.content=bn,tn.streaming=!1,oe.delete(tn.id),ae.delete(tn.id),f(tn))}else{let tn=Oe.getExtractedText(),co=u;co&&co.id===Ie.id&&(tn!==null&&tn.trim()!==""?co.content=tn:ae.has(co.id)||(co.content=ee(Y)),co.streaming=!1,oe.delete(co.id),ae.delete(co.id),f(co))}});else{let an=typeof Ht=="string"?Ht:(ma=Ht==null?void 0:Ht.text)!=null?ma:null;if(an!==null&&an.trim()!=="")Ie.content=an,ct=!0;else{let bn=Oe.getExtractedText();bn!==null&&bn.trim()!==""&&(Ie.content=bn,ct=!0)}}}}}if(!Ye){if(!Ie.rawContent){let Xe=ae.get(Ie.id);Ie.rawContent=Xe!=null?Xe:ee(Y)}if(!ct&&!ae.has(Ie.id)&&(Ie.content=ee(Y)),Oe){let Xe=(Dr=Oe.close)==null?void 0:Dr.call(Oe);Xe instanceof Promise&&Xe.catch(()=>{})}oe.delete(Ie.id),ae.delete(Ie.id),Ie.streaming=!1,f(Ie)}}else oe.delete(Ie.id),ae.delete(Ie.id),Ie.streaming=!1,f(Ie)}else if(Ge==="flow_complete"){let U=(bt=T.result)==null?void 0:bt.response;if(L){if(u!==null){let R=u;oe.delete(R.id),ae.delete(R.id),R.streaming!==!1&&(R.streaming=!1,f(R))}}else if(U!=null){let R=se(),J=ae.get(R.id),ie=J!=null?J:ee(U);R.rawContent=ie;let Y=ee(U),Ie=oe.get(R.id);if(Ie){let Ye=kr(ie);if(Ye!==null)Y=Ye;else{let Xe=Ie.processChunk(ie);Xe instanceof Promise&&Xe.then(Qt=>{var Ht;let Lt=typeof Qt=="string"?Qt:(Ht=Qt==null?void 0:Qt.text)!=null?Ht:null;Lt!==null&&(R.content=Lt,R.streaming=!1,f(R))});let Ze=Ie.getExtractedText();Ze!==null&&(Y=Ze)}}oe.delete(R.id),ae.delete(R.id);let Oe=Y!==R.content,ct=R.streaming!==!1;Oe&&(R.content=Y),R.streaming=!1,(Oe||ct)&&f(R)}else if(u!==null){let R=u;oe.delete(R.id),ae.delete(R.id),R.streaming!==!1&&(R.streaming=!1,f(R))}n({type:"status",status:"idle"})}else if(Ge==="agent_start")ce={executionId:T.executionId,agentId:(gs=T.agentId)!=null?gs:"virtual",agentName:(lo=T.agentName)!=null?lo:"",status:"running",currentIteration:0,maxTurns:(Wn=T.maxTurns)!=null?Wn:1,startedAt:Ue(T.startedAt)};else if(Ge==="agent_iteration_start"){if(ce&&(ce.currentIteration=T.iteration),$t==="separate"&&T.iteration>1){let U=u;U&&(U.streaming=!1,f(U),Rn.set(T.iteration-1,U),u=null)}}else if(Ge==="agent_turn_start")C=null;else if(Ge==="agent_turn_delta"){if(T.contentType==="text"){let U=se();U.content+=(ga=T.delta)!=null?ga:"",U.agentMetadata={executionId:T.executionId,iteration:T.iteration,turnId:T.turnId,agentName:ce==null?void 0:ce.agentName},C=U,f(U)}else if(T.contentType==="thinking"){let U=(fa=T.turnId)!=null?fa:`agent-think-${T.iteration}`,R=Fe(U);R.reasoning=(Fr=R.reasoning)!=null?Fr:{id:U,status:"streaming",chunks:[]},R.reasoning.chunks.push((Oo=T.delta)!=null?Oo:""),R.agentMetadata={executionId:T.executionId,iteration:T.iteration,turnId:T.turnId},f(R)}else if(T.contentType==="tool_input"){let U=(ha=T.toolCallId)!=null?ha:w.lastId;if(U){let R=P.get(U);R!=null&&R.toolCall&&(R.toolCall.chunks=(ur=R.toolCall.chunks)!=null?ur:[],R.toolCall.chunks.push((fs=T.delta)!=null?fs:""),f(R))}}}else if(Ge==="agent_turn_complete"){let U=T.turnId;if(U){let ie=I.get(U);if(ie!=null&&ie.reasoning){ie.reasoning.status="complete",ie.reasoning.completedAt=Ue(T.completedAt);let Y=(No=ie.reasoning.startedAt)!=null?No:Date.now();ie.reasoning.durationMs=Math.max(0,((hs=ie.reasoning.completedAt)!=null?hs:Date.now())-Y),ie.streaming=!1,f(ie)}}let R=T.stopReason,J=u!=null?u:C;if(R&&J!==null){let ie=T.turnId;(!ie||((Qo=J.agentMetadata)==null?void 0:Qo.turnId)===ie)&&(J.stopReason=R,f(J))}}else if(Ge==="agent_tool_start"){u&&(u.streaming=!1,f(u),u=null);let U=(Jo=T.toolCallId)!=null?Jo:`agent-tool-${l()}`;xe(G(T),U);let R=Ce(U),J=(ba=R.toolCall)!=null?ba:{id:U,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};J.name=(Gi=(ya=T.toolName)!=null?ya:T.name)!=null?Gi:J.name,J.status="running",T.parameters!==void 0&&(J.args=T.parameters),J.startedAt=Ue((mr=T.startedAt)!=null?mr:T.timestamp),R.toolCall=J,R.streaming=!0,R.agentMetadata={executionId:T.executionId,iteration:T.iteration},f(R)}else if(Ge==="agent_tool_delta"){let U=(Zo=T.toolCallId)!=null?Zo:w.lastId;if(U){let R=(va=P.get(U))!=null?va:Ce(U);R.toolCall&&(R.toolCall.chunks=(bs=R.toolCall.chunks)!=null?bs:[],R.toolCall.chunks.push((er=T.delta)!=null?er:""),R.toolCall.status="running",R.streaming=!0,f(R))}}else if(Ge==="agent_tool_complete"){let U=(xa=T.toolCallId)!=null?xa:w.lastId;if(U){let R=(ys=P.get(U))!=null?ys:Ce(U);if(R.toolCall){R.toolCall.status="complete",T.result!==void 0&&(R.toolCall.result=T.result),typeof T.executionTime=="number"&&(R.toolCall.durationMs=T.executionTime),R.toolCall.completedAt=Ue((tr=T.completedAt)!=null?tr:T.timestamp),R.streaming=!1,f(R);let J=G(T);J&&w.byCall.delete(J)}}}else if(Ge==="agent_media"){let U=Array.isArray(T.media)?T.media:[],R=[];for(let J of U){if(!J||typeof J!="object")continue;let ie=J,Y=typeof ie.type=="string"?ie.type:void 0,Ie=typeof ie.mediaType=="string"?ie.mediaType.toLowerCase():"",Oe=null,ct="";if(Y==="media"){let Ye=typeof ie.data=="string"?ie.data:void 0;if(!Ye)continue;ct=Ie.length>0?Ie:"application/octet-stream",Oe=`data:${ct};base64,${Ye}`}else if(Y==="image-url"){let Ye=typeof ie.url=="string"?ie.url:void 0;if(!Ye)continue;ct=Ie,Oe=Ye}else if(Y==="file-url"){let Ye=typeof ie.url=="string"?ie.url:void 0;if(!Ye)continue;ct=Ie,Oe=Ye}else continue;if(Oe)if(Y==="image-url"||ct.startsWith("image/"))R.push({type:"image",image:Oe,...ct?{mimeType:ct}:{}});else if(ct.startsWith("audio/"))R.push({type:"audio",audio:Oe,mimeType:ct});else if(ct.startsWith("video/"))R.push({type:"video",video:Oe,mimeType:ct});else{let Ye=ct||"application/octet-stream";R.push({type:"file",data:Oe,mimeType:Ye,filename:lh(Ye)})}}if(R.length>0){let J=l(),ie=T.toolCallId,Ie={id:`agent-media-${typeof ie=="string"&&ie.length>0?`${ie}-${J}`:String(J)}`,role:"assistant",content:"",contentParts:R,createdAt:new Date().toISOString(),streaming:!1,sequence:J,agentMetadata:{executionId:T.executionId,iteration:T.iteration}};f(Ie);let Oe=u;Oe&&(Oe.streaming=!1,f(Oe)),u=null,v.current=null}}else if(Ge!=="agent_iteration_complete"){if(Ge==="agent_reflection"||Ge==="agent_reflect"){let U=`agent-reflection-${T.executionId}-${T.iteration}`,R={id:U,role:"assistant",content:(vs=T.reflection)!=null?vs:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:U,status:"complete",chunks:[(wa=T.reflection)!=null?wa:""]},agentMetadata:{executionId:T.executionId,iteration:T.iteration}};f(R)}else if(Ge==="agent_complete"){ce&&(ce.status=T.success?"complete":"error",ce.completedAt=Ue(T.completedAt),ce.stopReason=T.stopReason);let U=u;U&&(U.streaming=!1,f(U)),n({type:"status",status:"idle"})}else if(Ge==="agent_error"){let U=typeof T.error=="string"?T.error:(Ca=(_o=T.error)==null?void 0:_o.message)!=null?Ca:"Agent execution error";T.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",U):n({type:"error",error:new Error(U)})}else if(Ge!=="agent_ping"){if(Ge==="agent_approval_start"){let U=(nr=T.approvalId)!=null?nr:`approval-${l()}`,R={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(Ft=ce==null?void 0:ce.agentId)!=null?Ft:"virtual",executionId:(Nr=(Or=T.executionId)!=null?Or:ce==null?void 0:ce.executionId)!=null?Nr:"",toolName:(xs=T.toolName)!=null?xs:"",toolType:T.toolType,description:(Sa=T.description)!=null?Sa:`Execute ${(Lo=T.toolName)!=null?Lo:"tool"}`,parameters:T.parameters}};f(R)}else if(Ge==="step_await"&&T.awaitReason==="approval_required"){let U=(ws=T.approvalId)!=null?ws:`approval-${l()}`,R={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(Cs=ce==null?void 0:ce.agentId)!=null?Cs:"virtual",executionId:(_r=(Aa=T.executionId)!=null?Aa:ce==null?void 0:ce.executionId)!=null?_r:"",toolName:(Vr=T.toolName)!=null?Vr:"",toolType:T.toolType,description:(Ta=T.description)!=null?Ta:`Execute ${(gr=T.toolName)!=null?gr:"tool"}`,parameters:T.parameters}};f(R)}else if(Ge==="agent_approval_complete"){let U=T.approvalId;if(U){let J={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:(ka=T.decision)!=null?ka:"approved",agentId:(Ss=ce==null?void 0:ce.agentId)!=null?Ss:"virtual",executionId:(Ts=(As=T.executionId)!=null?As:ce==null?void 0:ce.executionId)!=null?Ts:"",toolName:(ks=T.toolName)!=null?ks:"",description:(En=T.description)!=null?En:"",resolvedAt:Date.now()}};f(J)}}else if(Ge==="artifact_start"||Ge==="artifact_delta"||Ge==="artifact_update"||Ge==="artifact_complete"){if(Ge==="artifact_start"){let U=T.artifactType,R=String(T.id),J=typeof T.title=="string"?T.title:void 0;if(n({type:"artifact_start",id:R,artifactType:U,title:J,component:typeof T.component=="string"?T.component:void 0}),ye.set(R,{markdown:"",title:J}),!K.has(R)){K.add(R);let ie={id:`artifact-ref-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:R,title:J,artifactType:U,status:"streaming"}})};de.set(R,ie),f(ie)}}else if(Ge==="artifact_delta"){let U=String(T.id),R=typeof T.delta=="string"?T.delta:String((Gn=T.delta)!=null?Gn:"");n({type:"artifact_delta",id:U,artDelta:R});let J=ye.get(U);J&&(J.markdown+=R)}else if(Ge==="artifact_update"){let U=T.props&&typeof T.props=="object"&&!Array.isArray(T.props)?T.props:{};n({type:"artifact_update",id:String(T.id),props:U,component:typeof T.component=="string"?T.component:void 0})}else if(Ge==="artifact_complete"){let U=String(T.id);n({type:"artifact_complete",id:U});let R=de.get(U);if(R){R.streaming=!1;try{let J=JSON.parse((Vo=R.rawContent)!=null?Vo:"{}");if(J.props){J.props.status="complete";let ie=ye.get(U);ie!=null&&ie.markdown&&(J.props.markdown=ie.markdown)}R.rawContent=JSON.stringify(J)}catch{}ye.delete(U),f(R),de.delete(U)}}}else if(Ge==="transcript_insert"){let U=T.message;if(!U||typeof U!="object")continue;let R=String((lt=U.id)!=null?lt:`msg-${l()}`),J=U.role,Y={id:R,role:J==="user"?"user":J==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:l()};if(f(Y),Y.rawContent)try{let Ie=JSON.parse(Y.rawContent),Oe=(Es=Ie==null?void 0:Ie.props)==null?void 0:Es.artifactId;typeof Oe=="string"&&K.add(Oe)}catch{}u=null,v.current=null,oe.delete(R),ae.delete(R)}else if(Ge==="error"||Ge==="step_error"||Ge==="dispatch_error"||Ge==="flow_error"){let U=null;if(T.error instanceof Error)U=T.error;else if(Ge==="dispatch_error"){let R=(fr=T.message)!=null?fr:T.error;R!=null&&R!==""&&(U=new Error(String(R)))}else if(Ge==="step_error"||Ge==="flow_error"){let R=T.error;typeof R=="string"&&R!==""?U=new Error(R):R!=null&&typeof R=="object"&&"message"in R&&(U=new Error(String((So=R.message)!=null?So:R)))}else Ge==="error"&&T.error!=null&&T.error!==""&&(U=new Error(String(T.error)));if(U){n({type:"error",error:U});let R=u;R&&R.streaming&&(R.streaming=!1,f(R)),n({type:"status",status:"idle"})}}}}}ue.length=0};;){let{done:_,value:Me}=await r.read();if(_)break;a+=s.decode(Me,{stream:!0});let Be=a.split(`
10
10
 
11
- `);a=(Dn=He.pop())!=null?Dn:"";for(let De of He){let Ve=De.split(`
12
- `),dt="message",ot="";for(let q of Ve)q.startsWith("event:")?dt=q.replace("event:","").trim():q.startsWith("data:")&&(ot+=q.replace("data:","").trim());if(!ot)continue;let At;try{At=JSON.parse(ot)}catch(q){n({type:"error",error:q instanceof Error?q:new Error("Failed to parse chat stream payload")});continue}let Vt=dt!=="message"?dt:(Jn=At.type)!=null?Jn:"message";if((ze=this.onSSEEvent)==null||ze.call(this,Vt,At),this.parseSSEEvent){C.current=u;let q=await this.handleCustomSSEEvent(At,n,C,f,l,M);if(C.current&&C.current!==u&&(u=C.current),q)continue}pe.push(Vt,At),_e()}}pe.flushPending(),_e(),pe.destroy()}};function Ya(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Ws(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Xa="[Image]";function ll(e){return{type:"text",text:e}}var Iu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Xf=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],_o=[...Iu,...Xf];function Qf(e){return Iu.includes(e)||e.startsWith("image/")}function Qa(e){return Qf(e.type)}async function Ru(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Qa(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function Pu(e,t=_o,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Jf(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Wu(e,t){let n=Jf(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var Ja=class{constructor(t=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=t}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let d=new Uint8Array(this.remainder.length+t.length);d.set(this.remainder),d.set(t,this.remainder.length),n=d,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.ensureContext(),r=this.pcmToFloat32(n),s=o.createBuffer(1,r.length,this.sampleRate);s.getChannelData(0).set(r);let a=o.createBufferSource();a.buffer=s,a.connect(o.destination);let i=o.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=s.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=r.getInt16(s*2,!0);o[s]=a/32768}return o}};var Za=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,o,r,s){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(n),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let p=0;p<a.length;p++)i+=a[p]*a[p];let d=Math.sqrt(i/a.length);(o==="silence"?d<r.threshold:d>=r.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=r.duration&&(this.fired=!0,s()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Bs=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new Za;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,n,o;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let r=this.w;if(!r||!r.location)throw new Error("Window object or location not available");let s=r.location.protocol==="https:"?"wss:":"ws:",a=(t=this.config)==null?void 0:t.host,i=(n=this.config)==null?void 0:n.agentId,d=(o=this.config)==null?void 0:o.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let p=`${s}//${a}/ws/agents/${i}/voice?token=...`,m=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,u)=>{if(!this.ws)return u(new Error("WebSocket not created"));let w=!1,C=I=>{w||(w=!0,clearTimeout(M),u(new Error(I)))},M=setTimeout(()=>C("WebSocket connection timed out."+m),1e4);this.ws.addEventListener("open",()=>{w||(w=!0,clearTimeout(M),f())},{once:!0}),this.ws.addEventListener("error",()=>{C("WebSocket connection failed to "+p+"."+m)},{once:!0}),this.ws.addEventListener("close",I=>{if(!I.wasClean&&!w){let R=I.code!==1006?` (code ${I.code})`:"";C("WebSocket connection failed"+R+"."+m)}},{once:!0})}),this.sendHeartbeat()}catch(r){throw this.ws=null,this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(n=>n(new Error("WebSocket error"))),this.statusCallbacks.forEach(n=>n("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let n=JSON.parse(t.data);this.handleWebSocketMessage(n)}catch{this.errorCallbacks.forEach(o=>o(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var n,o;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(r=>r({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),(n=t.response.audio)!=null&&n.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(r=>r("speaking")),this.playAudio(t.response.audio).catch(r=>this.errorCallbacks.forEach(s=>s(r instanceof Error?r:new Error(String(r)))))):(o=t.response.audio)!=null&&o.base64;break;case"audio_end":if(t.requestId&&t.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(r=>r("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(r=>r(new Error(t.error))),this.statusCallbacks.forEach(r=>r("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Ja(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,n,o,r;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(r=(o=this.config)==null?void 0:o.silenceThreshold)!=null?r:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let p=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",m=new Blob(this.audioChunks,{type:p});await this.sendAudio(m),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var s,a;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let n=this.audioContext,o=(a=(s=this.config)==null?void 0:s.silenceThreshold)!=null?a:.01;this.vad.start(n,this.mediaStream,"speech",{threshold:o,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(n=>n(t instanceof Error?t:new Error(String(t))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(t){var n;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(o=>o(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(o=>o("error"));return}try{let o=await this.blobToBase64(t),r=this.getFormatFromMimeType(t.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:o,format:r,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:s}))}catch(o){this.errorCallbacks.forEach(r=>r(o)),this.statusCallbacks.forEach(r=>r("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,o)=>{let r=new FileReader;r.onload=()=>{let a=r.result.split(",")[1];n(a)},r.onerror=o,r.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let n=atob(t.base64),o=new Uint8Array(n.length);for(let l=0;l<n.length;l++)o[l]=n.charCodeAt(l);let r=t.format||"mp3",s=r==="mp3"?"audio/mpeg":`audio/${r}`,a=new Blob([o],{type:s}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Sr=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let o=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!o)throw new Error("Browser speech recognition not supported");this.recognition=new o,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=r=>{var i;let s=Array.from(r.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=r.results[r.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=r=>{this.errorCallbacks.forEach(s=>s(new Error(r.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(r=>r("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(r=>r("idle"))},this.recognition.start()}catch(o){throw this.errorCallbacks.forEach(r=>r(o)),this.statusCallbacks.forEach(r=>r("error")),o}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Hs(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Bs(e.runtype);case"browser":if(!Sr.isSupported())throw new Error("Browser speech recognition not supported");return new Sr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Bu(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Hs({type:"runtype",runtype:e.runtype});if(Sr.isSupported())return Hs({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function cl(e){try{return Bu(e),!0}catch{return!1}}function Hu(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let o="Sorry \u2014 I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
11
+ `);a=(Dn=Be.pop())!=null?Dn:"";for(let He of Be){let _e=He.split(`
12
+ `),ut="message",st="";for(let q of _e)q.startsWith("event:")?ut=q.replace("event:","").trim():q.startsWith("data:")&&(st+=q.replace("data:","").trim());if(!st)continue;let Rt;try{Rt=JSON.parse(st)}catch(q){n({type:"error",error:q instanceof Error?q:new Error("Failed to parse chat stream payload")});continue}let qt=ut!=="message"?ut:(eo=Rt.type)!=null?eo:"message";if((ze=this.onSSEEvent)==null||ze.call(this,qt,Rt),this.parseSSEEvent){v.current=u;let q=await this.handleCustomSSEEvent(Rt,n,v,f,l,E);if(v.current&&v.current!==u&&(u=v.current),q)continue}he.push(qt,Rt),Ne()}}he.flushPending(),Ne(),he.destroy()}};function Za(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function _s(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var ei="[Image]";function fl(e){return{type:"text",text:e}}var _u=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ph=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Uo=[..._u,...ph];function uh(e){return _u.includes(e)||e.startsWith("image/")}function ti(e){return uh(e.type)}async function Vu(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;ti(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function $u(e,t=Uo,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function mh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Uu(e,t){let n=mh(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var ni=class{constructor(t=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=t}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let d=new Uint8Array(this.remainder.length+t.length);d.set(this.remainder),d.set(t,this.remainder.length),n=d,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.ensureContext(),r=this.pcmToFloat32(n),s=o.createBuffer(1,r.length,this.sampleRate);s.getChannelData(0).set(r);let a=o.createBufferSource();a.buffer=s,a.connect(o.destination);let i=o.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=s.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=r.getInt16(s*2,!0);o[s]=a/32768}return o}};var oi=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,o,r,s){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(n),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let m=0;m<a.length;m++)i+=a[m]*a[m];let d=Math.sqrt(i/a.length);(o==="silence"?d<r.threshold:d>=r.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=r.duration&&(this.fired=!0,s()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Vs=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new oi;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,n,o;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let r=this.w;if(!r||!r.location)throw new Error("Window object or location not available");let s=r.location.protocol==="https:"?"wss:":"ws:",a=(t=this.config)==null?void 0:t.host,i=(n=this.config)==null?void 0:n.agentId,d=(o=this.config)==null?void 0:o.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let m=`${s}//${a}/ws/agents/${i}/voice?token=...`,p=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,u)=>{if(!this.ws)return u(new Error("WebSocket not created"));let C=!1,v=L=>{C||(C=!0,clearTimeout(E),u(new Error(L)))},E=setTimeout(()=>v("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{C||(C=!0,clearTimeout(E),f())},{once:!0}),this.ws.addEventListener("error",()=>{v("WebSocket connection failed to "+m+"."+p)},{once:!0}),this.ws.addEventListener("close",L=>{if(!L.wasClean&&!C){let I=L.code!==1006?` (code ${L.code})`:"";v("WebSocket connection failed"+I+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(r){throw this.ws=null,this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(n=>n(new Error("WebSocket error"))),this.statusCallbacks.forEach(n=>n("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let n=JSON.parse(t.data);this.handleWebSocketMessage(n)}catch{this.errorCallbacks.forEach(o=>o(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var n,o;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(r=>r({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),(n=t.response.audio)!=null&&n.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(r=>r("speaking")),this.playAudio(t.response.audio).catch(r=>this.errorCallbacks.forEach(s=>s(r instanceof Error?r:new Error(String(r)))))):(o=t.response.audio)!=null&&o.base64;break;case"audio_end":if(t.requestId&&t.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(r=>r("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(r=>r(new Error(t.error))),this.statusCallbacks.forEach(r=>r("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new ni(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,n,o,r;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(r=(o=this.config)==null?void 0:o.silenceThreshold)!=null?r:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let m=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:m});await this.sendAudio(p),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var s,a;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let n=this.audioContext,o=(a=(s=this.config)==null?void 0:s.silenceThreshold)!=null?a:.01;this.vad.start(n,this.mediaStream,"speech",{threshold:o,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(n=>n(t instanceof Error?t:new Error(String(t))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(t){var n;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(o=>o(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(o=>o("error"));return}try{let o=await this.blobToBase64(t),r=this.getFormatFromMimeType(t.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:o,format:r,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:s}))}catch(o){this.errorCallbacks.forEach(r=>r(o)),this.statusCallbacks.forEach(r=>r("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,o)=>{let r=new FileReader;r.onload=()=>{let a=r.result.split(",")[1];n(a)},r.onerror=o,r.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let n=atob(t.base64),o=new Uint8Array(n.length);for(let l=0;l<n.length;l++)o[l]=n.charCodeAt(l);let r=t.format||"mp3",s=r==="mp3"?"audio/mpeg":`audio/${r}`,a=new Blob([o],{type:s}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Er=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let o=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!o)throw new Error("Browser speech recognition not supported");this.recognition=new o,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=r=>{var i;let s=Array.from(r.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=r.results[r.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=r=>{this.errorCallbacks.forEach(s=>s(new Error(r.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(r=>r("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(r=>r("idle"))},this.recognition.start()}catch(o){throw this.errorCallbacks.forEach(r=>r(o)),this.statusCallbacks.forEach(r=>r("error")),o}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function $s(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Vs(e.runtype);case"browser":if(!Er.isSupported())throw new Error("Browser speech recognition not supported");return new Er(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function zu(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return $s({type:"runtype",runtype:e.runtype});if(Er.isSupported())return $s({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function hl(e){try{return zu(e),!0}catch{return!1}}function qu(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let o="Sorry \u2014 I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
13
13
 
14
- _Details: ${n.message}_`:o}var ei=class e{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=t=>{var n,o,r,s,a,i,d,l;if(t.type==="message"){this.upsertMessage(t.message);let p=t.message.toolCall;((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&(p!=null&&p.name)&&sl(p.name)&&this.enqueueWebMcpAwait(t.message),(o=t.message.agentMetadata)!=null&&o.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(r=t.message.agentMetadata.agentName)!=null?r:"",status:"running",currentIteration:(s=t.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let p=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":p||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var o,r;this.messages=[...(o=t.initialMessages)!=null?o:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Ps(t),this.wireDefaultWebMcpConfirm();for(let s of(r=t.initialArtifacts)!=null?r:[])this.artifacts.set(s.id,{...s,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return cl((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,o;return(o=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?o:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(t){var n,o,r;try{let s=t||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=Hs(s);let a=(n=this.config.voiceRecognition)!=null?n:{},i=(o=a.processingText)!=null?o:"\u{1F3A4} Processing voice...",d=(r=a.processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var p,m,f,u,w,C;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((p=l.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=l.transcript)!=null&&m.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=l.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(u=l.text)!=null&&u.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let M=(C=this.pendingVoiceAssistantMessageId)!=null?C:(w=[...this.messages].reverse().find(I=>I.role==="assistant"))==null?void 0:w.id;M&&this.ttsSpokenMessageIds.add(M)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var p,m;this.voiceStatus=l,this.voiceActive=l==="listening",(m=(p=this.callbacks).onVoiceStatusChanged)==null||m.call(p,l)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,o,r,s,a,i,d,l,p;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((o=t.runtype)==null?void 0:o.agentId)||"",clientToken:((r=t.runtype)==null?void 0:r.clientToken)||"",host:(s=t.runtype)==null?void 0:s.host,voiceId:(a=t.runtype)==null?void 0:a.voiceId,pauseDuration:(i=t.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=t.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=t.browser)==null?void 0:l.language)||"en-US",continuous:(p=t.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let o=await this.client.initSession();return this.setClientSession(o),o}catch(o){return(n=(t=this.callbacks).onError)==null||n.call(t,o instanceof Error?o:new Error(String(o))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let n=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new Ps(this.config),this.wireDefaultWebMcpConfirm(),n&&this.client.setSSEEventCallback(n)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:p,rawContent:m}=t,u={id:a!=null?a:n==="user"?Ya():n==="assistant"?Ws():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};return this.upsertMessage(u),u}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:p,streaming:m=!1,voiceProcessing:f,rawContent:u}=o,C={id:d!=null?d:r==="user"?Ya():r==="assistant"?Ws():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...u!==void 0&&{rawContent:u}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:i,sequence:d}=t,l={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(l),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var l,p,m,f,u;let o=t.trim();if(!o&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let r=Ya(),s=Ws(),a={id:r,role:"user",content:o||Xa,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(w){let C=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));if(!C){let M=Hu(w,this.config.errorMessage);if(M){let I={id:s,role:"assistant",createdAt:new Date().toISOString(),content:M,sequence:this.nextSequence()};this.appendMessage(I)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,C||(w instanceof Error?(m=(p=this.callbacks).onError)==null||m.call(p,w):(u=(f=this.callbacks).onError)==null||u.call(f,new Error(String(w))))}}async continueConversation(){var r,s,a,i,d;if(this.streaming)return;(r=this.abortController)==null||r.abort();let t=Ws();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(l){let p=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!p){let m=Hu(l,this.config.errorMessage);if(m){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:m,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var r,s,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(r=this.abortController)==null||r.abort();let o=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var r,s,a;try{if(((s=(r=this.config.webmcp)==null?void 0:r.autoApprove)==null?void 0:s.call(r,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(o,i)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r!=null&&r.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n){var d,l,p,m;let o=`approval-${t.id}`,r={...t,status:n,resolvedAt:Date.now()},s={id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:r};this.upsertMessage(s),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let f;if(i?f=await i({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n):f=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),f){let u=null;if(f instanceof Response){if(!f.ok){let w=await f.json().catch(()=>null);throw new Error((l=w==null?void 0:w.error)!=null?l:`Approval request failed: ${f.status}`)}u=f.body}else f instanceof ReadableStream&&(u=f);u?await this.connectStream(u,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(f){let u=f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||(m=(p=this.callbacks).onError)==null||m.call(p,f instanceof Error?f:new Error(String(f)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,m,f,u,w,C,M,I,R,H,D,B;let o=this.messages.find(v=>v.id===t.id);if(((p=o==null?void 0:o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let r=(m=t.agentMetadata)==null?void 0:m.executionId,s=(f=t.toolCall)==null?void 0:f.name;if(!r||!s){(w=(u=this.callbacks).onError)==null||w.call(u,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let v=(C=t.toolCall)==null?void 0:C.args,x=Array.isArray(v==null?void 0:v.questions)?v.questions:[];if(x.length===1){let k=typeof((M=x[0])==null?void 0:M.question)=="string"?x[0].question:"";k&&(a={[k]:n})}}this.markAskUserQuestionResolved(t,a),(I=this.abortController)==null||I.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(R=t.toolCall)==null?void 0:R.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let v=typeof n=="string"?n:Object.entries(n).map(([x,k])=>`${x}: ${Array.isArray(k)?k.join(", "):k}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:v,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let v=a!=null?a:{};l.forEach((x,k)=>{let S=typeof(x==null?void 0:x.question)=="string"?x.question:"";if(!S)return;let E=v[S],F=Array.isArray(E)?E.join(", "):typeof E=="string"?E:"";this.appendMessage({id:`ask-user-q-${i}-${k}`,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${k}`,role:"user",content:F||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let v=await this.client.resumeFlow(r,{[s]:n});if(!v.ok){let x=await v.json().catch(()=>null);throw new Error((H=x==null?void 0:x.error)!=null?H:`Resume failed: ${v.status}`)}v.body?await this.connectStream(v.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,x||(B=(D=this.callbacks).onError)==null||B.call(D,v instanceof Error?v:new Error(String(v)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,o=(a=t.toolCall)==null?void 0:a.id;if(!n||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}async resolveWebMcpToolCallBatch(t,n){var i,d,l;let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async p=>{var R,H,D,B,v,x,k;let m=(R=p.toolCall)==null?void 0:R.name,f=(H=p.toolCall)==null?void 0:H.id;if(!m||!f)return null;let u=`${t}:${f}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u))return null;this.webMcpInflightKeys.add(u),o.push(u),this.upsertMessage({...p,agentMetadata:{...p.agentMetadata,awaitingLocalTool:!1}});let w=new AbortController;this.webMcpResolveControllers.add(w),r.push(w);let C=(B=(D=p.agentMetadata)==null?void 0:D.webMcpToolCallId)!=null?B:m,M=this.client.executeWebMcpToolCall(m,(v=p.toolCall)==null?void 0:v.args,w.signal),I;if(!M)I={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{I=await M}catch(S){return S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"))||(k=(x=this.callbacks).onError)==null||k.call(x,S instanceof Error?S:new Error(String(S))),this.webMcpInflightKeys.delete(u),null}return w.signal.aborted?(this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:C,output:I}}));try{let p=a.filter(u=>u!==null);if(p.length===0)return;let m={};for(let u of p)m[u.resumeKey]=u.output;let f=await this.client.resumeFlow(t,m,{signal:s.signal});if(!f.ok){let u=await f.json().catch(()=>null);throw new Error((i=u==null?void 0:u.error)!=null?i:`Resume failed: ${f.status}`)}for(let u of p)this.webMcpResolvedKeys.add(u.dedupeKey);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(p){p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))||(l=(d=this.callbacks).onError)==null||l.call(d,p instanceof Error?p:new Error(String(p)))}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of r)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var p,m,f,u,w,C,M,I,R,H,D,B;let n=(p=t.agentMetadata)==null?void 0:p.executionId,o=(m=t.toolCall)==null?void 0:m.name,r=(f=t.toolCall)==null?void 0:f.id;if(!n){(w=(u=this.callbacks).onError)==null||w.call(u,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!o)return;if(!r){let v=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v))return;this.webMcpInflightKeys.add(v);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(v)}catch(x){(M=(C=this.callbacks).onError)==null||M.call(C,x instanceof Error?x:new Error(String(x)))}finally{this.webMcpInflightKeys.delete(v)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s))return;this.webMcpInflightKeys.add(s),this.upsertMessage({...t,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1}});let a=new AbortController;this.webMcpResolveControllers.add(a);let{signal:i}=a;this.setStreaming(!0);let d=(I=t.toolCall)==null?void 0:I.args,l=this.client.executeWebMcpToolCall(o,d,i);try{let v;if(l?v=await l:v={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},i.aborted)return;let x=(H=(R=t.agentMetadata)==null?void 0:R.webMcpToolCallId)!=null?H:o;await this.resumeWithToolOutput(n,x,v,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s)},signal:i})}catch(v){v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"))||(B=(D=this.callbacks).onError)==null||B.call(D,v instanceof Error?v:new Error(String(v)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){var a,i;let s=await this.client.resumeFlow(t,{[n]:o},{signal:r==null?void 0:r.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=r==null?void 0:r.onHttpOk)==null||i.call(r),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var r;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let o={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(r=t.props)!=null?r:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),o}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,o;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let r=this.artifacts.get(t.id);(r==null?void 0:r.artifactType)==="markdown"&&(r.markdown=((o=r.markdown)!=null?o:"")+t.artDelta);break}case"artifact_update":{let r=this.artifacts.get(t.id);(r==null?void 0:r.artifactType)==="component"&&(r.props={...r.props,...t.props},t.component&&(r.component=t.component));break}case"artifact_complete":{let r=this.artifacts.get(t.id);r&&(r.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>{var r;return{...o,streaming:!1,sequence:(r=o.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=o.content;r.trim()&&this.speak(r,t)}speak(t,n){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t),s=o.getVoices();if(n.voice){let a=s.find(i=>i.name===n.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=n.pickVoice?n.pickVoice(s):e.pickBestVoice(s));n.rate!==void 0&&(r.rate=n.rate),n.pitch!==void 0&&(r.pitch=n.pitch),setTimeout(()=>o.speak(r),50)}static pickBestVoice(t){var o;let n=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of n){let s=t.find(a=>a.name===r);if(s)return s}return(o=t.find(r=>r.lang.startsWith("en")))!=null?o:t[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{var p,m,f,u,w,C;if(s!==o)return r;let a={...r,...n};((p=r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(m=n.toolCall)==null?void 0:m.name,d=(f=n.agentMetadata)==null?void 0:f.executionId,l=(u=n.toolCall)==null?void 0:u.id;if(i&&sl(i)&&d&&l&&((w=n.agentMetadata)==null?void 0:w.awaitingLocalTool)===!0){let M=`${d}:${l}`;(this.webMcpInflightKeys.has(M)||this.webMcpResolvedKeys.has(M))&&(a.agentMetadata={...(C=a.agentMetadata)!=null?C:{},awaitingLocalTool:!1})}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{var d,l;let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=(d=n.sequence)!=null?d:0,i=(l=o.sequence)!=null?l:0;return a!==i?a-i:n.id.localeCompare(o.id)})}};var b=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Eo=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o};import{Activity as Zf,ArrowDown as eh,ArrowUp as th,ArrowUpRight as nh,Bot as oh,ChevronDown as rh,ChevronUp as sh,ChevronRight as ah,ChevronLeft as ih,Check as lh,Clipboard as ch,ClipboardCopy as dh,Copy as ph,File as uh,FileCode as mh,FileSpreadsheet as gh,FileText as fh,ImagePlus as hh,Loader as bh,LoaderCircle as yh,Mic as vh,Paperclip as xh,RefreshCw as wh,Search as Ch,Send as Sh,ShieldAlert as Ah,ShieldCheck as Th,ShieldX as kh,Square as Eh,ThumbsDown as Mh,ThumbsUp as Lh,Upload as Ih,Volume2 as Rh,X as Ph,User as Wh,Mail as Bh,Phone as Hh,Calendar as Dh,Clock as Fh,Building as Oh,MapPin as Nh,Lock as _h,Key as Vh,CreditCard as $h,AtSign as Uh,Hash as zh,Globe as qh,Link as jh,CircleCheck as Kh,CircleX as Gh,TriangleAlert as Yh,Info as Xh,Ban as Qh,Shield as Jh,ArrowLeft as Zh,ArrowRight as eb,ExternalLink as tb,Ellipsis as nb,EllipsisVertical as ob,Menu as rb,House as sb,Plus as ab,Minus as ib,Pencil as lb,Trash as cb,Trash2 as db,Save as pb,Download as ub,Share as mb,Funnel as gb,Settings as fb,RotateCw as hb,Maximize as bb,Minimize as yb,ShoppingCart as vb,ShoppingBag as xb,Package as wb,Truck as Cb,Tag as Sb,Gift as Ab,Receipt as Tb,Wallet as kb,Store as Eb,DollarSign as Mb,Percent as Lb,Play as Ib,Pause as Rb,VolumeX as Pb,Camera as Wb,Image as Bb,Film as Hb,Headphones as Db,MessageCircle as Fb,MessageSquare as Ob,Bell as Nb,Heart as _b,Star as Vb,Eye as $b,EyeOff as Ub,Bookmark as zb,CalendarDays as qb,History as jb,Timer as Kb,Folder as Gb,FolderOpen as Yb,Files as Xb,Sparkles as Qb,Zap as Jb,Sun as Zb,Moon as ey,Flag as ty,Monitor as ny,Smartphone as oy}from"lucide";var ry={activity:Zf,"arrow-down":eh,"arrow-up":th,"arrow-up-right":nh,bot:oh,"chevron-down":rh,"chevron-up":sh,"chevron-right":ah,"chevron-left":ih,check:lh,clipboard:ch,"clipboard-copy":dh,copy:ph,file:uh,"file-code":mh,"file-spreadsheet":gh,"file-text":fh,"image-plus":hh,loader:bh,"loader-circle":yh,mic:vh,paperclip:xh,"refresh-cw":wh,search:Ch,send:Sh,"shield-alert":Ah,"shield-check":Th,"shield-x":kh,square:Eh,"thumbs-down":Mh,"thumbs-up":Lh,upload:Ih,"volume-2":Rh,x:Ph,user:Wh,mail:Bh,phone:Hh,calendar:Dh,clock:Fh,building:Oh,"map-pin":Nh,lock:_h,key:Vh,"credit-card":$h,"at-sign":Uh,hash:zh,globe:qh,link:jh,"circle-check":Kh,"circle-x":Gh,"triangle-alert":Yh,info:Xh,ban:Qh,shield:Jh,"arrow-left":Zh,"arrow-right":eb,"external-link":tb,ellipsis:nb,"ellipsis-vertical":ob,menu:rb,house:sb,plus:ab,minus:ib,pencil:lb,trash:cb,"trash-2":db,save:pb,download:ub,share:mb,funnel:gb,settings:fb,"rotate-cw":hb,maximize:bb,minimize:yb,"shopping-cart":vb,"shopping-bag":xb,package:wb,truck:Cb,tag:Sb,gift:Ab,receipt:Tb,wallet:kb,store:Eb,"dollar-sign":Mb,percent:Lb,play:Ib,pause:Rb,"volume-x":Pb,camera:Wb,image:Bb,film:Hb,headphones:Db,"message-circle":Fb,"message-square":Ob,bell:Nb,heart:_b,star:Vb,eye:$b,"eye-off":Ub,bookmark:zb,"calendar-days":qb,history:jb,timer:Kb,folder:Gb,"folder-open":Yb,files:Xb,sparkles:Qb,zap:Jb,sun:Zb,moon:ey,flag:ty,monitor:ny,smartphone:oy},Te=(e,t=24,n="currentColor",o=2)=>{let r=ry[e];return r?sy(r,t,n,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function sy(e,t,n,o){if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,p])=>{l!=="stroke"&&d.setAttribute(l,String(p))}),r.appendChild(d)}),r}var ti={allowedTypes:_o,maxFileSize:10*1024*1024,maxFiles:4};function ay(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function iy(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var Ds=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,o,r;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:ti.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:ti.maxFileSize,maxFiles:(r=t.maxFiles)!=null?r:ti.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:ti.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,o,r,s,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(o=(n=this.config).onFileRejected)==null||o.call(n,l,"count");continue}let p=Pu(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let m=(r=p.error)!=null&&r.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,m);continue}try{let m=await Ru(l),f=Qa(l)?URL.createObjectURL(l):null,u={id:ay(),file:l,previewUrl:f,contentPart:m};this.attachments.push(u),this.renderPreview(u)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let o of this.attachments)o.previewUrl&&URL.revokeObjectURL(o.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Qa(t.file),o=b("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let a=b("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=b("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=iy(t.file.type),d=Te(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=b("span");l.textContent=Wu(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),o.appendChild(a)}let r=b("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=Te("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};import{Idiomorph as ly}from"idiomorph";var ni=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;ly.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){var a,i;if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=r.textContent)!=null?a:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var oi={index:-1,draft:""};function Du(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:o}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...oi}}}function Fu(e,t){var n,o,r,s,a,i,d,l,p,m,f,u,w,C,M,I,R,H,D,B,v,x,k,S,E,F,$,j,me,se,ge,ie,be,Fe,ve,J,Le,Y;return[e.id,e.role,(o=(n=e.content)==null?void 0:n.length)!=null?o:0,(s=(r=e.content)==null?void 0:r.slice(-32))!=null?s:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(l=e.llmContent)==null?void 0:l.length)!=null?p:0,(f=(m=e.approval)==null?void 0:m.status)!=null?f:"",(w=(u=e.toolCall)==null?void 0:u.status)!=null?w:"",(M=(C=e.toolCall)==null?void 0:C.name)!=null?M:"",(H=(R=(I=e.toolCall)==null?void 0:I.chunks)==null?void 0:R.length)!=null?H:0,(x=(v=(B=(D=e.toolCall)==null?void 0:D.chunks)==null?void 0:B[e.toolCall.chunks.length-1])==null?void 0:v.slice(-32))!=null?x:"",typeof((k=e.toolCall)==null?void 0:k.args)=="string"?e.toolCall.args.length:(S=e.toolCall)!=null&&S.args?JSON.stringify(e.toolCall.args).length:0,($=(F=(E=e.reasoning)==null?void 0:E.chunks)==null?void 0:F.length)!=null?$:0,(ge=(se=(me=(j=e.reasoning)==null?void 0:j.chunks)==null?void 0:me[e.reasoning.chunks.length-1])==null?void 0:se.length)!=null?ge:0,(ve=(Fe=(be=(ie=e.reasoning)==null?void 0:ie.chunks)==null?void 0:be[e.reasoning.chunks.length-1])==null?void 0:Fe.slice(-32))!=null?ve:"",(Le=(J=e.contentParts)==null?void 0:J.length)!=null?Le:0,(Y=e.stopReason)!=null?Y:"",t].join("\0")}function Ou(){return new Map}function Nu(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function _u(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Vu(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function ri(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Fs(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Os(e,t){return Fs(e)-e.scrollTop<=t}function si(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,p=n-o;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&r&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!r?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function ai(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}var fn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},hn=1e5,or=hn+1;var Ns={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},cy=["pre","code","a","script","style"],ii=e=>{var t,n,o,r,s;return{type:(t=e==null?void 0:e.type)!=null?t:Ns.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:Ns.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:Ns.speed,duration:(r=e==null?void 0:e.duration)!=null?r:Ns.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:Ns.buffer}},dy=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],Uu=new Map;for(let e of dy)Uu.set(e.name,e);var _s=(e,t)=>{var n,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(o=Uu.get(e))!=null?o:null},li=(e,t,n,o,r)=>{if(!r)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
15
- `);return s<0?"":e.slice(0,s)}return e},py=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},uy=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},dl=/\s/,my=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},gy=(e,t,n)=>{var d;let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=o.createDocumentFragment(),i=0;for(;i<s.length;)if(dl.test(s[i])){let l=i;for(;l<s.length&&dl.test(s[l]);)l+=1;a.appendChild(o.createTextNode(s.slice(i,l))),i=l}else{let l=o.createElement("span");l.className="persona-stream-word-group";let p=i;for(;p<s.length&&!dl.test(s[p]);)l.appendChild(py(o,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(l),i=p}r.replaceChild(a,e)},fy=(e,t,n)=>{var d;let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=o.createDocumentFragment(),i=s.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(o.createTextNode(l)):(a.appendChild(uy(o,l,t,n.value)),n.value+=1));r.replaceChild(a,e)},Vs=(e,t,n,o)=>{var m,f;if(!e||typeof document=="undefined")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set(((m=o==null?void 0:o.skipTags)!=null?m:cy).map(u=>u.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)my(d,s)||i.push(d),d=a.nextNode();let l={value:(f=o==null?void 0:o.startIndex)!=null?f:0},p=t==="char"?gy:fy;for(let u of i)p(u,n,l);return r.innerHTML},ci=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},$s=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},$u=new WeakMap,hy=(e,t)=>{var s;if(!e.styles)return;let n=$u.get(t);if(n||(n=new Set,$u.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},pl=new WeakMap,by=(e,t)=>{if(!e.onAttach)return;let n=pl.get(t);if(n||(n=new Map,pl.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},zu=e=>{let t=pl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},ul=(e,t)=>{hy(e,t),by(e,t)};function ml(e,t=hn){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var Us=0,rr=null;function gl(e=document){var n;if(Us++,Us===1){let o=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;rr={originalOverflow:o.style.overflow,originalPosition:o.style.position,originalTop:o.style.top,originalWidth:o.style.width,scrollY:s},o.style.overflow="hidden",o.style.position="fixed",o.style.top=`-${s}px`,o.style.width="100%"}let t=!1;return()=>{var o;if(!t&&(t=!0,Us=Math.max(0,Us-1),Us===0&&rr)){let r=e.body,s=(o=e.defaultView)!=null?o:window;r.style.overflow=rr.originalOverflow,r.style.position=rr.originalPosition,r.style.top=rr.originalTop,r.style.width=rr.originalWidth,s.scrollTo(0,rr.scrollY),rr=null}}}var di={side:"right",width:"420px",animate:!0,reveal:"resize"},pn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},zs=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},Mo=e=>{var n,o,r,s,a;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(o=t==null?void 0:t.side)!=null?o:di.side,width:(r=t==null?void 0:t.width)!=null?r:di.width,animate:(s=t==null?void 0:t.animate)!=null?s:di.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:di.reveal}};var xo={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var qs=(e,t)=>{let n=b("button");n.type="button",n.innerHTML=`
14
+ _Details: ${n.message}_`:o}var Us=e=>({isError:!0,content:[{type:"text",text:e}]}),ju=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,ri=class e{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=t=>{var n,o,r,s,a,i,d,l;if(t.type==="message"){this.upsertMessage(t.message);let m=t.message.toolCall;((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&(m!=null&&m.name)&&Qr(m.name)&&this.enqueueWebMcpAwait(t.message),(o=t.message.agentMetadata)!=null&&o.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(r=t.message.agentMetadata.agentName)!=null?r:"",status:"running",currentIteration:(s=t.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let m=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":m||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var o,r;this.messages=[...(o=t.initialMessages)!=null?o:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Ns(t),this.wireDefaultWebMcpConfirm();for(let s of(r=t.initialArtifacts)!=null?r:[])this.artifacts.set(s.id,{...s,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return hl((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,o;return(o=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?o:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(t){var n,o,r;try{let s=t||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=$s(s);let a=(n=this.config.voiceRecognition)!=null?n:{},i=(o=a.processingText)!=null?o:"\u{1F3A4} Processing voice...",d=(r=a.processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let m=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=m.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var m,p,f,u,C,v;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((m=l.transcript)!=null&&m.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=l.transcript)!=null&&p.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=l.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(u=l.text)!=null&&u.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let E=(v=this.pendingVoiceAssistantMessageId)!=null?v:(C=[...this.messages].reverse().find(L=>L.role==="assistant"))==null?void 0:C.id;E&&this.ttsSpokenMessageIds.add(E)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var m,p;this.voiceStatus=l,this.voiceActive=l==="listening",(p=(m=this.callbacks).onVoiceStatusChanged)==null||p.call(m,l)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,o,r,s,a,i,d,l,m;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((o=t.runtype)==null?void 0:o.agentId)||"",clientToken:((r=t.runtype)==null?void 0:r.clientToken)||"",host:(s=t.runtype)==null?void 0:s.host,voiceId:(a=t.runtype)==null?void 0:a.voiceId,pauseDuration:(i=t.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=t.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=t.browser)==null?void 0:l.language)||"en-US",continuous:(m=t.browser)==null?void 0:m.continuous}};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let o=await this.client.initSession();return this.setClientSession(o),o}catch(o){return(n=(t=this.callbacks).onError)==null||n.call(t,o instanceof Error?o:new Error(String(o))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let n=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new Ns(this.config),this.wireDefaultWebMcpConfirm(),n&&this.client.setSSEEventCallback(n)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:m,rawContent:p}=t,u={id:a!=null?a:n==="user"?Za():n==="assistant"?_s():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...m!==void 0&&{voiceProcessing:m},...p!==void 0&&{rawContent:p}};return this.upsertMessage(u),u}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:m,streaming:p=!1,voiceProcessing:f,rawContent:u}=o,v={id:d!=null?d:r==="user"?Za():r==="assistant"?_s():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:m!=null?m:this.nextSequence(),streaming:p,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...u!==void 0&&{rawContent:u}};n.push(v)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:i,sequence:d}=t,l={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(l),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var l,m,p,f,u;let o=t.trim();if(!o&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let r=Za(),s=_s(),a={id:r,role:"user",content:o||ei,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(C){let v=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!v){let E=qu(C,this.config.errorMessage);if(E){let L={id:s,role:"assistant",createdAt:new Date().toISOString(),content:E,sequence:this.nextSequence()};this.appendMessage(L)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(C instanceof Error?(p=(m=this.callbacks).onError)==null||p.call(m,C):(u=(f=this.callbacks).onError)==null||u.call(f,new Error(String(C))))}}async continueConversation(){var r,s,a,i,d;if(this.streaming)return;(r=this.abortController)==null||r.abort();let t=_s();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(l){let m=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!m){let p=qu(l,this.config.errorMessage);if(p){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:p,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,m||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var r,s,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(r=this.abortController)==null||r.abort();let o=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var r,s,a;try{if(((s=(r=this.config.webmcp)==null?void 0:r.autoApprove)==null?void 0:s.call(r,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(o,i)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r!=null&&r.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){var m,p,f,u,C;let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(v=>v.id===r),i={id:r,role:"assistant",content:"",createdAt:(m=a==null?void 0:a.createdAt)!=null?m:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(p=this.abortController)==null||p.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,l=d&&typeof d=="object"?d.onDecision:void 0;try{let v;if(l?v=await l({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):v=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),v){let E=null;if(v instanceof Response){if(!v.ok){let L=await v.json().catch(()=>null);throw new Error((f=L==null?void 0:L.error)!=null?f:`Approval request failed: ${v.status}`)}E=v.body}else v instanceof ReadableStream&&(E=v);E?await this.connectStream(E,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(v){let E=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,E||(C=(u=this.callbacks).onError)==null||C.call(u,v instanceof Error?v:new Error(String(v)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var m,p,f,u,C,v,E,L,I,P,H,W;let o=this.messages.find(x=>x.id===t.id);if(((m=o==null?void 0:o.agentMetadata)==null?void 0:m.askUserQuestionAnswered)===!0)return;let r=(p=t.agentMetadata)==null?void 0:p.executionId,s=(f=t.toolCall)==null?void 0:f.name;if(!r||!s){(C=(u=this.callbacks).onError)==null||C.call(u,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let x=(v=t.toolCall)==null?void 0:v.args,w=Array.isArray(x==null?void 0:x.questions)?x.questions:[];if(w.length===1){let k=typeof((E=w[0])==null?void 0:E.question)=="string"?w[0].question:"";k&&(a={[k]:n})}}this.markAskUserQuestionResolved(t,a),(L=this.abortController)==null||L.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(I=t.toolCall)==null?void 0:I.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let x=typeof n=="string"?n:Object.entries(n).map(([w,k])=>`${w}: ${Array.isArray(k)?k.join(", "):k}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:x,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let x=a!=null?a:{};l.forEach((w,k)=>{let S=typeof(w==null?void 0:w.question)=="string"?w.question:"";if(!S)return;let A=x[S],N=Array.isArray(A)?A.join(", "):typeof A=="string"?A:"";this.appendMessage({id:`ask-user-q-${i}-${k}`,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${k}`,role:"user",content:N||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let x=await this.client.resumeFlow(r,{[s]:n});if(!x.ok){let w=await x.json().catch(()=>null);throw new Error((P=w==null?void 0:w.error)!=null?P:`Resume failed: ${x.status}`)}x.body?await this.connectStream(x.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(x){let w=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));this.setStreaming(!1),this.abortController=null,w||(W=(H=this.callbacks).onError)==null||W.call(H,x instanceof Error?x:new Error(String(x)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,o=(a=t.toolCall)==null?void 0:a.id;if(!n||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){var r,s;let n=this.messages.find(a=>a.id===t.id),o=[(r=n==null?void 0:n.toolCall)==null?void 0:r.startedAt,(s=t.toolCall)==null?void 0:s.startedAt];for(let a of o)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now()){this.messages.some(s=>s.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,l,m;let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async p=>{var H,W,x,w,k,S,A;let f=(H=p.toolCall)==null?void 0:H.name,u=(W=p.toolCall)==null?void 0:W.id;if(!f||!u)return null;let C=`${t}:${u}`;if(this.webMcpInflightKeys.has(C)||this.webMcpResolvedKeys.has(C))return null;this.webMcpInflightKeys.add(C),o.push(C);let v=this.markWebMcpToolRunning(p),E=new AbortController;this.webMcpResolveControllers.add(E),r.push(E);let L=(w=(x=p.agentMetadata)==null?void 0:x.webMcpToolCallId)!=null?w:f,I=this.client.executeWebMcpToolCall(f,(k=p.toolCall)==null?void 0:k.args,E.signal),P;if(!I)P={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{P=await I}catch(N){let $=N instanceof Error&&(N.name==="AbortError"||N.message.includes("aborted")||N.message.includes("abort"));return $||(A=(S=this.callbacks).onError)==null||A.call(S,N instanceof Error?N:new Error(String(N))),this.markWebMcpToolComplete(p,Us($?"Aborted by cancel()":ju(N)),v),this.webMcpInflightKeys.delete(C),null}return E.signal.aborted?(this.markWebMcpToolComplete(p,Us("Aborted by cancel()"),v),this.webMcpInflightKeys.delete(C),null):{dedupeKey:C,resumeKey:L,output:P,toolMessage:p,startedAt:v,completedAt:Date.now()}})),i=[];try{if(i=a.filter(u=>u!==null),i.length===0)return;let p={};for(let u of i)p[u.resumeKey]=u.output;let f=await this.client.resumeFlow(t,p,{signal:s.signal});if(!f.ok){let u=await f.json().catch(()=>null);throw new Error((d=u==null?void 0:u.error)!=null?d:`Resume failed: ${f.status}`)}for(let u of i)this.webMcpResolvedKeys.add(u.dedupeKey),this.markWebMcpToolComplete(u.toolMessage,u.output,u.startedAt,u.completedAt);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))(m=(l=this.callbacks).onError)==null||m.call(l,p instanceof Error?p:new Error(String(p)));else for(let u of i)this.markWebMcpToolComplete(u.toolMessage,Us("Aborted by cancel()"),u.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of r)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var u,C,v,E,L,I,P,H,W,x,w,k;let n=(u=t.agentMetadata)==null?void 0:u.executionId,o=(C=t.toolCall)==null?void 0:C.name,r=(v=t.toolCall)==null?void 0:v.id;if(!n){(L=(E=this.callbacks).onError)==null||L.call(E,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!o)return;if(!r){let S=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(S)||this.webMcpResolvedKeys.has(S))return;this.webMcpInflightKeys.add(S);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(S)}catch(A){(P=(I=this.callbacks).onError)==null||P.call(I,A instanceof Error?A:new Error(String(A)))}finally{this.webMcpInflightKeys.delete(S)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let l=(H=t.toolCall)==null?void 0:H.args,m=this.client.executeWebMcpToolCall(o,l,d),p="execute",f=a;try{let S;if(m?S=await m:S={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),d.aborted){this.markWebMcpToolComplete(t,Us("Aborted by cancel()"),a);return}let A=(x=(W=t.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?x:o;p="resume",await this.resumeWithToolOutput(n,A,S,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,S,a,f)},signal:d})}catch(S){let A=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));(p==="execute"||A||d.aborted)&&this.markWebMcpToolComplete(t,Us(A||d.aborted?"Aborted by cancel()":ju(S)),a),A||(k=(w=this.callbacks).onError)==null||k.call(w,S instanceof Error?S:new Error(String(S)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){var a,i;let s=await this.client.resumeFlow(t,{[n]:o},{signal:r==null?void 0:r.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=r==null?void 0:r.onHttpOk)==null||i.call(r),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var r;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let o={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(r=t.props)!=null?r:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),o}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,o;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let r=this.artifacts.get(t.id);(r==null?void 0:r.artifactType)==="markdown"&&(r.markdown=((o=r.markdown)!=null?o:"")+t.artDelta);break}case"artifact_update":{let r=this.artifacts.get(t.id);(r==null?void 0:r.artifactType)==="component"&&(r.props={...r.props,...t.props},t.component&&(r.component=t.component));break}case"artifact_complete":{let r=this.artifacts.get(t.id);r&&(r.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>{var r;return{...o,streaming:!1,sequence:(r=o.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=o.content;r.trim()&&this.speak(r,t)}speak(t,n){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t),s=o.getVoices();if(n.voice){let a=s.find(i=>i.name===n.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=n.pickVoice?n.pickVoice(s):e.pickBestVoice(s));n.rate!==void 0&&(r.rate=n.rate),n.pitch!==void 0&&(r.pitch=n.pitch),setTimeout(()=>o.speak(r),50)}static pickBestVoice(t){var o;let n=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of n){let s=t.find(a=>a.name===r);if(s)return s}return(o=t.find(r=>r.lang.startsWith("en")))!=null?o:t[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{var m,p,f,u,C,v,E,L,I,P;if(s!==o)return r;let a={...r,...n};((m=r.agentMetadata)==null?void 0:m.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(p=n.toolCall)==null?void 0:p.name,d=(f=n.agentMetadata)==null?void 0:f.executionId,l=(u=n.toolCall)==null?void 0:u.id;if(i&&Qr(i)&&d&&l&&((C=n.agentMetadata)==null?void 0:C.awaitingLocalTool)===!0){let H=`${d}:${l}`,W=this.webMcpInflightKeys.has(H),x=this.webMcpResolvedKeys.has(H),w=(v=r.toolCall)==null?void 0:v.name,k=((E=r.agentMetadata)==null?void 0:E.executionId)===d&&((L=r.toolCall)==null?void 0:L.id)===l&&w!==void 0&&Qr(w)&&((I=r.toolCall)==null?void 0:I.status)==="complete";(W||x||k)&&(a.agentMetadata={...(P=a.agentMetadata)!=null?P:{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{var d,l;let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=(d=n.sequence)!=null?d:0,i=(l=o.sequence)!=null?l:0;return a!==i?a-i:n.id.localeCompare(o.id)})}};var b=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Po=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o};import{Activity as gh,ArrowDown as fh,ArrowUp as hh,ArrowUpRight as bh,Bot as yh,ChevronDown as vh,ChevronUp as xh,ChevronRight as wh,ChevronLeft as Ch,Check as Sh,Clipboard as Ah,ClipboardCopy as Th,Copy as kh,File as Eh,FileCode as Mh,FileSpreadsheet as Lh,FileText as Ih,ImagePlus as Rh,Loader as Ph,LoaderCircle as Wh,Mic as Bh,Paperclip as Hh,RefreshCw as Dh,Search as Fh,Send as Oh,ShieldAlert as Nh,ShieldCheck as _h,ShieldX as Vh,Square as $h,ThumbsDown as Uh,ThumbsUp as zh,Upload as qh,Volume2 as jh,X as Kh,User as Gh,Mail as Yh,Phone as Xh,Calendar as Qh,Clock as Jh,Building as Zh,MapPin as eb,Lock as tb,Key as nb,CreditCard as ob,AtSign as rb,Hash as sb,Globe as ab,Link as ib,CircleCheck as lb,CircleX as cb,TriangleAlert as db,Info as pb,Ban as ub,Shield as mb,ArrowLeft as gb,ArrowRight as fb,ExternalLink as hb,Ellipsis as bb,EllipsisVertical as yb,Menu as vb,House as xb,Plus as wb,Minus as Cb,Pencil as Sb,Trash as Ab,Trash2 as Tb,Save as kb,Download as Eb,Share as Mb,Funnel as Lb,Settings as Ib,RotateCw as Rb,Maximize as Pb,Minimize as Wb,ShoppingCart as Bb,ShoppingBag as Hb,Package as Db,Truck as Fb,Tag as Ob,Gift as Nb,Receipt as _b,Wallet as Vb,Store as $b,DollarSign as Ub,Percent as zb,Play as qb,Pause as jb,VolumeX as Kb,Camera as Gb,Image as Yb,Film as Xb,Headphones as Qb,MessageCircle as Jb,MessageSquare as Zb,Bell as ey,Heart as ty,Star as ny,Eye as oy,EyeOff as ry,Bookmark as sy,CalendarDays as ay,History as iy,Timer as ly,Folder as cy,FolderOpen as dy,Files as py,Sparkles as uy,Zap as my,Sun as gy,Moon as fy,Flag as hy,Monitor as by,Smartphone as yy}from"lucide";var vy={activity:gh,"arrow-down":fh,"arrow-up":hh,"arrow-up-right":bh,bot:yh,"chevron-down":vh,"chevron-up":xh,"chevron-right":wh,"chevron-left":Ch,check:Sh,clipboard:Ah,"clipboard-copy":Th,copy:kh,file:Eh,"file-code":Mh,"file-spreadsheet":Lh,"file-text":Ih,"image-plus":Rh,loader:Ph,"loader-circle":Wh,mic:Bh,paperclip:Hh,"refresh-cw":Dh,search:Fh,send:Oh,"shield-alert":Nh,"shield-check":_h,"shield-x":Vh,square:$h,"thumbs-down":Uh,"thumbs-up":zh,upload:qh,"volume-2":jh,x:Kh,user:Gh,mail:Yh,phone:Xh,calendar:Qh,clock:Jh,building:Zh,"map-pin":eb,lock:tb,key:nb,"credit-card":ob,"at-sign":rb,hash:sb,globe:ab,link:ib,"circle-check":lb,"circle-x":cb,"triangle-alert":db,info:pb,ban:ub,shield:mb,"arrow-left":gb,"arrow-right":fb,"external-link":hb,ellipsis:bb,"ellipsis-vertical":yb,menu:vb,house:xb,plus:wb,minus:Cb,pencil:Sb,trash:Ab,"trash-2":Tb,save:kb,download:Eb,share:Mb,funnel:Lb,settings:Ib,"rotate-cw":Rb,maximize:Pb,minimize:Wb,"shopping-cart":Bb,"shopping-bag":Hb,package:Db,truck:Fb,tag:Ob,gift:Nb,receipt:_b,wallet:Vb,store:$b,"dollar-sign":Ub,percent:zb,play:qb,pause:jb,"volume-x":Kb,camera:Gb,image:Yb,film:Xb,headphones:Qb,"message-circle":Jb,"message-square":Zb,bell:ey,heart:ty,star:ny,eye:oy,"eye-off":ry,bookmark:sy,"calendar-days":ay,history:iy,timer:ly,folder:cy,"folder-open":dy,files:py,sparkles:uy,zap:my,sun:gy,moon:fy,flag:hy,monitor:by,smartphone:yy},Ee=(e,t=24,n="currentColor",o=2)=>{let r=vy[e];return r?xy(r,t,n,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function xy(e,t,n,o){if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,m])=>{l!=="stroke"&&d.setAttribute(l,String(m))}),r.appendChild(d)}),r}var si={allowedTypes:Uo,maxFileSize:10*1024*1024,maxFiles:4};function wy(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Cy(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var zs=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,o,r;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:si.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:si.maxFileSize,maxFiles:(r=t.maxFiles)!=null?r:si.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:si.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,o,r,s,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(o=(n=this.config).onFileRejected)==null||o.call(n,l,"count");continue}let m=$u(l,this.config.allowedTypes,this.config.maxFileSize);if(!m.valid){let p=(r=m.error)!=null&&r.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,p);continue}try{let p=await Vu(l),f=ti(l)?URL.createObjectURL(l):null,u={id:wy(),file:l,previewUrl:f,contentPart:p};this.attachments.push(u),this.renderPreview(u)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let o of this.attachments)o.previewUrl&&URL.revokeObjectURL(o.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=ti(t.file),o=b("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let a=b("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=b("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=Cy(t.file.type),d=Ee(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=b("span");l.textContent=Uu(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),o.appendChild(a)}let r=b("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=Ee("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};import{Idiomorph as Sy}from"idiomorph";var ai=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;Sy.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){var a,i;if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=r.textContent)!=null?a:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var ii={index:-1,draft:""};function Ku(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:o}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...ii}}}function Gu(e,t){var n,o,r,s,a,i,d,l,m,p,f,u,C,v,E,L,I,P,H,W,x,w,k,S,A,N,$,G,fe,ge,se,ke,be,Fe,xe,j,de,K;return[e.id,e.role,(o=(n=e.content)==null?void 0:n.length)!=null?o:0,(s=(r=e.content)==null?void 0:r.slice(-32))!=null?s:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(m=(l=e.llmContent)==null?void 0:l.length)!=null?m:0,(f=(p=e.approval)==null?void 0:p.status)!=null?f:"",(C=(u=e.toolCall)==null?void 0:u.status)!=null?C:"",(E=(v=e.toolCall)==null?void 0:v.name)!=null?E:"",(P=(I=(L=e.toolCall)==null?void 0:L.chunks)==null?void 0:I.length)!=null?P:0,(w=(x=(W=(H=e.toolCall)==null?void 0:H.chunks)==null?void 0:W[e.toolCall.chunks.length-1])==null?void 0:x.slice(-32))!=null?w:"",typeof((k=e.toolCall)==null?void 0:k.args)=="string"?e.toolCall.args.length:(S=e.toolCall)!=null&&S.args?JSON.stringify(e.toolCall.args).length:0,($=(N=(A=e.reasoning)==null?void 0:A.chunks)==null?void 0:N.length)!=null?$:0,(se=(ge=(fe=(G=e.reasoning)==null?void 0:G.chunks)==null?void 0:fe[e.reasoning.chunks.length-1])==null?void 0:ge.length)!=null?se:0,(xe=(Fe=(be=(ke=e.reasoning)==null?void 0:ke.chunks)==null?void 0:be[e.reasoning.chunks.length-1])==null?void 0:Fe.slice(-32))!=null?xe:"",(de=(j=e.contentParts)==null?void 0:j.length)!=null?de:0,(K=e.stopReason)!=null?K:"",t].join("\0")}function Yu(){return new Map}function Xu(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function Qu(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Ju(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function li(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function qs(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function js(e,t){return qs(e)-e.scrollTop<=t}function ci(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,m=n-o;return a||Math.abs(m)<s?{action:"none",delta:m,nextLastScrollTop:n}:!t&&r&&(!l||m>0)?{action:"resume",delta:m,nextLastScrollTop:n}:t&&i&&m<0?{action:"pause",delta:m,nextLastScrollTop:n}:t&&d&&!r?{action:"pause",delta:m,nextLastScrollTop:n}:{action:"none",delta:m,nextLastScrollTop:n}}function di(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}var xn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},wn=1e5,ar=wn+1;var Ks={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Ay=["pre","code","a","script","style"],pi=e=>{var t,n,o,r,s;return{type:(t=e==null?void 0:e.type)!=null?t:Ks.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:Ks.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:Ks.speed,duration:(r=e==null?void 0:e.duration)!=null?r:Ks.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:Ks.buffer}},Ty=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],em=new Map;for(let e of Ty)em.set(e.name,e);var Gs=(e,t)=>{var n,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(o=em.get(e))!=null?o:null},ui=(e,t,n,o,r)=>{if(!r)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
15
+ `);return s<0?"":e.slice(0,s)}return e},ky=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},Ey=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},bl=/\s/,My=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Ly=(e,t,n)=>{var d;let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=o.createDocumentFragment(),i=0;for(;i<s.length;)if(bl.test(s[i])){let l=i;for(;l<s.length&&bl.test(s[l]);)l+=1;a.appendChild(o.createTextNode(s.slice(i,l))),i=l}else{let l=o.createElement("span");l.className="persona-stream-word-group";let m=i;for(;m<s.length&&!bl.test(s[m]);)l.appendChild(ky(o,s[m],t,n.value)),n.value+=1,m+=1;a.appendChild(l),i=m}r.replaceChild(a,e)},Iy=(e,t,n)=>{var d;let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=o.createDocumentFragment(),i=s.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(o.createTextNode(l)):(a.appendChild(Ey(o,l,t,n.value)),n.value+=1));r.replaceChild(a,e)},Ys=(e,t,n,o)=>{var p,f;if(!e||typeof document=="undefined")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set(((p=o==null?void 0:o.skipTags)!=null?p:Ay).map(u=>u.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)My(d,s)||i.push(d),d=a.nextNode();let l={value:(f=o==null?void 0:o.startIndex)!=null?f:0},m=t==="char"?Ly:Iy;for(let u of i)m(u,n,l);return r.innerHTML},mi=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Xs=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},Zu=new WeakMap,Ry=(e,t)=>{var s;if(!e.styles)return;let n=Zu.get(t);if(n||(n=new Set,Zu.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},yl=new WeakMap,Py=(e,t)=>{if(!e.onAttach)return;let n=yl.get(t);if(n||(n=new Map,yl.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},tm=e=>{let t=yl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},vl=(e,t)=>{Ry(e,t),Py(e,t)};function xl(e,t=wn){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var Qs=0,ir=null;function wl(e=document){var n;if(Qs++,Qs===1){let o=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;ir={originalOverflow:o.style.overflow,originalPosition:o.style.position,originalTop:o.style.top,originalWidth:o.style.width,scrollY:s},o.style.overflow="hidden",o.style.position="fixed",o.style.top=`-${s}px`,o.style.width="100%"}let t=!1;return()=>{var o;if(!t&&(t=!0,Qs=Math.max(0,Qs-1),Qs===0&&ir)){let r=e.body,s=(o=e.defaultView)!=null?o:window;r.style.overflow=ir.originalOverflow,r.style.position=ir.originalPosition,r.style.top=ir.originalTop,r.style.width=ir.originalWidth,s.scrollTo(0,ir.scrollY),ir=null}}}var gi={side:"right",width:"420px",animate:!0,reveal:"resize"},hn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},Js=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},Wo=e=>{var n,o,r,s,a;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(o=t==null?void 0:t.side)!=null?o:gi.side,width:(r=t==null?void 0:t.width)!=null?r:gi.width,animate:(s=t==null?void 0:t.animate)!=null?s:gi.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:gi.reveal}};var ko={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var Zs=(e,t)=>{let n=b("button");n.type="button",n.innerHTML=`
16
16
  <span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
17
17
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
18
18
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -20,14 +20,14 @@ _Details: ${n.message}_`:o}var ei=class e{constructor(t={},n){this.config=t;this
20
20
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
21
21
  </span>
22
22
  <span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
23
- `,n.addEventListener("click",t);let o=s=>{var H,D,B,v,x,k,S,E,F,$,j,me,se,ge;let a=(H=s.launcher)!=null?H:{},i=pn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let ie=(D=a.title)!=null?D:"Chat Assistant";d.textContent=ie,d.setAttribute("title",ie)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let ie=(B=a.subtitle)!=null?B:"Get answers fast";l.textContent=ie,l.setAttribute("title",ie)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let m=n.querySelector("[data-role='launcher-icon']");if(m)if(a.agentIconHidden)m.style.display="none";else{let ie=(v=a.agentIconSize)!=null?v:"40px";if(m.style.height=ie,m.style.width=ie,m.innerHTML="",a.agentIconName){let be=parseFloat(ie)||24,Fe=Te(a.agentIconName,be*.6,"var(--persona-text-inverse, #ffffff)",2);Fe?(m.appendChild(Fe),m.style.display=""):(m.textContent=(x=a.agentIconText)!=null?x:"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=(k=a.agentIconText)!=null?k:"\u{1F4AC}",m.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let ie=(S=a.agentIconSize)!=null?S:"40px";f.style.height=ie,f.style.width=ie,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let u=n.querySelector("[data-role='launcher-call-to-action-icon']");if(u){let ie=(E=a.callToActionIconSize)!=null?E:"32px";u.style.height=ie,u.style.width=ie,a.callToActionIconBackgroundColor?(u.style.backgroundColor=a.callToActionIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(u.style.color=a.callToActionIconColor,u.classList.remove("persona-text-persona-call-to-action")):(u.style.color="",u.classList.add("persona-text-persona-call-to-action"));let be=0;if(a.callToActionIconPadding?(u.style.boxSizing="border-box",u.style.padding=a.callToActionIconPadding,be=(parseFloat(a.callToActionIconPadding)||0)*2):(u.style.boxSizing="",u.style.padding=""),a.callToActionIconHidden)u.style.display="none";else if(u.style.display=i?"none":"",u.innerHTML="",a.callToActionIconName){let Fe=parseFloat(ie)||24,ve=Math.max(Fe-be,8),J=Te(a.callToActionIconName,ve,"currentColor",2);J?u.appendChild(J):u.textContent=(F=a.callToActionIconText)!=null?F:"\u2197"}else u.textContent=($=a.callToActionIconText)!=null?$:"\u2197"}let w=a.position&&xo[a.position]?xo[a.position]:xo["bottom-right"],C="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",M="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?M:`${C} ${w}`,i||(n.style.zIndex=String((j=a.zIndex)!=null?j:hn));let I="1px solid var(--persona-border, #e5e7eb)",R="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(me=a.border)!=null?me:I,n.style.boxShadow=(se=a.shadow)!=null?se:R,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(ge=a.collapsedMaxWidth)!=null?ge:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}};var yy="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",pi=(e,t={})=>{var C,M,I,R,H,D;let{showClose:n=!0,wrapperClassName:o=yy,buttonSize:r,iconSize:s="28px"}=t,a=(C=e==null?void 0:e.launcher)!=null?C:{},i=(M=r!=null?r:a.closeButtonSize)!=null?M:"32px",d=b("div",o),l=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let p=(I=a.closeButtonTooltipText)!=null?I:"Close chat",m=(R=a.closeButtonShowTooltip)!=null?R:!0;l.setAttribute("aria-label",p),l.style.display=n?"":"none";let f=(H=a.closeButtonIconName)!=null?H:"x",u=(D=a.closeButtonIconText)!=null?D:"\xD7";l.style.color=a.closeButtonColor||Mn.actionIconColor;let w=Te(f,s,"currentColor",1);if(w?(w.style.display="block",l.appendChild(w)):l.textContent=u,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let B=a.closeButtonBorderWidth||"0px",v=a.closeButtonBorderColor||"transparent";l.style.border=`${B} solid ${v}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),m&&p){let B=null,v=()=>{if(B)return;let k=l.ownerDocument,S=k.body;if(!S)return;B=Eo(k,"div","persona-clear-chat-tooltip"),B.textContent=p;let E=Eo(k,"div");E.className="persona-clear-chat-tooltip-arrow",B.appendChild(E);let F=l.getBoundingClientRect();B.style.position="fixed",B.style.zIndex=String(or),B.style.left=`${F.left+F.width/2}px`,B.style.top=`${F.top-8}px`,B.style.transform="translate(-50%, -100%)",S.appendChild(B)},x=()=>{B&&B.parentNode&&(B.parentNode.removeChild(B),B=null)};d.addEventListener("mouseenter",v),d.addEventListener("mouseleave",x),l.addEventListener("focus",v),l.addEventListener("blur",x),d._cleanupTooltip=()=>{x(),d.removeEventListener("mouseenter",v),d.removeEventListener("mouseleave",x),l.removeEventListener("focus",v),l.removeEventListener("blur",x)}}return{button:l,wrapper:d}},vy="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ui=(e,t={})=>{var B,v,x,k,S,E,F,$,j,me,se,ge,ie;let{wrapperClassName:n=vy,buttonSize:o,iconSize:r="20px"}=t,a=(v=((B=e==null?void 0:e.launcher)!=null?B:{}).clearChat)!=null?v:{},i=(x=o!=null?o:a.size)!=null?x:"32px",d=(k=a.iconName)!=null?k:"refresh-cw",l=(S=a.iconColor)!=null?S:"",p=(E=a.backgroundColor)!=null?E:"",m=(F=a.borderWidth)!=null?F:"",f=($=a.borderColor)!=null?$:"",u=(j=a.borderRadius)!=null?j:"",w=(me=a.paddingX)!=null?me:"",C=(se=a.paddingY)!=null?se:"",M=(ge=a.tooltipText)!=null?ge:"Clear chat",I=(ie=a.showTooltip)!=null?ie:!0,R=b("div",n),H=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");H.style.height=i,H.style.width=i,H.type="button",H.setAttribute("aria-label",M),H.style.color=l||Mn.actionIconColor;let D=Te(d,r,"currentColor",1);if(D&&(D.style.display="block",H.appendChild(D)),p&&(H.style.backgroundColor=p,H.classList.remove("hover:persona-bg-gray-100")),m||f){let be=m||"0px",Fe=f||"transparent";H.style.border=`${be} solid ${Fe}`,H.classList.remove("persona-border-none")}if(u&&(H.style.borderRadius=u,H.classList.remove("persona-rounded-full")),w&&(H.style.paddingLeft=w,H.style.paddingRight=w),C&&(H.style.paddingTop=C,H.style.paddingBottom=C),R.appendChild(H),I&&M){let be=null,Fe=()=>{if(be)return;let J=H.ownerDocument,Le=J.body;if(!Le)return;be=Eo(J,"div","persona-clear-chat-tooltip"),be.textContent=M;let Y=Eo(J,"div");Y.className="persona-clear-chat-tooltip-arrow",be.appendChild(Y);let xe=H.getBoundingClientRect();be.style.position="fixed",be.style.zIndex=String(or),be.style.left=`${xe.left+xe.width/2}px`,be.style.top=`${xe.top-8}px`,be.style.transform="translate(-50%, -100%)",Le.appendChild(be)},ve=()=>{be&&be.parentNode&&(be.parentNode.removeChild(be),be=null)};R.addEventListener("mouseenter",Fe),R.addEventListener("mouseleave",ve),H.addEventListener("focus",Fe),H.addEventListener("blur",ve),R._cleanupTooltip=()=>{ve(),R.removeEventListener("mouseenter",Fe),R.removeEventListener("mouseleave",ve),H.removeEventListener("focus",Fe),H.removeEventListener("blur",ve)}}return{button:H,wrapper:R}};var Mn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Ar=e=>{var B,v,x,k,S,E,F,$,j,me,se,ge,ie,be,Fe,ve;let{config:t,showClose:n=!0}=e,o=b("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");o.setAttribute("data-persona-theme-zone","header"),o.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",o.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",o.style.boxShadow="var(--persona-header-shadow, none)",o.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let r=(B=t==null?void 0:t.launcher)!=null?B:{},s=(v=r.headerIconSize)!=null?v:"48px",a=(x=r.closeButtonPlacement)!=null?x:"inline",i=(k=r.headerIconHidden)!=null?k:!1,d=r.headerIconName,l=b("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let J=parseFloat(s)||24,Le=Te(d,J*.6,"currentColor",1);Le?l.replaceChildren(Le):l.textContent=(E=(S=t==null?void 0:t.launcher)==null?void 0:S.agentIconText)!=null?E:"\u{1F4AC}"}else if((F=t==null?void 0:t.launcher)!=null&&F.iconUrl){let J=b("img");J.src=t.launcher.iconUrl,J.alt="",J.className="persona-rounded-xl persona-object-cover",J.style.height=s,J.style.width=s,l.replaceChildren(J)}else l.textContent=(j=($=t==null?void 0:t.launcher)==null?void 0:$.agentIconText)!=null?j:"\u{1F4AC}";let p=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=b("span","persona-text-base persona-font-semibold");m.style.color=Mn.titleColor,m.textContent=(se=(me=t==null?void 0:t.launcher)==null?void 0:me.title)!=null?se:"Chat Assistant";let f=b("span","persona-text-xs");f.style.color=Mn.subtitleColor,f.textContent=(ie=(ge=t==null?void 0:t.launcher)==null?void 0:ge.subtitle)!=null?ie:"Here to help you get answers fast",p.append(m,f),i?o.append(p):o.append(l,p);let u=(be=r.clearChat)!=null?be:{},w=(Fe=u.enabled)!=null?Fe:!0,C=(ve=u.placement)!=null?ve:"inline",M=null,I=null;if(w){let Le=ui(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=Le.button,I=Le.wrapper,C==="top-right"&&(I.style.right="48px"),C==="inline"&&o.appendChild(I)}let R=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":w&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:H,wrapper:D}=pi(t,{showClose:n,wrapperClassName:R});return a!=="top-right"&&o.appendChild(D),{header:o,iconHolder:l,headerTitle:m,headerSubtitle:f,closeButton:H,closeButtonWrapper:D,clearChatButton:M,clearChatButtonWrapper:I}},js=(e,t,n)=>{var a,i,d,l;let o=(a=n==null?void 0:n.launcher)!=null?a:{},r=(i=o.closeButtonPlacement)!=null?i:"inline",s=(l=(d=o.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function jr(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=e,a=b("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(or)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let u of t){if(u.dividerBefore){let M=document.createElement("hr");a.appendChild(M)}let w=document.createElement("button");if(w.type="button",w.setAttribute("role","menuitem"),w.setAttribute("data-dropdown-item-id",u.id),u.destructive&&w.setAttribute("data-destructive",""),u.icon){let M=Te(u.icon,16,"currentColor",1.5);M&&w.appendChild(M)}let C=document.createElement("span");C.textContent=u.label,w.appendChild(C),w.addEventListener("click",M=>{M.stopPropagation(),p(),n(u.id)}),a.appendChild(w)}let i=null;function d(){if(!s)return;let u=o.getBoundingClientRect();a.style.top=`${u.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-u.right}px`,a.style.left="auto"):(a.style.left=`${u.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let u=w=>{!a.contains(w.target)&&!o.contains(w.target)&&p()};document.addEventListener("click",u,!0),i=()=>document.removeEventListener("click",u,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function m(){a.classList.contains("persona-hidden")?l():p()}function f(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:p,toggle:m,destroy:f}}function bn(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:i}=e,d=b("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=Te(t,o!=null?o:16,"currentColor",r!=null?r:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[p,m]of Object.entries(i))d.setAttribute(p,m);return d}function fl(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";o!=="default"&&(l+=" persona-label-btn--"+o),l+=" persona-label-btn--"+r,a&&(l+=" "+a);let p=b("button",l);if(p.type="button",p.setAttribute("aria-label",n),t){let f=Te(t,s!=null?s:14,"currentColor",2);f&&p.appendChild(f)}let m=b("span");if(m.textContent=n,p.appendChild(m),i&&p.addEventListener("click",i),d)for(let[f,u]of Object.entries(d))p.setAttribute(f,u);return p}function qu(e){var u,w;let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:i,hover:d}=e,l=b("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let p=b("span","persona-combo-btn-label");p.textContent=t,l.appendChild(p);let m=Te(n,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",l.appendChild(m)),d&&(l.style.borderRadius=(u=d.borderRadius)!=null?u:"10px",l.style.padding=(w=d.padding)!=null?w:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var C,M;l.style.backgroundColor=(C=d.background)!=null?C:"",l.style.borderColor=(M=d.border)!=null?M:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=jr({items:o,onSelect:C=>{l.setAttribute("aria-expanded","false"),r(C)},anchor:l,position:s,portal:a});return a||l.appendChild(f.element),l.addEventListener("click",C=>{C.stopPropagation();let M=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",M?"false":"true"),f.toggle()}),l.addEventListener("keydown",C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),l.click())}),{element:l,setLabel:C=>{p.textContent=C,l.setAttribute("aria-label",C)},open:()=>{l.setAttribute("aria-expanded","true"),f.show()},close:()=>{l.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let C=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",C?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}var xy=e=>{var o;let t=Ar({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(o=e.layoutHeaderConfig)==null?void 0:o.onTitleClick;if(n){let r=t.headerTitle.parentElement;r&&(r.style.cursor="pointer",r.setAttribute("role","button"),r.setAttribute("tabindex","0"),r.addEventListener("click",()=>n()),r.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function wy(e,t,n){var o,r,s;if(t!=null&&t.length)for(let a of t){let i=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(r=(o=a.ariaLabel)!=null?o:a.label)!=null?r:a.id),a.icon){let d=Te(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=b("div","persona-relative");d.appendChild(i);let l=jr({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var Cy=e=>{var R,H,D,B,v,x,k,S,E;let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=(R=t==null?void 0:t.launcher)!=null?R:{},i=b("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=r==null?void 0:r.titleMenu,l,p;if(d)l=qu({label:(H=a.title)!=null?H:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Mn.titleColor,p=(D=l.querySelector(".persona-combo-btn-label"))!=null?D:l;else{if(l=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=b("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Mn.titleColor,p.textContent=(B=a.title)!=null?B:"Chat Assistant",l.appendChild(p),wy(l,r==null?void 0:r.trailingActions,(v=r==null?void 0:r.onAction)!=null?v:s),r!=null&&r.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let $=r.onTitleClick;l.addEventListener("click",j=>{j.target.closest("button")||$()}),l.addEventListener("keydown",j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),$())})}let F=r==null?void 0:r.titleRowHover;F&&(l.style.borderRadius=(x=F.borderRadius)!=null?x:"10px",l.style.padding=(k=F.padding)!=null?k:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var $,j;l.style.backgroundColor=($=F.background)!=null?$:"",l.style.borderColor=(j=F.border)!=null?j:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let m=(S=a.closeButtonSize)!=null?S:"32px",f=b("div",""),u=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");u.style.height=m,u.style.width=m,u.type="button",u.setAttribute("aria-label","Close chat"),u.style.display=n?"":"none",u.style.color=a.closeButtonColor||Mn.actionIconColor;let w=(E=a.closeButtonIconName)!=null?E:"x",C=Te(w,"28px","currentColor",1);C?u.appendChild(C):u.textContent="\xD7",o&&u.addEventListener("click",o),f.appendChild(u),i.appendChild(f);let M=b("div");M.style.display="none";let I=b("span");return I.style.display="none",{header:i,iconHolder:M,headerTitle:p,headerSubtitle:I,closeButton:u,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},ju={default:xy,minimal:Cy},Sy=e=>{var t;return(t=ju[e])!=null?t:ju.default},mi=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=b("div");p.style.display="none";let m=b("span"),f=b("span"),u=b("button");u.style.display="none";let w=b("div");return w.style.display="none",{header:l,iconHolder:p,headerTitle:m,headerSubtitle:f,closeButton:u,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}}let o=(a=t==null?void 0:t.layout)!=null?a:"default",s=Sy(o)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var gi=e=>{var a,i;let t=b("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;t.style.maxHeight=`${n*o}px`,t.style.overflowY="auto";let r=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*o},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,r());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},fi=e=>{var B,v,x,k,S,E,F,$,j,me,se,ge;let t=(B=e==null?void 0:e.sendButton)!=null?B:{},n=(v=t.useIcon)!=null?v:!1,o=(x=t.iconText)!=null?x:"\u2191",r=t.iconName,s=(k=t.stopIconName)!=null?k:"square",a=(S=t.tooltipText)!=null?S:"Send message",i=(E=t.stopTooltipText)!=null?E:"Stop generating",d=($=(F=e==null?void 0:e.copy)==null?void 0:F.sendButtonLabel)!=null?$:"Send",l=(me=(j=e==null?void 0:e.copy)==null?void 0:j.stopButtonLabel)!=null?me:"Stop",p=(se=t.showTooltip)!=null?se:!1,m=(ge=t.size)!=null?ge:"40px",f=t.backgroundColor,u=t.textColor,w=b("div","persona-send-button-wrapper"),C=b("button",n?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");C.type="submit",C.setAttribute("data-persona-composer-submit","");let M=null,I=null;if(n){C.style.width=m,C.style.height=m,C.style.minWidth=m,C.style.minHeight=m,C.style.fontSize="18px",C.style.lineHeight="1",C.innerHTML="",u?C.style.color=u:C.style.color="var(--persona-button-primary-fg, #ffffff)";let ie=parseFloat(m)||24,be=(u==null?void 0:u.trim())||"currentColor";r?(M=Te(r,ie,be,2),M?C.appendChild(M):C.textContent=o):C.textContent=o,I=Te(s,ie,be,2),f?C.style.backgroundColor=f:C.classList.add("persona-bg-persona-primary")}else C.textContent=d,u?C.style.color=u:C.classList.add("persona-text-white");t.borderWidth&&(C.style.borderWidth=t.borderWidth,C.style.borderStyle="solid"),t.borderColor&&(C.style.borderColor=t.borderColor),t.paddingX?(C.style.paddingLeft=t.paddingX,C.style.paddingRight=t.paddingX):(C.style.paddingLeft="",C.style.paddingRight=""),t.paddingY?(C.style.paddingTop=t.paddingY,C.style.paddingBottom=t.paddingY):(C.style.paddingTop="",C.style.paddingBottom="");let R=null;p&&a&&(R=b("div","persona-send-button-tooltip"),R.textContent=a,w.appendChild(R)),C.setAttribute("aria-label",a),w.appendChild(C);let H="send";return{button:C,wrapper:w,setMode:ie=>{if(ie===H)return;H=ie;let be=ie==="stop"?i:a;if(C.setAttribute("aria-label",be),R&&(R.textContent=be),n){if(M&&I){let Fe=ie==="stop"?I:M;C.replaceChildren(Fe)}}else C.textContent=ie==="stop"?l:d}}},hi=e=>{var R,H,D,B,v,x,k,S,E,F,$,j;let t=(R=e==null?void 0:e.voiceRecognition)!=null?R:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),r=((H=t.provider)==null?void 0:H.type)==="runtype";if(!(o||r))return null;let a=(B=(D=e==null?void 0:e.sendButton)==null?void 0:D.size)!=null?B:"40px",i=b("div","persona-send-button-wrapper"),d=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(v=t.iconName)!=null?v:"mic",p=(x=t.iconSize)!=null?x:a,m=parseFloat(p)||24,f=(S=t.backgroundColor)!=null?S:(k=e==null?void 0:e.sendButton)==null?void 0:k.backgroundColor,u=(F=t.iconColor)!=null?F:(E=e==null?void 0:e.sendButton)==null?void 0:E.textColor;d.style.width=p,d.style.height=p,d.style.minWidth=p,d.style.minHeight=p,d.style.fontSize="18px",d.style.lineHeight="1",u?d.style.color=u:d.style.color="var(--persona-text, #111827)";let C=Te(l,m,u||"currentColor",1.5);C?d.appendChild(C):d.textContent="\u{1F3A4}",f&&(d.style.backgroundColor=f),t.borderWidth&&(d.style.borderWidth=t.borderWidth,d.style.borderStyle="solid"),t.borderColor&&(d.style.borderColor=t.borderColor),t.paddingX&&(d.style.paddingLeft=t.paddingX,d.style.paddingRight=t.paddingX),t.paddingY&&(d.style.paddingTop=t.paddingY,d.style.paddingBottom=t.paddingY),i.appendChild(d);let M=($=t.tooltipText)!=null?$:"Start voice recognition";if(((j=t.showTooltip)!=null?j:!1)&&M){let me=b("div","persona-send-button-tooltip");me.textContent=M,i.appendChild(me)}return{button:d,wrapper:i}},bi=e=>{var w,C,M,I,R,H,D,B;let t=(w=e==null?void 0:e.attachments)!=null?w:{};if(t.enabled!==!0)return null;let n=(M=(C=e==null?void 0:e.sendButton)==null?void 0:C.size)!=null?M:"40px",o=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.style.display="none";let r=b("input");r.type="file",r.accept=((I=t.allowedTypes)!=null?I:_o).join(","),r.multiple=((R=t.maxFiles)!=null?R:4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=b("div","persona-send-button-wrapper"),a=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(H=t.buttonTooltipText)!=null?H:"Attach file");let i=(D=t.buttonIconName)!=null?D:"paperclip",d=n,l=parseFloat(d)||40,p=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let m=Te(i,p,"currentColor",1.5);m?a.appendChild(m):a.textContent="\u{1F4CE}",a.addEventListener("click",v=>{v.preventDefault(),r.click()}),s.appendChild(a);let f=(B=t.buttonTooltipText)!=null?B:"Attach file",u=b("div","persona-send-button-tooltip");return u.textContent=f,s.appendChild(u),{button:a,wrapper:s,input:r,previewsContainer:o}},yi=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=b("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=(i=t.visible)!=null?i:!0;o.style.display=r?"":"none";let s=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let l=b("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=s,l.style.color="inherit",l.style.textDecoration="none",o.appendChild(l)}else o.textContent=s;return o},vi=()=>b("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var xi=e=>{var w,C,M,I,R,H;let{config:t}=e,n=b("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");n.setAttribute("data-persona-theme-zone","composer");let o=vi(),r=b("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");r.setAttribute("data-persona-composer-form",""),r.style.outline="none";let{textarea:s,attachAutoResize:a}=gi(t);a();let i=fi(t),d=hi(t),l=bi(t),p=yi(t);l&&(l.previewsContainer.style.gap="8px",r.append(l.previewsContainer,l.input)),r.append(s);let m=b("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),f=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),u=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&f.append(l.wrapper),d&&u.append(d.wrapper),u.append(i.wrapper),m.append(f,u),r.append(m),r.addEventListener("click",D=>{D.target!==i.button&&D.target!==i.wrapper&&D.target!==(d==null?void 0:d.button)&&D.target!==(d==null?void 0:d.wrapper)&&D.target!==(l==null?void 0:l.button)&&D.target!==(l==null?void 0:l.wrapper)&&s.focus()}),n.append(o,r,p),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(w=d==null?void 0:d.button)!=null?w:null,micButtonWrapper:(C=d==null?void 0:d.wrapper)!=null?C:null,statusText:p,attachmentButton:(M=l==null?void 0:l.button)!=null?M:null,attachmentButtonWrapper:(I=l==null?void 0:l.wrapper)!=null?I:null,attachmentInput:(R=l==null?void 0:l.input)!=null?R:null,attachmentPreviewsContainer:(H=l==null?void 0:l.previewsContainer)!=null?H:null,actionsRow:m,leftActions:f,rightActions:u,setSendButtonMode:i.setMode}};var Ku=()=>{let e=b("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let t=b("span","persona-pill-peek__icon"),n=Te("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=b("span","persona-pill-peek__text"),r=b("span","persona-pill-peek__caret"),s=Te("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},Gu=e=>{var w,C,M,I,R,H;let{config:t}=e,n=b("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let o=vi();o.style.display="none";let r=yi(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=gi(t);s.style.maxHeight="100px",a();let i=fi(t),d=hi(t),l=bi(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=b("form","persona-widget-composer persona-pill-composer");p.setAttribute("data-persona-composer-form",""),p.style.outline="none";let m=b("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&m.append(l.wrapper);let f=b("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),p.addEventListener("click",D=>{D.target!==i.button&&D.target!==i.wrapper&&D.target!==(d==null?void 0:d.button)&&D.target!==(d==null?void 0:d.wrapper)&&D.target!==(l==null?void 0:l.button)&&D.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&p.append(l.input),p.append(m,s,f),l&&n.append(l.previewsContainer),n.append(p,o,r);let u=p;return{footer:n,suggestions:o,composerForm:p,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(w=d==null?void 0:d.button)!=null?w:null,micButtonWrapper:(C=d==null?void 0:d.wrapper)!=null?C:null,statusText:r,attachmentButton:(M=l==null?void 0:l.button)!=null?M:null,attachmentButtonWrapper:(I=l==null?void 0:l.wrapper)!=null?I:null,attachmentInput:(R=l==null?void 0:l.input)!=null?R:null,attachmentPreviewsContainer:(H=l==null?void 0:l.previewsContainer)!=null?H:null,actionsRow:u,leftActions:m,rightActions:f,setSendButtonMode:i.setMode}};var Yu=e=>{var p,m,f,u,w,C,M,I,R,H,D,B,v,x,k,S,E;let t=(m=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?m:!0,n=pn(e);if(zs(e)){let F=(u=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?u:{},$=b("div","persona-widget-wrapper persona-fixed persona-transition");$.setAttribute("data-persona-composer-bar",""),$.dataset.state="collapsed",$.dataset.expandedSize=(w=F.expandedSize)!=null?w:"anchored",$.style.zIndex=String((M=(C=e==null?void 0:e.launcher)==null?void 0:C.zIndex)!=null?M:hn);let j=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");j.style.width="100%",$.appendChild(j);let me=b("div","persona-widget-pill-root");return me.setAttribute("data-persona-composer-bar",""),me.dataset.state="collapsed",me.dataset.expandedSize=(I=F.expandedSize)!=null?I:"anchored",me.style.zIndex=String((H=(R=e==null?void 0:e.launcher)==null?void 0:R.zIndex)!=null?H:hn),{wrapper:$,panel:j,pillRoot:me}}if(n){let F=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),$=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return F.appendChild($),{wrapper:F,panel:$}}if(!t){let F=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),$=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),j=(B=(D=e==null?void 0:e.launcher)==null?void 0:D.width)!=null?B:"100%";return F.style.width=j,$.style.width="100%",F.appendChild($),{wrapper:F,panel:$}}let r=(v=e==null?void 0:e.launcher)!=null?v:{},s=r.position&&xo[r.position]?xo[r.position]:xo["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((k=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?k:hn);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(E=(S=e==null?void 0:e.launcher)==null?void 0:S.width)!=null?E:e==null?void 0:e.launcherWidth,l=d!=null?d:io;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Ay=(e,t)=>{var D,B,v,x,k,S,E,F,$;let n=b("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=pi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=(v=(B=(D=e==null?void 0:e.launcher)==null?void 0:D.clearChat)==null?void 0:B.enabled)!=null?v:!0,a=null,i=null;if(s){let j=ui(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=j.button,i=j.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=b("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=b("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let p=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");p.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",p.setAttribute("data-persona-intro-card","");let m=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");m.textContent=(k=(x=e==null?void 0:e.copy)==null?void 0:x.welcomeTitle)!=null?k:"Hello \u{1F44B}";let f=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(E=(S=e==null?void 0:e.copy)==null?void 0:S.welcomeSubtitle)!=null?E:"Ask anything about your account or products.",p.append(m,f);let u=b("div","persona-flex persona-flex-col persona-gap-3"),w=(F=e==null?void 0:e.layout)==null?void 0:F.contentMaxWidth;w&&(u.style.maxWidth=w,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),(($=e==null?void 0:e.copy)==null?void 0:$.showWelcomeCard)!==!1||(p.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(p,u);let M=b("div","persona-composer-overlay persona-pointer-events-none");M.setAttribute("data-persona-composer-overlay",""),M.style.position="absolute",M.style.left="0",M.style.right="0",M.style.bottom="0",M.style.zIndex="20";let I=Gu({config:e}),{root:R,textNode:H}=Ku();return n.append(d,r,l,M),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:u,composerOverlay:M,suggestions:I.suggestions,textarea:I.textarea,sendButton:I.sendButton,sendButtonWrapper:I.sendButtonWrapper,micButton:I.micButton,micButtonWrapper:I.micButtonWrapper,composerForm:I.composerForm,statusText:I.statusText,introTitle:m,introSubtitle:f,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:d,footer:I.footer,attachmentButton:I.attachmentButton,attachmentButtonWrapper:I.attachmentButtonWrapper,attachmentInput:I.attachmentInput,attachmentPreviewsContainer:I.attachmentPreviewsContainer,actionsRow:I.actionsRow,leftActions:I.leftActions,rightActions:I.rightActions,setSendButtonMode:I.setSendButtonMode,peekBanner:R,peekTextNode:H}},Xu=(e,t=!0)=>{var M,I,R,H,D,B,v,x,k;if(zs(e))return Ay(e,t);let n=b("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");n.setAttribute("data-persona-theme-zone","container");let o=(M=e==null?void 0:e.layout)==null?void 0:M.header,r=((I=e==null?void 0:e.layout)==null?void 0:I.showHeader)!==!1,s=o?mi(e,o,{showClose:t}):Ar({config:e,showClose:t}),a=b("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=pn(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(H=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeTitle)!=null?H:"Hello \u{1F44B}";let l=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(B=(D=e==null?void 0:e.copy)==null?void 0:D.welcomeSubtitle)!=null?B:"Ask anything about your account or products.",i.append(d,l);let p=b("div","persona-flex persona-flex-col persona-gap-3"),m=(v=e==null?void 0:e.layout)==null?void 0:v.contentMaxWidth;m&&(p.style.maxWidth=m,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((x=e==null?void 0:e.copy)==null?void 0:x.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,p);let u=xi({config:e}),w=((k=e==null?void 0:e.layout)==null?void 0:k.showFooter)!==!1;r?js(n,s,e):(s.header.style.display="none",js(n,s,e)),n.append(a);let C=b("div","persona-composer-overlay persona-pointer-events-none");return C.setAttribute("data-persona-composer-overlay",""),C.style.position="absolute",C.style.left="0",C.style.right="0",C.style.bottom="0",C.style.zIndex="20",w||(u.footer.style.display="none"),n.append(u.footer),n.append(C),{container:n,body:a,messagesWrapper:p,composerOverlay:C,suggestions:u.suggestions,textarea:u.textarea,sendButton:u.sendButton,sendButtonWrapper:u.sendButtonWrapper,micButton:u.micButton,micButtonWrapper:u.micButtonWrapper,composerForm:u.composerForm,statusText:u.statusText,introTitle:d,introSubtitle:l,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:u.footer,attachmentButton:u.attachmentButton,attachmentButtonWrapper:u.attachmentButtonWrapper,attachmentInput:u.attachmentInput,attachmentPreviewsContainer:u.attachmentPreviewsContainer,actionsRow:u.actionsRow,leftActions:u.leftActions,rightActions:u.rightActions,setSendButtonMode:u.setSendButtonMode}};var Ty=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},ky=(e,t)=>{if(!e)return null;let n=Ty(e);if(n===null)return null;let o=t==null?void 0:t[e],r=o!==void 0?o:n;return r||null},Ey=(e,t)=>{let n=b("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},My=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},hl=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},bl=320,Ju=320,Ly=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Iy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Ry=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Py=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Wy=(e,t,n)=>{if(e.length===0)return null;try{let o=b("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n==null||n())};return e.forEach((i,d)=>{var m;let l=b("img");l.alt=((m=i.alt)==null?void 0:m.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${bl}px`,l.style.maxHeight=`${Ju}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;r+=1,l.addEventListener("error",()=>{p||(p=!0,r=Math.max(0,r-1),l.remove(),r===0&&a())}),l.addEventListener("load",()=>{p=!0}),My(i.image)?(l.src=i.image,o.appendChild(l)):(p=!0,r=Math.max(0,r-1),l.remove())}),r===0?(a(),null):o}catch{return n==null||n(),null}},By=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!hl(o.audio))return;let r=b("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${bl}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Hy=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!hl(o.video))return;let r=b("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${bl}px`,r.style.maxHeight=`${Ju}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Dy=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!hl(o.data))return;let r=b("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Ks=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},Fy=(e,t,n)=>{let o={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Ks};if(t){let r=t(o);if(r!==null)return r}return Ks()},Oy=(e,t)=>{let n=b("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=b("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Qu=(e,t)=>{let n=b("div","persona-text-xs persona-text-persona-muted"),o=new Date(e.createdAt);return t.format?n.textContent=t.format(o):n.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},Ny=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},_y=(e,t,n)=>{var u,w,C,M,I,R;let o=(u=t.showCopy)!=null?u:!0,r=(w=t.showUpvote)!=null?w:!0,s=(C=t.showDownvote)!=null?C:!0;if(!o&&!r&&!s){let H=b("div");return H.style.display="none",H.id=`actions-${e.id}`,H.setAttribute("data-actions-for",e.id),H}let a=(M=t.visibility)!=null?M:"hover",i=(I=t.align)!=null?I:"right",d=(R=t.layout)!=null?R:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],p={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],m=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);m.id=`actions-${e.id}`,m.setAttribute("data-actions-for",e.id);let f=(H,D,B)=>{let v=bn({icon:H,label:D,size:14,className:"persona-message-action-btn"});return v.setAttribute("data-action",B),v};return o&&m.appendChild(f("copy","Copy message","copy")),r&&m.appendChild(f("thumbs-up","Upvote","upvote")),s&&m.appendChild(f("thumbs-down","Downvote","downvote")),m},yl=(e,t,n,o,r,s)=>{var J,Le,Y,xe,Se,de,we,Ue,te,ne,re,nt,ye,le,$e,Be,ce;let a=n!=null?n:{},i=(J=a.layout)!=null?J:"bubble",d=a.avatar,l=a.timestamp,p=(Le=d==null?void 0:d.show)!=null?Le:!1,m=(Y=l==null?void 0:l.show)!=null?Y:!1,f=(xe=d==null?void 0:d.position)!=null?xe:"left",u=(Se=l==null?void 0:l.position)!=null?Se:"below",w=Ny(e.role,i),C=b("div",w.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let M=Ly(e),I=(we=(de=e.content)==null?void 0:de.trim())!=null?we:"",H=M.length>0&&I===Xa,D=ii((te=(Ue=s==null?void 0:s.widgetConfig)==null?void 0:Ue.features)==null?void 0:te.streamAnimation),B=(nt=(re=(ne=s==null?void 0:s.widgetConfig)==null?void 0:ne.features)==null?void 0:re.streamAnimation)==null?void 0:nt.plugins,v=e.role==="assistant"&&D.type!=="none"?_s(D.type,B):null,x=e.role==="assistant"&&((ye=v==null?void 0:v.isAnimating)==null?void 0:ye.call(v,e))===!0,k=e.role==="assistant"&&v!==null&&(!!e.streaming||x);k&&(v!=null&&v.bubbleClass)&&C.classList.add(v.bubbleClass);let S=document.createElement("div");S.classList.add("persona-message-content"),k&&v&&(v.containerClass&&S.classList.add(v.containerClass),S.style.setProperty("--persona-stream-step",`${D.speed}ms`),S.style.setProperty("--persona-stream-duration",`${D.duration}ms`));let E=k?li((le=e.content)!=null?le:"",D.buffer,v,e,!!e.streaming):($e=e.content)!=null?$e:"",F=t({text:E,message:e,streaming:!!e.streaming,raw:e.rawContent}),$=F;k&&(v==null?void 0:v.wrap)==="char"?$=Vs(F,"char",e.id,{skipTags:v.skipTags}):k&&(v==null?void 0:v.wrap)==="word"&&($=Vs(F,"word",e.id,{skipTags:v.skipTags}));let j=null;if(H?(j=document.createElement("div"),j.innerHTML=$,j.style.display="none",S.appendChild(j)):S.innerHTML=$,k&&(v!=null&&v.useCaret)&&!H&&I){let K=ci(),_e=S.querySelectorAll(".persona-stream-char, .persona-stream-word"),Et=_e[_e.length-1];if(Et!=null&&Et.parentNode)Et.parentNode.insertBefore(K,Et.nextSibling);else{let pe=S.lastElementChild;pe?pe.appendChild(K):S.appendChild(K)}}if(m&&u==="inline"&&e.createdAt){let K=Qu(e,l);K.classList.add("persona-ml-2","persona-inline"),S.appendChild(K)}if(M.length>0){let K=Wy(M,!H&&!!I,()=>{H&&j&&(j.style.display="")});K?C.appendChild(K):H&&j&&(j.style.display="")}let me=Iy(e);if(me.length>0){let K=By(me);K&&C.appendChild(K)}let se=Ry(e);if(se.length>0){let K=Hy(se);K&&C.appendChild(K)}let ge=Py(e);if(ge.length>0){let K=Dy(ge);K&&C.appendChild(K)}if(C.appendChild(S),m&&u==="below"&&e.createdAt){let K=Qu(e,l);K.classList.add("persona-mt-1"),C.appendChild(K)}let ie=e.role==="assistant"?ky(e.stopReason,(ce=(Be=s==null?void 0:s.widgetConfig)==null?void 0:Be.copy)==null?void 0:ce.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let K=!!(E&&E.trim()),_e=D.placeholder==="skeleton",Et=_e&&D.buffer==="line"&&K;if(K)Et&&C.appendChild($s());else if(_e)C.appendChild($s());else{let pe=Fy("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);pe&&C.appendChild(pe)}}if(ie&&e.stopReason&&!e.streaming&&(I||(S.style.display="none"),C.appendChild(Ey(e.stopReason,ie))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let K=_y(e,o,r);C.appendChild(K)}if(!p||e.role==="system")return C;let Fe=b("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ve=Oy(d,e.role);return f==="right"||f==="left"&&e.role==="user"?Fe.append(C,ve):Fe.append(ve,C),C.classList.remove("persona-max-w-[85%]"),C.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Fe};var Kr=new Set,Vy=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),$y=(e,t)=>{var o,r;let n=(r=(o=e.reasoning)==null?void 0:o.chunks.join("").trim())!=null?r:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
24
- `):""},Zu=(e,t)=>{let n=Kr.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let a=o.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=Te(n?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},vl=(e,t)=>{var se,ge,ie,be,Fe,ve,J,Le,Y,xe,Se;let n=e.reasoning,o=b("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let r=(ge=(se=t==null?void 0:t.features)==null?void 0:se.reasoningDisplay)!=null?ge:{},s=r.expandable!==!1,a=s&&Kr.has(e.id),i=n.status!=="complete",d=$y(e,(ie=r.previewMaxLines)!=null?ie:3),l=b("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",s&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let p=b("div","persona-flex persona-flex-col persona-text-left"),m=b("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",u=(be=t==null?void 0:t.reasoning)!=null?be:{},w=String((Fe=n.startedAt)!=null?Fe:Date.now()),C=()=>{let de=b("span","");return de.setAttribute("data-tool-elapsed",w),de.textContent=qa(n),de},M=(ve=u.renderCollapsedSummary)==null?void 0:ve.call(u,{message:e,reasoning:n,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:qa(n),createElapsedElement:C});typeof M=="string"&&M.trim()?(m.textContent=M,p.appendChild(m)):M instanceof HTMLElement?p.appendChild(M):(m.textContent=f,p.appendChild(m));let I=b("span","persona-text-xs persona-text-persona-primary");I.textContent=Su(n),p.appendChild(I);let R=(J=r.loadingAnimation)!=null?J:"none",H=u.activeTextTemplate,D=u.completeTextTemplate,B=i?H:D,v=M instanceof HTMLElement,x=(de,we,Ue)=>{let te=Ue;for(let ne of we){let re=b("span","persona-tool-char");re.style.setProperty("--char-index",String(te)),re.textContent=ne===" "?"\xA0":ne,de.appendChild(re),te++}return te},k=(de,we)=>{m.textContent="";let Ue=ja(de,""),te=0;for(let ne of Ue){let re=ne.styles.length>0?(()=>{let nt=b("span",ne.styles.map(ye=>`persona-tool-text-${ye}`).join(" "));return m.appendChild(nt),nt})():m;if(ne.isDuration&&i)re.appendChild(C());else{let nt=ne.isDuration?qa(n):ne.text;we?te=x(re,nt,te):re.appendChild(document.createTextNode(nt))}}};if(!v&&B)if(I.style.display="none",m.style.display="",i&&R!=="none"){let de=(Le=u.loadingAnimationDuration)!=null?Le:2e3;m.setAttribute("data-preserve-animation","true"),R==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${de}ms`),k(B,!1)):(m.classList.add(`persona-tool-loading-${R}`),m.style.setProperty("--persona-tool-anim-duration",`${de}ms`),R==="shimmer-color"&&(u.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",u.loadingAnimationColor),u.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",u.loadingAnimationSecondaryColor)),k(B,!0))}else k(B,!1);else if(!v&&i&&R!=="none"){m.style.display="";let de=(Y=u.loadingAnimationDuration)!=null?Y:2e3;if(m.setAttribute("data-preserve-animation","true"),R==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${de}ms`);else{m.classList.add(`persona-tool-loading-${R}`),m.style.setProperty("--persona-tool-anim-duration",`${de}ms`),R==="shimmer-color"&&(u.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",u.loadingAnimationColor),u.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",u.loadingAnimationSecondaryColor));let we=m.textContent||f;m.textContent="",x(m,we,0)}n.status==="complete"&&(m.style.display="none")}else v||(n.status==="complete"?m.style.display="none":m.style.display="");let S=null;if(s){S=b("div","persona-flex persona-items-center");let we=Te(a?"chevron-up":"chevron-down",16,"currentColor",2);we?S.appendChild(we):S.textContent=a?"Hide":"Show";let Ue=b("div","persona-flex persona-items-center persona-ml-auto");Ue.append(S),l.append(p,Ue)}else l.append(p);let E=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(E.setAttribute("data-persona-collapsed-preview","reasoning"),E.style.display="none",E.style.whiteSpace="pre-wrap",!a&&i&&r.activePreview&&d){let de=(Se=(xe=t==null?void 0:t.reasoning)==null?void 0:xe.renderCollapsedPreview)==null?void 0:Se.call(xe,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});Vy(E,de)||(E.textContent=d),E.style.display=""}if(!a&&i&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(l,E),o;let F=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");F.style.display=a?"":"none";let $=n.chunks.join(""),j=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return j.textContent=$||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),F.appendChild(j),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),S){S.innerHTML="";let we=Te(a?"chevron-up":"chevron-down",16,"currentColor",2);we?S.appendChild(we):S.textContent=a?"Hide":"Show"}F.style.display=a?"":"none",E.style.display=a?"none":E.textContent||E.childNodes.length?"":"none"})(),o.append(l,E,F),o};var Gr=new Set,Uy=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),zy=(e,t)=>{var s;let n=e.toolCall;if(!n)return"";let o=((s=n.chunks)!=null?s:[]).join("").trim();if(o)return o.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
25
- `);let r=qr(n.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
26
- `):""},qy=(e,t)=>{var p,m,f,u,w;let n=e.toolCall,o=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,r=(m=o==null?void 0:o.collapsedMode)!=null?m:"tool-call",s=zy(e,(f=o==null?void 0:o.previewMaxLines)!=null?f:3),a=n?Au(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(u=t==null?void 0:t.toolCall)!=null?u:{},l=a;return r==="tool-name"?l=((w=n.name)==null?void 0:w.trim())||a:r==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=al(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=al(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},em=(e,t,n)=>{var p;let o=Gr.has(e),r=(p=n==null?void 0:n.toolCall)!=null?p:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let m=r.toggleTextColor||r.headerTextColor||"currentColor",f=Te(o?"chevron-up":"chevron-down",16,m,2);f?l.appendChild(f):l.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},xl=(e,t)=>{var $,j,me,se,ge,ie,be,Fe,ve;let n=e.toolCall,o=($=t==null?void 0:t.toolCall)!=null?$:{},r=b("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),!n)return r;let s=(me=(j=t==null?void 0:t.features)==null?void 0:j.toolCallDisplay)!=null?me:{},a=s.expandable!==!1,i=a&&Gr.has(e.id),{summary:d,previewText:l,isActive:p}=qy(e,t),m=b("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");m.type="button",a&&(m.setAttribute("aria-expanded",i?"true":"false"),m.setAttribute("data-expand-header","true")),m.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(m.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(m.style.paddingLeft=o.headerPaddingX,m.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(m.style.paddingTop=o.headerPaddingY,m.style.paddingBottom=o.headerPaddingY);let f=b("div","persona-flex persona-flex-col persona-text-left"),u=b("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(u.style.color=o.headerTextColor);let w=String((se=n.startedAt)!=null?se:Date.now()),C=()=>{let J=b("span","");return J.setAttribute("data-tool-elapsed",w),J.textContent=Rs(n),J},M=(ie=o.renderCollapsedSummary)==null?void 0:ie.call(o,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(ge=s.collapsedMode)!=null?ge:"tool-call",isActive:p,config:t!=null?t:{},elapsed:Rs(n),createElapsedElement:C});typeof M=="string"&&M.trim()?(u.textContent=M,f.appendChild(u)):M instanceof HTMLElement?f.appendChild(M):(u.textContent=d,f.appendChild(u));let I=(be=s.loadingAnimation)!=null?be:"none",R=o.activeTextTemplate,H=o.completeTextTemplate,D=p?R:H,B=M instanceof HTMLElement,v=(J,Le,Y)=>{let xe=Y;for(let Se of Le){let de=b("span","persona-tool-char");de.style.setProperty("--char-index",String(xe)),de.textContent=Se===" "?"\xA0":Se,J.appendChild(de),xe++}return xe},x=(J,Le)=>{var de;u.textContent="";let Y=((de=n.name)==null?void 0:de.trim())||"tool",xe=ja(J,Y),Se=0;for(let we of xe){let Ue=we.styles.length>0?(()=>{let te=b("span",we.styles.map(ne=>`persona-tool-text-${ne}`).join(" "));return u.appendChild(te),te})():u;if(we.isDuration&&p)Ue.appendChild(C());else{let te=we.isDuration?Rs(n):we.text;Le?Se=v(Ue,te,Se):Ue.appendChild(document.createTextNode(te))}}};if(!B)if(p&&I!=="none"){let J=(Fe=o.loadingAnimationDuration)!=null?Fe:2e3;if(u.setAttribute("data-preserve-animation","true"),I==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${J}ms`),D&&x(D,!1);else if(u.classList.add(`persona-tool-loading-${I}`),u.style.setProperty("--persona-tool-anim-duration",`${J}ms`),I==="shimmer-color"&&(o.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),D)x(D,!0);else{let Le=u.textContent||d;u.textContent="",v(u,Le,0)}}else D&&x(D,!1);let k=null;if(a){k=b("div","persona-flex persona-items-center");let J=o.toggleTextColor||o.headerTextColor||"currentColor",Le=Te(i?"chevron-up":"chevron-down",16,J,2);Le?k.appendChild(Le):k.textContent=i?"Hide":"Show";let Y=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Y.append(k),m.append(f,Y)}else m.append(f);let S=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(S.setAttribute("data-persona-collapsed-preview","tool"),S.style.display="none",S.style.whiteSpace="pre-wrap",!i&&p&&s.activePreview&&l){let J=(ve=o.renderCollapsedPreview)==null?void 0:ve.call(o,{message:e,toolCall:n,defaultPreview:l,isActive:p,config:t!=null?t:{}});Uy(S,J)||(S.textContent=l),S.style.display=""}if(!i&&p&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(m,S),r;let E=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(E.style.display=i?"":"none",o.contentBackgroundColor&&(E.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(E.style.color=o.contentTextColor),o.contentPaddingX&&(E.style.paddingLeft=o.contentPaddingX,E.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(E.style.paddingTop=o.contentPaddingY,E.style.paddingBottom=o.contentPaddingY),n.name){let J=b("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?J.style.color=o.contentTextColor:o.headerTextColor&&(J.style.color=o.headerTextColor),J.textContent=n.name,E.appendChild(J)}if(n.args!==void 0){let J=b("div","persona-space-y-1"),Le=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Le.style.color=o.labelTextColor),Le.textContent="Arguments";let Y=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(Y.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(Y.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(Y.style.color=o.codeBlockTextColor),Y.textContent=qr(n.args),J.append(Le,Y),E.appendChild(J)}if(n.chunks&&n.chunks.length){let J=b("div","persona-space-y-1"),Le=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Le.style.color=o.labelTextColor),Le.textContent="Activity";let Y=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(Y.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(Y.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(Y.style.color=o.codeBlockTextColor),Y.textContent=n.chunks.join(""),J.append(Le,Y),E.appendChild(J)}if(n.status==="complete"&&n.result!==void 0){let J=b("div","persona-space-y-1"),Le=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Le.style.color=o.labelTextColor),Le.textContent="Result";let Y=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(Y.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(Y.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(Y.style.color=o.codeBlockTextColor),Y.textContent=qr(n.result),J.append(Le,Y),E.appendChild(J)}if(n.status==="complete"&&typeof n.duration=="number"){let J=b("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(J.style.color=o.contentTextColor),J.textContent=`Duration: ${n.duration}ms`,E.appendChild(J)}return(()=>{if(m.setAttribute("aria-expanded",i?"true":"false"),k){k.innerHTML="";let J=o.toggleTextColor||o.headerTextColor||"currentColor",Le=Te(i?"chevron-up":"chevron-down",16,J,2);Le?k.appendChild(Le):k.textContent=i?"Hide":"Show"}E.style.display=i?"":"none",S.style.display=i?"none":S.textContent||S.childNodes.length?"":"none"})(),r.append(m,S,E),r};import{parse as jy,ARR as Ky,OBJ as Gy,STR as Yy}from"partial-json";var Xy="ask_user_question",wl=8,Yr="data-persona-ask-sheet-for",Qy="Other",Jy="Other\u2026",nm="Type your own answer here",om="Send",Zy="Next",ev="Back",tv="Submit all",nv="Skip",ov=3,Cl="data-ask-current-index",Sl="data-ask-question-count",rm="data-ask-answers",Al="data-ask-grouped",sm="data-ask-layout",rv=e=>e.layout==="pills"?"pills":"rows",sv=e=>e.getAttribute(sm)==="pills"?"pills":"rows",tm=!1,am=e=>e.replace(/["\\]/g,"\\$&"),Tr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Xy,Tl=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},Xr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=jy(r,Yy|Gy|Ky);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Gs=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>wl&&!tm&&(tm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${wl}.`)),t.slice(0,wl)},av=e=>{var t;return(t=Gs(e)[0])!=null?t:null},iv=(e,t)=>{var n;return(n=Gs(e)[t])!=null?n:null},lv=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},im=(e,t,n)=>{if(e!=="rows")return null;let o=b("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=b("span","persona-ask-row-check");o.appendChild(r)}else{let r=b("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},cv=(e,t,n,o)=>{let s=b("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=b("span","persona-ask-row-content"),i=b("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=b("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}s.appendChild(a);let d=im(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},dv=e=>{let n=b("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},pv=(e,t,n,o)=>{var p,m,f;let s=b("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(u=>u&&typeof u.label=="string"&&u.label.length>0);if(d.length===0&&!n){for(let u=0;u<ov;u++)s.appendChild(dv(o));return s}if(d.forEach((u,w)=>{s.appendChild(cv(u,w,o,a))}),(e==null?void 0:e.allowFreeText)!==!1){let u=o==="rows"?Qy:Jy;if(o==="rows"){let w=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");w.setAttribute("data-ask-user-action","focus-free-text"),w.setAttribute("data-option-index",String(d.length)),w.setAttribute("data-ask-other-row","true");let C=b("span","persona-ask-row-content"),M=document.createElement("input");M.type="text",M.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",M.placeholder=(p=t.freeTextPlaceholder)!=null?p:nm,M.setAttribute("data-ask-free-text-input","true"),M.setAttribute("aria-label",(m=t.freeTextLabel)!=null?m:u),C.appendChild(M),w.appendChild(C);let I=im(o,a,d.length);I&&w.appendChild(I),s.appendChild(w)}else{let w=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");w.type="button",w.setAttribute("data-ask-user-action","open-free-text"),w.textContent=(f=t.freeTextLabel)!=null?f:u,s.appendChild(w)}}return s},lm=(e,t)=>{var s,a;let o=b("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=(s=e.freeTextPlaceholder)!=null?s:nm,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let i=b("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:om,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},uv=e=>{var o;let t=b("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=b("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(o=e.submitLabel)!=null?o:om,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},mv=(e,t,n)=>{var l,p,m,f;let o=b("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=b("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=(l=n.backLabel)!=null?l:ev,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=n.skipLabel)!=null?p:nv,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=b("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(m=n.submitAllLabel)!=null?m:tv:(f=n.nextLabel)!=null?f:Zy,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},kr=e=>{let t=e.getAttribute(rm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},cm=(e,t)=>{e.setAttribute(rm,JSON.stringify(t))},lo=e=>{var n;let t=Number((n=e.getAttribute(Cl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},gv=(e,t)=>{e.setAttribute(Cl,String(Math.max(0,Math.floor(t))))},Qr=e=>{var n;let t=Number((n=e.getAttribute(Sl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},sr=e=>e.getAttribute(Al)==="true",fv=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(o[a]=d)}}),o},hv=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},wi=(e,t)=>{let{payload:n}=Xr(t),o=Gs(n),r=kr(e),s={},a=new Set;return o.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(r,d)&&(s[l]=r[d]))}),s},dm=e=>{let t=kr(e),n=lo(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(d=>r.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var m;let l=(m=d.getAttribute("data-option-label"))!=null?m:"",p=r.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!a.has(o)){i.value=o;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},pm=e=>{if(!sr(e))return;let t=kr(e),n=lo(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},kl=(e,t,n)=>{let o=Tl(n),r=sv(e),{payload:s,complete:a}=Xr(t),i=sr(e),d=lo(e),l=Qr(e),p=i?iv(s,d):av(s),m=!!(p!=null&&p.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let u=e.querySelector('[data-ask-stepper="true"]');u&&u.remove();let w=e.querySelector('[data-ask-question="true"]');if(w){let R=typeof(p==null?void 0:p.question)=="string"?p.question:"";w.textContent=R,w.classList.toggle("persona-ask-question-skeleton",!R&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let R=pv(p,o,a,r);C.replaceWith(R)}if(r!=="rows"){let R=e.querySelector('[data-ask-free-text-row="true"]');R&&R.replaceWith(lm(o,r))}let M=e.querySelector('[data-ask-multi-actions="true"]');!i&&m&&!M?e.appendChild(uv(o)):(!m||i)&&M&&M.remove(),e.setAttribute("data-multi-select",m?"true":"false");let I=e.querySelector('[data-ask-nav-row="true"]');if(i){let R=mv(d,l,o);I?I.replaceWith(R):e.appendChild(R)}else I&&I.remove();dm(e),pm(e)},bv=(e,t,n)=>{let o=Tl(t),r=rv(o),s=e.toolCall.id,a=Gs(n),i=Math.max(1,a.length),d=i>1,l=fv(e,a),p=d?hv(e,i):0,m=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(Yr,s),m.setAttribute("data-tool-call-id",s),m.setAttribute("data-message-id",e.id),m.setAttribute(Sl,String(i)),m.setAttribute(Cl,String(p)),m.setAttribute(Al,d?"true":"false"),m.setAttribute(sm,r),cm(m,l),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),lv(m,o);let f=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),u=b("div","persona-ask-sheet-question persona-flex-1");u.setAttribute("data-ask-question","true"),u.textContent="",f.appendChild(u);let w=b("span","persona-ask-sheet-step-inline");w.setAttribute("data-ask-step-inline","true"),w.textContent="",f.appendChild(w),m.appendChild(f);let M=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),m.appendChild(M),r!=="rows"&&m.appendChild(lm(o,r)),kl(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},yv=(e,t,n)=>{let{payload:o}=Xr(t),r=Math.max(1,Gs(o).length);r>Qr(e)&&(e.setAttribute(Sl,String(r)),r>1&&!sr(e)&&e.setAttribute(Al,"true")),kl(e,t,n)};var Ci=(e,t,n)=>{if(!n||!Tr(e)||Tl(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Yr}]`).forEach(l=>{l.getAttribute(Yr)!==r&&l.remove()});let a=n.querySelector(`[${Yr}="${am(r)}"]`);if(a){yv(a,e,t);return}let{payload:i}=Xr(e),d=bv(e,t,i);n.appendChild(d)},Jr=(e,t)=>{if(!e)return;let n=t?`[${Yr}="${am(t)}"]`:`[${Yr}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},El=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),ar=(e,t)=>{let n=kr(e),o=lo(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,cm(e,n),dm(e),pm(e)},Si=(e,t,n,o)=>{let r=Qr(e),s=Math.max(0,Math.min(r-1,o));gv(e,s),kl(e,t,n)};var Ml=(e,t)=>{var C,M,I,R,H,D,B,v,x,k,S,E;let n=e.approval,o=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,r=(n==null?void 0:n.status)==="pending",s=b("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(C=o==null?void 0:o.backgroundColor)!=null?C:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(M=o==null?void 0:o.borderColor)!=null?M:"var(--persona-approval-border, #fef08a)",!n)return s;let a=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=b("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",l=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(I=o==null?void 0:o.titleColor)!=null?I:"currentColor",p=Te(d,20,l,2);p&&i.appendChild(p);let m=b("div","persona-flex-1 persona-min-w-0"),f=b("div","persona-flex persona-items-center persona-gap-2"),u=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o!=null&&o.titleColor&&(u.style.color=o.titleColor),u.textContent=(R=o==null?void 0:o.title)!=null?R:"Approval Required",f.appendChild(u),!r){let F=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");F.setAttribute("data-approval-status",n.status),n.status==="approved"?(F.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",F.style.color="var(--persona-palette-colors-success-700, #15803d)",F.textContent="Approved"):n.status==="denied"?(F.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",F.style.color="var(--persona-palette-colors-error-700, #b91c1c)",F.textContent="Denied"):n.status==="timeout"&&(F.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",F.style.color="var(--persona-palette-colors-warning-700, #b45309)",F.textContent="Timeout"),f.appendChild(F)}m.appendChild(f);let w=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(o!=null&&o.descriptionColor&&(w.style.color=o.descriptionColor),w.textContent=n.description,m.appendChild(w),n.parameters){let F=b("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o!=null&&o.parameterBackgroundColor&&(F.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(F.style.color=o.parameterTextColor),F.style.fontSize="0.75rem",F.style.lineHeight="1rem",F.textContent=qr(n.parameters),m.appendChild(F)}if(r){let F=b("div","persona-flex persona-gap-2 persona-mt-2");F.setAttribute("data-approval-buttons","true");let $=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");$.type="button",$.style.backgroundColor=(H=o==null?void 0:o.approveButtonColor)!=null?H:"var(--persona-approval-approve-bg, #22c55e)",$.style.color=(D=o==null?void 0:o.approveButtonTextColor)!=null?D:"#ffffff",$.setAttribute("data-approval-action","approve");let j=Te("shield-check",14,(B=o==null?void 0:o.approveButtonTextColor)!=null?B:"#ffffff",2);j&&(j.style.marginRight="4px",$.appendChild(j));let me=document.createTextNode((v=o==null?void 0:o.approveLabel)!=null?v:"Approve");$.appendChild(me);let se=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");se.type="button",se.style.backgroundColor=(x=o==null?void 0:o.denyButtonColor)!=null?x:"transparent",se.style.color=(k=o==null?void 0:o.denyButtonTextColor)!=null?k:"var(--persona-feedback-error, #dc2626)",se.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,se.setAttribute("data-approval-action","deny");let ge=Te("shield-x",14,(S=o==null?void 0:o.denyButtonTextColor)!=null?S:"var(--persona-feedback-error, #dc2626)",2);ge&&(ge.style.marginRight="4px",se.appendChild(ge));let ie=document.createTextNode((E=o==null?void 0:o.denyLabel)!=null?E:"Deny");se.appendChild(ie),F.append($,se),m.appendChild(F)}return a.append(i,m),s.appendChild(a),s};var um=e=>{let t=[];return{buttons:t,render:(o,r,s,a,i)=>{if(e.innerHTML="",t.length=0,!o||!o.length||(a!=null?a:r?r.getMessages():[]).some(u=>u.role==="user"))return;let p=document.createDocumentFragment(),m=r?r.isStreaming():!1,f=u=>{switch(u){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};o.forEach(u=>{let w=b("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");w.type="button",w.textContent=u,w.disabled=m,i!=null&&i.fontFamily&&(w.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(w.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(w.style.paddingLeft=i.paddingX,w.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(w.style.paddingTop=i.paddingY,w.style.paddingBottom=i.paddingY),w.addEventListener("click",()=>{!r||r.isStreaming()||(s.value="",r.sendMessage(u))}),p.appendChild(w),t.push(w)}),e.appendChild(p)}}};var Ys=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Xs=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}};var vv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),xv=new Set(["step_start","execution_start"]),wv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Cv=new Set(["step_complete","agent_turn_complete"]),Sv=new Set(["flow_complete","agent_complete"]),mm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),fm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Er=(e,t)=>{let n=e[t];return fm(n)?n:void 0};function Ll(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Ai(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Av(e,t){return typeof t.type=="string"?t.type:e}function Tv(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function kv(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function gm(e){var o,r,s,a,i;let t=Er(e,"result"),n=[Er(e,"tokens"),Er(e,"totalTokens"),t?Er(t,"tokens"):void 0,Er(e,"usage"),t?Er(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(r=(o=Qn(d.output))!=null?o:Qn(d.outputTokens))!=null?r:Qn(d.completionTokens);if(l!==void 0)return l}return(i=(s=Qn(e.outputTokens))!=null?s:Qn(e.completionTokens))!=null?i:t?(a=Qn(t.outputTokens))!=null?a:Qn(t.completionTokens):void 0}function Ev(e){var n,o,r,s,a;let t=Er(e,"result");return(a=(r=(o=(n=Qn(e.executionTime))!=null?n:Qn(e.executionTimeMs))!=null?o:Qn(e.execution_time))!=null?r:Qn(e.duration))!=null?a:t?(s=Qn(t.executionTime))!=null?s:Qn(t.executionTimeMs):void 0}function Mv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Qs=class{constructor(t=Mv){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:Ai(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var s;if(!fm(n)){mm.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Av(t,n),r=this.now();if(vv.has(o)){this.startRun(r);return}if(xv.has(o)){this.run||this.startRun(r);return}if(wv.has(o)){if(!kv(o,n))return;let a=Tv(n);if(!a)return;this.run||this.startRun(r);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=r),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Ll(i.visibleCharCount),l=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ai(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Cv.has(o)){if(!this.run)return;let a=this.run,i=gm(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Ll(a.visibleCharCount),p=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:Ai(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(Sv.has(o)){if(!this.run)return;let a=this.run,i=gm(n),d=i!=null?i:a.exactOutputTokens+Ll(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:Ai(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(mm.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;if(r!==void 0&&r>=250)return r;let s=Ev(n);return s!=null?s:o-t.startedAt}};function Zr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Lv={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},Iv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Rv=["flowName","stepName","reasoningText","text","name","tool","toolName"],Pv=100;function Wv(e,t){let n={...Lv,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Iv}function Bv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Hv(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function Dv(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Fv(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let o=document.createElement("textarea");o.value=e,o.style.position="fixed",o.style.opacity="0",document.body.appendChild(o),o.select(),document.execCommand("copy"),document.body.removeChild(o),n()})}function Ov(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function Nv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function _v(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function Vv(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(i)return i}return a();function a(){let i=b("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=b("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=o,i.appendChild(d),i}}function Il(e,t,n,o,r,s,a,i){var f;let d=r.has(e.id),l=b("div","persona-border-b persona-border-persona-divider persona-text-xs");Zr(l,(f=o.classNames)==null?void 0:f.eventRow);let p=a.find(u=>u.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let u=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>m(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(u)return l.appendChild(u),l}return l.appendChild(m()),l;function m(){var $,j;let u=b("div",""),w=b("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");w.setAttribute("data-event-id",e.id);let C=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),M=Te(d?"chevron-down":"chevron-right","14px","currentColor",2);M&&C.appendChild(M);let I=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),R=($=o.timestampFormat)!=null?$:"relative";I.textContent=R==="relative"?Bv(e.timestamp,n):Hv(e.timestamp);let H=null;o.showSequenceNumbers!==!1&&(H=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),H.textContent=String(t+1));let D=Wv(e.type,o.badgeColors),B=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");B.style.backgroundColor=D.bg,B.style.color=D.text,B.style.borderColor=D.text+"50",B.textContent=e.type;let v=(j=o.descriptionFields)!=null?j:Rv,x=Dv(e.payload,v),k=null;x&&(k=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),k.textContent=x);let S=b("div","persona-flex-1 persona-min-w-0"),E=b("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),F=Te("clipboard","12px","currentColor",1.5);return F&&E.appendChild(F),E.addEventListener("click",async me=>{me.stopPropagation(),await Fv(Ov(e)),E.innerHTML="";let se=Te("check","12px","currentColor",1.5);se&&E.appendChild(se),setTimeout(()=>{E.innerHTML="";let ge=Te("clipboard","12px","currentColor",1.5);ge&&E.appendChild(ge)},1500)}),w.appendChild(C),w.appendChild(I),H&&w.appendChild(H),w.appendChild(B),k&&w.appendChild(k),w.appendChild(S),w.appendChild(E),u.appendChild(w),d&&u.appendChild(Vv(e,a,i)),u}}function hm(e){var w,C,M,I,R;let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,i=(w=r==null?void 0:r.features)==null?void 0:w.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(C=i==null?void 0:i.iconName)!=null?C:"arrow-down",p=(M=i==null?void 0:i.label)!=null?M:"",m=(R=(I=r==null?void 0:r.features)==null?void 0:I.eventStream)!=null?R:{},f=s.find(H=>H.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&r){let H=f.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>u().element,onClose:o});if(H)return{element:H,update:()=>{},destroy:()=>{}}}return u();function u(){let H=m.classNames,D=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Zr(D,H==null?void 0:H.panel);let B=[],v="",x="",k=null,S=[],E={},F=0,$=ri(),j=0,me=0,se=!1,ge=null,ie=!1,be=0,Fe=new Set,ve=new Map,J="",Le="",Y=null,xe,Se,de,we,Ue,te=null,ne=null,re=null;function nt(){let oe=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),fe=b("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");Zr(fe,H==null?void 0:H.headerBar);let xt=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(xt.textContent="Events",xe=b("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),xe.textContent="0",a){ne=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ne.style.cursor="help";let Fn=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Fn.textContent="Throughput",te=b("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),te.textContent="-- tok/s",re=b("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),re.style.display="none",re.style.pointerEvents="none";let Zn=ne,vn=re,On=()=>{if(!vn.textContent)return;let wo=Zn.getBoundingClientRect(),Nn=oe.getBoundingClientRect();vn.style.left=`${wo.left-Nn.left}px`,vn.style.top=`${wo.bottom-Nn.top+4}px`,vn.style.display="block"},ut=()=>{vn.style.display="none"};ne.addEventListener("mouseenter",On),ne.addEventListener("mouseleave",ut),ne.appendChild(Fn),ne.appendChild(te)}let $t=b("div","persona-flex-1");Se=b("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Jt=b("option","");Jt.value="",Jt.textContent="All events",Se.appendChild(Jt),de=b("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),de.type="button",de.title="Copy All";let Tt=Te("clipboard-copy","12px","currentColor",1.5);Tt&&de.appendChild(Tt);let wt=b("span","persona-text-xs");wt.textContent="Copy All",de.appendChild(wt),fe.appendChild(xt),fe.appendChild(xe),ne&&fe.appendChild(ne),fe.appendChild($t),fe.appendChild(Se),fe.appendChild(de);let ft=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Zr(ft,H==null?void 0:H.searchBar);let bt=Te("search","14px","var(--persona-muted, #9ca3af)",1.5),zt=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");bt&&zt.appendChild(bt),we=b("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Zr(we,H==null?void 0:H.searchInput),we.type="text",we.placeholder="Search event payloads...",Ue=b("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Ue.type="button",Ue.style.display="none";let et=Te("x","12px","currentColor",2);return et&&Ue.appendChild(et),ft.appendChild(zt),ft.appendChild(we),ft.appendChild(Ue),oe.appendChild(fe),oe.appendChild(ft),re&&oe.appendChild(re),oe}let ye,le=s.find(oe=>oe.renderEventStreamToolbar);if(le!=null&&le.renderEventStreamToolbar&&r){let oe=le.renderEventStreamToolbar({config:r,defaultRenderer:()=>nt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:fe=>{v=fe,Dn(),_()},onSearchChange:fe=>{x=fe,Dn(),_()}});ye=oe!=null?oe:nt()}else ye=nt();let $e=b("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");$e.style.display="none";function Be(){if(!a||!te||!ne)return;let oe=a();te.textContent=Nv(oe);let fe=_v(oe);re&&(re.textContent=fe,fe||(re.style.display="none")),fe?ne.setAttribute("aria-label",fe):ne.removeAttribute("aria-label")}let ce=b("div","persona-flex-1 persona-min-h-0 persona-relative"),K=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");K.style.height="100%";let _e=b("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Zr(_e,H==null?void 0:H.scrollIndicator),_e.style.display="none",_e.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let Et=Te(l,"14px","currentColor",2);Et&&_e.appendChild(Et);let pe=b("span","");pe.textContent=p,_e.appendChild(pe);let ae=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ae.style.display="none",ce.appendChild(K),ce.appendChild(ae),ce.appendChild(_e),D.setAttribute("tabindex","0"),D.appendChild(ye),D.appendChild($e),D.appendChild(ce);function Ln(){let oe=t.getAll(),fe={};for(let wt of oe)fe[wt.type]=(fe[wt.type]||0)+1;let xt=Object.keys(fe).sort(),$t=xt.length!==S.length||!xt.every((wt,ft)=>wt===S[ft]),Jt=!$t&&xt.some(wt=>fe[wt]!==E[wt]),yn=oe.length!==Object.values(E).reduce((wt,ft)=>wt+ft,0);if(!$t&&!Jt&&!yn||(S=xt,E=fe,!Se))return;let Tt=Se.value;if(Se.options[0].textContent="All events",$t){for(;Se.options.length>1;)Se.remove(1);for(let wt of xt){let ft=b("option","");ft.value=wt,ft.textContent=`${wt} (${fe[wt]||0})`,Se.appendChild(ft)}Tt&&xt.includes(Tt)?Se.value=Tt:Tt&&(Se.value="",v="")}else for(let wt=1;wt<Se.options.length;wt++){let ft=Se.options[wt];ft.textContent=`${ft.value} (${fe[ft.value]||0})`}}function Nt(){let oe=t.getAll();if(v&&(oe=oe.filter(fe=>fe.type===v)),x){let fe=x.toLowerCase();oe=oe.filter(xt=>xt.type.toLowerCase().includes(fe)||xt.payload.toLowerCase().includes(fe))}return oe}function ln(){return v!==""||x!==""}function Dn(){F=0,j=0,$.resume(),_e.style.display="none"}function Jn(oe){Fe.has(oe)?Fe.delete(oe):Fe.add(oe),Y=oe;let fe=K.scrollTop,xt=$.isFollowing();ie=!0,$.pause(),_(),K.scrollTop=fe,xt&&$.resume(),ie=!1}function ze(){return Os(K,50)}function _(){me=Date.now(),se=!1,Be(),Ln();let oe=t.getEvictedCount();oe>0?($e.textContent=`${oe.toLocaleString()} older events truncated`,$e.style.display=""):$e.style.display="none",B=Nt();let fe=B.length,xt=t.getSize()>0;xe&&(xe.textContent=String(t.getSize())),fe===0&&xt&&ln()?(ae.textContent=x?`No events matching '${x}'`:"No events matching filter",ae.style.display="",K.style.display="none"):(ae.style.display="none",K.style.display=""),de&&(de.title=ln()?`Copy Filtered (${fe})`:"Copy All"),d&&!$.isFollowing()&&fe>F&&(j+=fe-F,pe.textContent=p?`${p}${j>0?` (${j})`:""}`:"",_e.style.display=""),F=fe;let $t=t.getAll(),Jt=$t.length>0?$t[0].timestamp:0,yn=new Set(B.map(ft=>ft.id));for(let ft of Fe)yn.has(ft)||Fe.delete(ft);let Tt=v!==J||x!==Le,wt=ve.size===0&&B.length>0;if(Tt||wt||B.length===0){K.innerHTML="",ve.clear();let ft=document.createDocumentFragment();for(let bt=0;bt<B.length;bt++){let zt=Il(B[bt],bt,Jt,m,Fe,Jn,s,r);ve.set(B[bt].id,zt),ft.appendChild(zt)}K.appendChild(ft),J=v,Le=x,Y=null}else{if(Y!==null){let bt=ve.get(Y);if(bt&&bt.parentNode===K){let zt=B.findIndex(et=>et.id===Y);if(zt>=0){let et=Il(B[zt],zt,Jt,m,Fe,Jn,s,r);K.insertBefore(et,bt),bt.remove(),ve.set(Y,et)}}Y=null}let ft=new Set(B.map(bt=>bt.id));for(let[bt,zt]of ve)ft.has(bt)||(zt.remove(),ve.delete(bt));for(let bt=0;bt<B.length;bt++){let zt=B[bt];if(!ve.has(zt.id)){let et=Il(zt,bt,Jt,m,Fe,Jn,s,r);ve.set(zt.id,et),K.appendChild(et)}}}$.isFollowing()&&(K.scrollTop=K.scrollHeight)}function ke(){if(Date.now()-me>=Pv){ge!==null&&(cancelAnimationFrame(ge),ge=null),_();return}se||(se=!0,ge=requestAnimationFrame(()=>{ge=null,_()}))}let He=(oe,fe)=>{if(!de)return;de.innerHTML="";let xt=Te(oe,"12px","currentColor",1.5);xt&&de.appendChild(xt);let $t=b("span","persona-text-xs");$t.textContent="Copy All",de.appendChild($t),setTimeout(()=>{de.innerHTML="";let Jt=Te("clipboard-copy","12px","currentColor",1.5);Jt&&de.appendChild(Jt);let yn=b("span","persona-text-xs");yn.textContent="Copy All",de.appendChild(yn),de.disabled=!1},fe)},De=async()=>{if(de){de.disabled=!0;try{let oe;ln()?oe=B:n?(oe=await n(),oe.length===0&&(oe=t.getAll())):oe=t.getAll();let fe=oe.map(xt=>{try{return JSON.parse(xt.payload)}catch{return xt.payload}});await navigator.clipboard.writeText(JSON.stringify(fe,null,2)),He("check",1500)}catch{He("x",1500)}}},Ve=()=>{Se&&(v=Se.value,Dn(),_())},dt=()=>{!we||!Ue||(Ue.style.display=we.value?"":"none",k&&clearTimeout(k),k=setTimeout(()=>{x=we.value,Dn(),_()},150))},ot=()=>{!we||!Ue||(we.value="",x="",Ue.style.display="none",k&&clearTimeout(k),Dn(),_())},At=()=>{if(ie)return;let oe=K.scrollTop,{action:fe,nextLastScrollTop:xt}=si({following:$.isFollowing(),currentScrollTop:oe,lastScrollTop:be,nearBottom:ze(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});be=xt,fe==="resume"?($.resume(),j=0,_e.style.display="none"):fe==="pause"&&($.pause(),d&&(pe.textContent=p,_e.style.display=""))},Vt=oe=>{let fe=ai({following:$.isFollowing(),deltaY:oe.deltaY,nearBottom:ze(),resumeWhenNearBottom:!0});fe==="pause"?($.pause(),d&&(pe.textContent=p,_e.style.display="")):fe==="resume"&&($.resume(),j=0,_e.style.display="none")},q=()=>{d&&(K.scrollTop=K.scrollHeight,$.resume(),j=0,_e.style.display="none")},_t=oe=>{let fe=oe.target;if(!fe||fe.closest("button"))return;let xt=fe.closest("[data-event-id]");if(!xt)return;let $t=xt.getAttribute("data-event-id");$t&&Jn($t)},Qe=oe=>{if((oe.metaKey||oe.ctrlKey)&&oe.key==="f"){oe.preventDefault(),we==null||we.focus(),we==null||we.select();return}oe.key==="Escape"&&(we&&document.activeElement===we?(ot(),we.blur(),D.focus()):o&&o())};de&&de.addEventListener("click",De),Se&&Se.addEventListener("change",Ve),we&&we.addEventListener("input",dt),Ue&&Ue.addEventListener("click",ot),K.addEventListener("scroll",At),K.addEventListener("wheel",Vt,{passive:!0}),K.addEventListener("click",_t),_e.addEventListener("click",q),D.addEventListener("keydown",Qe);function Ft(){k&&clearTimeout(k),ge!==null&&(cancelAnimationFrame(ge),ge=null),se=!1,ve.clear(),de&&de.removeEventListener("click",De),Se&&Se.removeEventListener("change",Ve),we&&we.removeEventListener("input",dt),Ue&&Ue.removeEventListener("click",ot),K.removeEventListener("scroll",At),K.removeEventListener("wheel",Vt),K.removeEventListener("click",_t),_e.removeEventListener("click",q),D.removeEventListener("keydown",Qe)}return{element:D,update:ke,destroy:Ft}}}function bm(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",o=typeof e.artifactId=="string"?e.artifactId:"",r=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),o&&i.setAttribute("data-open-artifact",o);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=n;let m=document.createElement("div");if(m.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",m.style.color="var(--persona-muted, #9ca3af)",r==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",m.appendChild(f);let u=document.createElement("span");u.textContent=`Generating ${a.toLowerCase()}...`,m.appendChild(u)}else m.textContent=a;if(l.append(p,m),i.append(d,l),r==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${n}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",o),i.append(f)}return i}var ym=(e,t)=>{var o,r,s;let n=(s=(r=(o=t==null?void 0:t.config)==null?void 0:o.features)==null?void 0:r.artifacts)==null?void 0:s.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>bm(e,t)});if(p)return p}return bm(e,t)};var Rl=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},Mr=new Rl;Mr.register("PersonaArtifactCard",ym);function $v(e){var r;let t=b("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=b("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify((r=e.props)!=null?r:{},null,2),t.appendChild(n),t.appendChild(o),t}function vm(e,t){var Se,de,we,Ue;let n=(de=(Se=e.features)==null?void 0:Se.artifacts)==null?void 0:de.layout,r=((we=n==null?void 0:n.toolbarPreset)!=null?we:"default")==="document",s=(Ue=n==null?void 0:n.panePadding)==null?void 0:Ue.trim(),a=e.markdown?_a(e.markdown):null,i=Va(e.sanitize),d=te=>{let ne=a?a(te):Ls(te);return i?i(ne):ne},l=typeof document!="undefined"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{l==null||l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"),F==null||F.hide()};l&&l.addEventListener("click",()=>{var te;p(),(te=t.onDismiss)==null||te.call(t)});let m=b("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");m.setAttribute("data-persona-theme-zone","artifact-pane"),r&&m.classList.add("persona-artifact-pane-document");let f=b("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&f.classList.add("persona-artifact-toolbar-document");let u=b("span","persona-text-xs persona-font-medium persona-truncate");u.textContent="Artifacts";let w=b("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");w.type="button",w.textContent="Close",w.setAttribute("aria-label","Close artifacts panel"),w.addEventListener("click",()=>{var te;p(),(te=t.onDismiss)==null||te.call(t)});let C="rendered",M=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),I=r?bn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):bn({icon:"eye",label:"Rendered view"}),R=r?bn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):bn({icon:"code-2",label:"Source"}),H=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),D=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,B=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,v=n==null?void 0:n.documentToolbarCopyMenuItems,x=!!(B&&v&&v.length>0),k=null,S,E=null,F=null;if(r&&(D||B)&&!x){if(S=D?fl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):bn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),B){let te=Te("chevron-down",14,"currentColor",2);te&&S.appendChild(te)}}else r&&x?(k=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),S=D?fl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):bn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),E=bn({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),k.append(S,E)):r?S=bn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):S=bn({icon:"copy",label:"Copy"});let $=r?bn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):bn({icon:"refresh-cw",label:"Refresh"}),j=r?bn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):bn({icon:"x",label:"Close"}),me=()=>{var ye,le,$e;let te=(ye=ve.find(Be=>Be.id===J))!=null?ye:ve[ve.length-1],ne=(le=te==null?void 0:te.id)!=null?le:null,re=(te==null?void 0:te.artifactType)==="markdown"&&($e=te.markdown)!=null?$e:"",nt=te?JSON.stringify({component:te.component,props:te.props},null,2):"";return{markdown:re,jsonPayload:nt,id:ne}},se=async()=>{var ye;let{markdown:te,jsonPayload:ne}=me(),re=(ye=ve.find(le=>le.id===J))!=null?ye:ve[ve.length-1],nt=(re==null?void 0:re.artifactType)==="markdown"?te:re?ne:"";try{await navigator.clipboard.writeText(nt)}catch{}};if(S.addEventListener("click",async()=>{let te=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(te&&x){let{markdown:ne,jsonPayload:re,id:nt}=me();try{await te({actionId:"primary",artifactId:nt,markdown:ne,jsonPayload:re})}catch{}return}await se()}),E&&(v!=null&&v.length)){let te=()=>{var re;return(re=m.closest("[data-persona-root]"))!=null?re:document.body},ne=()=>{F=jr({items:v.map(re=>({id:re.id,label:re.label})),onSelect:async re=>{let{markdown:nt,jsonPayload:ye,id:le}=me(),$e=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{$e?await $e({actionId:re,artifactId:le,markdown:nt,jsonPayload:ye}):re==="markdown"||re==="md"?await navigator.clipboard.writeText(nt):re==="json"||re==="source"?await navigator.clipboard.writeText(ye):await navigator.clipboard.writeText(nt||ye)}catch{}},anchor:k!=null?k:E,position:"bottom-right",portal:te()})};m.isConnected?ne():requestAnimationFrame(ne),E.addEventListener("click",re=>{re.stopPropagation(),F==null||F.toggle()})}$.addEventListener("click",async()=>{var te;try{await((te=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:te.call(n))}catch{}Y()}),j.addEventListener("click",()=>{var te;p(),(te=t.onDismiss)==null||te.call(t)});let ge=()=>{r&&(I.setAttribute("aria-pressed",C==="rendered"?"true":"false"),R.setAttribute("aria-pressed",C==="source"?"true":"false"))};I.addEventListener("click",()=>{C="rendered",ge(),Y()}),R.addEventListener("click",()=>{C="source",ge(),Y()});let ie=b("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");r?(f.replaceChildren(),M.append(I,R),k?H.append(k,$,j):H.append(S,$,j),f.append(M,ie,H),ge()):(f.appendChild(u),f.appendChild(w)),s&&(f.style.paddingLeft=s,f.style.paddingRight=s);let be=b("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Fe=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(be.style.paddingLeft=s,be.style.paddingRight=s,Fe.style.padding=s),m.appendChild(f),m.appendChild(be),m.appendChild(Fe);let ve=[],J=null,Le=!1,Y=()=>{var nt,ye,le,$e;let te=r&&ve.length<=1;be.classList.toggle("persona-hidden",te),be.replaceChildren();for(let Be of ve){let ce=b("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");ce.type="button",ce.textContent=Be.title||Be.id.slice(0,8),Be.id===J&&ce.classList.add("persona-bg-persona-container","persona-border-persona-border"),ce.addEventListener("click",()=>t.onSelect(Be.id)),be.appendChild(ce)}Fe.replaceChildren();let ne=J&&ve.find(Be=>Be.id===J)||ve[ve.length-1];if(!ne)return;if(r){let Be=ne.artifactType==="markdown"?"MD":(nt=ne.component)!=null?nt:"Component",K=(ne.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ie.textContent=`${K} \xB7 ${Be}`}else u.textContent="Artifacts";if(ne.artifactType==="markdown"){if(r&&C==="source"){let ce=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ce.textContent=(ye=ne.markdown)!=null?ye:"",Fe.appendChild(ce);return}let Be=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Be.innerHTML=d((le=ne.markdown)!=null?le:""),Fe.appendChild(Be);return}let re=ne.component?Mr.get(ne.component):void 0;if(re){let ce={message:{id:ne.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let K=re(($e=ne.props)!=null?$e:{},ce);if(K){Fe.appendChild(K);return}}catch{}}Fe.appendChild($v(ne))},xe=()=>{var ne;let te=ve.length>0;if(m.classList.toggle("persona-hidden",!te),l){let re=typeof m.closest=="function"?m.closest("[data-persona-root]"):null,ye=((ne=re==null?void 0:re.classList.contains("persona-artifact-narrow-host"))!=null?ne:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;te&&ye&&Le?(l.classList.remove("persona-hidden"),m.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"))}};return{element:m,backdrop:l,update(te){var ne,re,nt;ve=te.artifacts,J=(nt=(re=te.selectedId)!=null?re:(ne=te.artifacts[te.artifacts.length-1])==null?void 0:ne.id)!=null?nt:null,ve.length>0&&(Le=!0),Y(),xe()},setMobileOpen(te){Le=te,!te&&l?(l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open")):xe()}}}function co(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function xm(e,t){var s,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!co(t))return;let n=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,o=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),r=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function Uv(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function Ti(e,t){var d,l,p,m,f,u,w,C,M,I;if(!co(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),Uv(e),xm(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(p=n==null?void 0:n.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(m=n==null?void 0:n.paneWidth)!=null?m:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=n==null?void 0:n.paneMaxWidth)!=null?f:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=(u=n==null?void 0:n.paneBackground)==null?void 0:u.trim();o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let r=(w=n==null?void 0:n.panePadding)==null?void 0:w.trim();r?e.style.setProperty("--persona-artifact-pane-padding",r):e.style.removeProperty("--persona-artifact-pane-padding");let s=(C=n==null?void 0:n.documentToolbarIconColor)==null?void 0:C.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(M=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:M.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(I=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:I.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),xm(e,t)}var wm=["panel","seamless"];function ki(e,t){var i,d,l,p,m,f;for(let u of wm)e.classList.remove(`persona-artifact-appearance-${u}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!co(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,o=(l=n==null?void 0:n.paneAppearance)!=null?l:"panel",r=wm.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${r}`);let s=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(m=n==null?void 0:n.paneShadow)==null?void 0:m.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let u=((f=n.unifiedSplitOuterRadius)==null?void 0:f.trim())||s;u&&e.style.setProperty("--persona-artifact-unified-outer-radius",u)}}function Cm(e,t){var n,o,r;return!t||!co(e)?!1:((r=(o=(n=e.features)==null?void 0:n.artifacts)==null?void 0:o.layout)==null?void 0:r.expandLauncherPanelWhenOpen)!==!1}function zv(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function qv(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function jv(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Kv(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Sm(e,t){var a;let o=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function Am(e,t,n,o,r,s){let a=zv(r,200),i=Kv(t,n,o,200);i=Math.max(a,i);let d=qv(s);return d!==null&&(i=Math.min(i,d)),jv(e,a,i)}var Tm={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Pl=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var w,C,M;if(s.dataset.enhanced==="true")return;let a=(w=s.dataset.tvForm)!=null?w:"init";s.dataset.enhanced="true";let i=(C=Tm[a])!=null?C:Tm.init;s.classList.add("persona-form-card","persona-space-y-4");let d=b("div","persona-space-y-1"),l=b("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let I=b("p","persona-text-sm persona-text-persona-muted");I.textContent=i.description,d.appendChild(I)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(I=>{var v,x;let R=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");R.htmlFor=`${t.id}-${a}-${I.name}`;let H=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");H.textContent=I.label,R.appendChild(H);let D=(v=I.type)!=null?v:"text",B;D==="textarea"?(B=document.createElement("textarea"),B.rows=3):(B=document.createElement("input"),B.type=D),B.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",B.id=`${t.id}-${a}-${I.name}`,B.name=I.name,B.placeholder=(x=I.placeholder)!=null?x:"",I.required&&(B.required=!0),R.appendChild(B),p.appendChild(R)});let m=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),u=b("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");u.type="submit",u.textContent=(M=i.submitLabel)!=null?M:"Submit",m.appendChild(f),m.appendChild(u),p.appendChild(m),s.replaceChildren(d,p),p.addEventListener("submit",async I=>{var B,v;I.preventDefault();let R=(B=n.formEndpoint)!=null?B:"/form",H=new FormData(p),D={};H.forEach((x,k)=>{D[k]=x}),D.type=a,u.disabled=!0,f.textContent="Submitting\u2026";try{let x=await fetch(R,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D)});if(!x.ok)throw new Error(`Form submission failed (${x.status})`);let k=await x.json();f.textContent=(v=k.message)!=null?v:"Thanks! We'll be in touch soon.",k.success&&k.nextPrompt&&await o.sendMessage(String(k.nextPrompt))}catch(x){f.textContent=x instanceof Error?x.message:"Something went wrong. Please try again."}finally{u.disabled=!1}})})};var Wl=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var o;let n=this.plugins.get(t);n&&((o=n.onUnregister)==null||o.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var o,r;return((o=n.priority)!=null?o:0)-((r=t.priority)!=null?r:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},Bl=new Wl;var km=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{var a;(a=e.get(r))==null||a.delete(s)};return{on:t,off:n,emit:(r,s)=>{var a;(a=e.get(r))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Gv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Yv=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},Dl=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Gv(e),n=Yv(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},Hl=e=>typeof e=="string"?e:e==null?"":String(e),Js={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Hl(e.payload.text)},messageAndClick:(e,t)=>{var r;if(e.type!=="message_and_click")return;let n=e.payload,o=Hl(n.element);if(o&&((r=t.document)!=null&&r.querySelector)){let s=t.document.querySelector(o);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Hl(n.text)}}},Em=e=>Array.isArray(e)?e.map(t=>String(t)):[],Fl=e=>{let t=new Set(Em(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Em(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,p)=>l||(p==null?void 0:p({text:a,message:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),o();let d={action:i,message:s.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let p=()=>{e.emit("action:resubmit",d)},m=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!m)continue;if(m.handled){let f=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:f,resubmit:m.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var Xv=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Qv=e=>e.map(t=>({...t,streaming:!1})),Jv=e=>e.map(t=>({...t,status:"complete"})),Mm=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Xv(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?Qv(n.messages):void 0,artifacts:n.artifacts?Jv(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};import{parse as j0,STR as K0,OBJ as G0}from"partial-json";function Lm(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Mr.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:i=>{r&&r(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Im(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function Rm(e){let t=Im(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Pm(e){let t=Im(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var Zv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Wm(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=Zv}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let m=null,f=document.createElement("div");f.className="persona-feedback-content";let u=document.createElement("div");u.className="persona-feedback-header";let w=document.createElement("h3");w.className="persona-feedback-title",w.textContent=o,u.appendChild(w);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,u.appendChild(C),f.appendChild(u);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let I=[];for(let v=1;v<=5;v++){let x=document.createElement("button");x.type="button",x.className="persona-feedback-rating-btn persona-feedback-star-btn",x.setAttribute("role","radio"),x.setAttribute("aria-checked","false"),x.setAttribute("aria-label",`${v} star${v>1?"s":""}: ${l[v-1]}`),x.title=l[v-1],x.dataset.rating=String(v),x.innerHTML=`
23
+ `,n.addEventListener("click",t);let o=s=>{var P,H,W,x,w,k,S,A,N,$,G,fe,ge;let a=(P=s.launcher)!=null?P:{},i=hn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let se=(H=a.title)!=null?H:"Chat Assistant";d.textContent=se,d.setAttribute("title",se)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let se=(W=a.subtitle)!=null?W:"Get answers fast";l.textContent=se,l.setAttribute("title",se)}let m=n.querySelector(".persona-flex-col");m&&(a.textHidden||i?m.style.display="none":m.style.display="");let p=n.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let se=(x=a.agentIconSize)!=null?x:"40px";if(p.style.height=se,p.style.width=se,p.innerHTML="",a.agentIconName){let ke=parseFloat(se)||24,be=Ee(a.agentIconName,ke*.6,"var(--persona-text-inverse, #ffffff)",2);be?(p.appendChild(be),p.style.display=""):(p.textContent=(w=a.agentIconText)!=null?w:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(k=a.agentIconText)!=null?k:"\u{1F4AC}",p.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let se=(S=a.agentIconSize)!=null?S:"40px";f.style.height=se,f.style.width=se,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let u=n.querySelector("[data-role='launcher-call-to-action-icon']");if(u){let se=(A=a.callToActionIconSize)!=null?A:"32px";u.style.height=se,u.style.width=se,a.callToActionIconBackgroundColor?(u.style.backgroundColor=a.callToActionIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(u.style.color=a.callToActionIconColor,u.classList.remove("persona-text-persona-call-to-action")):(u.style.color="",u.classList.add("persona-text-persona-call-to-action"));let ke=0;if(a.callToActionIconPadding?(u.style.boxSizing="border-box",u.style.padding=a.callToActionIconPadding,ke=(parseFloat(a.callToActionIconPadding)||0)*2):(u.style.boxSizing="",u.style.padding=""),a.callToActionIconHidden)u.style.display="none";else if(u.style.display=i?"none":"",u.innerHTML="",a.callToActionIconName){let be=parseFloat(se)||24,Fe=Math.max(be-ke,8),xe=Ee(a.callToActionIconName,Fe,"currentColor",2);xe?u.appendChild(xe):u.textContent=(N=a.callToActionIconText)!=null?N:"\u2197"}else u.textContent=($=a.callToActionIconText)!=null?$:"\u2197"}let C=a.position&&ko[a.position]?ko[a.position]:ko["bottom-right"],v="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?E:`${v} ${C}`,i||(n.style.zIndex=String((G=a.zIndex)!=null?G:wn));let L="1px solid var(--persona-border, #e5e7eb)",I="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(fe=a.border)!=null?fe:L,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:I,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(ge=a.collapsedMaxWidth)!=null?ge:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}};var Wy="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",fi=(e,t={})=>{var v,E,L,I,P,H;let{showClose:n=!0,wrapperClassName:o=Wy,buttonSize:r,iconSize:s="28px"}=t,a=(v=e==null?void 0:e.launcher)!=null?v:{},i=(E=r!=null?r:a.closeButtonSize)!=null?E:"32px",d=b("div",o),l=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let m=(L=a.closeButtonTooltipText)!=null?L:"Close chat",p=(I=a.closeButtonShowTooltip)!=null?I:!0;l.setAttribute("aria-label",m),l.style.display=n?"":"none";let f=(P=a.closeButtonIconName)!=null?P:"x",u=(H=a.closeButtonIconText)!=null?H:"\xD7";l.style.color=a.closeButtonColor||In.actionIconColor;let C=Ee(f,s,"currentColor",1);if(C?(C.style.display="block",l.appendChild(C)):l.textContent=u,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let W=a.closeButtonBorderWidth||"0px",x=a.closeButtonBorderColor||"transparent";l.style.border=`${W} solid ${x}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),p&&m){let W=null,x=()=>{if(W)return;let k=l.ownerDocument,S=k.body;if(!S)return;W=Po(k,"div","persona-clear-chat-tooltip"),W.textContent=m;let A=Po(k,"div");A.className="persona-clear-chat-tooltip-arrow",W.appendChild(A);let N=l.getBoundingClientRect();W.style.position="fixed",W.style.zIndex=String(ar),W.style.left=`${N.left+N.width/2}px`,W.style.top=`${N.top-8}px`,W.style.transform="translate(-50%, -100%)",S.appendChild(W)},w=()=>{W&&W.parentNode&&(W.parentNode.removeChild(W),W=null)};d.addEventListener("mouseenter",x),d.addEventListener("mouseleave",w),l.addEventListener("focus",x),l.addEventListener("blur",w),d._cleanupTooltip=()=>{w(),d.removeEventListener("mouseenter",x),d.removeEventListener("mouseleave",w),l.removeEventListener("focus",x),l.removeEventListener("blur",w)}}return{button:l,wrapper:d}},By="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",hi=(e,t={})=>{var W,x,w,k,S,A,N,$,G,fe,ge,se,ke;let{wrapperClassName:n=By,buttonSize:o,iconSize:r="20px"}=t,a=(x=((W=e==null?void 0:e.launcher)!=null?W:{}).clearChat)!=null?x:{},i=(w=o!=null?o:a.size)!=null?w:"32px",d=(k=a.iconName)!=null?k:"refresh-cw",l=(S=a.iconColor)!=null?S:"",m=(A=a.backgroundColor)!=null?A:"",p=(N=a.borderWidth)!=null?N:"",f=($=a.borderColor)!=null?$:"",u=(G=a.borderRadius)!=null?G:"",C=(fe=a.paddingX)!=null?fe:"",v=(ge=a.paddingY)!=null?ge:"",E=(se=a.tooltipText)!=null?se:"Clear chat",L=(ke=a.showTooltip)!=null?ke:!0,I=b("div",n),P=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");P.style.height=i,P.style.width=i,P.type="button",P.setAttribute("aria-label",E),P.style.color=l||In.actionIconColor;let H=Ee(d,r,"currentColor",1);if(H&&(H.style.display="block",P.appendChild(H)),m&&(P.style.backgroundColor=m,P.classList.remove("hover:persona-bg-gray-100")),p||f){let be=p||"0px",Fe=f||"transparent";P.style.border=`${be} solid ${Fe}`,P.classList.remove("persona-border-none")}if(u&&(P.style.borderRadius=u,P.classList.remove("persona-rounded-full")),C&&(P.style.paddingLeft=C,P.style.paddingRight=C),v&&(P.style.paddingTop=v,P.style.paddingBottom=v),I.appendChild(P),L&&E){let be=null,Fe=()=>{if(be)return;let j=P.ownerDocument,de=j.body;if(!de)return;be=Po(j,"div","persona-clear-chat-tooltip"),be.textContent=E;let K=Po(j,"div");K.className="persona-clear-chat-tooltip-arrow",be.appendChild(K);let ye=P.getBoundingClientRect();be.style.position="fixed",be.style.zIndex=String(ar),be.style.left=`${ye.left+ye.width/2}px`,be.style.top=`${ye.top-8}px`,be.style.transform="translate(-50%, -100%)",de.appendChild(be)},xe=()=>{be&&be.parentNode&&(be.parentNode.removeChild(be),be=null)};I.addEventListener("mouseenter",Fe),I.addEventListener("mouseleave",xe),P.addEventListener("focus",Fe),P.addEventListener("blur",xe),I._cleanupTooltip=()=>{xe(),I.removeEventListener("mouseenter",Fe),I.removeEventListener("mouseleave",xe),P.removeEventListener("focus",Fe),P.removeEventListener("blur",xe)}}return{button:P,wrapper:I}};var In={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Mr=e=>{var W,x,w,k,S,A,N,$,G,fe,ge,se,ke,be,Fe,xe;let{config:t,showClose:n=!0}=e,o=b("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");o.setAttribute("data-persona-theme-zone","header"),o.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",o.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",o.style.boxShadow="var(--persona-header-shadow, none)",o.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let r=(W=t==null?void 0:t.launcher)!=null?W:{},s=(x=r.headerIconSize)!=null?x:"48px",a=(w=r.closeButtonPlacement)!=null?w:"inline",i=(k=r.headerIconHidden)!=null?k:!1,d=r.headerIconName,l=b("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let j=parseFloat(s)||24,de=Ee(d,j*.6,"currentColor",1);de?l.replaceChildren(de):l.textContent=(A=(S=t==null?void 0:t.launcher)==null?void 0:S.agentIconText)!=null?A:"\u{1F4AC}"}else if((N=t==null?void 0:t.launcher)!=null&&N.iconUrl){let j=b("img");j.src=t.launcher.iconUrl,j.alt="",j.className="persona-rounded-xl persona-object-cover",j.style.height=s,j.style.width=s,l.replaceChildren(j)}else l.textContent=(G=($=t==null?void 0:t.launcher)==null?void 0:$.agentIconText)!=null?G:"\u{1F4AC}";let m=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),p=b("span","persona-text-base persona-font-semibold");p.style.color=In.titleColor,p.textContent=(ge=(fe=t==null?void 0:t.launcher)==null?void 0:fe.title)!=null?ge:"Chat Assistant";let f=b("span","persona-text-xs");f.style.color=In.subtitleColor,f.textContent=(ke=(se=t==null?void 0:t.launcher)==null?void 0:se.subtitle)!=null?ke:"Here to help you get answers fast",m.append(p,f),i?o.append(m):o.append(l,m);let u=(be=r.clearChat)!=null?be:{},C=(Fe=u.enabled)!=null?Fe:!0,v=(xe=u.placement)!=null?xe:"inline",E=null,L=null;if(C){let de=hi(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=de.button,L=de.wrapper,v==="top-right"&&(L.style.right="48px"),v==="inline"&&o.appendChild(L)}let I=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":C&&v==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:P,wrapper:H}=fi(t,{showClose:n,wrapperClassName:I});return a!=="top-right"&&o.appendChild(H),{header:o,iconHolder:l,headerTitle:p,headerSubtitle:f,closeButton:P,closeButtonWrapper:H,clearChatButton:E,clearChatButtonWrapper:L}},ea=(e,t,n)=>{var a,i,d,l;let o=(a=n==null?void 0:n.launcher)!=null?a:{},r=(i=o.closeButtonPlacement)!=null?i:"inline",s=(l=(d=o.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Zr(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=e,a=b("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(ar)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let u of t){if(u.dividerBefore){let E=document.createElement("hr");a.appendChild(E)}let C=document.createElement("button");if(C.type="button",C.setAttribute("role","menuitem"),C.setAttribute("data-dropdown-item-id",u.id),u.destructive&&C.setAttribute("data-destructive",""),u.icon){let E=Ee(u.icon,16,"currentColor",1.5);E&&C.appendChild(E)}let v=document.createElement("span");v.textContent=u.label,C.appendChild(v),C.addEventListener("click",E=>{E.stopPropagation(),m(),n(u.id)}),a.appendChild(C)}let i=null;function d(){if(!s)return;let u=o.getBoundingClientRect();a.style.top=`${u.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-u.right}px`,a.style.left="auto"):(a.style.left=`${u.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let u=C=>{!a.contains(C.target)&&!o.contains(C.target)&&m()};document.addEventListener("click",u,!0),i=()=>document.removeEventListener("click",u,!0)})}function m(){a.classList.add("persona-hidden"),i==null||i(),i=null}function p(){a.classList.contains("persona-hidden")?l():m()}function f(){m(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:m,toggle:p,destroy:f}}function Cn(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:i}=e,d=b("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=Ee(t,o!=null?o:16,"currentColor",r!=null?r:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[m,p]of Object.entries(i))d.setAttribute(m,p);return d}function Cl(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";o!=="default"&&(l+=" persona-label-btn--"+o),l+=" persona-label-btn--"+r,a&&(l+=" "+a);let m=b("button",l);if(m.type="button",m.setAttribute("aria-label",n),t){let f=Ee(t,s!=null?s:14,"currentColor",2);f&&m.appendChild(f)}let p=b("span");if(p.textContent=n,m.appendChild(p),i&&m.addEventListener("click",i),d)for(let[f,u]of Object.entries(d))m.setAttribute(f,u);return m}function nm(e){var u,C;let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:i,hover:d}=e,l=b("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let m=b("span","persona-combo-btn-label");m.textContent=t,l.appendChild(m);let p=Ee(n,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",l.appendChild(p)),d&&(l.style.borderRadius=(u=d.borderRadius)!=null?u:"10px",l.style.padding=(C=d.padding)!=null?C:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var v,E;l.style.backgroundColor=(v=d.background)!=null?v:"",l.style.borderColor=(E=d.border)!=null?E:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=Zr({items:o,onSelect:v=>{l.setAttribute("aria-expanded","false"),r(v)},anchor:l,position:s,portal:a});return a||l.appendChild(f.element),l.addEventListener("click",v=>{v.stopPropagation();let E=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",E?"false":"true"),f.toggle()}),l.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),l.click())}),{element:l,setLabel:v=>{m.textContent=v,l.setAttribute("aria-label",v)},open:()=>{l.setAttribute("aria-expanded","true"),f.show()},close:()=>{l.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let v=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",v?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}var Hy=e=>{var o;let t=Mr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(o=e.layoutHeaderConfig)==null?void 0:o.onTitleClick;if(n){let r=t.headerTitle.parentElement;r&&(r.style.cursor="pointer",r.setAttribute("role","button"),r.setAttribute("tabindex","0"),r.addEventListener("click",()=>n()),r.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function Dy(e,t,n){var o,r,s;if(t!=null&&t.length)for(let a of t){let i=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(r=(o=a.ariaLabel)!=null?o:a.label)!=null?r:a.id),a.icon){let d=Ee(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=b("div","persona-relative");d.appendChild(i);let l=Zr({items:a.menuItems,onSelect:m=>n==null?void 0:n(m),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",m=>{m.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var Fy=e=>{var I,P,H,W,x,w,k,S,A;let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=(I=t==null?void 0:t.launcher)!=null?I:{},i=b("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=r==null?void 0:r.titleMenu,l,m;if(d)l=nm({label:(P=a.title)!=null?P:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=In.titleColor,m=(H=l.querySelector(".persona-combo-btn-label"))!=null?H:l;else{if(l=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),m=b("span","persona-text-base persona-font-semibold persona-truncate"),m.style.color=In.titleColor,m.textContent=(W=a.title)!=null?W:"Chat Assistant",l.appendChild(m),Dy(l,r==null?void 0:r.trailingActions,(x=r==null?void 0:r.onAction)!=null?x:s),r!=null&&r.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let $=r.onTitleClick;l.addEventListener("click",G=>{G.target.closest("button")||$()}),l.addEventListener("keydown",G=>{(G.key==="Enter"||G.key===" ")&&(G.preventDefault(),$())})}let N=r==null?void 0:r.titleRowHover;N&&(l.style.borderRadius=(w=N.borderRadius)!=null?w:"10px",l.style.padding=(k=N.padding)!=null?k:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var $,G;l.style.backgroundColor=($=N.background)!=null?$:"",l.style.borderColor=(G=N.border)!=null?G:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let p=(S=a.closeButtonSize)!=null?S:"32px",f=b("div",""),u=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");u.style.height=p,u.style.width=p,u.type="button",u.setAttribute("aria-label","Close chat"),u.style.display=n?"":"none",u.style.color=a.closeButtonColor||In.actionIconColor;let C=(A=a.closeButtonIconName)!=null?A:"x",v=Ee(C,"28px","currentColor",1);v?u.appendChild(v):u.textContent="\xD7",o&&u.addEventListener("click",o),f.appendChild(u),i.appendChild(f);let E=b("div");E.style.display="none";let L=b("span");return L.style.display="none",{header:i,iconHolder:E,headerTitle:m,headerSubtitle:L,closeButton:u,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},om={default:Hy,minimal:Fy},Oy=e=>{var t;return(t=om[e])!=null?t:om.default},bi=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),m=b("div");m.style.display="none";let p=b("span"),f=b("span"),u=b("button");u.style.display="none";let C=b("div");return C.style.display="none",{header:l,iconHolder:m,headerTitle:p,headerSubtitle:f,closeButton:u,closeButtonWrapper:C,clearChatButton:null,clearChatButtonWrapper:null}}let o=(a=t==null?void 0:t.layout)!=null?a:"default",s=Oy(o)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var yi=e=>{var a,i;let t=b("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;t.style.maxHeight=`${n*o}px`,t.style.overflowY="auto";let r=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*o},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,r());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},vi=e=>{var W,x,w,k,S,A,N,$,G,fe,ge,se;let t=(W=e==null?void 0:e.sendButton)!=null?W:{},n=(x=t.useIcon)!=null?x:!1,o=(w=t.iconText)!=null?w:"\u2191",r=t.iconName,s=(k=t.stopIconName)!=null?k:"square",a=(S=t.tooltipText)!=null?S:"Send message",i=(A=t.stopTooltipText)!=null?A:"Stop generating",d=($=(N=e==null?void 0:e.copy)==null?void 0:N.sendButtonLabel)!=null?$:"Send",l=(fe=(G=e==null?void 0:e.copy)==null?void 0:G.stopButtonLabel)!=null?fe:"Stop",m=(ge=t.showTooltip)!=null?ge:!1,p=(se=t.size)!=null?se:"40px",f=t.backgroundColor,u=t.textColor,C=b("div","persona-send-button-wrapper"),v=b("button",n?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");v.type="submit",v.setAttribute("data-persona-composer-submit","");let E=null,L=null;if(n){v.style.width=p,v.style.height=p,v.style.minWidth=p,v.style.minHeight=p,v.style.fontSize="18px",v.style.lineHeight="1",v.innerHTML="",u?v.style.color=u:v.style.color="var(--persona-button-primary-fg, #ffffff)";let ke=parseFloat(p)||24,be=(u==null?void 0:u.trim())||"currentColor";r?(E=Ee(r,ke,be,2),E?v.appendChild(E):v.textContent=o):v.textContent=o,L=Ee(s,ke,be,2),f?v.style.backgroundColor=f:v.classList.add("persona-bg-persona-primary")}else v.textContent=d,u?v.style.color=u:v.classList.add("persona-text-white");t.borderWidth&&(v.style.borderWidth=t.borderWidth,v.style.borderStyle="solid"),t.borderColor&&(v.style.borderColor=t.borderColor),t.paddingX?(v.style.paddingLeft=t.paddingX,v.style.paddingRight=t.paddingX):(v.style.paddingLeft="",v.style.paddingRight=""),t.paddingY?(v.style.paddingTop=t.paddingY,v.style.paddingBottom=t.paddingY):(v.style.paddingTop="",v.style.paddingBottom="");let I=null;m&&a&&(I=b("div","persona-send-button-tooltip"),I.textContent=a,C.appendChild(I)),v.setAttribute("aria-label",a),C.appendChild(v);let P="send";return{button:v,wrapper:C,setMode:ke=>{if(ke===P)return;P=ke;let be=ke==="stop"?i:a;if(v.setAttribute("aria-label",be),I&&(I.textContent=be),n){if(E&&L){let Fe=ke==="stop"?L:E;v.replaceChildren(Fe)}}else v.textContent=ke==="stop"?l:d}}},xi=e=>{var I,P,H,W,x,w,k,S,A,N,$,G;let t=(I=e==null?void 0:e.voiceRecognition)!=null?I:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),r=((P=t.provider)==null?void 0:P.type)==="runtype";if(!(o||r))return null;let a=(W=(H=e==null?void 0:e.sendButton)==null?void 0:H.size)!=null?W:"40px",i=b("div","persona-send-button-wrapper"),d=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(x=t.iconName)!=null?x:"mic",m=(w=t.iconSize)!=null?w:a,p=parseFloat(m)||24,f=(S=t.backgroundColor)!=null?S:(k=e==null?void 0:e.sendButton)==null?void 0:k.backgroundColor,u=(N=t.iconColor)!=null?N:(A=e==null?void 0:e.sendButton)==null?void 0:A.textColor;d.style.width=m,d.style.height=m,d.style.minWidth=m,d.style.minHeight=m,d.style.fontSize="18px",d.style.lineHeight="1",u?d.style.color=u:d.style.color="var(--persona-text, #111827)";let v=Ee(l,p,u||"currentColor",1.5);v?d.appendChild(v):d.textContent="\u{1F3A4}",f&&(d.style.backgroundColor=f),t.borderWidth&&(d.style.borderWidth=t.borderWidth,d.style.borderStyle="solid"),t.borderColor&&(d.style.borderColor=t.borderColor),t.paddingX&&(d.style.paddingLeft=t.paddingX,d.style.paddingRight=t.paddingX),t.paddingY&&(d.style.paddingTop=t.paddingY,d.style.paddingBottom=t.paddingY),i.appendChild(d);let E=($=t.tooltipText)!=null?$:"Start voice recognition";if(((G=t.showTooltip)!=null?G:!1)&&E){let fe=b("div","persona-send-button-tooltip");fe.textContent=E,i.appendChild(fe)}return{button:d,wrapper:i}},wi=e=>{var C,v,E,L,I,P,H,W;let t=(C=e==null?void 0:e.attachments)!=null?C:{};if(t.enabled!==!0)return null;let n=(E=(v=e==null?void 0:e.sendButton)==null?void 0:v.size)!=null?E:"40px",o=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.style.display="none";let r=b("input");r.type="file",r.accept=((L=t.allowedTypes)!=null?L:Uo).join(","),r.multiple=((I=t.maxFiles)!=null?I:4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=b("div","persona-send-button-wrapper"),a=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(P=t.buttonTooltipText)!=null?P:"Attach file");let i=(H=t.buttonIconName)!=null?H:"paperclip",d=n,l=parseFloat(d)||40,m=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let p=Ee(i,m,"currentColor",1.5);p?a.appendChild(p):a.textContent="\u{1F4CE}",a.addEventListener("click",x=>{x.preventDefault(),r.click()}),s.appendChild(a);let f=(W=t.buttonTooltipText)!=null?W:"Attach file",u=b("div","persona-send-button-tooltip");return u.textContent=f,s.appendChild(u),{button:a,wrapper:s,input:r,previewsContainer:o}},Ci=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=b("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=(i=t.visible)!=null?i:!0;o.style.display=r?"":"none";let s=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let l=b("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=s,l.style.color="inherit",l.style.textDecoration="none",o.appendChild(l)}else o.textContent=s;return o},Si=()=>b("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var Ai=e=>{var C,v,E,L,I,P;let{config:t}=e,n=b("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");n.setAttribute("data-persona-theme-zone","composer");let o=Si(),r=b("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");r.setAttribute("data-persona-composer-form",""),r.style.outline="none";let{textarea:s,attachAutoResize:a}=yi(t);a();let i=vi(t),d=xi(t),l=wi(t),m=Ci(t);l&&(l.previewsContainer.style.gap="8px",r.append(l.previewsContainer,l.input)),r.append(s);let p=b("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),f=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),u=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&f.append(l.wrapper),d&&u.append(d.wrapper),u.append(i.wrapper),p.append(f,u),r.append(p),r.addEventListener("click",H=>{H.target!==i.button&&H.target!==i.wrapper&&H.target!==(d==null?void 0:d.button)&&H.target!==(d==null?void 0:d.wrapper)&&H.target!==(l==null?void 0:l.button)&&H.target!==(l==null?void 0:l.wrapper)&&s.focus()}),n.append(o,r,m),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(C=d==null?void 0:d.button)!=null?C:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:m,attachmentButton:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(L=l==null?void 0:l.wrapper)!=null?L:null,attachmentInput:(I=l==null?void 0:l.input)!=null?I:null,attachmentPreviewsContainer:(P=l==null?void 0:l.previewsContainer)!=null?P:null,actionsRow:p,leftActions:f,rightActions:u,setSendButtonMode:i.setMode}};var rm=()=>{let e=b("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let t=b("span","persona-pill-peek__icon"),n=Ee("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=b("span","persona-pill-peek__text"),r=b("span","persona-pill-peek__caret"),s=Ee("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},sm=e=>{var C,v,E,L,I,P;let{config:t}=e,n=b("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let o=Si();o.style.display="none";let r=Ci(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=yi(t);s.style.maxHeight="100px",a();let i=vi(t),d=xi(t),l=wi(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let m=b("form","persona-widget-composer persona-pill-composer");m.setAttribute("data-persona-composer-form",""),m.style.outline="none";let p=b("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&p.append(l.wrapper);let f=b("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),m.addEventListener("click",H=>{H.target!==i.button&&H.target!==i.wrapper&&H.target!==(d==null?void 0:d.button)&&H.target!==(d==null?void 0:d.wrapper)&&H.target!==(l==null?void 0:l.button)&&H.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&m.append(l.input),m.append(p,s,f),l&&n.append(l.previewsContainer),n.append(m,o,r);let u=m;return{footer:n,suggestions:o,composerForm:m,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(C=d==null?void 0:d.button)!=null?C:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:r,attachmentButton:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(L=l==null?void 0:l.wrapper)!=null?L:null,attachmentInput:(I=l==null?void 0:l.input)!=null?I:null,attachmentPreviewsContainer:(P=l==null?void 0:l.previewsContainer)!=null?P:null,actionsRow:u,leftActions:p,rightActions:f,setSendButtonMode:i.setMode}};var am=e=>{var m,p,f,u,C,v,E,L,I,P,H,W,x,w,k,S,A;let t=(p=(m=e==null?void 0:e.launcher)==null?void 0:m.enabled)!=null?p:!0,n=hn(e);if(Js(e)){let N=(u=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?u:{},$=b("div","persona-widget-wrapper persona-fixed persona-transition");$.setAttribute("data-persona-composer-bar",""),$.dataset.state="collapsed",$.dataset.expandedSize=(C=N.expandedSize)!=null?C:"anchored",$.style.zIndex=String((E=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?E:wn);let G=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");G.style.width="100%",$.appendChild(G);let fe=b("div","persona-widget-pill-root");return fe.setAttribute("data-persona-composer-bar",""),fe.dataset.state="collapsed",fe.dataset.expandedSize=(L=N.expandedSize)!=null?L:"anchored",fe.style.zIndex=String((P=(I=e==null?void 0:e.launcher)==null?void 0:I.zIndex)!=null?P:wn),{wrapper:$,panel:G,pillRoot:fe}}if(n){let N=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),$=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return N.appendChild($),{wrapper:N,panel:$}}if(!t){let N=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),$=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),G=(W=(H=e==null?void 0:e.launcher)==null?void 0:H.width)!=null?W:"100%";return N.style.width=G,$.style.width="100%",N.appendChild($),{wrapper:N,panel:$}}let r=(x=e==null?void 0:e.launcher)!=null?x:{},s=r.position&&ko[r.position]?ko[r.position]:ko["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((k=(w=e==null?void 0:e.launcher)==null?void 0:w.zIndex)!=null?k:wn);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(A=(S=e==null?void 0:e.launcher)==null?void 0:S.width)!=null?A:e==null?void 0:e.launcherWidth,l=d!=null?d:go;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Ny=(e,t)=>{var H,W,x,w,k,S,A,N,$;let n=b("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=fi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=(x=(W=(H=e==null?void 0:e.launcher)==null?void 0:H.clearChat)==null?void 0:W.enabled)!=null?x:!0,a=null,i=null;if(s){let G=hi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=G.button,i=G.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=b("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=b("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let m=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");m.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",m.setAttribute("data-persona-intro-card","");let p=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");p.textContent=(k=(w=e==null?void 0:e.copy)==null?void 0:w.welcomeTitle)!=null?k:"Hello \u{1F44B}";let f=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(A=(S=e==null?void 0:e.copy)==null?void 0:S.welcomeSubtitle)!=null?A:"Ask anything about your account or products.",m.append(p,f);let u=b("div","persona-flex persona-flex-col persona-gap-3"),C=(N=e==null?void 0:e.layout)==null?void 0:N.contentMaxWidth;C&&(u.style.maxWidth=C,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),(($=e==null?void 0:e.copy)==null?void 0:$.showWelcomeCard)!==!1||(m.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(m,u);let E=b("div","persona-composer-overlay persona-pointer-events-none");E.setAttribute("data-persona-composer-overlay",""),E.style.position="absolute",E.style.left="0",E.style.right="0",E.style.bottom="0",E.style.zIndex="20";let L=sm({config:e}),{root:I,textNode:P}=rm();return n.append(d,r,l,E),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:u,composerOverlay:E,suggestions:L.suggestions,textarea:L.textarea,sendButton:L.sendButton,sendButtonWrapper:L.sendButtonWrapper,micButton:L.micButton,micButtonWrapper:L.micButtonWrapper,composerForm:L.composerForm,statusText:L.statusText,introTitle:p,introSubtitle:f,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:d,footer:L.footer,attachmentButton:L.attachmentButton,attachmentButtonWrapper:L.attachmentButtonWrapper,attachmentInput:L.attachmentInput,attachmentPreviewsContainer:L.attachmentPreviewsContainer,actionsRow:L.actionsRow,leftActions:L.leftActions,rightActions:L.rightActions,setSendButtonMode:L.setSendButtonMode,peekBanner:I,peekTextNode:P}},im=(e,t=!0)=>{var E,L,I,P,H,W,x,w,k;if(Js(e))return Ny(e,t);let n=b("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");n.setAttribute("data-persona-theme-zone","container");let o=(E=e==null?void 0:e.layout)==null?void 0:E.header,r=((L=e==null?void 0:e.layout)==null?void 0:L.showHeader)!==!1,s=o?bi(e,o,{showClose:t}):Mr({config:e,showClose:t}),a=b("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=hn(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(P=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeTitle)!=null?P:"Hello \u{1F44B}";let l=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(W=(H=e==null?void 0:e.copy)==null?void 0:H.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",i.append(d,l);let m=b("div","persona-flex persona-flex-col persona-gap-3"),p=(x=e==null?void 0:e.layout)==null?void 0:x.contentMaxWidth;p&&(m.style.maxWidth=p,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((w=e==null?void 0:e.copy)==null?void 0:w.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,m);let u=Ai({config:e}),C=((k=e==null?void 0:e.layout)==null?void 0:k.showFooter)!==!1;r?ea(n,s,e):(s.header.style.display="none",ea(n,s,e)),n.append(a);let v=b("div","persona-composer-overlay persona-pointer-events-none");return v.setAttribute("data-persona-composer-overlay",""),v.style.position="absolute",v.style.left="0",v.style.right="0",v.style.bottom="0",v.style.zIndex="20",C||(u.footer.style.display="none"),n.append(u.footer),n.append(v),{container:n,body:a,messagesWrapper:m,composerOverlay:v,suggestions:u.suggestions,textarea:u.textarea,sendButton:u.sendButton,sendButtonWrapper:u.sendButtonWrapper,micButton:u.micButton,micButtonWrapper:u.micButtonWrapper,composerForm:u.composerForm,statusText:u.statusText,introTitle:d,introSubtitle:l,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:u.footer,attachmentButton:u.attachmentButton,attachmentButtonWrapper:u.attachmentButtonWrapper,attachmentInput:u.attachmentInput,attachmentPreviewsContainer:u.attachmentPreviewsContainer,actionsRow:u.actionsRow,leftActions:u.leftActions,rightActions:u.rightActions,setSendButtonMode:u.setSendButtonMode}};var _y=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Vy=(e,t)=>{if(!e)return null;let n=_y(e);if(n===null)return null;let o=t==null?void 0:t[e],r=o!==void 0?o:n;return r||null},$y=(e,t)=>{let n=b("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},Uy=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Sl=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Al=320,cm=320,zy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),qy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),jy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Ky=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Gy=(e,t,n)=>{if(e.length===0)return null;try{let o=b("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n==null||n())};return e.forEach((i,d)=>{var p;let l=b("img");l.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${Al}px`,l.style.maxHeight=`${cm}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let m=!1;r+=1,l.addEventListener("error",()=>{m||(m=!0,r=Math.max(0,r-1),l.remove(),r===0&&a())}),l.addEventListener("load",()=>{m=!0}),Uy(i.image)?(l.src=i.image,o.appendChild(l)):(m=!0,r=Math.max(0,r-1),l.remove())}),r===0?(a(),null):o}catch{return n==null||n(),null}},Yy=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!Sl(o.audio))return;let r=b("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Al}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Xy=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!Sl(o.video))return;let r=b("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Al}px`,r.style.maxHeight=`${cm}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Qy=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!Sl(o.data))return;let r=b("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ta=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},Jy=(e,t,n)=>{let o={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:ta};if(t){let r=t(o);if(r!==null)return r}return ta()},Zy=(e,t)=>{let n=b("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=b("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},lm=(e,t)=>{let n=b("div","persona-text-xs persona-text-persona-muted"),o=new Date(e.createdAt);return t.format?n.textContent=t.format(o):n.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},ev=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},tv=(e,t,n)=>{var u,C,v,E,L,I;let o=(u=t.showCopy)!=null?u:!0,r=(C=t.showUpvote)!=null?C:!0,s=(v=t.showDownvote)!=null?v:!0;if(!o&&!r&&!s){let P=b("div");return P.style.display="none",P.id=`actions-${e.id}`,P.setAttribute("data-actions-for",e.id),P}let a=(E=t.visibility)!=null?E:"hover",i=(L=t.align)!=null?L:"right",d=(I=t.layout)!=null?I:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],m={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${m} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let f=(P,H,W)=>{let x=Cn({icon:P,label:H,size:14,className:"persona-message-action-btn"});return x.setAttribute("data-action",W),x};return o&&p.appendChild(f("copy","Copy message","copy")),r&&p.appendChild(f("thumbs-up","Upvote","upvote")),s&&p.appendChild(f("thumbs-down","Downvote","downvote")),p},Tl=(e,t,n,o,r,s)=>{var j,de,K,ye,le,te,Ce,Ue,ee,oe,ae,rt,Ae,pe,$e,We,ue;let a=n!=null?n:{},i=(j=a.layout)!=null?j:"bubble",d=a.avatar,l=a.timestamp,m=(de=d==null?void 0:d.show)!=null?de:!1,p=(K=l==null?void 0:l.show)!=null?K:!1,f=(ye=d==null?void 0:d.position)!=null?ye:"left",u=(le=l==null?void 0:l.position)!=null?le:"below",C=ev(e.role,i),v=b("div",C.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=zy(e),L=(Ce=(te=e.content)==null?void 0:te.trim())!=null?Ce:"",P=E.length>0&&L===ei,H=pi((ee=(Ue=s==null?void 0:s.widgetConfig)==null?void 0:Ue.features)==null?void 0:ee.streamAnimation),W=(rt=(ae=(oe=s==null?void 0:s.widgetConfig)==null?void 0:oe.features)==null?void 0:ae.streamAnimation)==null?void 0:rt.plugins,x=e.role==="assistant"&&H.type!=="none"?Gs(H.type,W):null,w=e.role==="assistant"&&((Ae=x==null?void 0:x.isAnimating)==null?void 0:Ae.call(x,e))===!0,k=e.role==="assistant"&&x!==null&&(!!e.streaming||w);k&&(x!=null&&x.bubbleClass)&&v.classList.add(x.bubbleClass);let S=document.createElement("div");S.classList.add("persona-message-content"),k&&x&&(x.containerClass&&S.classList.add(x.containerClass),S.style.setProperty("--persona-stream-step",`${H.speed}ms`),S.style.setProperty("--persona-stream-duration",`${H.duration}ms`));let A=k?ui((pe=e.content)!=null?pe:"",H.buffer,x,e,!!e.streaming):($e=e.content)!=null?$e:"",N=t({text:A,message:e,streaming:!!e.streaming,raw:e.rawContent}),$=N;k&&(x==null?void 0:x.wrap)==="char"?$=Ys(N,"char",e.id,{skipTags:x.skipTags}):k&&(x==null?void 0:x.wrap)==="word"&&($=Ys(N,"word",e.id,{skipTags:x.skipTags}));let G=null;if(P?(G=document.createElement("div"),G.innerHTML=$,G.style.display="none",S.appendChild(G)):S.innerHTML=$,k&&(x!=null&&x.useCaret)&&!P&&L){let X=mi(),Ne=S.querySelectorAll(".persona-stream-char, .persona-stream-word"),Bt=Ne[Ne.length-1];if(Bt!=null&&Bt.parentNode)Bt.parentNode.insertBefore(X,Bt.nextSibling);else{let he=S.lastElementChild;he?he.appendChild(X):S.appendChild(X)}}if(p&&u==="inline"&&e.createdAt){let X=lm(e,l);X.classList.add("persona-ml-2","persona-inline"),S.appendChild(X)}if(E.length>0){let X=Gy(E,!P&&!!L,()=>{P&&G&&(G.style.display="")});X?v.appendChild(X):P&&G&&(G.style.display="")}let fe=qy(e);if(fe.length>0){let X=Yy(fe);X&&v.appendChild(X)}let ge=jy(e);if(ge.length>0){let X=Xy(ge);X&&v.appendChild(X)}let se=Ky(e);if(se.length>0){let X=Qy(se);X&&v.appendChild(X)}if(v.appendChild(S),p&&u==="below"&&e.createdAt){let X=lm(e,l);X.classList.add("persona-mt-1"),v.appendChild(X)}let ke=e.role==="assistant"?Vy(e.stopReason,(ue=(We=s==null?void 0:s.widgetConfig)==null?void 0:We.copy)==null?void 0:ue.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let X=!!(A&&A.trim()),Ne=H.placeholder==="skeleton",Bt=Ne&&H.buffer==="line"&&X;if(X)Bt&&v.appendChild(Xs());else if(Ne)v.appendChild(Xs());else{let he=Jy("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);he&&v.appendChild(he)}}if(ke&&e.stopReason&&!e.streaming&&(L||(S.style.display="none"),v.appendChild($y(e.stopReason,ke))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let X=tv(e,o,r);v.appendChild(X)}if(!m||e.role==="system")return v;let Fe=b("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),xe=Zy(d,e.role);return f==="right"||f==="left"&&e.role==="user"?Fe.append(v,xe):Fe.append(xe,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Fe};var es=new Set,nv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),ov=(e,t)=>{var o,r;let n=(r=(o=e.reasoning)==null?void 0:o.chunks.join("").trim())!=null?r:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
24
+ `):""},dm=(e,t)=>{let n=es.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let a=o.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=Ee(n?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},kl=(e,t)=>{var ge,se,ke,be,Fe,xe,j,de,K,ye,le;let n=e.reasoning,o=b("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let r=(se=(ge=t==null?void 0:t.features)==null?void 0:ge.reasoningDisplay)!=null?se:{},s=r.expandable!==!1,a=s&&es.has(e.id),i=n.status!=="complete",d=ov(e,(ke=r.previewMaxLines)!=null?ke:3),l=b("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",s&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let m=b("div","persona-flex persona-flex-col persona-text-left"),p=b("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",u=(be=t==null?void 0:t.reasoning)!=null?be:{},C=String((Fe=n.startedAt)!=null?Fe:Date.now()),v=()=>{let te=b("span","");return te.setAttribute("data-tool-elapsed",C),te.textContent=Ya(n),te},E=(xe=u.renderCollapsedSummary)==null?void 0:xe.call(u,{message:e,reasoning:n,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Ya(n),createElapsedElement:v});typeof E=="string"&&E.trim()?(p.textContent=E,m.appendChild(p)):E instanceof HTMLElement?m.appendChild(E):(p.textContent=f,m.appendChild(p));let L=b("span","persona-text-xs persona-text-persona-primary");L.textContent=Wu(n),m.appendChild(L);let I=(j=r.loadingAnimation)!=null?j:"none",P=u.activeTextTemplate,H=u.completeTextTemplate,W=i?P:H,x=E instanceof HTMLElement,w=(te,Ce,Ue)=>{let ee=Ue;for(let oe of Ce){let ae=b("span","persona-tool-char");ae.style.setProperty("--char-index",String(ee)),ae.textContent=oe===" "?"\xA0":oe,te.appendChild(ae),ee++}return ee},k=(te,Ce)=>{p.textContent="";let Ue=Xa(te,""),ee=0;for(let oe of Ue){let ae=oe.styles.length>0?(()=>{let rt=b("span",oe.styles.map(Ae=>`persona-tool-text-${Ae}`).join(" "));return p.appendChild(rt),rt})():p;if(oe.isDuration&&i)ae.appendChild(v());else{let rt=oe.isDuration?Ya(n):oe.text;Ce?ee=w(ae,rt,ee):ae.appendChild(document.createTextNode(rt))}}};if(!x&&W)if(L.style.display="none",p.style.display="",i&&I!=="none"){let te=(de=u.loadingAnimationDuration)!=null?de:2e3;p.setAttribute("data-preserve-animation","true"),I==="pulse"?(p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${te}ms`),k(W,!1)):(p.classList.add(`persona-tool-loading-${I}`),p.style.setProperty("--persona-tool-anim-duration",`${te}ms`),I==="shimmer-color"&&(u.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",u.loadingAnimationColor),u.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",u.loadingAnimationSecondaryColor)),k(W,!0))}else k(W,!1);else if(!x&&i&&I!=="none"){p.style.display="";let te=(K=u.loadingAnimationDuration)!=null?K:2e3;if(p.setAttribute("data-preserve-animation","true"),I==="pulse")p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${te}ms`);else{p.classList.add(`persona-tool-loading-${I}`),p.style.setProperty("--persona-tool-anim-duration",`${te}ms`),I==="shimmer-color"&&(u.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",u.loadingAnimationColor),u.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",u.loadingAnimationSecondaryColor));let Ce=p.textContent||f;p.textContent="",w(p,Ce,0)}n.status==="complete"&&(p.style.display="none")}else x||(n.status==="complete"?p.style.display="none":p.style.display="");let S=null;if(s){S=b("div","persona-flex persona-items-center");let Ce=Ee(a?"chevron-up":"chevron-down",16,"currentColor",2);Ce?S.appendChild(Ce):S.textContent=a?"Hide":"Show";let Ue=b("div","persona-flex persona-items-center persona-ml-auto");Ue.append(S),l.append(m,Ue)}else l.append(m);let A=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(A.setAttribute("data-persona-collapsed-preview","reasoning"),A.style.display="none",A.style.whiteSpace="pre-wrap",!a&&i&&r.activePreview&&d){let te=(le=(ye=t==null?void 0:t.reasoning)==null?void 0:ye.renderCollapsedPreview)==null?void 0:le.call(ye,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});nv(A,te)||(A.textContent=d),A.style.display=""}if(!a&&i&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(l,A),o;let N=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");N.style.display=a?"":"none";let $=n.chunks.join(""),G=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return G.textContent=$||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),N.appendChild(G),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),S){S.innerHTML="";let Ce=Ee(a?"chevron-up":"chevron-down",16,"currentColor",2);Ce?S.appendChild(Ce):S.textContent=a?"Hide":"Show"}N.style.display=a?"":"none",A.style.display=a?"none":A.textContent||A.childNodes.length?"":"none"})(),o.append(l,A,N),o};var ts=new Set,rv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),sv=(e,t)=>{var s;let n=e.toolCall;if(!n)return"";let o=((s=n.chunks)!=null?s:[]).join("").trim();if(o)return o.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
25
+ `);let r=Jr(n.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
26
+ `):""},av=(e,t)=>{var m,p,f,u,C;let n=e.toolCall,o=(m=t==null?void 0:t.features)==null?void 0:m.toolCallDisplay,r=(p=o==null?void 0:o.collapsedMode)!=null?p:"tool-call",s=sv(e,(f=o==null?void 0:o.previewMaxLines)!=null?f:3),a=n?Bu(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(u=t==null?void 0:t.toolCall)!=null?u:{},l=a;return r==="tool-name"?l=((C=n.name)==null?void 0:C.trim())||a:r==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=ml(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=ml(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},pm=(e,t,n)=>{var m;let o=ts.has(e),r=(m=n==null?void 0:n.toolCall)!=null?m:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let p=r.toggleTextColor||r.headerTextColor||"currentColor",f=Ee(o?"chevron-up":"chevron-down",16,p,2);f?l.appendChild(f):l.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},El=(e,t)=>{var $,G,fe,ge,se,ke,be,Fe,xe;let n=e.toolCall,o=($=t==null?void 0:t.toolCall)!=null?$:{},r=b("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=(fe=(G=t==null?void 0:t.features)==null?void 0:G.toolCallDisplay)!=null?fe:{},a=s.expandable!==!1,i=a&&ts.has(e.id),{summary:d,previewText:l,isActive:m}=av(e,t),p=b("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");p.type="button",a&&(p.setAttribute("aria-expanded",i?"true":"false"),p.setAttribute("data-expand-header","true")),p.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(p.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(p.style.paddingLeft=o.headerPaddingX,p.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(p.style.paddingTop=o.headerPaddingY,p.style.paddingBottom=o.headerPaddingY);let f=b("div","persona-flex persona-flex-col persona-text-left"),u=b("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(u.style.color=o.headerTextColor);let C=String((ge=n.startedAt)!=null?ge:Date.now()),v=()=>{let j=b("span","");return j.setAttribute("data-tool-elapsed",C),j.textContent=Os(n),j},E=(ke=o.renderCollapsedSummary)==null?void 0:ke.call(o,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(se=s.collapsedMode)!=null?se:"tool-call",isActive:m,config:t!=null?t:{},elapsed:Os(n),createElapsedElement:v});typeof E=="string"&&E.trim()?(u.textContent=E,f.appendChild(u)):E instanceof HTMLElement?f.appendChild(E):(u.textContent=d,f.appendChild(u));let L=(be=s.loadingAnimation)!=null?be:"none",I=o.activeTextTemplate,P=o.completeTextTemplate,H=m?I:P,W=E instanceof HTMLElement,x=(j,de,K)=>{let ye=K;for(let le of de){let te=b("span","persona-tool-char");te.style.setProperty("--char-index",String(ye)),te.textContent=le===" "?"\xA0":le,j.appendChild(te),ye++}return ye},w=(j,de)=>{var te;u.textContent="";let K=((te=n.name)==null?void 0:te.trim())||"tool",ye=Xa(j,K),le=0;for(let Ce of ye){let Ue=Ce.styles.length>0?(()=>{let ee=b("span",Ce.styles.map(oe=>`persona-tool-text-${oe}`).join(" "));return u.appendChild(ee),ee})():u;if(Ce.isDuration&&m)Ue.appendChild(v());else{let ee=Ce.isDuration?Os(n):Ce.text;de?le=x(Ue,ee,le):Ue.appendChild(document.createTextNode(ee))}}};if(!W)if(m&&L!=="none"){let j=(Fe=o.loadingAnimationDuration)!=null?Fe:2e3;if(u.setAttribute("data-preserve-animation","true"),L==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${j}ms`),H&&w(H,!1);else if(u.classList.add(`persona-tool-loading-${L}`),u.style.setProperty("--persona-tool-anim-duration",`${j}ms`),L==="shimmer-color"&&(o.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),H)w(H,!0);else{let de=u.textContent||d;u.textContent="",x(u,de,0)}}else H&&w(H,!1);let k=null;if(a){k=b("div","persona-flex persona-items-center");let j=o.toggleTextColor||o.headerTextColor||"currentColor",de=Ee(i?"chevron-up":"chevron-down",16,j,2);de?k.appendChild(de):k.textContent=i?"Hide":"Show";let K=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");K.append(k),p.append(f,K)}else p.append(f);let S=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(S.setAttribute("data-persona-collapsed-preview","tool"),S.style.display="none",S.style.whiteSpace="pre-wrap",!i&&m&&s.activePreview&&l){let j=(xe=o.renderCollapsedPreview)==null?void 0:xe.call(o,{message:e,toolCall:n,defaultPreview:l,isActive:m,config:t!=null?t:{}});rv(S,j)||(S.textContent=l),S.style.display=""}if(!i&&m&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(p,S),r;let A=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(A.style.display=i?"":"none",o.contentBackgroundColor&&(A.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(A.style.color=o.contentTextColor),o.contentPaddingX&&(A.style.paddingLeft=o.contentPaddingX,A.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(A.style.paddingTop=o.contentPaddingY,A.style.paddingBottom=o.contentPaddingY),n.name){let j=b("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?j.style.color=o.contentTextColor:o.headerTextColor&&(j.style.color=o.headerTextColor),j.textContent=n.name,A.appendChild(j)}if(n.args!==void 0){let j=b("div","persona-space-y-1"),de=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(de.style.color=o.labelTextColor),de.textContent="Arguments";let K=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");K.style.fontSize="0.75rem",K.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(K.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(K.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(K.style.color=o.codeBlockTextColor),K.textContent=Jr(n.args),j.append(de,K),A.appendChild(j)}if(n.chunks&&n.chunks.length){let j=b("div","persona-space-y-1"),de=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(de.style.color=o.labelTextColor),de.textContent="Activity";let K=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");K.style.fontSize="0.75rem",K.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(K.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(K.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(K.style.color=o.codeBlockTextColor),K.textContent=n.chunks.join(""),j.append(de,K),A.appendChild(j)}if(n.status==="complete"&&n.result!==void 0){let j=b("div","persona-space-y-1"),de=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(de.style.color=o.labelTextColor),de.textContent="Result";let K=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");K.style.fontSize="0.75rem",K.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(K.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(K.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(K.style.color=o.codeBlockTextColor),K.textContent=Jr(n.result),j.append(de,K),A.appendChild(j)}if(n.status==="complete"&&typeof n.duration=="number"){let j=b("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(j.style.color=o.contentTextColor),j.textContent=`Duration: ${n.duration}ms`,A.appendChild(j)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),k){k.innerHTML="";let j=o.toggleTextColor||o.headerTextColor||"currentColor",de=Ee(i?"chevron-up":"chevron-down",16,j,2);de?k.appendChild(de):k.textContent=i?"Hide":"Show"}A.style.display=i?"":"none",S.style.display=i?"none":S.textContent||S.childNodes.length?"":"none"})(),r.append(p,S,A),r};import{parse as iv,ARR as lv,OBJ as cv,STR as dv}from"partial-json";var pv="ask_user_question",Ml=8,ns="data-persona-ask-sheet-for",uv="Other",mv="Other\u2026",mm="Type your own answer here",gm="Send",gv="Next",fv="Back",hv="Submit all",bv="Skip",yv=3,Ll="data-ask-current-index",Il="data-ask-question-count",fm="data-ask-answers",Rl="data-ask-grouped",hm="data-ask-layout",vv=e=>e.layout==="pills"?"pills":"rows",xv=e=>e.getAttribute(hm)==="pills"?"pills":"rows",um=!1,bm=e=>e.replace(/["\\]/g,"\\$&"),Lr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===pv,Pl=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},os=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=iv(r,dv|cv|lv);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},na=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>Ml&&!um&&(um=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Ml}.`)),t.slice(0,Ml)},wv=e=>{var t;return(t=na(e)[0])!=null?t:null},Cv=(e,t)=>{var n;return(n=na(e)[t])!=null?n:null},Sv=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},ym=(e,t,n)=>{if(e!=="rows")return null;let o=b("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=b("span","persona-ask-row-check");o.appendChild(r)}else{let r=b("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Av=(e,t,n,o)=>{let s=b("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=b("span","persona-ask-row-content"),i=b("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=b("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}s.appendChild(a);let d=ym(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Tv=e=>{let n=b("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},kv=(e,t,n,o)=>{var m,p,f;let s=b("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(u=>u&&typeof u.label=="string"&&u.label.length>0);if(d.length===0&&!n){for(let u=0;u<yv;u++)s.appendChild(Tv(o));return s}if(d.forEach((u,C)=>{s.appendChild(Av(u,C,o,a))}),(e==null?void 0:e.allowFreeText)!==!1){let u=o==="rows"?uv:mv;if(o==="rows"){let C=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");C.setAttribute("data-ask-user-action","focus-free-text"),C.setAttribute("data-option-index",String(d.length)),C.setAttribute("data-ask-other-row","true");let v=b("span","persona-ask-row-content"),E=document.createElement("input");E.type="text",E.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",E.placeholder=(m=t.freeTextPlaceholder)!=null?m:mm,E.setAttribute("data-ask-free-text-input","true"),E.setAttribute("aria-label",(p=t.freeTextLabel)!=null?p:u),v.appendChild(E),C.appendChild(v);let L=ym(o,a,d.length);L&&C.appendChild(L),s.appendChild(C)}else{let C=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");C.type="button",C.setAttribute("data-ask-user-action","open-free-text"),C.textContent=(f=t.freeTextLabel)!=null?f:u,s.appendChild(C)}}return s},vm=(e,t)=>{var s,a;let o=b("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=(s=e.freeTextPlaceholder)!=null?s:mm,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let i=b("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:gm,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},Ev=e=>{var o;let t=b("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=b("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(o=e.submitLabel)!=null?o:gm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Mv=(e,t,n)=>{var l,m,p,f;let o=b("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=b("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=(l=n.backLabel)!=null?l:fv,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(m=n.skipLabel)!=null?m:bv,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=b("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(p=n.submitAllLabel)!=null?p:hv:(f=n.nextLabel)!=null?f:gv,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},Ir=e=>{let t=e.getAttribute(fm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},xm=(e,t)=>{e.setAttribute(fm,JSON.stringify(t))},fo=e=>{var n;let t=Number((n=e.getAttribute(Ll))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Lv=(e,t)=>{e.setAttribute(Ll,String(Math.max(0,Math.floor(t))))},rs=e=>{var n;let t=Number((n=e.getAttribute(Il))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},lr=e=>e.getAttribute(Rl)==="true",Iv=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(o[a]=d)}}),o},Rv=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Ti=(e,t)=>{let{payload:n}=os(t),o=na(n),r=Ir(e),s={},a=new Set;return o.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(r,d)&&(s[l]=r[d]))}),s},wm=e=>{let t=Ir(e),n=fo(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(d=>r.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var p;let l=(p=d.getAttribute("data-option-label"))!=null?p:"",m=r.has(l);d.setAttribute("aria-pressed",m?"true":"false"),d.classList.toggle("persona-ask-pill-selected",m)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!a.has(o)){i.value=o;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Cm=e=>{if(!lr(e))return;let t=Ir(e),n=fo(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Wl=(e,t,n)=>{let o=Pl(n),r=xv(e),{payload:s,complete:a}=os(t),i=lr(e),d=fo(e),l=rs(e),m=i?Cv(s,d):wv(s),p=!!(m!=null&&m.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let u=e.querySelector('[data-ask-stepper="true"]');u&&u.remove();let C=e.querySelector('[data-ask-question="true"]');if(C){let I=typeof(m==null?void 0:m.question)=="string"?m.question:"";C.textContent=I,C.classList.toggle("persona-ask-question-skeleton",!I&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let I=kv(m,o,a,r);v.replaceWith(I)}if(r!=="rows"){let I=e.querySelector('[data-ask-free-text-row="true"]');I&&I.replaceWith(vm(o,r))}let E=e.querySelector('[data-ask-multi-actions="true"]');!i&&p&&!E?e.appendChild(Ev(o)):(!p||i)&&E&&E.remove(),e.setAttribute("data-multi-select",p?"true":"false");let L=e.querySelector('[data-ask-nav-row="true"]');if(i){let I=Mv(d,l,o);L?L.replaceWith(I):e.appendChild(I)}else L&&L.remove();wm(e),Cm(e)},Pv=(e,t,n)=>{let o=Pl(t),r=vv(o),s=e.toolCall.id,a=na(n),i=Math.max(1,a.length),d=i>1,l=Iv(e,a),m=d?Rv(e,i):0,p=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(ns,s),p.setAttribute("data-tool-call-id",s),p.setAttribute("data-message-id",e.id),p.setAttribute(Il,String(i)),p.setAttribute(Ll,String(m)),p.setAttribute(Rl,d?"true":"false"),p.setAttribute(hm,r),xm(p,l),p.setAttribute("role","group"),p.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&p.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Sv(p,o);let f=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),u=b("div","persona-ask-sheet-question persona-flex-1");u.setAttribute("data-ask-question","true"),u.textContent="",f.appendChild(u);let C=b("span","persona-ask-sheet-step-inline");C.setAttribute("data-ask-step-inline","true"),C.textContent="",f.appendChild(C),p.appendChild(f);let E=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),p.appendChild(E),r!=="rows"&&p.appendChild(vm(o,r)),Wl(p,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p},Wv=(e,t,n)=>{let{payload:o}=os(t),r=Math.max(1,na(o).length);r>rs(e)&&(e.setAttribute(Il,String(r)),r>1&&!lr(e)&&e.setAttribute(Rl,"true")),Wl(e,t,n)};var ki=(e,t,n)=>{if(!n||!Lr(e)||Pl(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${ns}]`).forEach(l=>{l.getAttribute(ns)!==r&&l.remove()});let a=n.querySelector(`[${ns}="${bm(r)}"]`);if(a){Wv(a,e,t);return}let{payload:i}=os(e),d=Pv(e,t,i);n.appendChild(d)},ss=(e,t)=>{if(!e)return;let n=t?`[${ns}="${bm(t)}"]`:`[${ns}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},Bl=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),cr=(e,t)=>{let n=Ir(e),o=fo(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,xm(e,n),wm(e),Cm(e)},Ei=(e,t,n,o)=>{let r=rs(e),s=Math.max(0,Math.min(r-1,o));Lv(e,s),Wl(e,t,n)};var Mi=new Map,Bv=e=>{let n=(e.startsWith(Tr)?e.slice(Tr.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Sm=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Am=(e,t)=>{var o,r,s;let n=(r=(o=Sm(t))==null?void 0:o.detailsDisplay)!=null?r:"collapsed";return(s=Mi.get(e))!=null?s:n==="expanded"},Tm=(e,t,n)=>{var a,i;let o=Sm(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?(a=o==null?void 0:o.hideDetailsLabel)!=null?a:"Hide details":(i=o==null?void 0:o.showDetailsLabel)!=null?i:"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=Ee(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},km=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=Am(e,n);Tm(o,s,n),r.style.display=s?"":"none"};var Li=(e,t)=>{var w,k,S,A,N,$,G,fe,ge,se,ke,be,Fe,xe;let n=e.approval,o=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,r=(n==null?void 0:n.status)==="pending",s=b("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(w=o==null?void 0:o.backgroundColor)!=null?w:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(k=o==null?void 0:o.borderColor)!=null?k:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(o==null?void 0:o.shadow)!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=b("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",l=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(S=o==null?void 0:o.titleColor)!=null?S:"currentColor",m=Ee(d,20,l,2);m&&i.appendChild(m);let p=b("div","persona-flex-1 persona-min-w-0"),f=b("div","persona-flex persona-items-center persona-gap-2"),u=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o!=null&&o.titleColor&&(u.style.color=o.titleColor),u.textContent=(A=o==null?void 0:o.title)!=null?A:"Approval Required",f.appendChild(u),!r){let j=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");j.setAttribute("data-approval-status",n.status),n.status==="approved"?(j.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",j.style.color="var(--persona-palette-colors-success-700, #15803d)",j.textContent="Approved"):n.status==="denied"?(j.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",j.style.color="var(--persona-palette-colors-error-700, #b91c1c)",j.textContent="Denied"):n.status==="timeout"&&(j.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",j.style.color="var(--persona-palette-colors-warning-700, #b45309)",j.textContent="Timeout"),f.appendChild(j)}p.appendChild(f);let v=n.toolType==="webmcp"||n.toolName.startsWith(Tr)?ul(n.toolName):void 0,E=(N=o==null?void 0:o.formatDescription)==null?void 0:N.call(o,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...v?{displayTitle:v}:{}}),L=!n.toolName,I=E||(L?n.description:`The assistant wants to use \u201C${v!=null?v:Bv(n.toolName)}\u201D.`),P=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");P.setAttribute("data-approval-summary","true"),o!=null&&o.descriptionColor&&(P.style.color=o.descriptionColor),P.textContent=I,p.appendChild(P);let H=($=o==null?void 0:o.detailsDisplay)!=null?$:"collapsed",W=!!n.description&&!L,x=W||!!n.parameters;if(H!=="hidden"&&x){let j=Am(e.id,t),de=b("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");de.type="button",de.setAttribute("data-expand-header","true"),de.setAttribute("data-bubble-type","approval"),o!=null&&o.descriptionColor&&(de.style.color=o.descriptionColor);let K=b("span");K.setAttribute("data-approval-details-label","true");let ye=b("span","persona-inline-flex persona-items-center");ye.setAttribute("data-approval-details-chevron","true"),de.append(K,ye),Tm(de,j,t),p.appendChild(de);let le=b("div");if(le.setAttribute("data-approval-details","true"),le.style.display=j?"":"none",W){let te=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o!=null&&o.descriptionColor&&(te.style.color=o.descriptionColor),te.textContent=n.description,le.appendChild(te)}if(n.parameters){let te=b("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o!=null&&o.parameterBackgroundColor&&(te.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(te.style.color=o.parameterTextColor),te.style.fontSize="0.75rem",te.style.lineHeight="1rem",te.textContent=Jr(n.parameters),le.appendChild(te)}p.appendChild(le)}if(r){let j=b("div","persona-flex persona-gap-2 persona-mt-2");j.setAttribute("data-approval-buttons","true");let de=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");de.type="button",de.style.backgroundColor=(G=o==null?void 0:o.approveButtonColor)!=null?G:"var(--persona-approval-approve-bg, #22c55e)",de.style.color=(fe=o==null?void 0:o.approveButtonTextColor)!=null?fe:"#ffffff",de.setAttribute("data-approval-action","approve");let K=Ee("shield-check",14,(ge=o==null?void 0:o.approveButtonTextColor)!=null?ge:"#ffffff",2);K&&(K.style.marginRight="4px",de.appendChild(K));let ye=document.createTextNode((se=o==null?void 0:o.approveLabel)!=null?se:"Approve");de.appendChild(ye);let le=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");le.type="button",le.style.backgroundColor=(ke=o==null?void 0:o.denyButtonColor)!=null?ke:"transparent",le.style.color=(be=o==null?void 0:o.denyButtonTextColor)!=null?be:"var(--persona-feedback-error, #dc2626)",le.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,le.setAttribute("data-approval-action","deny");let te=Ee("shield-x",14,(Fe=o==null?void 0:o.denyButtonTextColor)!=null?Fe:"var(--persona-feedback-error, #dc2626)",2);te&&(te.style.marginRight="4px",le.appendChild(te));let Ce=document.createTextNode((xe=o==null?void 0:o.denyLabel)!=null?xe:"Deny");le.appendChild(Ce),j.append(de,le),p.appendChild(j)}return a.append(i,p),s.appendChild(a),s};var Em=e=>{let t=[];return{buttons:t,render:(o,r,s,a,i)=>{if(e.innerHTML="",t.length=0,!o||!o.length||(a!=null?a:r?r.getMessages():[]).some(u=>u.role==="user"))return;let m=document.createDocumentFragment(),p=r?r.isStreaming():!1,f=u=>{switch(u){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};o.forEach(u=>{let C=b("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");C.type="button",C.textContent=u,C.disabled=p,i!=null&&i.fontFamily&&(C.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(C.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(C.style.paddingLeft=i.paddingX,C.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(C.style.paddingTop=i.paddingY,C.style.paddingBottom=i.paddingY),C.addEventListener("click",()=>{!r||r.isStreaming()||(s.value="",r.sendMessage(u))}),m.appendChild(C),t.push(C)}),e.appendChild(m)}}};var oa=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var ra=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}};var Hv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Dv=new Set(["step_start","execution_start"]),Fv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Ov=new Set(["step_complete","agent_turn_complete"]),Nv=new Set(["flow_complete","agent_complete"]),Mm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Im=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Zn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Rr=(e,t)=>{let n=e[t];return Im(n)?n:void 0};function Hl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Ii(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function _v(e,t){return typeof t.type=="string"?t.type:e}function Vv(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function $v(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function Lm(e){var o,r,s,a,i;let t=Rr(e,"result"),n=[Rr(e,"tokens"),Rr(e,"totalTokens"),t?Rr(t,"tokens"):void 0,Rr(e,"usage"),t?Rr(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(r=(o=Zn(d.output))!=null?o:Zn(d.outputTokens))!=null?r:Zn(d.completionTokens);if(l!==void 0)return l}return(i=(s=Zn(e.outputTokens))!=null?s:Zn(e.completionTokens))!=null?i:t?(a=Zn(t.outputTokens))!=null?a:Zn(t.completionTokens):void 0}function Uv(e){var n,o,r,s,a;let t=Rr(e,"result");return(a=(r=(o=(n=Zn(e.executionTime))!=null?n:Zn(e.executionTimeMs))!=null?o:Zn(e.execution_time))!=null?r:Zn(e.duration))!=null?a:t?(s=Zn(t.executionTime))!=null?s:Zn(t.executionTimeMs):void 0}function zv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var sa=class{constructor(t=zv){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:Ii(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var s;if(!Im(n)){Mm.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=_v(t,n),r=this.now();if(Hv.has(o)){this.startRun(r);return}if(Dv.has(o)){this.run||this.startRun(r);return}if(Fv.has(o)){if(!$v(o,n))return;let a=Vv(n);if(!a)return;this.run||this.startRun(r);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=r),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Hl(i.visibleCharCount),l=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ii(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Ov.has(o)){if(!this.run)return;let a=this.run,i=Lm(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Hl(a.visibleCharCount),m=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:Ii(l,m),outputTokens:l,durationMs:m,source:d?"usage":"estimate"};return}if(Nv.has(o)){if(!this.run)return;let a=this.run,i=Lm(n),d=i!=null?i:a.exactOutputTokens+Hl(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",m=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:Ii(d,m),outputTokens:d,durationMs:m,source:l},this.run=null;return}if(Mm.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;if(r!==void 0&&r>=250)return r;let s=Uv(n);return s!=null?s:o-t.startedAt}};function as(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var qv={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},jv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Kv=["flowName","stepName","reasoningText","text","name","tool","toolName"],Gv=100;function Yv(e,t){let n={...qv,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return jv}function Xv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Qv(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function Jv(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Zv(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let o=document.createElement("textarea");o.value=e,o.style.position="fixed",o.style.opacity="0",document.body.appendChild(o),o.select(),document.execCommand("copy"),document.body.removeChild(o),n()})}function ex(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function tx(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function nx(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function ox(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(i)return i}return a();function a(){let i=b("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=b("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=o,i.appendChild(d),i}}function Dl(e,t,n,o,r,s,a,i){var f;let d=r.has(e.id),l=b("div","persona-border-b persona-border-persona-divider persona-text-xs");as(l,(f=o.classNames)==null?void 0:f.eventRow);let m=a.find(u=>u.renderEventStreamRow);if(m!=null&&m.renderEventStreamRow&&i){let u=m.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(u)return l.appendChild(u),l}return l.appendChild(p()),l;function p(){var $,G;let u=b("div",""),C=b("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");C.setAttribute("data-event-id",e.id);let v=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),E=Ee(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&v.appendChild(E);let L=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),I=($=o.timestampFormat)!=null?$:"relative";L.textContent=I==="relative"?Xv(e.timestamp,n):Qv(e.timestamp);let P=null;o.showSequenceNumbers!==!1&&(P=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),P.textContent=String(t+1));let H=Yv(e.type,o.badgeColors),W=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");W.style.backgroundColor=H.bg,W.style.color=H.text,W.style.borderColor=H.text+"50",W.textContent=e.type;let x=(G=o.descriptionFields)!=null?G:Kv,w=Jv(e.payload,x),k=null;w&&(k=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),k.textContent=w);let S=b("div","persona-flex-1 persona-min-w-0"),A=b("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),N=Ee("clipboard","12px","currentColor",1.5);return N&&A.appendChild(N),A.addEventListener("click",async fe=>{fe.stopPropagation(),await Zv(ex(e)),A.innerHTML="";let ge=Ee("check","12px","currentColor",1.5);ge&&A.appendChild(ge),setTimeout(()=>{A.innerHTML="";let se=Ee("clipboard","12px","currentColor",1.5);se&&A.appendChild(se)},1500)}),C.appendChild(v),C.appendChild(L),P&&C.appendChild(P),C.appendChild(W),k&&C.appendChild(k),C.appendChild(S),C.appendChild(A),u.appendChild(C),d&&u.appendChild(ox(e,a,i)),u}}function Rm(e){var C,v,E,L,I;let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,i=(C=r==null?void 0:r.features)==null?void 0:C.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(v=i==null?void 0:i.iconName)!=null?v:"arrow-down",m=(E=i==null?void 0:i.label)!=null?E:"",p=(I=(L=r==null?void 0:r.features)==null?void 0:L.eventStream)!=null?I:{},f=s.find(P=>P.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&r){let P=f.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>u().element,onClose:o});if(P)return{element:P,update:()=>{},destroy:()=>{}}}return u();function u(){let P=p.classNames,H=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");as(H,P==null?void 0:P.panel);let W=[],x="",w="",k=null,S=[],A={},N=0,$=li(),G=0,fe=0,ge=!1,se=null,ke=!1,be=0,Fe=new Set,xe=new Map,j="",de="",K=null,ye,le,te,Ce,Ue,ee=null,oe=null,ae=null;function rt(){let re=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),we=b("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");as(we,P==null?void 0:P.headerBar);let Tt=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Tt.textContent="Events",ye=b("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),ye.textContent="0",a){oe=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),oe.style.cursor="help";let Fn=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Fn.textContent="Throughput",ee=b("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),ee.textContent="-- tok/s",ae=b("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),ae.style.display="none",ae.style.pointerEvents="none";let to=oe,An=ae,On=()=>{if(!An.textContent)return;let Eo=to.getBoundingClientRect(),Nn=re.getBoundingClientRect();An.style.left=`${Eo.left-Nn.left}px`,An.style.top=`${Eo.bottom-Nn.top+4}px`,An.style.display="block"},ht=()=>{An.style.display="none"};oe.addEventListener("mouseenter",On),oe.addEventListener("mouseleave",ht),oe.appendChild(Fn),oe.appendChild(ee)}let jt=b("div","persona-flex-1");le=b("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let en=b("option","");en.value="",en.textContent="All events",le.appendChild(en),te=b("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),te.type="button",te.title="Copy All";let Pt=Ee("clipboard-copy","12px","currentColor",1.5);Pt&&te.appendChild(Pt);let Et=b("span","persona-text-xs");Et.textContent="Copy All",te.appendChild(Et),we.appendChild(Tt),we.appendChild(ye),oe&&we.appendChild(oe),we.appendChild(jt),we.appendChild(le),we.appendChild(te);let xt=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");as(xt,P==null?void 0:P.searchBar);let Ct=Ee("search","14px","var(--persona-muted, #9ca3af)",1.5),Kt=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Ct&&Kt.appendChild(Ct),Ce=b("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),as(Ce,P==null?void 0:P.searchInput),Ce.type="text",Ce.placeholder="Search event payloads...",Ue=b("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Ue.type="button",Ue.style.display="none";let nt=Ee("x","12px","currentColor",2);return nt&&Ue.appendChild(nt),xt.appendChild(Kt),xt.appendChild(Ce),xt.appendChild(Ue),re.appendChild(we),re.appendChild(xt),ae&&re.appendChild(ae),re}let Ae,pe=s.find(re=>re.renderEventStreamToolbar);if(pe!=null&&pe.renderEventStreamToolbar&&r){let re=pe.renderEventStreamToolbar({config:r,defaultRenderer:()=>rt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:we=>{x=we,Dn(),_()},onSearchChange:we=>{w=we,Dn(),_()}});Ae=re!=null?re:rt()}else Ae=rt();let $e=b("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");$e.style.display="none";function We(){if(!a||!ee||!oe)return;let re=a();ee.textContent=tx(re);let we=nx(re);ae&&(ae.textContent=we,we||(ae.style.display="none")),we?oe.setAttribute("aria-label",we):oe.removeAttribute("aria-label")}let ue=b("div","persona-flex-1 persona-min-h-0 persona-relative"),X=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");X.style.height="100%";let Ne=b("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");as(Ne,P==null?void 0:P.scrollIndicator),Ne.style.display="none",Ne.setAttribute("data-persona-scroll-to-bottom-has-label",m?"true":"false");let Bt=Ee(l,"14px","currentColor",2);Bt&&Ne.appendChild(Bt);let he=b("span","");he.textContent=m,Ne.appendChild(he);let ce=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ce.style.display="none",ue.appendChild(X),ue.appendChild(ce),ue.appendChild(Ne),H.setAttribute("tabindex","0"),H.appendChild(Ae),H.appendChild($e),H.appendChild(ue);function Rn(){let re=t.getAll(),we={};for(let Et of re)we[Et.type]=(we[Et.type]||0)+1;let Tt=Object.keys(we).sort(),jt=Tt.length!==S.length||!Tt.every((Et,xt)=>Et===S[xt]),en=!jt&&Tt.some(Et=>we[Et]!==A[Et]),Sn=re.length!==Object.values(A).reduce((Et,xt)=>Et+xt,0);if(!jt&&!en&&!Sn||(S=Tt,A=we,!le))return;let Pt=le.value;if(le.options[0].textContent="All events",jt){for(;le.options.length>1;)le.remove(1);for(let Et of Tt){let xt=b("option","");xt.value=Et,xt.textContent=`${Et} (${we[Et]||0})`,le.appendChild(xt)}Pt&&Tt.includes(Pt)?le.value=Pt:Pt&&(le.value="",x="")}else for(let Et=1;Et<le.options.length;Et++){let xt=le.options[Et];xt.textContent=`${xt.value} (${we[xt.value]||0})`}}function $t(){let re=t.getAll();if(x&&(re=re.filter(we=>we.type===x)),w){let we=w.toLowerCase();re=re.filter(Tt=>Tt.type.toLowerCase().includes(we)||Tt.payload.toLowerCase().includes(we))}return re}function mn(){return x!==""||w!==""}function Dn(){N=0,G=0,$.resume(),Ne.style.display="none"}function eo(re){Fe.has(re)?Fe.delete(re):Fe.add(re),K=re;let we=X.scrollTop,Tt=$.isFollowing();ke=!0,$.pause(),_(),X.scrollTop=we,Tt&&$.resume(),ke=!1}function ze(){return js(X,50)}function _(){fe=Date.now(),ge=!1,We(),Rn();let re=t.getEvictedCount();re>0?($e.textContent=`${re.toLocaleString()} older events truncated`,$e.style.display=""):$e.style.display="none",W=$t();let we=W.length,Tt=t.getSize()>0;ye&&(ye.textContent=String(t.getSize())),we===0&&Tt&&mn()?(ce.textContent=w?`No events matching '${w}'`:"No events matching filter",ce.style.display="",X.style.display="none"):(ce.style.display="none",X.style.display=""),te&&(te.title=mn()?`Copy Filtered (${we})`:"Copy All"),d&&!$.isFollowing()&&we>N&&(G+=we-N,he.textContent=m?`${m}${G>0?` (${G})`:""}`:"",Ne.style.display=""),N=we;let jt=t.getAll(),en=jt.length>0?jt[0].timestamp:0,Sn=new Set(W.map(xt=>xt.id));for(let xt of Fe)Sn.has(xt)||Fe.delete(xt);let Pt=x!==j||w!==de,Et=xe.size===0&&W.length>0;if(Pt||Et||W.length===0){X.innerHTML="",xe.clear();let xt=document.createDocumentFragment();for(let Ct=0;Ct<W.length;Ct++){let Kt=Dl(W[Ct],Ct,en,p,Fe,eo,s,r);xe.set(W[Ct].id,Kt),xt.appendChild(Kt)}X.appendChild(xt),j=x,de=w,K=null}else{if(K!==null){let Ct=xe.get(K);if(Ct&&Ct.parentNode===X){let Kt=W.findIndex(nt=>nt.id===K);if(Kt>=0){let nt=Dl(W[Kt],Kt,en,p,Fe,eo,s,r);X.insertBefore(nt,Ct),Ct.remove(),xe.set(K,nt)}}K=null}let xt=new Set(W.map(Ct=>Ct.id));for(let[Ct,Kt]of xe)xt.has(Ct)||(Kt.remove(),xe.delete(Ct));for(let Ct=0;Ct<W.length;Ct++){let Kt=W[Ct];if(!xe.has(Kt.id)){let nt=Dl(Kt,Ct,en,p,Fe,eo,s,r);xe.set(Kt.id,nt),X.appendChild(nt)}}}$.isFollowing()&&(X.scrollTop=X.scrollHeight)}function Me(){if(Date.now()-fe>=Gv){se!==null&&(cancelAnimationFrame(se),se=null),_();return}ge||(ge=!0,se=requestAnimationFrame(()=>{se=null,_()}))}let Be=(re,we)=>{if(!te)return;te.innerHTML="";let Tt=Ee(re,"12px","currentColor",1.5);Tt&&te.appendChild(Tt);let jt=b("span","persona-text-xs");jt.textContent="Copy All",te.appendChild(jt),setTimeout(()=>{te.innerHTML="";let en=Ee("clipboard-copy","12px","currentColor",1.5);en&&te.appendChild(en);let Sn=b("span","persona-text-xs");Sn.textContent="Copy All",te.appendChild(Sn),te.disabled=!1},we)},He=async()=>{if(te){te.disabled=!0;try{let re;mn()?re=W:n?(re=await n(),re.length===0&&(re=t.getAll())):re=t.getAll();let we=re.map(Tt=>{try{return JSON.parse(Tt.payload)}catch{return Tt.payload}});await navigator.clipboard.writeText(JSON.stringify(we,null,2)),Be("check",1500)}catch{Be("x",1500)}}},_e=()=>{le&&(x=le.value,Dn(),_())},ut=()=>{!Ce||!Ue||(Ue.style.display=Ce.value?"":"none",k&&clearTimeout(k),k=setTimeout(()=>{w=Ce.value,Dn(),_()},150))},st=()=>{!Ce||!Ue||(Ce.value="",w="",Ue.style.display="none",k&&clearTimeout(k),Dn(),_())},Rt=()=>{if(ke)return;let re=X.scrollTop,{action:we,nextLastScrollTop:Tt}=ci({following:$.isFollowing(),currentScrollTop:re,lastScrollTop:be,nearBottom:ze(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});be=Tt,we==="resume"?($.resume(),G=0,Ne.style.display="none"):we==="pause"&&($.pause(),d&&(he.textContent=m,Ne.style.display=""))},qt=re=>{let we=di({following:$.isFollowing(),deltaY:re.deltaY,nearBottom:ze(),resumeWhenNearBottom:!0});we==="pause"?($.pause(),d&&(he.textContent=m,Ne.style.display="")):we==="resume"&&($.resume(),G=0,Ne.style.display="none")},q=()=>{d&&(X.scrollTop=X.scrollHeight,$.resume(),G=0,Ne.style.display="none")},Ut=re=>{let we=re.target;if(!we||we.closest("button"))return;let Tt=we.closest("[data-event-id]");if(!Tt)return;let jt=Tt.getAttribute("data-event-id");jt&&eo(jt)},Je=re=>{if((re.metaKey||re.ctrlKey)&&re.key==="f"){re.preventDefault(),Ce==null||Ce.focus(),Ce==null||Ce.select();return}re.key==="Escape"&&(Ce&&document.activeElement===Ce?(st(),Ce.blur(),H.focus()):o&&o())};te&&te.addEventListener("click",He),le&&le.addEventListener("change",_e),Ce&&Ce.addEventListener("input",ut),Ue&&Ue.addEventListener("click",st),X.addEventListener("scroll",Rt),X.addEventListener("wheel",qt,{passive:!0}),X.addEventListener("click",Ut),Ne.addEventListener("click",q),H.addEventListener("keydown",Je);function _t(){k&&clearTimeout(k),se!==null&&(cancelAnimationFrame(se),se=null),ge=!1,xe.clear(),te&&te.removeEventListener("click",He),le&&le.removeEventListener("change",_e),Ce&&Ce.removeEventListener("input",ut),Ue&&Ue.removeEventListener("click",st),X.removeEventListener("scroll",Rt),X.removeEventListener("wheel",qt),X.removeEventListener("click",Ut),Ne.removeEventListener("click",q),H.removeEventListener("keydown",Je)}return{element:H,update:Me,destroy:_t}}}function Pm(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",o=typeof e.artifactId=="string"?e.artifactId:"",r=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),o&&i.setAttribute("data-open-artifact",o);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let m=document.createElement("div");m.className="persona-truncate persona-text-sm persona-font-medium",m.style.color="var(--persona-text, #1f2937)",m.textContent=n;let p=document.createElement("div");if(p.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",p.style.color="var(--persona-muted, #9ca3af)",r==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",p.appendChild(f);let u=document.createElement("span");u.textContent=`Generating ${a.toLowerCase()}...`,p.appendChild(u)}else p.textContent=a;if(l.append(m,p),i.append(d,l),r==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${n}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",o),i.append(f)}return i}var Wm=(e,t)=>{var o,r,s;let n=(s=(r=(o=t==null?void 0:t.config)==null?void 0:o.features)==null?void 0:r.artifacts)==null?void 0:s.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",m=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>Pm(e,t)});if(m)return m}return Pm(e,t)};var Fl=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},Pr=new Fl;Pr.register("PersonaArtifactCard",Wm);function rx(e){var r;let t=b("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=b("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify((r=e.props)!=null?r:{},null,2),t.appendChild(n),t.appendChild(o),t}function Bm(e,t){var le,te,Ce,Ue;let n=(te=(le=e.features)==null?void 0:le.artifacts)==null?void 0:te.layout,r=((Ce=n==null?void 0:n.toolbarPreset)!=null?Ce:"default")==="document",s=(Ue=n==null?void 0:n.panePadding)==null?void 0:Ue.trim(),a=e.markdown?za(e.markdown):null,i=qa(e.sanitize),d=ee=>{let oe=a?a(ee):Ds(ee);return i?i(oe):oe},l=typeof document!="undefined"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,m=()=>{l==null||l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"),N==null||N.hide()};l&&l.addEventListener("click",()=>{var ee;m(),(ee=t.onDismiss)==null||ee.call(t)});let p=b("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");p.setAttribute("data-persona-theme-zone","artifact-pane"),r&&p.classList.add("persona-artifact-pane-document");let f=b("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&f.classList.add("persona-artifact-toolbar-document");let u=b("span","persona-text-xs persona-font-medium persona-truncate");u.textContent="Artifacts";let C=b("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");C.type="button",C.textContent="Close",C.setAttribute("aria-label","Close artifacts panel"),C.addEventListener("click",()=>{var ee;m(),(ee=t.onDismiss)==null||ee.call(t)});let v="rendered",E=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),L=r?Cn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Cn({icon:"eye",label:"Rendered view"}),I=r?Cn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Cn({icon:"code-2",label:"Source"}),P=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),H=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,W=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,x=n==null?void 0:n.documentToolbarCopyMenuItems,w=!!(W&&x&&x.length>0),k=null,S,A=null,N=null;if(r&&(H||W)&&!w){if(S=H?Cl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Cn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W){let ee=Ee("chevron-down",14,"currentColor",2);ee&&S.appendChild(ee)}}else r&&w?(k=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),S=H?Cl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Cn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),A=Cn({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),k.append(S,A)):r?S=Cn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):S=Cn({icon:"copy",label:"Copy"});let $=r?Cn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Cn({icon:"refresh-cw",label:"Refresh"}),G=r?Cn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Cn({icon:"x",label:"Close"}),fe=()=>{var Ae,pe,$e;let ee=(Ae=xe.find(We=>We.id===j))!=null?Ae:xe[xe.length-1],oe=(pe=ee==null?void 0:ee.id)!=null?pe:null,ae=(ee==null?void 0:ee.artifactType)==="markdown"&&($e=ee.markdown)!=null?$e:"",rt=ee?JSON.stringify({component:ee.component,props:ee.props},null,2):"";return{markdown:ae,jsonPayload:rt,id:oe}},ge=async()=>{var Ae;let{markdown:ee,jsonPayload:oe}=fe(),ae=(Ae=xe.find(pe=>pe.id===j))!=null?Ae:xe[xe.length-1],rt=(ae==null?void 0:ae.artifactType)==="markdown"?ee:ae?oe:"";try{await navigator.clipboard.writeText(rt)}catch{}};if(S.addEventListener("click",async()=>{let ee=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(ee&&w){let{markdown:oe,jsonPayload:ae,id:rt}=fe();try{await ee({actionId:"primary",artifactId:rt,markdown:oe,jsonPayload:ae})}catch{}return}await ge()}),A&&(x!=null&&x.length)){let ee=()=>{var ae;return(ae=p.closest("[data-persona-root]"))!=null?ae:document.body},oe=()=>{N=Zr({items:x.map(ae=>({id:ae.id,label:ae.label})),onSelect:async ae=>{let{markdown:rt,jsonPayload:Ae,id:pe}=fe(),$e=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{$e?await $e({actionId:ae,artifactId:pe,markdown:rt,jsonPayload:Ae}):ae==="markdown"||ae==="md"?await navigator.clipboard.writeText(rt):ae==="json"||ae==="source"?await navigator.clipboard.writeText(Ae):await navigator.clipboard.writeText(rt||Ae)}catch{}},anchor:k!=null?k:A,position:"bottom-right",portal:ee()})};p.isConnected?oe():requestAnimationFrame(oe),A.addEventListener("click",ae=>{ae.stopPropagation(),N==null||N.toggle()})}$.addEventListener("click",async()=>{var ee;try{await((ee=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:ee.call(n))}catch{}K()}),G.addEventListener("click",()=>{var ee;m(),(ee=t.onDismiss)==null||ee.call(t)});let se=()=>{r&&(L.setAttribute("aria-pressed",v==="rendered"?"true":"false"),I.setAttribute("aria-pressed",v==="source"?"true":"false"))};L.addEventListener("click",()=>{v="rendered",se(),K()}),I.addEventListener("click",()=>{v="source",se(),K()});let ke=b("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");r?(f.replaceChildren(),E.append(L,I),k?P.append(k,$,G):P.append(S,$,G),f.append(E,ke,P),se()):(f.appendChild(u),f.appendChild(C)),s&&(f.style.paddingLeft=s,f.style.paddingRight=s);let be=b("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Fe=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(be.style.paddingLeft=s,be.style.paddingRight=s,Fe.style.padding=s),p.appendChild(f),p.appendChild(be),p.appendChild(Fe);let xe=[],j=null,de=!1,K=()=>{var rt,Ae,pe,$e;let ee=r&&xe.length<=1;be.classList.toggle("persona-hidden",ee),be.replaceChildren();for(let We of xe){let ue=b("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");ue.type="button",ue.textContent=We.title||We.id.slice(0,8),We.id===j&&ue.classList.add("persona-bg-persona-container","persona-border-persona-border"),ue.addEventListener("click",()=>t.onSelect(We.id)),be.appendChild(ue)}Fe.replaceChildren();let oe=j&&xe.find(We=>We.id===j)||xe[xe.length-1];if(!oe)return;if(r){let We=oe.artifactType==="markdown"?"MD":(rt=oe.component)!=null?rt:"Component",X=(oe.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ke.textContent=`${X} \xB7 ${We}`}else u.textContent="Artifacts";if(oe.artifactType==="markdown"){if(r&&v==="source"){let ue=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ue.textContent=(Ae=oe.markdown)!=null?Ae:"",Fe.appendChild(ue);return}let We=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");We.innerHTML=d((pe=oe.markdown)!=null?pe:""),Fe.appendChild(We);return}let ae=oe.component?Pr.get(oe.component):void 0;if(ae){let ue={message:{id:oe.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let X=ae(($e=oe.props)!=null?$e:{},ue);if(X){Fe.appendChild(X);return}}catch{}}Fe.appendChild(rx(oe))},ye=()=>{var oe;let ee=xe.length>0;if(p.classList.toggle("persona-hidden",!ee),l){let ae=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,Ae=((oe=ae==null?void 0:ae.classList.contains("persona-artifact-narrow-host"))!=null?oe:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;ee&&Ae&&de?(l.classList.remove("persona-hidden"),p.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"))}};return{element:p,backdrop:l,update(ee){var oe,ae,rt;xe=ee.artifacts,j=(rt=(ae=ee.selectedId)!=null?ae:(oe=ee.artifacts[ee.artifacts.length-1])==null?void 0:oe.id)!=null?rt:null,xe.length>0&&(de=!0),K(),ye()},setMobileOpen(ee){de=ee,!ee&&l?(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):ye()}}}function ho(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function Hm(e,t){var s,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!ho(t))return;let n=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,o=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),r=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function sx(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function Ri(e,t){var d,l,m,p,f,u,C,v,E,L;if(!ho(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),sx(e),Hm(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(m=n==null?void 0:n.splitGap)!=null?m:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=n==null?void 0:n.paneWidth)!=null?p:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=n==null?void 0:n.paneMaxWidth)!=null?f:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=(u=n==null?void 0:n.paneBackground)==null?void 0:u.trim();o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let r=(C=n==null?void 0:n.panePadding)==null?void 0:C.trim();r?e.style.setProperty("--persona-artifact-pane-padding",r):e.style.removeProperty("--persona-artifact-pane-padding");let s=(v=n==null?void 0:n.documentToolbarIconColor)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(E=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:E.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(L=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:L.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Hm(e,t)}var Dm=["panel","seamless"];function Pi(e,t){var i,d,l,m,p,f;for(let u of Dm)e.classList.remove(`persona-artifact-appearance-${u}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!ho(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,o=(l=n==null?void 0:n.paneAppearance)!=null?l:"panel",r=Dm.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${r}`);let s=(m=n==null?void 0:n.paneBorderRadius)==null?void 0:m.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(p=n==null?void 0:n.paneShadow)==null?void 0:p.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let u=((f=n.unifiedSplitOuterRadius)==null?void 0:f.trim())||s;u&&e.style.setProperty("--persona-artifact-unified-outer-radius",u)}}function Fm(e,t){var n,o,r;return!t||!ho(e)?!1:((r=(o=(n=e.features)==null?void 0:n.artifacts)==null?void 0:o.layout)==null?void 0:r.expandLauncherPanelWhenOpen)!==!1}function ax(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function ix(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function lx(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function cx(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Om(e,t){var a;let o=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function Nm(e,t,n,o,r,s){let a=ax(r,200),i=cx(t,n,o,200);i=Math.max(a,i);let d=ix(s);return d!==null&&(i=Math.min(i,d)),lx(e,a,i)}var _m={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Ol=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var C,v,E;if(s.dataset.enhanced==="true")return;let a=(C=s.dataset.tvForm)!=null?C:"init";s.dataset.enhanced="true";let i=(v=_m[a])!=null?v:_m.init;s.classList.add("persona-form-card","persona-space-y-4");let d=b("div","persona-space-y-1"),l=b("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let L=b("p","persona-text-sm persona-text-persona-muted");L.textContent=i.description,d.appendChild(L)}let m=document.createElement("form");m.className="persona-form-grid persona-space-y-3",i.fields.forEach(L=>{var x,w;let I=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");I.htmlFor=`${t.id}-${a}-${L.name}`;let P=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");P.textContent=L.label,I.appendChild(P);let H=(x=L.type)!=null?x:"text",W;H==="textarea"?(W=document.createElement("textarea"),W.rows=3):(W=document.createElement("input"),W.type=H),W.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",W.id=`${t.id}-${a}-${L.name}`,W.name=L.name,W.placeholder=(w=L.placeholder)!=null?w:"",L.required&&(W.required=!0),I.appendChild(W),m.appendChild(I)});let p=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),u=b("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");u.type="submit",u.textContent=(E=i.submitLabel)!=null?E:"Submit",p.appendChild(f),p.appendChild(u),m.appendChild(p),s.replaceChildren(d,m),m.addEventListener("submit",async L=>{var W,x;L.preventDefault();let I=(W=n.formEndpoint)!=null?W:"/form",P=new FormData(m),H={};P.forEach((w,k)=>{H[k]=w}),H.type=a,u.disabled=!0,f.textContent="Submitting\u2026";try{let w=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(H)});if(!w.ok)throw new Error(`Form submission failed (${w.status})`);let k=await w.json();f.textContent=(x=k.message)!=null?x:"Thanks! We'll be in touch soon.",k.success&&k.nextPrompt&&await o.sendMessage(String(k.nextPrompt))}catch(w){f.textContent=w instanceof Error?w.message:"Something went wrong. Please try again."}finally{u.disabled=!1}})})};var Nl=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var o;let n=this.plugins.get(t);n&&((o=n.onUnregister)==null||o.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var o,r;return((o=n.priority)!=null?o:0)-((r=t.priority)!=null?r:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},_l=new Nl;var Vm=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{var a;(a=e.get(r))==null||a.delete(s)};return{on:t,off:n,emit:(r,s)=>{var a;(a=e.get(r))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var dx=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},px=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},$l=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=dx(e),n=px(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},Vl=e=>typeof e=="string"?e:e==null?"":String(e),aa={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Vl(e.payload.text)},messageAndClick:(e,t)=>{var r;if(e.type!=="message_and_click")return;let n=e.payload,o=Vl(n.element);if(o&&((r=t.document)!=null&&r.querySelector)){let s=t.document.querySelector(o);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Vl(n.text)}}},$m=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ul=e=>{let t=new Set($m(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set($m(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,m)=>l||(m==null?void 0:m({text:a,message:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),o();let d={action:i,message:s.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let m=()=>{e.emit("action:resubmit",d)},p=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:m});if(!p)continue;if(p.handled){let f=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:f,resubmit:p.resubmit}}}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",m)}return{text:"",persist:!0}},syncFromMetadata:n}};var ux=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},mx=e=>e.map(t=>({...t,streaming:!1})),gx=e=>e.map(t=>({...t,status:"complete"})),Um=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?ux(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?mx(n.messages):void 0,artifacts:n.artifacts?gx(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};import{parse as cS,STR as dS,OBJ as pS}from"partial-json";function zm(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Pr.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:i=>{r&&r(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function qm(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function jm(e){let t=qm(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Km(e){let t=qm(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var fx=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Gm(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=fx}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-csat",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Customer satisfaction feedback");let p=null,f=document.createElement("div");f.className="persona-feedback-content";let u=document.createElement("div");u.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,u.appendChild(C);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=r,u.appendChild(v),f.appendChild(u);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let L=[];for(let x=1;x<=5;x++){let w=document.createElement("button");w.type="button",w.className="persona-feedback-rating-btn persona-feedback-star-btn",w.setAttribute("role","radio"),w.setAttribute("aria-checked","false"),w.setAttribute("aria-label",`${x} star${x>1?"s":""}: ${l[x-1]}`),w.title=l[x-1],w.dataset.rating=String(x),w.innerHTML=`
27
27
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
28
28
  <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
29
29
  </svg>
30
- `,x.addEventListener("click",()=>{m=v,I.forEach((k,S)=>{let E=S<v;k.classList.toggle("selected",E),k.setAttribute("aria-checked",S===v-1?"true":"false")})}),I.push(x),M.appendChild(x)}f.appendChild(M);let R=null;if(d){let v=document.createElement("div");v.className="persona-feedback-comment-container",R=document.createElement("textarea"),R.className="persona-feedback-comment",R.placeholder=s,R.rows=3,R.setAttribute("aria-label","Additional comments"),v.appendChild(R),f.appendChild(v)}let H=document.createElement("div");H.className="persona-feedback-actions";let D=document.createElement("button");D.type="button",D.className="persona-feedback-btn persona-feedback-btn-skip",D.textContent=i,D.addEventListener("click",()=>{n==null||n(),p.remove()});let B=document.createElement("button");return B.type="button",B.className="persona-feedback-btn persona-feedback-btn-submit",B.textContent=a,B.addEventListener("click",async()=>{if(m===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}B.disabled=!0,B.textContent="Submitting...";try{let v=(R==null?void 0:R.value.trim())||void 0;await t(m,v),p.remove()}catch(v){B.disabled=!1,B.textContent=a,console.error("[CSAT Feedback] Failed to submit:",v)}}),H.appendChild(D),H.appendChild(B),f.appendChild(H),p.appendChild(f),p}function Bm(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:p="Very likely"}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let f=null,u=document.createElement("div");u.className="persona-feedback-content";let w=document.createElement("div");w.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,w.appendChild(C);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=r,w.appendChild(M),u.appendChild(w);let I=document.createElement("div");I.className="persona-feedback-rating persona-feedback-rating-nps",I.setAttribute("role","radiogroup"),I.setAttribute("aria-label","Likelihood rating from 0 to 10");let R=document.createElement("div");R.className="persona-feedback-labels";let H=document.createElement("span");H.className="persona-feedback-label-low",H.textContent=l;let D=document.createElement("span");D.className="persona-feedback-label-high",D.textContent=p,R.appendChild(H),R.appendChild(D);let B=document.createElement("div");B.className="persona-feedback-numbers";let v=[];for(let F=0;F<=10;F++){let $=document.createElement("button");$.type="button",$.className="persona-feedback-rating-btn persona-feedback-number-btn",$.setAttribute("role","radio"),$.setAttribute("aria-checked","false"),$.setAttribute("aria-label",`Rating ${F} out of 10`),$.textContent=String(F),$.dataset.rating=String(F),F<=6?$.classList.add("persona-feedback-detractor"):F<=8?$.classList.add("persona-feedback-passive"):$.classList.add("persona-feedback-promoter"),$.addEventListener("click",()=>{f=F,v.forEach((j,me)=>{j.classList.toggle("selected",me===F),j.setAttribute("aria-checked",me===F?"true":"false")})}),v.push($),B.appendChild($)}I.appendChild(R),I.appendChild(B),u.appendChild(I);let x=null;if(d){let F=document.createElement("div");F.className="persona-feedback-comment-container",x=document.createElement("textarea"),x.className="persona-feedback-comment",x.placeholder=s,x.rows=3,x.setAttribute("aria-label","Additional comments"),F.appendChild(x),u.appendChild(F)}let k=document.createElement("div");k.className="persona-feedback-actions";let S=document.createElement("button");S.type="button",S.className="persona-feedback-btn persona-feedback-btn-skip",S.textContent=i,S.addEventListener("click",()=>{n==null||n(),m.remove()});let E=document.createElement("button");return E.type="button",E.className="persona-feedback-btn persona-feedback-btn-submit",E.textContent=a,E.addEventListener("click",async()=>{if(f===null){B.classList.add("persona-feedback-shake"),setTimeout(()=>B.classList.remove("persona-feedback-shake"),500);return}E.disabled=!0,E.textContent="Submitting...";try{let F=(x==null?void 0:x.value.trim())||void 0;await t(f,F),m.remove()}catch(F){E.disabled=!1,E.textContent=a,console.error("[NPS Feedback] Failed to submit:",F)}}),k.appendChild(S),k.appendChild(E),u.appendChild(k),m.appendChild(u),m}var es="persona-chat-history",ex=30*1e3,tx={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function nx(e){var o,r,s;if(!e)return[];let t=[],n=Array.from((o=e.items)!=null?o:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(r=tx[i.type])!=null?r:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((s=e.files)!=null?s:[]))a.type.startsWith("image/")&&t.push(a);return t}function Ei(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function ox(e){var t,n,o,r,s,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(r=(o=e.persist)==null?void 0:o.openState)!=null?r:!0,voiceState:(a=(s=e.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function rx(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Ol=e=>!e||typeof e!="object"?{}:{...e},Hm=e=>e.map(t=>({...t,streaming:!1})),Dm=(e,t,n)=>{let o=e!=null&&e.markdown?_a(e.markdown):null,r=Va(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&r&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var l,p,m;let a=(l=s.text)!=null?l:"",i=(p=s.message.rawContent)!=null?p:null;if(t){let f=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});f!==null&&(a=f.text,f.persist||(s.message.__skipPersist=!0),f.resubmit&&!s.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...s,text:a,raw:(m=i!=null?i:s.text)!=null?m:""}):o?d=o(a):d=Ls(a),r?r(d):d}};function Fm(e){var i,d,l,p;let t=b("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",o=(d=e==null?void 0:e.iconSize)!=null?d:"48px",r=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=Te(n,o,r,s);if(a&&t.appendChild(a),e!=null&&e.label){let m=b("span","persona-drop-overlay-label");m.textContent=e.label,t.appendChild(m)}return t}var Om=(e,t,n)=>{var sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,bc,yc,vc,xc,wc,Cc,Sc,Ac,Tc,kc,Ec,Mc,Lc,Ic,Rc,Pc,Wc,Bc,Hc,Dc,Fc,Oc,Nc,_c,Vc,$c,Uc,zc,qc,jc,Kc,Gc,Yc,Xc,Qc,Jc;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=Qp(t),r=Bl.getForInstance(o.plugins);o.components&&Mr.registerAll(o.components);let s=km(),i=o.persistState===!1?null:(sc=o.storageAdapter)!=null?sc:Mm(),d={},l=null,p=!1,m=c=>{if(o.onStateLoaded)try{let g=o.onStateLoaded(c);if(g&&typeof g=="object"&&"state"in g){let{state:h,open:y}=g;return y&&(p=!0),h}return g}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(g=>{let h=g!=null?g:{messages:[],metadata:{}};return m(h)});else{let g=c!=null?c:{messages:[],metadata:{}},h=m(g);h.metadata&&(d=Ol(h.metadata)),(ac=h.messages)!=null&&ac.length&&(o={...o,initialMessages:h.messages}),(ic=h.artifacts)!=null&&ic.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(lc=h.selectedArtifactId)!=null?lc:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(o.onStateLoaded)try{let c=m({messages:[],metadata:{}});(cc=c.messages)!=null&&cc.length&&(o={...o,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let f=()=>d,u=c=>{var h;d=(h=c({...d}))!=null?h:{},Wr()},w=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Dl],C=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Js.message,Js.messageAndClick],M=Fl({parsers:w,handlers:C,getSessionMetadata:f,updateSessionMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let I=(pc=(dc=o.launcher)==null?void 0:dc.enabled)!=null?pc:!0,R=(mc=(uc=o.launcher)==null?void 0:uc.autoExpand)!=null?mc:!1,H=(gc=o.autoFocusInput)!=null?gc:!1,D=R,B=I,v=(hc=(fc=o.layout)==null?void 0:fc.header)==null?void 0:hc.layout,x=!1,k=()=>zs(o),S=()=>I||k(),E=k()?!1:I?R:!0,F=!1,$=null,j=()=>{F=!0,$&&clearTimeout($),$=setTimeout(()=>{F&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),F=!1)},1e4)},me=Dm(o,M,j),se=(yc=(bc=o.features)==null?void 0:bc.showReasoning)!=null?yc:!0,ge=(xc=(vc=o.features)==null?void 0:vc.showToolCalls)!=null?xc:!0,ie=(Cc=(wc=o.features)==null?void 0:wc.showEventStreamToggle)!=null?Cc:!1,be=(Ac=(Sc=o.features)==null?void 0:Sc.scrollToBottom)!=null?Ac:{},ve=`${(kc=typeof o.persistState=="object"?(Tc=o.persistState)==null?void 0:Tc.keyPrefix:void 0)!=null?kc:"persona-"}event-stream`,J=ie?new Xs(ve):null,Le=(Lc=(Mc=(Ec=o.features)==null?void 0:Ec.eventStream)==null?void 0:Mc.maxEvents)!=null?Lc:2e3,Y=ie?new Ys(Le,J):null,xe=ie?new Qs:null,Se=null,de=!1,we=null,Ue=0;J==null||J.open().then(()=>Y==null?void 0:Y.restore()).catch(c=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let te={onCopy:c=>{var g,h;s.emit("message:copy",c),T!=null&&T.isClientTokenMode()&&T.submitMessageFeedback(c.id,"copy").catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",y)}),(h=(g=o.messageActions)==null?void 0:g.onCopy)==null||h.call(g,c)},onFeedback:c=>{var g,h;s.emit("message:feedback",c),T!=null&&T.isClientTokenMode()&&T.submitMessageFeedback(c.messageId,c.type).catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",y)}),(h=(g=o.messageActions)==null?void 0:g.onFeedback)==null||h.call(g,c)}},ne=(Ic=o.statusIndicator)!=null?Ic:{},re=c=>{var g,h,y,P;return c==="idle"?(g=ne.idleText)!=null?g:fn.idle:c==="connecting"?(h=ne.connectingText)!=null?h:fn.connecting:c==="connected"?(y=ne.connectedText)!=null?y:fn.connected:c==="error"?(P=ne.errorText)!=null?P:fn.error:fn[c]};function nt(c,g,h,y){if(y==="idle"&&h.idleLink){c.textContent="";let P=document.createElement("a");P.href=h.idleLink,P.target="_blank",P.rel="noopener noreferrer",P.textContent=g,P.style.color="inherit",P.style.textDecoration="none",c.appendChild(P)}else c.textContent=g}let{wrapper:ye,panel:le,pillRoot:$e}=Yu(o),Be=Xu(o,S()),{container:ce,body:K,messagesWrapper:_e,suggestions:Et,textarea:pe,sendButton:ae,sendButtonWrapper:Ln,composerForm:Nt,statusText:ln,introTitle:Dn,introSubtitle:Jn,closeButton:ze,iconHolder:_,headerTitle:ke,headerSubtitle:He,header:De,footer:Ve,actionsRow:dt,leftActions:ot,rightActions:At}=Be,Vt=Be.setSendButtonMode,q=Be.micButton,_t=Be.micButtonWrapper,Qe=Be.attachmentButton,Ft=Be.attachmentButtonWrapper,oe=Be.attachmentInput,fe=Be.attachmentPreviewsContainer;ce.classList.add("persona-relative"),K.classList.add("persona-relative");let xt=12,$t=()=>{var c;return(c=be.label)!=null?c:""},Jt=()=>{var c;return(c=be.iconName)!=null?c:"arrow-down"},yn=()=>be.enabled!==!1,Tt=b("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Tt.type="button",Tt.style.display="none",Tt.setAttribute("data-persona-scroll-to-bottom","true");let wt=b("span","persona-flex persona-items-center"),ft=b("span","");Tt.append(wt,ft),ce.appendChild(Tt);let bt=()=>{let g=Ve.style.display==="none"?0:Ve.offsetHeight;Tt.style.bottom=`${g+xt}px`};bt();let zt=()=>{let c=!!$t();Tt.setAttribute("aria-label",$t()||"Jump to latest"),Tt.title=$t(),Tt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),wt.innerHTML="";let g=Te(Jt(),"14px","currentColor",2);g?(wt.appendChild(g),wt.style.display=""):wt.style.display="none",ft.textContent=$t(),ft.style.display=c?"":"none"};zt();let et=null,Fn=null,Zn=r.find(c=>c.renderHeader);if(Zn!=null&&Zn.renderHeader){let c=Zn.renderHeader({config:o,defaultRenderer:()=>{let g=Ar({config:o,showClose:S()});return js(ce,g,o),g.header},onClose:()=>Bt(!1,"user")});if(c){let g=ce.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),De=c)}}let vn=()=>{var g,h,y,P;if(!Y)return;if(de=!0,!Se&&Y&&(Se=hm({buffer:Y,getFullHistory:()=>Y.getAllFromStore(),onClose:()=>On(),config:o,plugins:r,getThroughput:()=>{var N;return(N=xe==null?void 0:xe.getMetric())!=null?N:{status:"idle"}}})),Se&&(K.style.display="none",(g=Ve.parentNode)==null||g.insertBefore(Se.element,Ve),Se.update()),ut){ut.style.boxShadow=`inset 0 0 0 1.5px ${Mn.actionIconColor}`;let N=(P=(y=(h=o.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:P.toggleButtonActive;N&&N.split(/\s+/).forEach(V=>V&&ut.classList.add(V))}let c=()=>{if(!de)return;let N=Date.now();N-Ue>=200&&(Se==null||Se.update(),Ue=N),we=requestAnimationFrame(c)};Ue=0,we=requestAnimationFrame(c),Ho(),s.emit("eventStream:opened",{timestamp:Date.now()})},On=()=>{var c,g,h;if(de){if(de=!1,Se&&Se.element.remove(),K.style.display="",ut){ut.style.boxShadow="";let y=(h=(g=(c=o.features)==null?void 0:c.eventStream)==null?void 0:g.classNames)==null?void 0:h.toggleButtonActive;y&&y.split(/\s+/).forEach(P=>P&&ut.classList.remove(P))}we!==null&&(cancelAnimationFrame(we),we=null),Ho(),s.emit("eventStream:closed",{timestamp:Date.now()})}},ut=null;if(ie){let c=(Pc=(Rc=o.features)==null?void 0:Rc.eventStream)==null?void 0:Pc.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");ut=b("button",g),ut.style.width="28px",ut.style.height="28px",ut.style.color=Mn.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let h=Te("activity","18px","currentColor",1.5);h&&ut.appendChild(h);let y=Be.clearChatButtonWrapper,P=Be.closeButtonWrapper,N=y||P;N&&N.parentNode===De?De.insertBefore(ut,N):De.appendChild(ut),ut.addEventListener("click",()=>{de?On():vn()})}let wo=c=>{var y,P,N;let g=o.attachments;if(!(g!=null&&g.enabled))return;let h=c.querySelector(".persona-attachment-previews");if(!h){h=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.style.display="none";let V=c.querySelector("[data-persona-composer-form]");V!=null&&V.parentNode?V.parentNode.insertBefore(h,V):c.insertBefore(h,c.firstChild)}if(!c.querySelector('input[type="file"]')){let V=b("input");V.type="file",V.accept=((y=g.allowedTypes)!=null?y:_o).join(","),V.multiple=((P=g.maxFiles)!=null?P:4)>1,V.style.display="none",V.setAttribute("aria-label",(N=g.buttonTooltipText)!=null?N:"Attach files"),c.appendChild(V)}},Nn=r.find(c=>c.renderComposer);if(Nn!=null&&Nn.renderComposer){let c=o.composer,g=Nn.renderComposer({config:o,defaultRenderer:()=>xi({config:o}).footer,onSubmit:h=>{var V;if(!T||T.isStreaming())return;let y=h.trim(),P=(V=et==null?void 0:et.hasAttachments())!=null?V:!1;if(!y&&!P)return;gs();let N;P&&(N=[],N.push(...et.getContentParts()),y&&N.push(ll(y))),T.sendMessage(y,{contentParts:N}),P&&et.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{oe==null||oe.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:((Wc=o.voiceRecognition)==null?void 0:Wc.enabled)===!0?()=>{Fn==null||Fn()}:void 0});g&&(Ve.replaceWith(g),Ve=g)}let ir=c=>{let g=c.querySelector("[data-persona-composer-form]"),h=c.querySelector("[data-persona-composer-input]"),y=c.querySelector("[data-persona-composer-submit]"),P=c.querySelector("[data-persona-composer-mic]"),N=c.querySelector("[data-persona-composer-status]");g&&(Nt=g),h&&(pe=h),y&&(ae=y),P&&(q=P,_t=P.parentElement),N&&(ln=N);let V=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");V&&(Et=V);let z=c.querySelector(".persona-attachment-button");z&&(Qe=z,Ft=z.parentElement),oe=c.querySelector('input[type="file"]'),fe=c.querySelector(".persona-attachment-previews");let O=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");O&&(dt=O)};wo(Ve),ir(Ve);let In=(Oc=(Bc=o.layout)==null?void 0:Bc.contentMaxWidth)!=null?Oc:k()?(Fc=(Dc=(Hc=o.launcher)==null?void 0:Hc.composerBar)==null?void 0:Dc.contentMaxWidth)!=null?Fc:"720px":void 0;if(In&&(_e.style.maxWidth=In,_e.style.marginLeft="auto",_e.style.marginRight="auto",_e.style.width="100%"),In&&Nt&&!k()&&(Nt.style.maxWidth=In,Nt.style.marginLeft="auto",Nt.style.marginRight="auto"),In&&Et&&!k()&&(Et.style.maxWidth=In,Et.style.marginLeft="auto",Et.style.marginRight="auto"),In&&fe&&!k()&&(fe.style.maxWidth=In,fe.style.marginLeft="auto",fe.style.marginRight="auto"),(Nc=o.attachments)!=null&&Nc.enabled&&oe&&fe){et=Ds.fromConfig(o.attachments),et.setPreviewsContainer(fe),oe.addEventListener("change",h=>{let y=h.target;et==null||et.handleFileSelect(y.files),y.value=""});let c=o.attachments.dropOverlay,g=Fm(c);ce.appendChild(g)}(()=>{var y,P;let c=(P=(y=o.layout)==null?void 0:y.slots)!=null?P:{},g=N=>{switch(N){case"body-top":return ce.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return _e;case"footer-top":return Et;case"composer":return Nt;case"footer-bottom":return ln;default:return null}},h=(N,V)=>{var z;switch(N){case"header-left":case"header-center":case"header-right":if(N==="header-left")De.insertBefore(V,De.firstChild);else if(N==="header-right")De.appendChild(V);else{let O=De.querySelector(".persona-flex-col");O?(z=O.parentNode)==null||z.insertBefore(V,O.nextSibling):De.appendChild(V)}break;case"body-top":{let O=K.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");O?O.replaceWith(V):K.insertBefore(V,K.firstChild);break}case"body-bottom":K.appendChild(V);break;case"footer-top":Et.replaceWith(V);break;case"footer-bottom":ln.replaceWith(V);break;default:break}};for(let[N,V]of Object.entries(c))if(V)try{let z=V({config:o,defaultContent:()=>g(N)});z&&h(N,z)}catch(z){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${N}":`,z)}})();let $o=c=>{let h=c.target.closest('button[data-expand-header="true"]');if(!h)return;let y=h.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!y)return;let P=y.getAttribute("data-message-id");if(!P)return;let N=h.getAttribute("data-bubble-type");N==="reasoning"?(Kr.has(P)?Kr.delete(P):Kr.add(P),Zu(P,y)):N==="tool"&&(Gr.has(P)?Gr.delete(P):Gr.add(P),em(P,y,o)),mo.delete(P)};_e.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),$o(c))}),_e.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),$o(c))});let Lo=new Map;_e.addEventListener("click",c=>{var V;let h=c.target.closest(".persona-message-action-btn[data-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.closest("[data-actions-for]");if(!y)return;let P=y.getAttribute("data-actions-for");if(!P)return;let N=h.getAttribute("data-action");if(N==="copy"){let O=T.getMessages().find(Ae=>Ae.id===P);if(O&&te.onCopy){let Ae=O.content||"";navigator.clipboard.writeText(Ae).then(()=>{h.classList.add("persona-message-action-success");let ue=Te("check",14,"currentColor",2);ue&&(h.innerHTML="",h.appendChild(ue)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let ee=Te("copy",14,"currentColor",2);ee&&(h.innerHTML="",h.appendChild(ee))},2e3)}).catch(ue=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ue)}),te.onCopy(O)}}else if(N==="upvote"||N==="downvote"){let O=((V=Lo.get(P))!=null?V:null)===N,Ae=N==="upvote"?"thumbs-up":"thumbs-down";if(O){Lo.delete(P),h.classList.remove("persona-message-action-active");let ue=Te(Ae,14,"currentColor",2);ue&&(h.innerHTML="",h.appendChild(ue))}else{let ue=N==="upvote"?"downvote":"upvote",ee=y.querySelector(`[data-action="${ue}"]`);if(ee){ee.classList.remove("persona-message-action-active");let Ye=Te(ue==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ye&&(ee.innerHTML="",ee.appendChild(Ye))}Lo.set(P,N),h.classList.add("persona-message-action-active");let he=Te(Ae,14,"currentColor",2);he&&(he.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(he)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Oe=T.getMessages().find(tt=>tt.id===P);Oe&&te.onFeedback&&te.onFeedback({type:N,messageId:Oe.id,message:Oe})}}}),_e.addEventListener("click",c=>{let h=c.target.closest("button[data-approval-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.closest(".persona-approval-bubble");if(!y)return;let P=y.getAttribute("data-message-id");if(!P)return;let N=h.getAttribute("data-approval-action");if(!N)return;let V=N==="approve"?"approved":"denied",O=T.getMessages().find(ue=>ue.id===P);if(!(O!=null&&O.approval))return;let Ae=y.querySelector("[data-approval-buttons]");Ae&&Ae.querySelectorAll("button").forEach(ee=>{ee.disabled=!0,ee.style.opacity="0.5",ee.style.cursor="not-allowed"}),O.approval.toolType==="webmcp"?T.resolveWebMcpApproval(P,V):T.resolveApproval(O.approval,V)});let yt=null,_n=null,Vn={artifacts:[],selectedId:null},xn=!1,It={current:null};_e.addEventListener("click",c=>{var ee,he,Ee,Oe,tt;let h=c.target.closest("[data-download-artifact]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||((Ee=(he=(ee=o.features)==null?void 0:ee.artifacts)==null?void 0:he.onArtifactAction)==null?void 0:Ee.call(he,{type:"download",artifactId:y}))===!0)return;let N=T.getArtifactById(y),V=N==null?void 0:N.markdown,z=(N==null?void 0:N.title)||"artifact";if(!V){let Ye=h.closest("[data-open-artifact]"),at=Ye==null?void 0:Ye.closest("[data-message-id]"),it=at==null?void 0:at.getAttribute("data-message-id");if(it){let Re=T.getMessages().find(qe=>qe.id===it);if(Re!=null&&Re.rawContent)try{let qe=JSON.parse(Re.rawContent);V=(Oe=qe==null?void 0:qe.props)==null?void 0:Oe.markdown,z=((tt=qe==null?void 0:qe.props)==null?void 0:tt.title)||z}catch{}}}if(!V)return;let O=new Blob([V],{type:"text/markdown"}),Ae=URL.createObjectURL(O),ue=document.createElement("a");ue.href=Ae,ue.download=`${z}.md`,ue.click(),URL.revokeObjectURL(Ae)}),_e.addEventListener("click",c=>{var N,V,z;let h=c.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||((z=(V=(N=o.features)==null?void 0:N.artifacts)==null?void 0:V.onArtifactAction)==null?void 0:z.call(V,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),xn=!1,T.selectArtifact(y),zn())}),_e.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let eo=Be.composerOverlay,to=(c,g,h)=>{var z,O,Ae,ue;let y=g.trim();if(!y||!It.current)return;let P=(z=c.getAttribute("data-tool-call-id"))!=null?z:"",N=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:P,answer:y,answers:h.structured,values:(O=h.values)!=null?O:h.source==="multi"?y.split(", "):[y],isFreeText:N,source:h.source},bubbles:!0,composed:!0})),Jr(eo,P);let V=It.current.getMessages().find(ee=>{var he;return((he=ee.toolCall)==null?void 0:he.id)===P});(Ae=V==null?void 0:V.agentMetadata)!=null&&Ae.awaitingLocalTool?It.current.resolveAskUserQuestion(V,(ue=h.structured)!=null?ue:y):It.current.sendMessage(y)},$n=c=>{var P;let g=It.current;if(!g)return;let h=(P=c.getAttribute("data-tool-call-id"))!=null?P:"",y=g.getMessages().find(N=>{var V;return((V=N.toolCall)==null?void 0:V.id)===h});y&&g.persistAskUserQuestionProgress(y,{answers:wi(c,y),currentIndex:lo(c)})},Uo=c=>Object.entries(c).map(([g,h])=>`${g}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Io=c=>{var P,N,V;if(((N=(P=o.features)==null?void 0:P.askUserQuestion)==null?void 0:N.groupedAutoAdvance)===!1)return;let g=lo(c),h=Qr(c);if(g>=h-1)return;let y=(V=It.current)==null?void 0:V.getMessages().find(z=>{var O;return((O=z.toolCall)==null?void 0:O.id)===c.getAttribute("data-tool-call-id")});y&&(Si(c,y,o,g+1),$n(c))};eo.addEventListener("click",c=>{var N,V,z,O,Ae,ue,ee,he,Ee,Oe,tt,Ye,at,it;let h=c.target.closest("[data-ask-user-action]");if(!h)return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;let P=h.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),P==="dismiss"){let Pe=(N=y.getAttribute("data-tool-call-id"))!=null?N:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),Jr(eo,Pe);let Re=(V=It.current)==null?void 0:V.getMessages().find(qe=>{var L;return((L=qe.toolCall)==null?void 0:L.id)===Pe});(z=Re==null?void 0:Re.agentMetadata)!=null&&z.awaitingLocalTool&&((O=It.current)==null||O.markAskUserQuestionResolved(Re),(Ae=It.current)==null||Ae.resolveAskUserQuestion(Re,"(dismissed)"));return}if(P==="pick"){let Pe=h.getAttribute("data-option-label");if(!Pe)return;let Re=y.getAttribute("data-multi-select")==="true",qe=sr(y);if(qe&&Re){let L=kr(y)[lo(y)],Me=new Set(Array.isArray(L)?L:[]);Me.has(Pe)?Me.delete(Pe):Me.add(Pe),ar(y,Array.from(Me)),$n(y);return}if(qe){ar(y,Pe),$n(y),Io(y);return}if(Re){let L=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",L?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!L);let Me=y.querySelector('[data-ask-user-action="submit-multi"]');Me&&(Me.disabled=El(y).length===0);return}to(y,Pe,{source:"pick",values:[Pe]});return}if(P==="submit-multi"){let Pe=El(y);if(Pe.length===0)return;to(y,Pe.join(", "),{source:"multi",values:Pe});return}if(P==="open-free-text"){let Pe=y.querySelector('[data-ask-free-text-row="true"]');if(Pe){Pe.classList.remove("persona-hidden");let Re=Pe.querySelector('[data-ask-free-text-input="true"]');Re==null||Re.focus()}return}if(P==="focus-free-text"){let Pe=y.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus();return}if(P==="submit-free-text"){let Pe=y.querySelector('[data-ask-free-text-input="true"]'),Re=(ue=Pe==null?void 0:Pe.value)!=null?ue:"";if(!Re.trim())return;if(sr(y)){ar(y,Re.trim()),$n(y),Io(y);return}to(y,Re,{source:"free-text"});return}if(P==="next"||P==="back"){if(!It.current)return;let Pe=(ee=y.getAttribute("data-tool-call-id"))!=null?ee:"",Re=It.current.getMessages().find(Ke=>{var Ce;return((Ce=Ke.toolCall)==null?void 0:Ce.id)===Pe});if(!Re)return;let qe=y.querySelector('[data-ask-free-text-input="true"]'),L=(Ee=(he=qe==null?void 0:qe.value)==null?void 0:he.trim())!=null?Ee:"";if(L){let Ke=kr(y)[lo(y)];(typeof Ke!="string"||Ke!==L)&&ar(y,L)}let Me=P==="next"?1:-1,We=lo(y)+Me;Si(y,Re,o,We),$n(y);return}if(P==="submit-all"){if(!It.current)return;let Pe=(Oe=y.getAttribute("data-tool-call-id"))!=null?Oe:"",Re=It.current.getMessages().find(Ke=>{var Ce;return((Ce=Ke.toolCall)==null?void 0:Ce.id)===Pe});if(!Re)return;let qe=y.querySelector('[data-ask-free-text-input="true"]'),L=(Ye=(tt=qe==null?void 0:qe.value)==null?void 0:tt.trim())!=null?Ye:"";L&&ar(y,L);let Me=wi(y,Re);It.current.persistAskUserQuestionProgress(Re,{answers:Me,currentIndex:lo(y)});let We=Uo(Me);to(y,We||"(submitted)",{source:"submit-all",structured:Me});return}if(P==="skip"){if(!It.current)return;let Pe=(at=y.getAttribute("data-tool-call-id"))!=null?at:"",Re=It.current.getMessages().find(Ce=>{var Lt;return((Lt=Ce.toolCall)==null?void 0:Lt.id)===Pe});if(!Re)return;let qe=sr(y),L=lo(y),Me=Qr(y),We=L>=Me-1;if(!qe){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),Jr(eo,Pe),(it=Re.agentMetadata)!=null&&it.awaitingLocalTool&&(It.current.markAskUserQuestionResolved(Re),It.current.resolveAskUserQuestion(Re,"(dismissed)"));return}ar(y,"");let Ke=y.querySelector('[data-ask-free-text-input="true"]');if(Ke&&(Ke.value=""),We){let Ce=wi(y,Re),Lt=Uo(Ce);to(y,Lt||"(skipped)",{source:"submit-all",structured:Ce});return}Si(y,Re,o,L+1),$n(y);return}}),eo.addEventListener("keydown",c=>{var N;if(c.key!=="Enter")return;let h=c.target;if(!((N=h.matches)!=null&&N.call(h,'[data-ask-free-text-input="true"]')))return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;c.preventDefault();let P=h.value;if(P.trim()){if(sr(y)){ar(y,P.trim()),$n(y),Io(y);return}to(y,P,{source:"free-text"})}});let zo=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let g=c.target;if((g==null?void 0:g.tagName)==="INPUT"||(g==null?void 0:g.tagName)==="TEXTAREA"||g!=null&&g.isContentEditable)return;let h=eo.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let y=Number(c.key),N=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];N&&(c.preventDefault(),N.click())};document.addEventListener("keydown",zo);let Un=null,Wt=null,wn=null,no=null,qo=()=>{};function Ro(){no==null||no(),no=null}let jo=()=>{var V;if(!Un||!Wt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),h=((V=e.ownerDocument.defaultView)!=null?V:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||h){Wt.style.removeProperty("position"),Wt.style.removeProperty("left"),Wt.style.removeProperty("top"),Wt.style.removeProperty("bottom"),Wt.style.removeProperty("width"),Wt.style.removeProperty("z-index");return}let y=Un.firstElementChild;if(!y||y===Wt)return;let P=10;Wt.style.position="absolute",Wt.style.top="0",Wt.style.bottom="0",Wt.style.width=`${P}px`,Wt.style.zIndex="5";let N=y.offsetWidth-P/2;Wt.style.left=`${Math.max(0,N)}px`},Co=()=>{},zn=()=>{var h,y,P,N,V;if(!yt||!co(o))return;Ti(e,o),ki(e,o),Co();let c=(N=(P=(y=(h=o.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:P.narrowHostMaxWidth)!=null?N:520,g=le.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),yt.update(Vn),xn?(yt.setMobileOpen(!1),yt.element.classList.add("persona-hidden"),(V=yt.backdrop)==null||V.classList.add("persona-hidden")):Vn.artifacts.length>0&&(yt.element.classList.remove("persona-hidden"),yt.setMobileOpen(!0)),qo()};if(co(o)){le.style.position="relative";let c=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(ce),yt=vm(o,{onSelect:h=>{var y;return(y=It.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{xn=!0,zn()}}),yt.element.classList.add("persona-hidden"),Un=g,g.appendChild(c),g.appendChild(yt.element),yt.backdrop&&le.appendChild(yt.backdrop),le.appendChild(g),qo=()=>{var y,P,N,V;if(!Un||!yt)return;if(!(((N=(P=(y=o.features)==null?void 0:y.artifacts)==null?void 0:P.layout)==null?void 0:N.resizable)===!0)){wn==null||wn(),wn=null,Ro(),Wt&&(Wt.remove(),Wt=null),yt.element.style.removeProperty("width"),yt.element.style.removeProperty("maxWidth");return}if(!Wt){let z=b("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");z.setAttribute("role","separator"),z.setAttribute("aria-orientation","vertical"),z.setAttribute("aria-label","Resize artifacts panel"),z.tabIndex=0;let O=e.ownerDocument,Ae=(V=O.defaultView)!=null?V:window,ue=ee=>{var at,it;if(!yt||ee.button!==0||e.classList.contains("persona-artifact-narrow-host")||Ae.innerWidth<=640)return;ee.preventDefault(),Ro();let he=ee.clientX,Ee=yt.element.getBoundingClientRect().width,Oe=(it=(at=o.features)==null?void 0:at.artifacts)==null?void 0:it.layout,tt=Pe=>{let Re=Un.getBoundingClientRect().width,qe=e.classList.contains("persona-artifact-appearance-seamless"),L=qe?0:Sm(Un,Ae),Me=qe?0:z.getBoundingClientRect().width||6,We=Ee-(Pe.clientX-he),Ke=Am(We,Re,L,Me,Oe==null?void 0:Oe.resizableMinWidth,Oe==null?void 0:Oe.resizableMaxWidth);yt.element.style.width=`${Ke}px`,yt.element.style.maxWidth="none",jo()},Ye=()=>{O.removeEventListener("pointermove",tt),O.removeEventListener("pointerup",Ye),O.removeEventListener("pointercancel",Ye),no=null;try{z.releasePointerCapture(ee.pointerId)}catch{}};no=Ye,O.addEventListener("pointermove",tt),O.addEventListener("pointerup",Ye),O.addEventListener("pointercancel",Ye);try{z.setPointerCapture(ee.pointerId)}catch{}};z.addEventListener("pointerdown",ue),Wt=z,Un.insertBefore(z,yt.element),wn=()=>{z.removeEventListener("pointerdown",ue)}}if(Wt){let z=Vn.artifacts.length>0&&!xn;Wt.classList.toggle("persona-hidden",!z),jo()}},Co=()=>{var Ae,ue,ee,he,Ee,Oe,tt,Ye,at,it,Pe,Re,qe,L;if(!I||!yt||((ue=(Ae=o.launcher)==null?void 0:Ae.sidebarMode)!=null?ue:!1)||pn(o)&&Mo(o).reveal==="emerge")return;let y=(ee=e.ownerDocument.defaultView)!=null?ee:window,P=(Ee=(he=o.launcher)==null?void 0:he.mobileFullscreen)!=null?Ee:!0,N=(tt=(Oe=o.launcher)==null?void 0:Oe.mobileBreakpoint)!=null?tt:640;if(P&&y.innerWidth<=N||!Cm(o,I))return;let V=(it=(at=(Ye=o.launcher)==null?void 0:Ye.width)!=null?at:o.launcherWidth)!=null?it:io,z=(L=(qe=(Re=(Pe=o.features)==null?void 0:Pe.artifacts)==null?void 0:Re.layout)==null?void 0:qe.expandedPanelWidth)!=null?L:"min(720px, calc(100vw - 24px))";Vn.artifacts.length>0&&!xn?(le.style.width=z,le.style.maxWidth=z):(le.style.width=V,le.style.maxWidth=V)},typeof ResizeObserver!="undefined"&&(_n=new ResizeObserver(()=>{zn()}),_n.observe(le))}else le.appendChild(ce),k()&&$e&&(Be.peekBanner&&$e.appendChild(Be.peekBanner),$e.appendChild(Ve));e.appendChild(ye),$e&&e.appendChild($e);let po=()=>{var Ke,Ce,Lt,st,Xt,cn,Pt,An,dn,Je,lt,Tn,mn,mr,gr,fr,Nr,_r,qt,hr,nr,ht,Pn,Oo,kn,Wn,Ht,Ut;if(k()){le.style.width="100%",le.style.maxWidth="100%";let Dt=(Ce=(Ke=o.launcher)==null?void 0:Ke.composerBar)!=null?Ce:{},jt=ye.dataset.state==="expanded",Bn=(Lt=Dt.expandedSize)!=null?Lt:"anchored";if(!(jt&&Bn!=="fullscreen")){ce.style.background="",ce.style.border="",ce.style.borderRadius="",ce.style.overflow="",ce.style.boxShadow="";return}let en=(Xt=(st=o.theme)==null?void 0:st.components)==null?void 0:Xt.panel,To=ka(o),No=(br,Aa)=>{var Cs;return br==null||br===""?Aa:(Cs=Vr(To,br))!=null?Cs:br},wa="1px solid var(--persona-border)",Ca="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Sa="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ce.style.background="var(--persona-surface, #ffffff)",ce.style.border=No(en==null?void 0:en.border,wa),ce.style.borderRadius=No(en==null?void 0:en.borderRadius,Sa),ce.style.boxShadow=No(en==null?void 0:en.shadow,Ca),ce.style.overflow="hidden";return}let c=pn(o),g=(Pt=(cn=o.launcher)==null?void 0:cn.sidebarMode)!=null?Pt:!1,h=c||g||((dn=(An=o.launcher)==null?void 0:An.fullHeight)!=null?dn:!1),y=((Je=o.launcher)==null?void 0:Je.enabled)===!1,P=(Tn=(lt=o.theme)==null?void 0:lt.components)==null?void 0:Tn.panel,N=ka(o),V=(Dt,jt)=>{var Bn;return Dt==null||Dt===""?jt:(Bn=Vr(N,Dt))!=null?Bn:Dt},z=(mn=e.ownerDocument.defaultView)!=null?mn:window,O=(gr=(mr=o.launcher)==null?void 0:mr.mobileFullscreen)!=null?gr:!0,Ae=(Nr=(fr=o.launcher)==null?void 0:fr.mobileBreakpoint)!=null?Nr:640,ue=z.innerWidth<=Ae,ee=O&&ue&&I,he=(qt=(_r=o.launcher)==null?void 0:_r.position)!=null?qt:"bottom-left",Ee=he==="bottom-left"||he==="top-left",Oe=(nr=(hr=o.launcher)==null?void 0:hr.zIndex)!=null?nr:hn,tt=g||ee?"none":"1px solid var(--persona-border)",Ye=ee?"none":g?Ee?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!ee&&(Ye="none",tt="none");let at=g||ee?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",it=V(P==null?void 0:P.border,tt),Pe=V(P==null?void 0:P.shadow,Ye),Re=V(P==null?void 0:P.borderRadius,at),qe=K.scrollTop;e.style.cssText="",ye.style.cssText="",le.style.cssText="",ce.style.cssText="",K.style.cssText="",Ve.style.cssText="";let L=()=>{var jt;if(qe<=0)return;((jt=K.ownerDocument.defaultView)!=null?jt:window).requestAnimationFrame(()=>{if(K.scrollTop===qe)return;let Bn=K.scrollHeight-K.clientHeight;Bn<=0||(K.scrollTop=Math.min(qe,Bn))})};if(ee){ye.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),ye.style.cssText=`
30
+ `,w.addEventListener("click",()=>{p=x,L.forEach((k,S)=>{let A=S<x;k.classList.toggle("selected",A),k.setAttribute("aria-checked",S===x-1?"true":"false")})}),L.push(w),E.appendChild(w)}f.appendChild(E);let I=null;if(d){let x=document.createElement("div");x.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=s,I.rows=3,I.setAttribute("aria-label","Additional comments"),x.appendChild(I),f.appendChild(x)}let P=document.createElement("div");P.className="persona-feedback-actions";let H=document.createElement("button");H.type="button",H.className="persona-feedback-btn persona-feedback-btn-skip",H.textContent=i,H.addEventListener("click",()=>{n==null||n(),m.remove()});let W=document.createElement("button");return W.type="button",W.className="persona-feedback-btn persona-feedback-btn-submit",W.textContent=a,W.addEventListener("click",async()=>{if(p===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}W.disabled=!0,W.textContent="Submitting...";try{let x=(I==null?void 0:I.value.trim())||void 0;await t(p,x),m.remove()}catch(x){W.disabled=!1,W.textContent=a,console.error("[CSAT Feedback] Failed to submit:",x)}}),P.appendChild(H),P.appendChild(W),f.appendChild(P),m.appendChild(f),m}function Ym(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:m="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let f=null,u=document.createElement("div");u.className="persona-feedback-content";let C=document.createElement("div");C.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=o,C.appendChild(v);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=r,C.appendChild(E),u.appendChild(C);let L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-nps",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Likelihood rating from 0 to 10");let I=document.createElement("div");I.className="persona-feedback-labels";let P=document.createElement("span");P.className="persona-feedback-label-low",P.textContent=l;let H=document.createElement("span");H.className="persona-feedback-label-high",H.textContent=m,I.appendChild(P),I.appendChild(H);let W=document.createElement("div");W.className="persona-feedback-numbers";let x=[];for(let N=0;N<=10;N++){let $=document.createElement("button");$.type="button",$.className="persona-feedback-rating-btn persona-feedback-number-btn",$.setAttribute("role","radio"),$.setAttribute("aria-checked","false"),$.setAttribute("aria-label",`Rating ${N} out of 10`),$.textContent=String(N),$.dataset.rating=String(N),N<=6?$.classList.add("persona-feedback-detractor"):N<=8?$.classList.add("persona-feedback-passive"):$.classList.add("persona-feedback-promoter"),$.addEventListener("click",()=>{f=N,x.forEach((G,fe)=>{G.classList.toggle("selected",fe===N),G.setAttribute("aria-checked",fe===N?"true":"false")})}),x.push($),W.appendChild($)}L.appendChild(I),L.appendChild(W),u.appendChild(L);let w=null;if(d){let N=document.createElement("div");N.className="persona-feedback-comment-container",w=document.createElement("textarea"),w.className="persona-feedback-comment",w.placeholder=s,w.rows=3,w.setAttribute("aria-label","Additional comments"),N.appendChild(w),u.appendChild(N)}let k=document.createElement("div");k.className="persona-feedback-actions";let S=document.createElement("button");S.type="button",S.className="persona-feedback-btn persona-feedback-btn-skip",S.textContent=i,S.addEventListener("click",()=>{n==null||n(),p.remove()});let A=document.createElement("button");return A.type="button",A.className="persona-feedback-btn persona-feedback-btn-submit",A.textContent=a,A.addEventListener("click",async()=>{if(f===null){W.classList.add("persona-feedback-shake"),setTimeout(()=>W.classList.remove("persona-feedback-shake"),500);return}A.disabled=!0,A.textContent="Submitting...";try{let N=(w==null?void 0:w.value.trim())||void 0;await t(f,N),p.remove()}catch(N){A.disabled=!1,A.textContent=a,console.error("[NPS Feedback] Failed to submit:",N)}}),k.appendChild(S),k.appendChild(A),u.appendChild(k),p.appendChild(u),p}var is="persona-chat-history",hx=30*1e3,bx={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function yx(e){var o,r,s;if(!e)return[];let t=[],n=Array.from((o=e.items)!=null?o:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(r=bx[i.type])!=null?r:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((s=e.files)!=null?s:[]))a.type.startsWith("image/")&&t.push(a);return t}function Wi(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function vx(e){var t,n,o,r,s,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(r=(o=e.persist)==null?void 0:o.openState)!=null?r:!0,voiceState:(a=(s=e.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function xx(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var zl=e=>!e||typeof e!="object"?{}:{...e},Xm=e=>e.map(t=>({...t,streaming:!1})),Qm=(e,t,n)=>{let o=e!=null&&e.markdown?za(e.markdown):null,r=qa(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&r&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var l,m,p;let a=(l=s.text)!=null?l:"",i=(m=s.message.rawContent)!=null?m:null;if(t){let f=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});f!==null&&(a=f.text,f.persist||(s.message.__skipPersist=!0),f.resubmit&&!s.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...s,text:a,raw:(p=i!=null?i:s.text)!=null?p:""}):o?d=o(a):d=Ds(a),r?r(d):d}};function Jm(e){var i,d,l,m;let t=b("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",o=(d=e==null?void 0:e.iconSize)!=null?d:"48px",r=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(m=e==null?void 0:e.iconStrokeWidth)!=null?m:.5,a=Ee(n,o,r,s);if(a&&t.appendChild(a),e!=null&&e.label){let p=b("span","persona-drop-overlay-label");p.textContent=e.label,t.appendChild(p)}return t}var Zm=(e,t,n)=>{var uc,mc,gc,fc,hc,bc,yc,vc,xc,wc,Cc,Sc,Ac,Tc,kc,Ec,Mc,Lc,Ic,Rc,Pc,Wc,Bc,Hc,Dc,Fc,Oc,Nc,_c,Vc,$c,Uc,zc,qc,jc,Kc,Gc,Yc,Xc,Qc,Jc,Zc,ed,td,nd,od,rd,sd;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=ru(t),r=_l.getForInstance(o.plugins);o.components&&Pr.registerAll(o.components);let s=Vm(),i=o.persistState===!1?null:(uc=o.storageAdapter)!=null?uc:Um(),d={},l=null,m=!1,p=c=>{if(o.onStateLoaded)try{let g=o.onStateLoaded(c);if(g&&typeof g=="object"&&"state"in g){let{state:h,open:y}=g;return y&&(m=!0),h}return g}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(g=>{let h=g!=null?g:{messages:[],metadata:{}};return p(h)});else{let g=c!=null?c:{messages:[],metadata:{}},h=p(g);h.metadata&&(d=zl(h.metadata)),(mc=h.messages)!=null&&mc.length&&(o={...o,initialMessages:h.messages}),(gc=h.artifacts)!=null&&gc.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(fc=h.selectedArtifactId)!=null?fc:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(o.onStateLoaded)try{let c=p({messages:[],metadata:{}});(hc=c.messages)!=null&&hc.length&&(o={...o,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let f=()=>d,u=c=>{var h;d=(h=c({...d}))!=null?h:{},Fr()},C=o.actionParsers&&o.actionParsers.length?o.actionParsers:[$l],v=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[aa.message,aa.messageAndClick],E=Ul({parsers:C,handlers:v,getSessionMetadata:f,updateSessionMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null});E.syncFromMetadata();let L=(yc=(bc=o.launcher)==null?void 0:bc.enabled)!=null?yc:!0,I=(xc=(vc=o.launcher)==null?void 0:vc.autoExpand)!=null?xc:!1,P=(wc=o.autoFocusInput)!=null?wc:!1,H=I,W=L,x=(Sc=(Cc=o.layout)==null?void 0:Cc.header)==null?void 0:Sc.layout,w=!1,k=()=>Js(o),S=()=>L||k(),A=k()?!1:L?I:!0,N=!1,$=null,G=()=>{N=!0,$&&clearTimeout($),$=setTimeout(()=>{N&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),N=!1)},1e4)},fe=Qm(o,E,G),ge=(Tc=(Ac=o.features)==null?void 0:Ac.showReasoning)!=null?Tc:!0,se=(Ec=(kc=o.features)==null?void 0:kc.showToolCalls)!=null?Ec:!0,ke=(Lc=(Mc=o.features)==null?void 0:Mc.showEventStreamToggle)!=null?Lc:!1,be=(Rc=(Ic=o.features)==null?void 0:Ic.scrollToBottom)!=null?Rc:{},xe=`${(Wc=typeof o.persistState=="object"?(Pc=o.persistState)==null?void 0:Pc.keyPrefix:void 0)!=null?Wc:"persona-"}event-stream`,j=ke?new ra(xe):null,de=(Dc=(Hc=(Bc=o.features)==null?void 0:Bc.eventStream)==null?void 0:Hc.maxEvents)!=null?Dc:2e3,K=ke?new oa(de,j):null,ye=ke?new sa:null,le=null,te=!1,Ce=null,Ue=0;j==null||j.open().then(()=>K==null?void 0:K.restore()).catch(c=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let ee={onCopy:c=>{var g,h;s.emit("message:copy",c),V!=null&&V.isClientTokenMode()&&V.submitMessageFeedback(c.id,"copy").catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",y)}),(h=(g=o.messageActions)==null?void 0:g.onCopy)==null||h.call(g,c)},onFeedback:c=>{var g,h;s.emit("message:feedback",c),V!=null&&V.isClientTokenMode()&&V.submitMessageFeedback(c.messageId,c.type).catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",y)}),(h=(g=o.messageActions)==null?void 0:g.onFeedback)==null||h.call(g,c)}},oe=(Fc=o.statusIndicator)!=null?Fc:{},ae=c=>{var g,h,y,M;return c==="idle"?(g=oe.idleText)!=null?g:xn.idle:c==="connecting"?(h=oe.connectingText)!=null?h:xn.connecting:c==="connected"?(y=oe.connectedText)!=null?y:xn.connected:c==="error"?(M=oe.errorText)!=null?M:xn.error:xn[c]};function rt(c,g,h,y){if(y==="idle"&&h.idleLink){c.textContent="";let M=document.createElement("a");M.href=h.idleLink,M.target="_blank",M.rel="noopener noreferrer",M.textContent=g,M.style.color="inherit",M.style.textDecoration="none",c.appendChild(M)}else c.textContent=g}let{wrapper:Ae,panel:pe,pillRoot:$e}=am(o),We=im(o,S()),{container:ue,body:X,messagesWrapper:Ne,suggestions:Bt,textarea:he,sendButton:ce,sendButtonWrapper:Rn,composerForm:$t,statusText:mn,introTitle:Dn,introSubtitle:eo,closeButton:ze,iconHolder:_,headerTitle:Me,headerSubtitle:Be,header:He,footer:_e,actionsRow:ut,leftActions:st,rightActions:Rt}=We,qt=We.setSendButtonMode,q=We.micButton,Ut=We.micButtonWrapper,Je=We.attachmentButton,_t=We.attachmentButtonWrapper,re=We.attachmentInput,we=We.attachmentPreviewsContainer;ue.classList.add("persona-relative"),X.classList.add("persona-relative");let Tt=12,jt=()=>{var c;return(c=be.label)!=null?c:""},en=()=>{var c;return(c=be.iconName)!=null?c:"arrow-down"},Sn=()=>be.enabled!==!1,Pt=b("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Pt.type="button",Pt.style.display="none",Pt.setAttribute("data-persona-scroll-to-bottom","true");let Et=b("span","persona-flex persona-items-center"),xt=b("span","");Pt.append(Et,xt),ue.appendChild(Pt);let Ct=()=>{let g=_e.style.display==="none"?0:_e.offsetHeight;Pt.style.bottom=`${g+Tt}px`};Ct();let Kt=()=>{let c=!!jt();Pt.setAttribute("aria-label",jt()||"Jump to latest"),Pt.title=jt(),Pt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Et.innerHTML="";let g=Ee(en(),"14px","currentColor",2);g?(Et.appendChild(g),Et.style.display=""):Et.style.display="none",xt.textContent=jt(),xt.style.display=c?"":"none"};Kt();let nt=null,Fn=null,to=r.find(c=>c.renderHeader);if(to!=null&&to.renderHeader){let c=to.renderHeader({config:o,defaultRenderer:()=>{let g=Mr({config:o,showClose:S()});return ea(ue,g,o),g.header},onClose:()=>Ft(!1,"user")});if(c){let g=ue.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),He=c)}}let An=()=>{var g,h,y,M;if(!K)return;if(te=!0,!le&&K&&(le=Rm({buffer:K,getFullHistory:()=>K.getAllFromStore(),onClose:()=>On(),config:o,plugins:r,getThroughput:()=>{var F;return(F=ye==null?void 0:ye.getMetric())!=null?F:{status:"idle"}}})),le&&(X.style.display="none",(g=_e.parentNode)==null||g.insertBefore(le.element,_e),le.update()),ht){ht.style.boxShadow=`inset 0 0 0 1.5px ${In.actionIconColor}`;let F=(M=(y=(h=o.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:M.toggleButtonActive;F&&F.split(/\s+/).forEach(O=>O&&ht.classList.add(O))}let c=()=>{if(!te)return;let F=Date.now();F-Ue>=200&&(le==null||le.update(),Ue=F),Ce=requestAnimationFrame(c)};Ue=0,Ce=requestAnimationFrame(c),No(),s.emit("eventStream:opened",{timestamp:Date.now()})},On=()=>{var c,g,h;if(te){if(te=!1,le&&le.element.remove(),X.style.display="",ht){ht.style.boxShadow="";let y=(h=(g=(c=o.features)==null?void 0:c.eventStream)==null?void 0:g.classNames)==null?void 0:h.toggleButtonActive;y&&y.split(/\s+/).forEach(M=>M&&ht.classList.remove(M))}Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),No(),s.emit("eventStream:closed",{timestamp:Date.now()})}},ht=null;if(ke){let c=(Nc=(Oc=o.features)==null?void 0:Oc.eventStream)==null?void 0:Nc.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");ht=b("button",g),ht.style.width="28px",ht.style.height="28px",ht.style.color=In.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let h=Ee("activity","18px","currentColor",1.5);h&&ht.appendChild(h);let y=We.clearChatButtonWrapper,M=We.closeButtonWrapper,F=y||M;F&&F.parentNode===He?He.insertBefore(ht,F):He.appendChild(ht),ht.addEventListener("click",()=>{te?On():An()})}let Eo=c=>{var y,M,F;let g=o.attachments;if(!(g!=null&&g.enabled))return;let h=c.querySelector(".persona-attachment-previews");if(!h){h=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.style.display="none";let O=c.querySelector("[data-persona-composer-form]");O!=null&&O.parentNode?O.parentNode.insertBefore(h,O):c.insertBefore(h,c.firstChild)}if(!c.querySelector('input[type="file"]')){let O=b("input");O.type="file",O.accept=((y=g.allowedTypes)!=null?y:Uo).join(","),O.multiple=((M=g.maxFiles)!=null?M:4)>1,O.style.display="none",O.setAttribute("aria-label",(F=g.buttonTooltipText)!=null?F:"Attach files"),c.appendChild(O)}},Nn=r.find(c=>c.renderComposer);if(Nn!=null&&Nn.renderComposer){let c=o.composer,g=Nn.renderComposer({config:o,defaultRenderer:()=>Ai({config:o}).footer,onSubmit:h=>{var O;if(!V||V.isStreaming())return;let y=h.trim(),M=(O=nt==null?void 0:nt.hasAttachments())!=null?O:!1;if(!y&&!M)return;ws();let F;M&&(F=[],F.push(...nt.getContentParts()),y&&F.push(fl(y))),V.sendMessage(y,{contentParts:F}),M&&nt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{re==null||re.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:((_c=o.voiceRecognition)==null?void 0:_c.enabled)===!0?()=>{Fn==null||Fn()}:void 0});g&&(_e.replaceWith(g),_e=g)}let dr=c=>{let g=c.querySelector("[data-persona-composer-form]"),h=c.querySelector("[data-persona-composer-input]"),y=c.querySelector("[data-persona-composer-submit]"),M=c.querySelector("[data-persona-composer-mic]"),F=c.querySelector("[data-persona-composer-status]");g&&($t=g),h&&(he=h),y&&(ce=y),M&&(q=M,Ut=M.parentElement),F&&(mn=F);let O=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(Bt=O);let z=c.querySelector(".persona-attachment-button");z&&(Je=z,_t=z.parentElement),re=c.querySelector('input[type="file"]'),we=c.querySelector(".persona-attachment-previews");let D=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");D&&(ut=D)};Eo(_e),dr(_e);let Pn=(qc=(Vc=o.layout)==null?void 0:Vc.contentMaxWidth)!=null?qc:k()?(zc=(Uc=($c=o.launcher)==null?void 0:$c.composerBar)==null?void 0:Uc.contentMaxWidth)!=null?zc:"720px":void 0;if(Pn&&(Ne.style.maxWidth=Pn,Ne.style.marginLeft="auto",Ne.style.marginRight="auto",Ne.style.width="100%"),Pn&&$t&&!k()&&($t.style.maxWidth=Pn,$t.style.marginLeft="auto",$t.style.marginRight="auto"),Pn&&Bt&&!k()&&(Bt.style.maxWidth=Pn,Bt.style.marginLeft="auto",Bt.style.marginRight="auto"),Pn&&we&&!k()&&(we.style.maxWidth=Pn,we.style.marginLeft="auto",we.style.marginRight="auto"),(jc=o.attachments)!=null&&jc.enabled&&re&&we){nt=zs.fromConfig(o.attachments),nt.setPreviewsContainer(we),re.addEventListener("change",h=>{let y=h.target;nt==null||nt.handleFileSelect(y.files),y.value=""});let c=o.attachments.dropOverlay,g=Jm(c);ue.appendChild(g)}(()=>{var y,M;let c=(M=(y=o.layout)==null?void 0:y.slots)!=null?M:{},g=F=>{switch(F){case"body-top":return ue.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ne;case"footer-top":return Bt;case"composer":return $t;case"footer-bottom":return mn;default:return null}},h=(F,O)=>{var z;switch(F){case"header-left":case"header-center":case"header-right":if(F==="header-left")He.insertBefore(O,He.firstChild);else if(F==="header-right")He.appendChild(O);else{let D=He.querySelector(".persona-flex-col");D?(z=D.parentNode)==null||z.insertBefore(O,D.nextSibling):He.appendChild(O)}break;case"body-top":{let D=X.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");D?D.replaceWith(O):X.insertBefore(O,X.firstChild);break}case"body-bottom":X.appendChild(O);break;case"footer-top":Bt.replaceWith(O);break;case"footer-bottom":mn.replaceWith(O);break;default:break}};for(let[F,O]of Object.entries(c))if(O)try{let z=O({config:o,defaultContent:()=>g(F)});z&&h(F,z)}catch(z){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${F}":`,z)}})();let qo=c=>{var O,z;let h=c.target.closest('button[data-expand-header="true"]');if(!h)return;let y=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!y)return;let M=y.getAttribute("data-message-id");if(!M)return;let F=h.getAttribute("data-bubble-type");if(F==="reasoning")es.has(M)?es.delete(M):es.add(M),dm(M,y);else if(F==="tool")ts.has(M)?ts.delete(M):ts.add(M),pm(M,y,o);else if(F==="approval"){let D=o.approval!==!1?o.approval:void 0,Te=((O=D==null?void 0:D.detailsDisplay)!=null?O:"collapsed")==="expanded",me=(z=Mi.get(M))!=null?z:Te;Mi.set(M,!me),km(M,y,o)}ve.delete(M)};Ne.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),qo(c))}),Ne.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),qo(c))});let Bo=new Map;Ne.addEventListener("click",c=>{var O;let h=c.target.closest(".persona-message-action-btn[data-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.closest("[data-actions-for]");if(!y)return;let M=y.getAttribute("data-actions-for");if(!M)return;let F=h.getAttribute("data-action");if(F==="copy"){let D=V.getMessages().find(Te=>Te.id===M);if(D&&ee.onCopy){let Te=D.content||"";navigator.clipboard.writeText(Te).then(()=>{h.classList.add("persona-message-action-success");let me=Ee("check",14,"currentColor",2);me&&(h.innerHTML="",h.appendChild(me)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Z=Ee("copy",14,"currentColor",2);Z&&(h.innerHTML="",h.appendChild(Z))},2e3)}).catch(me=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",me)}),ee.onCopy(D)}}else if(F==="upvote"||F==="downvote"){let D=((O=Bo.get(M))!=null?O:null)===F,Te=F==="upvote"?"thumbs-up":"thumbs-down";if(D){Bo.delete(M),h.classList.remove("persona-message-action-active");let me=Ee(Te,14,"currentColor",2);me&&(h.innerHTML="",h.appendChild(me))}else{let me=F==="upvote"?"downvote":"upvote",Z=y.querySelector(`[data-action="${me}"]`);if(Z){Z.classList.remove("persona-message-action-active");let je=Ee(me==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);je&&(Z.innerHTML="",Z.appendChild(je))}Bo.set(M,F),h.classList.add("persona-message-action-active");let Se=Ee(Te,14,"currentColor",2);Se&&(Se.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(Se)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ve=V.getMessages().find(ot=>ot.id===M);Ve&&ee.onFeedback&&ee.onFeedback({type:F,messageId:Ve.id,message:Ve})}}}),Ne.addEventListener("click",c=>{let h=c.target.closest("button[data-approval-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.closest(".persona-approval-bubble");if(!y)return;let M=y.getAttribute("data-message-id");if(!M)return;let F=h.getAttribute("data-approval-action");if(!F)return;let O=F==="approve"?"approved":"denied",D=V.getMessages().find(me=>me.id===M);if(!(D!=null&&D.approval))return;let Te=y.querySelector("[data-approval-buttons]");Te&&Te.querySelectorAll("button").forEach(Z=>{Z.disabled=!0,Z.style.opacity="0.5",Z.style.cursor="not-allowed"}),D.approval.toolType==="webmcp"?V.resolveWebMcpApproval(M,O):V.resolveApproval(D.approval,O)});let St=null,_n=null,Vn={artifacts:[],selectedId:null},Tn=!1,Mt={current:null};Ne.addEventListener("click",c=>{var Z,Se,Le,Ve,ot;let h=c.target.closest("[data-download-artifact]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||((Le=(Se=(Z=o.features)==null?void 0:Z.artifacts)==null?void 0:Se.onArtifactAction)==null?void 0:Le.call(Se,{type:"download",artifactId:y}))===!0)return;let F=V.getArtifactById(y),O=F==null?void 0:F.markdown,z=(F==null?void 0:F.title)||"artifact";if(!O){let je=h.closest("[data-open-artifact]"),mt=je==null?void 0:je.closest("[data-message-id]"),dt=mt==null?void 0:mt.getAttribute("data-message-id");if(dt){let Re=V.getMessages().find(qe=>qe.id===dt);if(Re!=null&&Re.rawContent)try{let qe=JSON.parse(Re.rawContent);O=(Ve=qe==null?void 0:qe.props)==null?void 0:Ve.markdown,z=((ot=qe==null?void 0:qe.props)==null?void 0:ot.title)||z}catch{}}}if(!O)return;let D=new Blob([O],{type:"text/markdown"}),Te=URL.createObjectURL(D),me=document.createElement("a");me.href=Te,me.download=`${z}.md`,me.click(),URL.revokeObjectURL(Te)}),Ne.addEventListener("click",c=>{var F,O,z;let h=c.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||((z=(O=(F=o.features)==null?void 0:F.artifacts)==null?void 0:O.onArtifactAction)==null?void 0:z.call(O,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),Tn=!1,V.selectArtifact(y),zn())}),Ne.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let no=We.composerOverlay,oo=(c,g,h)=>{var z,D,Te,me;let y=g.trim();if(!y||!Mt.current)return;let M=(z=c.getAttribute("data-tool-call-id"))!=null?z:"",F=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:M,answer:y,answers:h.structured,values:(D=h.values)!=null?D:h.source==="multi"?y.split(", "):[y],isFreeText:F,source:h.source},bubbles:!0,composed:!0})),ss(no,M);let O=Mt.current.getMessages().find(Z=>{var Se;return((Se=Z.toolCall)==null?void 0:Se.id)===M});(Te=O==null?void 0:O.agentMetadata)!=null&&Te.awaitingLocalTool?Mt.current.resolveAskUserQuestion(O,(me=h.structured)!=null?me:y):Mt.current.sendMessage(y)},$n=c=>{var M;let g=Mt.current;if(!g)return;let h=(M=c.getAttribute("data-tool-call-id"))!=null?M:"",y=g.getMessages().find(F=>{var O;return((O=F.toolCall)==null?void 0:O.id)===h});y&&g.persistAskUserQuestionProgress(y,{answers:Ti(c,y),currentIndex:fo(c)})},jo=c=>Object.entries(c).map(([g,h])=>`${g}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Ho=c=>{var M,F,O;if(((F=(M=o.features)==null?void 0:M.askUserQuestion)==null?void 0:F.groupedAutoAdvance)===!1)return;let g=fo(c),h=rs(c);if(g>=h-1)return;let y=(O=Mt.current)==null?void 0:O.getMessages().find(z=>{var D;return((D=z.toolCall)==null?void 0:D.id)===c.getAttribute("data-tool-call-id")});y&&(Ei(c,y,o,g+1),$n(c))};no.addEventListener("click",c=>{var F,O,z,D,Te,me,Z,Se,Le,Ve,ot,je,mt,dt;let h=c.target.closest("[data-ask-user-action]");if(!h)return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;let M=h.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),M==="dismiss"){let Pe=(F=y.getAttribute("data-tool-call-id"))!=null?F:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),ss(no,Pe);let Re=(O=Mt.current)==null?void 0:O.getMessages().find(qe=>{var Qe;return((Qe=qe.toolCall)==null?void 0:Qe.id)===Pe});(z=Re==null?void 0:Re.agentMetadata)!=null&&z.awaitingLocalTool&&((D=Mt.current)==null||D.markAskUserQuestionResolved(Re),(Te=Mt.current)==null||Te.resolveAskUserQuestion(Re,"(dismissed)"));return}if(M==="pick"){let Pe=h.getAttribute("data-option-label");if(!Pe)return;let Re=y.getAttribute("data-multi-select")==="true",qe=lr(y);if(qe&&Re){let Qe=Ir(y)[fo(y)],vt=new Set(Array.isArray(Qe)?Qe:[]);vt.has(Pe)?vt.delete(Pe):vt.add(Pe),cr(y,Array.from(vt)),$n(y);return}if(qe){cr(y,Pe),$n(y),Ho(y);return}if(Re){let Qe=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Qe?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Qe);let vt=y.querySelector('[data-ask-user-action="submit-multi"]');vt&&(vt.disabled=Bl(y).length===0);return}oo(y,Pe,{source:"pick",values:[Pe]});return}if(M==="submit-multi"){let Pe=Bl(y);if(Pe.length===0)return;oo(y,Pe.join(", "),{source:"multi",values:Pe});return}if(M==="open-free-text"){let Pe=y.querySelector('[data-ask-free-text-row="true"]');if(Pe){Pe.classList.remove("persona-hidden");let Re=Pe.querySelector('[data-ask-free-text-input="true"]');Re==null||Re.focus()}return}if(M==="focus-free-text"){let Pe=y.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus();return}if(M==="submit-free-text"){let Pe=y.querySelector('[data-ask-free-text-input="true"]'),Re=(me=Pe==null?void 0:Pe.value)!=null?me:"";if(!Re.trim())return;if(lr(y)){cr(y,Re.trim()),$n(y),Ho(y);return}oo(y,Re,{source:"free-text"});return}if(M==="next"||M==="back"){if(!Mt.current)return;let Pe=(Z=y.getAttribute("data-tool-call-id"))!=null?Z:"",Re=Mt.current.getMessages().find(De=>{var ne;return((ne=De.toolCall)==null?void 0:ne.id)===Pe});if(!Re)return;let qe=y.querySelector('[data-ask-free-text-input="true"]'),Qe=(Le=(Se=qe==null?void 0:qe.value)==null?void 0:Se.trim())!=null?Le:"";if(Qe){let De=Ir(y)[fo(y)];(typeof De!="string"||De!==Qe)&&cr(y,Qe)}let vt=M==="next"?1:-1,B=fo(y)+vt;Ei(y,Re,o,B),$n(y);return}if(M==="submit-all"){if(!Mt.current)return;let Pe=(Ve=y.getAttribute("data-tool-call-id"))!=null?Ve:"",Re=Mt.current.getMessages().find(De=>{var ne;return((ne=De.toolCall)==null?void 0:ne.id)===Pe});if(!Re)return;let qe=y.querySelector('[data-ask-free-text-input="true"]'),Qe=(je=(ot=qe==null?void 0:qe.value)==null?void 0:ot.trim())!=null?je:"";Qe&&cr(y,Qe);let vt=Ti(y,Re);Mt.current.persistAskUserQuestionProgress(Re,{answers:vt,currentIndex:fo(y)});let B=jo(vt);oo(y,B||"(submitted)",{source:"submit-all",structured:vt});return}if(M==="skip"){if(!Mt.current)return;let Pe=(mt=y.getAttribute("data-tool-call-id"))!=null?mt:"",Re=Mt.current.getMessages().find(ne=>{var et;return((et=ne.toolCall)==null?void 0:et.id)===Pe});if(!Re)return;let qe=lr(y),Qe=fo(y),vt=rs(y),B=Qe>=vt-1;if(!qe){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),ss(no,Pe),(dt=Re.agentMetadata)!=null&&dt.awaitingLocalTool&&(Mt.current.markAskUserQuestionResolved(Re),Mt.current.resolveAskUserQuestion(Re,"(dismissed)"));return}cr(y,"");let De=y.querySelector('[data-ask-free-text-input="true"]');if(De&&(De.value=""),B){let ne=Ti(y,Re),et=jo(ne);oo(y,et||"(skipped)",{source:"submit-all",structured:ne});return}Ei(y,Re,o,Qe+1),$n(y);return}}),no.addEventListener("keydown",c=>{var F;if(c.key!=="Enter")return;let h=c.target;if(!((F=h.matches)!=null&&F.call(h,'[data-ask-free-text-input="true"]')))return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;c.preventDefault();let M=h.value;if(M.trim()){if(lr(y)){cr(y,M.trim()),$n(y),Ho(y);return}oo(y,M,{source:"free-text"})}});let Ko=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let g=c.target;if((g==null?void 0:g.tagName)==="INPUT"||(g==null?void 0:g.tagName)==="TEXTAREA"||g!=null&&g.isContentEditable)return;let h=no.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let y=Number(c.key),F=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];F&&(c.preventDefault(),F.click())};document.addEventListener("keydown",Ko);let Un=null,Dt=null,kn=null,ro=null,Go=()=>{};function Do(){ro==null||ro(),ro=null}let Yo=()=>{var O;if(!Un||!Dt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),h=((O=e.ownerDocument.defaultView)!=null?O:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||h){Dt.style.removeProperty("position"),Dt.style.removeProperty("left"),Dt.style.removeProperty("top"),Dt.style.removeProperty("bottom"),Dt.style.removeProperty("width"),Dt.style.removeProperty("z-index");return}let y=Un.firstElementChild;if(!y||y===Dt)return;let M=10;Dt.style.position="absolute",Dt.style.top="0",Dt.style.bottom="0",Dt.style.width=`${M}px`,Dt.style.zIndex="5";let F=y.offsetWidth-M/2;Dt.style.left=`${Math.max(0,F)}px`},Mo=()=>{},zn=()=>{var h,y,M,F,O;if(!St||!ho(o))return;Ri(e,o),Pi(e,o),Mo();let c=(F=(M=(y=(h=o.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:M.narrowHostMaxWidth)!=null?F:520,g=pe.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),St.update(Vn),Tn?(St.setMobileOpen(!1),St.element.classList.add("persona-hidden"),(O=St.backdrop)==null||O.classList.add("persona-hidden")):Vn.artifacts.length>0&&(St.element.classList.remove("persona-hidden"),St.setMobileOpen(!0)),Go()};if(ho(o)){pe.style.position="relative";let c=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(ue),St=Bm(o,{onSelect:h=>{var y;return(y=Mt.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{Tn=!0,zn()}}),St.element.classList.add("persona-hidden"),Un=g,g.appendChild(c),g.appendChild(St.element),St.backdrop&&pe.appendChild(St.backdrop),pe.appendChild(g),Go=()=>{var y,M,F,O;if(!Un||!St)return;if(!(((F=(M=(y=o.features)==null?void 0:y.artifacts)==null?void 0:M.layout)==null?void 0:F.resizable)===!0)){kn==null||kn(),kn=null,Do(),Dt&&(Dt.remove(),Dt=null),St.element.style.removeProperty("width"),St.element.style.removeProperty("maxWidth");return}if(!Dt){let z=b("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");z.setAttribute("role","separator"),z.setAttribute("aria-orientation","vertical"),z.setAttribute("aria-label","Resize artifacts panel"),z.tabIndex=0;let D=e.ownerDocument,Te=(O=D.defaultView)!=null?O:window,me=Z=>{var mt,dt;if(!St||Z.button!==0||e.classList.contains("persona-artifact-narrow-host")||Te.innerWidth<=640)return;Z.preventDefault(),Do();let Se=Z.clientX,Le=St.element.getBoundingClientRect().width,Ve=(dt=(mt=o.features)==null?void 0:mt.artifacts)==null?void 0:dt.layout,ot=Pe=>{let Re=Un.getBoundingClientRect().width,qe=e.classList.contains("persona-artifact-appearance-seamless"),Qe=qe?0:Om(Un,Te),vt=qe?0:z.getBoundingClientRect().width||6,B=Le-(Pe.clientX-Se),De=Nm(B,Re,Qe,vt,Ve==null?void 0:Ve.resizableMinWidth,Ve==null?void 0:Ve.resizableMaxWidth);St.element.style.width=`${De}px`,St.element.style.maxWidth="none",Yo()},je=()=>{D.removeEventListener("pointermove",ot),D.removeEventListener("pointerup",je),D.removeEventListener("pointercancel",je),ro=null;try{z.releasePointerCapture(Z.pointerId)}catch{}};ro=je,D.addEventListener("pointermove",ot),D.addEventListener("pointerup",je),D.addEventListener("pointercancel",je);try{z.setPointerCapture(Z.pointerId)}catch{}};z.addEventListener("pointerdown",me),Dt=z,Un.insertBefore(z,St.element),kn=()=>{z.removeEventListener("pointerdown",me)}}if(Dt){let z=Vn.artifacts.length>0&&!Tn;Dt.classList.toggle("persona-hidden",!z),Yo()}},Mo=()=>{var Te,me,Z,Se,Le,Ve,ot,je,mt,dt,Pe,Re,qe,Qe;if(!L||!St||((me=(Te=o.launcher)==null?void 0:Te.sidebarMode)!=null?me:!1)||hn(o)&&Wo(o).reveal==="emerge")return;let y=(Z=e.ownerDocument.defaultView)!=null?Z:window,M=(Le=(Se=o.launcher)==null?void 0:Se.mobileFullscreen)!=null?Le:!0,F=(ot=(Ve=o.launcher)==null?void 0:Ve.mobileBreakpoint)!=null?ot:640;if(M&&y.innerWidth<=F||!Fm(o,L))return;let O=(dt=(mt=(je=o.launcher)==null?void 0:je.width)!=null?mt:o.launcherWidth)!=null?dt:go,z=(Qe=(qe=(Re=(Pe=o.features)==null?void 0:Pe.artifacts)==null?void 0:Re.layout)==null?void 0:qe.expandedPanelWidth)!=null?Qe:"min(720px, calc(100vw - 24px))";Vn.artifacts.length>0&&!Tn?(pe.style.width=z,pe.style.maxWidth=z):(pe.style.width=O,pe.style.maxWidth=O)},typeof ResizeObserver!="undefined"&&(_n=new ResizeObserver(()=>{zn()}),_n.observe(pe))}else pe.appendChild(ue),k()&&$e&&(We.peekBanner&&$e.appendChild(We.peekBanner),$e.appendChild(_e));e.appendChild(Ae),$e&&e.appendChild($e);let bo=()=>{var De,ne,et,Nt,Ot,zt,at,ln,Yn,Ke,wt,Xn,on,uo,Qn,hr,zr,qr,Gt,br,rr,sr,$o,yr,tt,yn,gn,cn;if(k()){pe.style.width="100%",pe.style.maxWidth="100%";let gt=(ne=(De=o.launcher)==null?void 0:De.composerBar)!=null?ne:{},it=Ae.dataset.state==="expanded",kt=(et=gt.expandedSize)!=null?et:"anchored";if(!(it&&kt!=="fullscreen")){ue.style.background="",ue.style.border="",ue.style.borderRadius="",ue.style.overflow="",ue.style.boxShadow="";return}let Zt=(Ot=(Nt=o.theme)==null?void 0:Nt.components)==null?void 0:Ot.panel,Io=Ia(o),rn=(xr,Ma)=>{var Ls;return xr==null||xr===""?Ma:(Ls=jr(Io,xr))!=null?Ls:xr},Mn="1px solid var(--persona-border)",mo="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",vr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ue.style.background="var(--persona-surface, #ffffff)",ue.style.border=rn(Zt==null?void 0:Zt.border,Mn),ue.style.borderRadius=rn(Zt==null?void 0:Zt.borderRadius,vr),ue.style.boxShadow=rn(Zt==null?void 0:Zt.shadow,mo),ue.style.overflow="hidden";return}let c=hn(o),g=(at=(zt=o.launcher)==null?void 0:zt.sidebarMode)!=null?at:!1,h=c||g||((Yn=(ln=o.launcher)==null?void 0:ln.fullHeight)!=null?Yn:!1),y=((Ke=o.launcher)==null?void 0:Ke.enabled)===!1,M=(Xn=(wt=o.theme)==null?void 0:wt.components)==null?void 0:Xn.panel,F=Ia(o),O=(gt,it)=>{var kt;return gt==null||gt===""?it:(kt=jr(F,gt))!=null?kt:gt},z=(on=e.ownerDocument.defaultView)!=null?on:window,D=(Qn=(uo=o.launcher)==null?void 0:uo.mobileFullscreen)!=null?Qn:!0,Te=(zr=(hr=o.launcher)==null?void 0:hr.mobileBreakpoint)!=null?zr:640,me=z.innerWidth<=Te,Z=D&&me&&L,Se=(Gt=(qr=o.launcher)==null?void 0:qr.position)!=null?Gt:"bottom-left",Le=Se==="bottom-left"||Se==="top-left",Ve=(rr=(br=o.launcher)==null?void 0:br.zIndex)!=null?rr:wn,ot=g||Z?"none":"1px solid var(--persona-border)",je=Z?"none":g?Le?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!Z&&(je="none",ot="none");let mt=g||Z?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",dt=O(M==null?void 0:M.border,ot),Pe=O(M==null?void 0:M.shadow,je),Re=O(M==null?void 0:M.borderRadius,mt),qe=X.scrollTop;e.style.cssText="",Ae.style.cssText="",pe.style.cssText="",ue.style.cssText="",X.style.cssText="",_e.style.cssText="";let Qe=()=>{var it;if(qe<=0)return;((it=X.ownerDocument.defaultView)!=null?it:window).requestAnimationFrame(()=>{if(X.scrollTop===qe)return;let kt=X.scrollHeight-X.clientHeight;kt<=0||(X.scrollTop=Math.min(qe,kt))})};if(Z){Ae.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Ae.style.cssText=`
31
31
  position: fixed !important;
32
32
  inset: 0 !important;
33
33
  width: 100% !important;
@@ -37,9 +37,9 @@ _Details: ${n.message}_`:o}var ei=class e{constructor(t={},n){this.config=t;this
37
37
  padding: 0 !important;
38
38
  display: flex !important;
39
39
  flex-direction: column !important;
40
- z-index: ${Oe} !important;
40
+ z-index: ${Ve} !important;
41
41
  background-color: var(--persona-surface, #ffffff) !important;
42
- `,le.style.cssText=`
42
+ `,pe.style.cssText=`
43
43
  position: relative !important;
44
44
  display: flex !important;
45
45
  flex-direction: column !important;
@@ -52,7 +52,7 @@ _Details: ${n.message}_`:o}var ei=class e{constructor(t={},n){this.config=t;this
52
52
  padding: 0 !important;
53
53
  box-shadow: none !important;
54
54
  border-radius: 0 !important;
55
- `,ce.style.cssText=`
55
+ `,ue.style.cssText=`
56
56
  display: flex !important;
57
57
  flex-direction: column !important;
58
58
  flex: 1 1 0% !important;
@@ -63,20 +63,20 @@ _Details: ${n.message}_`:o}var ei=class e{constructor(t={},n){this.config=t;this
63
63
  overflow: hidden !important;
64
64
  border-radius: 0 !important;
65
65
  border: none !important;
66
- `,K.style.flex="1 1 0%",K.style.minHeight="0",K.style.overflowY="auto",Ve.style.flexShrink="0",x=!0,L();return}let Me=(Pn=(ht=o==null?void 0:o.launcher)==null?void 0:ht.width)!=null?Pn:o==null?void 0:o.launcherWidth,We=Me!=null?Me:io;if(!g&&!c)y&&h?(le.style.width="100%",le.style.maxWidth="100%"):(le.style.width=We,le.style.maxWidth=We);else if(c)if(Mo(o).reveal==="emerge"){let jt=Mo(o).width;le.style.width=jt,le.style.maxWidth=jt}else le.style.width="100%",le.style.maxWidth="100%";if(Co(),le.style.boxShadow=Pe,le.style.borderRadius=Re,ce.style.border=it,ce.style.borderRadius=Re,c&&!ee&&(P==null?void 0:P.border)===void 0&&(ce.style.border="none",Mo(o).side==="right"?ce.style.borderLeft="1px solid var(--persona-border)":ce.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",y&&(e.style.width="100%"),ye.style.display="flex",ye.style.flexDirection="column",ye.style.flex="1 1 0%",ye.style.minHeight="0",ye.style.maxHeight="100%",ye.style.height="100%",y&&(ye.style.overflow="hidden"),le.style.display="flex",le.style.flexDirection="column",le.style.flex="1 1 0%",le.style.minHeight="0",le.style.maxHeight="100%",le.style.height="100%",le.style.overflow="hidden",ce.style.display="flex",ce.style.flexDirection="column",ce.style.flex="1 1 0%",ce.style.minHeight="0",ce.style.maxHeight="100%",ce.style.overflow="hidden",K.style.flex="1 1 0%",K.style.minHeight="0",K.style.overflowY="auto",Ve.style.flexShrink="0"),ye.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!g&&!y&&!c&&((Oo=xo[he])!=null?Oo:xo["bottom-right"]).split(" ").forEach(jt=>ye.classList.add(jt)),g){let Dt=(Wn=(kn=o.launcher)==null?void 0:kn.sidebarWidth)!=null?Wn:"420px";ye.style.cssText=`
66
+ `,X.style.flex="1 1 0%",X.style.minHeight="0",X.style.overflowY="auto",_e.style.flexShrink="0",w=!0,Qe();return}let vt=($o=(sr=o==null?void 0:o.launcher)==null?void 0:sr.width)!=null?$o:o==null?void 0:o.launcherWidth,B=vt!=null?vt:go;if(!g&&!c)y&&h?(pe.style.width="100%",pe.style.maxWidth="100%"):(pe.style.width=B,pe.style.maxWidth=B);else if(c)if(Wo(o).reveal==="emerge"){let it=Wo(o).width;pe.style.width=it,pe.style.maxWidth=it}else pe.style.width="100%",pe.style.maxWidth="100%";if(Mo(),pe.style.boxShadow=Pe,pe.style.borderRadius=Re,ue.style.border=dt,ue.style.borderRadius=Re,c&&!Z&&(M==null?void 0:M.border)===void 0&&(ue.style.border="none",Wo(o).side==="right"?ue.style.borderLeft="1px solid var(--persona-border)":ue.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",y&&(e.style.width="100%"),Ae.style.display="flex",Ae.style.flexDirection="column",Ae.style.flex="1 1 0%",Ae.style.minHeight="0",Ae.style.maxHeight="100%",Ae.style.height="100%",y&&(Ae.style.overflow="hidden"),pe.style.display="flex",pe.style.flexDirection="column",pe.style.flex="1 1 0%",pe.style.minHeight="0",pe.style.maxHeight="100%",pe.style.height="100%",pe.style.overflow="hidden",ue.style.display="flex",ue.style.flexDirection="column",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.maxHeight="100%",ue.style.overflow="hidden",X.style.flex="1 1 0%",X.style.minHeight="0",X.style.overflowY="auto",_e.style.flexShrink="0"),Ae.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!g&&!y&&!c&&((yr=ko[Se])!=null?yr:ko["bottom-right"]).split(" ").forEach(it=>Ae.classList.add(it)),g){let gt=(yn=(tt=o.launcher)==null?void 0:tt.sidebarWidth)!=null?yn:"420px";Ae.style.cssText=`
67
67
  position: fixed !important;
68
68
  top: 0 !important;
69
69
  bottom: 0 !important;
70
- width: ${Dt} !important;
70
+ width: ${gt} !important;
71
71
  height: 100vh !important;
72
72
  max-height: 100vh !important;
73
73
  margin: 0 !important;
74
74
  padding: 0 !important;
75
75
  display: flex !important;
76
76
  flex-direction: column !important;
77
- z-index: ${Oe} !important;
78
- ${Ee?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
79
- `,le.style.cssText=`
77
+ z-index: ${Ve} !important;
78
+ ${Le?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
79
+ `,pe.style.cssText=`
80
80
  position: relative !important;
81
81
  display: flex !important;
82
82
  flex-direction: column !important;
@@ -89,7 +89,7 @@ _Details: ${n.message}_`:o}var ei=class e{constructor(t={},n){this.config=t;this
89
89
  padding: 0 !important;
90
90
  box-shadow: ${Pe} !important;
91
91
  border-radius: ${Re} !important;
92
- `,le.style.setProperty("width","100%","important"),le.style.setProperty("max-width","100%","important"),ce.style.cssText=`
92
+ `,pe.style.setProperty("width","100%","important"),pe.style.setProperty("max-width","100%","important"),ue.style.cssText=`
93
93
  display: flex !important;
94
94
  flex-direction: column !important;
95
95
  flex: 1 1 0% !important;
@@ -99,12 +99,12 @@ _Details: ${n.message}_`:o}var ei=class e{constructor(t={},n){this.config=t;this
99
99
  max-height: 100% !important;
100
100
  overflow: hidden !important;
101
101
  border-radius: ${Re} !important;
102
- border: ${it} !important;
103
- `,Ve.style.cssText=`
102
+ border: ${dt} !important;
103
+ `,_e.style.cssText=`
104
104
  flex-shrink: 0 !important;
105
105
  border-top: none !important;
106
106
  padding: 8px 16px 12px 16px !important;
107
- `}if(!y&&!c){let Dt="max-height: -moz-available !important; max-height: stretch !important;",jt=g?"":"padding-top: 1.25em !important;",Bn=g?"":`z-index: ${(Ut=(Ht=o.launcher)==null?void 0:Ht.zIndex)!=null?Ut:hn} !important;`;ye.style.cssText+=Dt+jt+Bn}L()};po(),$r(e,o),Ti(e,o),ki(e,o);let gt=[];gt.push(()=>{document.removeEventListener("keydown",zo)});let Kt=null,Gt=null;gt.push(()=>{Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null}),_n&&gt.push(()=>{_n==null||_n.disconnect(),_n=null}),gt.push(()=>{wn==null||wn(),wn=null,Ro(),Wt&&(Wt.remove(),Wt=null),yt==null||yt.element.style.removeProperty("width"),yt==null||yt.element.style.removeProperty("maxWidth")}),ie&&gt.push(()=>{we!==null&&(cancelAnimationFrame(we),we=null),Se==null||Se.destroy(),Se=null,Y==null||Y.destroy(),Y=null,J=null});let qn=null,Ko=()=>{qn&&(qn(),qn=null),o.colorScheme==="auto"&&(qn=nu(()=>{$r(e,o)}))};Ko(),gt.push(()=>{qn&&(qn(),qn=null)});let oo=(_c=o.features)==null?void 0:_c.streamAnimation;if(oo!=null&&oo.type&&oo.type!=="none"){let c=_s(oo.type,oo.plugins);c&&(ul(c,e),gt.push(()=>zu(e)))}let uo=um(Et),jn=null,T,Kn=!1,mo=Ou(),Po=new Map,So=new Map,ss=0,go=ri(),fo=0,ho=null,Wo=!1,lr=!1,ra=4,as=24,sa=80,Pr=new Map,mt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},is=($c=(Vc=o.voiceRecognition)==null?void 0:Vc.autoResume)!=null?$c:!1,ro=c=>{s.emit("voice:state",{active:mt.active,source:c,timestamp:Date.now()})},Rn=()=>{u(c=>({...c,voiceState:{active:mt.active,timestamp:Date.now(),manuallyDeactivated:mt.manuallyDeactivated}}))},aa=()=>{var y,P;if(((y=o.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=Ol(d.voiceState),g=!!c.active,h=Number((P=c.timestamp)!=null?P:0);mt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-h<ex&&setTimeout(()=>{var N,V;mt.active||(mt.manuallyDeactivated=!1,((V=(N=o.voiceRecognition)==null?void 0:N.provider)==null?void 0:V.type)==="runtype"?T.toggleVoice().then(()=>{mt.active=T.isVoiceActive(),ro("restore"),T.isVoiceActive()&&U()}):ur("restore"))},1e3)},ia=()=>T?Hm(T.getMessages()).filter(c=>!c.__skipPersist):[];function Wr(c){if(!(i!=null&&i.save))return;let h={messages:c?Hm(c):T?ia():[],metadata:d,artifacts:Vn.artifacts,selectedArtifactId:Vn.selectedId};try{let y=i.save(h);y instanceof Promise&&y.catch(P=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",P)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let Bo=null,la=()=>ye.querySelector("#persona-scroll-container")||K,cr=()=>{Bo!==null&&(cancelAnimationFrame(Bo),Bo=null),Wo=!1},ls=()=>{ho!==null&&(cancelAnimationFrame(ho),ho=null),lr=!1,cr()},Ho=()=>{if(!yn()||de){Tt.parentNode&&Tt.remove(),Tt.style.display="none";return}Tt.parentNode!==ce&&ce.appendChild(Tt),bt();let c=Fs(K)>0;Tt.style.display=go.isFollowing()||!c?"none":""},cs=()=>{go.pause()&&(ls(),Ho())},Go=()=>{go.resume(),Ho()},Yo=(c=!1)=>{go.isFollowing()&&(!c&&!Kn||(ho!==null&&(cancelAnimationFrame(ho),ho=null),lr=!0,ho=requestAnimationFrame(()=>{ho=null,lr=!1,go.isFollowing()&&ca(la(),c?220:140)})))},ca=(c,g=500)=>{let h=c.scrollTop,y=Fs(c),P=y-h;if(Math.abs(P)<1){fo=c.scrollTop;return}if(Math.abs(P)>=sa){cr(),Wo=!0,c.scrollTop=y,fo=c.scrollTop,Wo=!1;return}cr();let N=performance.now();Wo=!0;let V=O=>1-Math.pow(1-O,3),z=O=>{if(!go.isFollowing()){cr();return}let Ae=Fs(c);Ae!==y&&(y=Ae,P=y-h);let ue=O-N,ee=Math.min(ue/g,1),he=V(ee),Ee=h+P*he;c.scrollTop=Ee,fo=c.scrollTop,ee<1?Bo=requestAnimationFrame(z):(c.scrollTop=y,fo=c.scrollTop,Bo=null,Wo=!1)};Bo=requestAnimationFrame(z)},da=c=>{let g=new Map;c.forEach(h=>{let y=Pr.get(h.id);g.set(h.id,{streaming:h.streaming,role:h.role}),!y&&h.role==="assistant"&&s.emit("assistant:message",h),h.role==="assistant"&&(y!=null&&y.streaming)&&h.streaming===!1&&s.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(y?h.approval.status!=="pending"&&s.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):s.emit("approval:requested",{approval:h.approval,message:h}))}),Pr.clear(),g.forEach((h,y)=>{Pr.set(y,h)})},dr=(c,g,h)=>{var Ye,at,it,Pe,Re,qe;let y=document.createElement("div"),N=(()=>{var Me;let L=r.find(We=>We.renderLoadingIndicator);if(L!=null&&L.renderLoadingIndicator)return L.renderLoadingIndicator;if((Me=o.loadingIndicator)!=null&&Me.render)return o.loadingIndicator.render})(),V=(L,Me)=>Me==null?!1:typeof Me=="string"?(L.textContent=Me,!0):(L.appendChild(Me),!0),z=new Set,O=new Set,Ae=r.some(L=>L.renderAskUserQuestion),ue=[],ee=[],he=o.enableComponentStreaming!==!1;if(g.forEach(L=>{var An,dn,Je,lt,Tn,mn,mr,gr,fr,Nr,_r,qt,hr,nr;z.add(L.id);let Me=Ae&&Tr(L),We=!Me&&L.role==="assistant"&&!L.variant&&he&&Rm(L);if(!We&&So.has(L.id)){let ht=c.querySelector(`#wrapper-${L.id}`);ht==null||ht.removeAttribute("data-preserve-runtime"),So.delete(L.id)}let Ke=Tr(L)?`:${(An=L.agentMetadata)!=null&&An.askUserQuestionAnswered?"a":"u"}:${(dn=L.agentMetadata)!=null&&dn.askUserQuestionAnswers?Object.keys(L.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ce=Fu(L,ss)+Ke,Lt=Me||We?null:Nu(mo,L.id,Ce);if(Lt){y.appendChild(Lt.cloneNode(!0)),Tr(L)&&((Je=L.toolCall)!=null&&Je.id)&&((lt=L.agentMetadata)==null?void 0:lt.awaitingLocalTool)===!0&&!((Tn=L.agentMetadata)!=null&&Tn.askUserQuestionAnswered)&&(O.add(L.toolCall.id),Ci(L,o,Be.composerOverlay));return}let st=null,Xt=r.find(ht=>!!(L.variant==="reasoning"&&ht.renderReasoning||L.variant==="tool"&&ht.renderToolCall||L.variant==="approval"&&ht.renderApproval||!L.variant&&ht.renderMessage)),cn=(mn=o.layout)==null?void 0:mn.messages;if(Tr(L)&&((mr=L.agentMetadata)==null?void 0:mr.askUserQuestionAnswered)===!0){Po.delete(L.id);let ht=c.querySelector(`#wrapper-${L.id}`);ht==null||ht.removeAttribute("data-preserve-runtime");return}if(Tr(L)&&((fr=(gr=o.features)==null?void 0:gr.askUserQuestion)==null?void 0:fr.enabled)!==!1){let ht=r.find(Pn=>typeof Pn.renderAskUserQuestion=="function");if(ht&&It.current){let Pn=Po.get(L.id),Oo=Pn!==Ce,kn=null;if(Oo){let{payload:Ut,complete:Dt}=Xr(L),jt=L.id,Bn=()=>{var Yn;return(Yn=It.current)==null?void 0:Yn.getMessages().find(en=>en.id===jt)};kn=ht.renderAskUserQuestion({message:L,payload:Ut,complete:Dt,resolve:Yn=>{var To;let en=Bn();en&&((To=It.current)==null||To.resolveAskUserQuestion(en,Yn))},dismiss:()=>{var en,To,No;let Yn=Bn();(en=Yn==null?void 0:Yn.agentMetadata)!=null&&en.awaitingLocalTool&&((To=It.current)==null||To.markAskUserQuestionResolved(Yn),(No=It.current)==null||No.resolveAskUserQuestion(Yn,"(dismissed)"))},config:o})}let Wn=Pn!=null;if(Oo&&kn===null&&!Wn){((Nr=L.agentMetadata)==null?void 0:Nr.awaitingLocalTool)===!0&&!((_r=L.agentMetadata)!=null&&_r.askUserQuestionAnswered)&&(O.add(L.toolCall.id),Ci(L,o,Be.composerOverlay));return}let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${L.id}`,Ht.setAttribute("data-wrapper-id",L.id),Ht.setAttribute("data-ask-plugin-stub","true"),Ht.setAttribute("data-preserve-runtime","true"),y.appendChild(Ht),ue.push({messageId:L.id,fingerprint:Ce,bubble:kn});return}else{((qt=L.agentMetadata)==null?void 0:qt.awaitingLocalTool)===!0&&!((hr=L.agentMetadata)!=null&&hr.askUserQuestionAnswered)&&(O.add(L.toolCall.id),Ci(L,o,Be.composerOverlay));return}}else if(Xt)if(L.variant==="reasoning"&&L.reasoning&&Xt.renderReasoning){if(!se)return;st=Xt.renderReasoning({message:L,defaultRenderer:()=>vl(L,o),config:o})}else if(L.variant==="tool"&&L.toolCall&&Xt.renderToolCall){if(!ge)return;st=Xt.renderToolCall({message:L,defaultRenderer:()=>xl(L,o),config:o})}else if(L.variant==="approval"&&L.approval&&Xt.renderApproval){if(o.approval===!1)return;st=Xt.renderApproval({message:L,defaultRenderer:()=>Ml(L,o),config:o})}else Xt.renderMessage&&(st=Xt.renderMessage({message:L,defaultRenderer:()=>{let ht=yl(L,h,cn,o.messageActions,te,{loadingIndicatorRenderer:N,widgetConfig:o});return L.role!=="user"&&Pl(ht,L,o,T),ht},config:o}));if(!st&&We){let ht=Pm(L);if(ht){let Pn=So.get(L.id),Oo=Pn!==Ce,kn=o.wrapComponentDirectiveInBubble!==!1,Wn=null;if(Oo){let Ht=Lm(ht,{config:o,message:L,transform:h});if(Ht)if(kn){let Ut=document.createElement("div");if(Ut.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ut.id=`bubble-${L.id}`,Ut.setAttribute("data-message-id",L.id),L.content&&L.content.trim()){let Dt=document.createElement("div");Dt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Dt.innerHTML=h({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),Ut.appendChild(Dt)}Ut.appendChild(Ht),Wn=Ut}else{let Ut=document.createElement("div");if(Ut.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ut.id=`bubble-${L.id}`,Ut.setAttribute("data-message-id",L.id),Ut.setAttribute("data-persona-component-directive","true"),L.content&&L.content.trim()){let Dt=document.createElement("div");Dt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Dt.innerHTML=h({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),Ut.appendChild(Dt)}Ut.appendChild(Ht),Wn=Ut}}if(Wn||Pn!=null){let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${L.id}`,Ht.setAttribute("data-wrapper-id",L.id),Ht.setAttribute("data-component-directive-stub","true"),Ht.setAttribute("data-preserve-runtime","true"),kn||Ht.classList.add("persona-w-full"),y.appendChild(Ht),ee.push({messageId:L.id,fingerprint:Ce,bubble:Wn});return}}}if(!st)if(L.variant==="reasoning"&&L.reasoning){if(!se)return;st=vl(L,o)}else if(L.variant==="tool"&&L.toolCall){if(!ge)return;st=xl(L,o)}else if(L.variant==="approval"&&L.approval){if(o.approval===!1)return;st=Ml(L,o)}else{let ht=(nr=o.layout)==null?void 0:nr.messages;ht!=null&&ht.renderUserMessage&&L.role==="user"?st=ht.renderUserMessage({message:L,config:o,streaming:!!L.streaming}):ht!=null&&ht.renderAssistantMessage&&L.role==="assistant"?st=ht.renderAssistantMessage({message:L,config:o,streaming:!!L.streaming}):st=yl(L,h,ht,o.messageActions,te,{loadingIndicatorRenderer:N,widgetConfig:o}),L.role!=="user"&&st&&Pl(st,L,o,T)}let Pt=document.createElement("div");Pt.className="persona-flex",Pt.id=`wrapper-${L.id}`,Pt.setAttribute("data-wrapper-id",L.id),L.role==="user"&&Pt.classList.add("persona-justify-end"),(st==null?void 0:st.getAttribute("data-persona-component-directive"))==="true"&&Pt.classList.add("persona-w-full"),Pt.appendChild(st),_u(mo,L.id,Ce,Pt),y.appendChild(Pt)}),Be.composerOverlay&&Be.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Me=>{let We=Me.getAttribute("data-persona-ask-sheet-for");We&&!O.has(We)&&Jr(Be.composerOverlay,We)}),(at=(Ye=o.features)==null?void 0:Ye.toolCallDisplay)!=null&&at.grouped){let L=[],Me=[];g.forEach(We=>{if(We.variant==="tool"&&We.toolCall&&ge){Me.push(We);return}Me.length>1&&L.push(Me),Me=[]}),Me.length>1&&L.push(Me),L.forEach((We,Ke)=>{var dn,Je;let Ce=We.map(lt=>Array.from(y.children).find(Tn=>Tn instanceof HTMLElement&&Tn.getAttribute("data-wrapper-id")===lt.id)).filter(lt=>!!lt);if(Ce.length<2)return;let Lt=document.createElement("div");Lt.className="persona-flex",Lt.id=`wrapper-tool-group-${Ke}-${We[0].id}`,Lt.setAttribute("data-wrapper-id",`tool-group-${Ke}-${We[0].id}`);let st=document.createElement("div");st.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",st.setAttribute("data-persona-tool-group","true");let Xt=document.createElement("div");Xt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let cn=`Called ${We.length} tools`,Pt=(Je=(dn=o.toolCall)==null?void 0:dn.renderGroupedSummary)==null?void 0:Je.call(dn,{messages:We,toolCalls:We.map(lt=>lt.toolCall).filter(lt=>!!lt),defaultSummary:cn,config:o});V(Xt,Pt)||(Xt.textContent=cn);let An=document.createElement("div");An.className="persona-tool-group-stack persona-flex persona-flex-col",st.append(Xt,An),Lt.appendChild(st),Ce[0].before(Lt),Ce.forEach((lt,Tn)=>{let mn=document.createElement("div");mn.className="persona-tool-group-item persona-relative",mn.setAttribute("data-persona-tool-group-item","true"),Tn<Ce.length-1&&mn.setAttribute("data-persona-tool-group-connector","true"),mn.appendChild(lt),An.appendChild(mn)})})}Vu(mo,z);let Ee=g.some(L=>L.role==="assistant"&&L.streaming),Oe=g[g.length-1],tt=(Oe==null?void 0:Oe.role)==="assistant"&&!Oe.streaming&&Oe.variant!=="approval";if(Kn&&g.some(L=>L.role==="user")&&!Ee&&!tt){let L={config:o,streaming:!0,location:"standalone",defaultRenderer:Ks},Me=r.find(Ke=>Ke.renderLoadingIndicator),We=null;if(Me!=null&&Me.renderLoadingIndicator&&(We=Me.renderLoadingIndicator(L)),We===null&&((it=o.loadingIndicator)!=null&&it.render)&&(We=o.loadingIndicator.render(L)),We===null&&(We=Ks()),We){let Ke=document.createElement("div"),Ce=((Pe=o.loadingIndicator)==null?void 0:Pe.showBubble)!==!1;Ke.className=Ce?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ke.setAttribute("data-typing-indicator","true"),Ke.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ke.appendChild(We);let Lt=document.createElement("div");Lt.className="persona-flex",Lt.id="wrapper-typing-indicator",Lt.setAttribute("data-wrapper-id","typing-indicator"),Lt.appendChild(Ke),y.appendChild(Lt)}}if(!Kn&&g.length>0){let L=g[g.length-1],Me={config:o,lastMessage:L,messageCount:g.length},We=r.find(Ce=>Ce.renderIdleIndicator),Ke=null;if(We!=null&&We.renderIdleIndicator&&(Ke=We.renderIdleIndicator(Me)),Ke===null&&((Re=o.loadingIndicator)!=null&&Re.renderIdle)&&(Ke=o.loadingIndicator.renderIdle(Me)),Ke){let Ce=document.createElement("div"),Lt=((qe=o.loadingIndicator)==null?void 0:qe.showBubble)!==!1;Ce.className=Lt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ce.setAttribute("data-idle-indicator","true"),Ce.appendChild(Ke);let st=document.createElement("div");st.className="persona-flex",st.id="wrapper-idle-indicator",st.setAttribute("data-wrapper-id","idle-indicator"),st.appendChild(Ce),y.appendChild(st)}}if(ni(c,y),ue.length>0)for(let{messageId:L,fingerprint:Me,bubble:We}of ue){let Ke=c.querySelector(`#wrapper-${L}`);Ke&&We!==null&&(Ke.replaceChildren(We),Ke.setAttribute("data-bubble-fp",Me),Po.set(L,Me))}if(Po.size>0)for(let L of Po.keys())z.has(L)||Po.delete(L);if(ee.length>0)for(let{messageId:L,fingerprint:Me,bubble:We}of ee){let Ke=c.querySelector(`#wrapper-${L}`);Ke&&We!==null&&(Ke.replaceChildren(We),Ke.setAttribute("data-bubble-fp",Me),So.set(L,Me))}if(So.size>0)for(let L of So.keys())z.has(L)||So.delete(L)},Xo=null,pa=()=>{var h;if(Xo)return;let c=y=>{let P=y.composedPath();P.includes(ye)||$e&&P.includes($e)||Bt(!1,"user")};Xo=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},ds=()=>{var g;if(!Xo)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("pointerdown",Xo,!0),Xo=null};gt.push(()=>ds());let Qo=null,ua=()=>{var h;if(Qo)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Bt(!1,"user"))};Qo=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},ps=()=>{var g;if(!Qo)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("keydown",Qo,!0),Qo=null};gt.push(()=>ps());let Jo=!1,us=new Set,ma=()=>{var g,h,y,P;let c=(y=(h=(g=o.launcher)==null?void 0:g.composerBar)==null?void 0:h.peek)==null?void 0:y.streamAnimation;return c||((P=o.features)==null?void 0:P.streamAnimation)},Do=()=>{var at,it,Pe,Re;if(!k())return;let c=Be.peekBanner,g=Be.peekTextNode;if(!c||!g)return;if(E){c.classList.remove("persona-pill-peek--visible");return}let h=(at=T==null?void 0:T.getMessages())!=null?at:[],y;for(let qe=h.length-1;qe>=0;qe--){let L=h[qe];if(L.role==="assistant"&&L.content){y=L;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let P=y.content,N=!!y.streaming,V=ma(),z=ii(V),O=z.type!=="none"?_s(z.type,V==null?void 0:V.plugins):null,Ae=((it=O==null?void 0:O.isAnimating)==null?void 0:it.call(O,y))===!0,ue=O!==null&&(N||Ae);ue&&O&&!us.has(O.name)&&(ul(O,e),us.add(O.name));let ee=ue&&(O!=null&&O.containerClass)?O.containerClass:null,he=(Pe=g.dataset.personaPeekStreamClass)!=null?Pe:null;he&&he!==ee&&(g.classList.remove(he),delete g.dataset.personaPeekStreamClass),ee&&he!==ee&&(g.classList.add(ee),g.dataset.personaPeekStreamClass=ee),ue?(g.style.setProperty("--persona-stream-step",`${z.speed}ms`),g.style.setProperty("--persona-stream-duration",`${z.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ee=ue?li(P,z.buffer,O,y,N):P;if(ue&&z.placeholder==="skeleton"&&N&&(!Ee||!Ee.trim())){let qe=document.createElement("div"),L=$s();L.classList.add("persona-pill-peek__skeleton"),qe.appendChild(L),ni(g,qe)}else{let qe=Math.max(0,Ee.length-100),L=Ee.length>100?Ee.slice(-100):Ee,Me=Ls(L);if(!ue||!O){let We=Ee.length>100?`\u2026${L}`:L;g.textContent!==We&&(g.textContent=We)}else{let We=Me;(O.wrap==="char"||O.wrap==="word")&&(We=Vs(Me,O.wrap,`peek-${y.id}`,{skipTags:O.skipTags,startIndex:qe}));let Ke=document.createElement("div");if(Ke.innerHTML=We,O.useCaret&&L.length>0){let Ce=ci(),Lt=Ke.querySelectorAll(".persona-stream-char, .persona-stream-word"),st=Lt[Lt.length-1];st!=null&&st.parentNode?st.parentNode.insertBefore(Ce,st.nextSibling):Ke.appendChild(Ce)}ni(g,Ke),(Re=O.onAfterRender)==null||Re.call(O,{container:g,bubble:c,messageId:y.id,message:y,speed:z.speed,duration:z.duration})}}let Ye=Kn||Jo;c.classList.toggle("persona-pill-peek--visible",Ye)};if(k()){let c=Be.peekBanner;if(c){let y=P=>{P.preventDefault(),P.stopPropagation(),Bt(!0,"user")};c.addEventListener("pointerdown",y),gt.push(()=>{c.removeEventListener("pointerdown",y)})}let g=()=>{Jo||(Jo=!0,Do())},h=()=>{Jo&&(Jo=!1,Do())};le.addEventListener("pointerenter",g),le.addEventListener("pointerleave",h),gt.push(()=>{le.removeEventListener("pointerenter",g),le.removeEventListener("pointerleave",h)}),$e&&($e.addEventListener("pointerenter",g),$e.addEventListener("pointerleave",h),gt.push(()=>{$e.removeEventListener("pointerenter",g),$e.removeEventListener("pointerleave",h)}))}let ga=c=>{var he,Ee,Oe,tt,Ye,at,it,Pe;let g=(Ee=(he=o.launcher)==null?void 0:he.composerBar)!=null?Ee:{},h=(Oe=g.expandedSize)!=null?Oe:"anchored",y=(tt=g.bottomOffset)!=null?tt:"16px",P=g.collapsedMaxWidth,N=(Ye=g.expandedMaxWidth)!=null?Ye:"880px",V=(at=g.expandedTopOffset)!=null?at:"5vh",z=(it=g.modalMaxWidth)!=null?it:"880px",O=(Pe=g.modalMaxHeight)!=null?Pe:"min(90vh, 800px)",Ae="calc(100vw - 32px)",ue="var(--persona-pill-area-height, 80px)",ee=ye.style;if(ee.left="",ee.right="",ee.top="",ee.bottom="",ee.transform="",ee.width="",ee.maxWidth="",ee.height="",ee.maxHeight="",$e){let Re=$e.style;Re.bottom=y,Re.width=P!=null?P:""}if(c&&h!=="fullscreen"){if(h==="modal"){ee.top="50%",ee.left="50%",ee.transform="translate(-50%, -50%)",ee.bottom="auto",ee.right="auto",ee.width=z,ee.maxWidth=Ae,ee.maxHeight=O,ee.height=O;return}ee.left="50%",ee.transform="translateX(-50%)",ee.bottom=`calc(${y} + ${ue})`,ee.top=V,ee.width=N,ee.maxWidth=Ae}},Zo=()=>{var O,Ae,ue,ee,he,Ee,Oe,tt;if(!S())return;if(k()){let at=(ue=((Ae=(O=o.launcher)==null?void 0:O.composerBar)!=null?Ae:{}).expandedSize)!=null?ue:"anchored",it=E?"expanded":"collapsed";ye.dataset.state=it,ye.dataset.expandedSize=at,$e&&($e.dataset.state=it,$e.dataset.expandedSize=at),ye.style.removeProperty("display"),ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ga(E),ce.style.display=E?"flex":"none",po(),E?(pa(),ua()):(ds(),ps()),Do();return}let c=pn(o),g=(ee=e.ownerDocument.defaultView)!=null?ee:window,h=(Ee=(he=o.launcher)==null?void 0:he.mobileBreakpoint)!=null?Ee:640,y=(tt=(Oe=o.launcher)==null?void 0:Oe.mobileFullscreen)!=null?tt:!0,P=g.innerWidth<=h,N=y&&P&&I,V=Mo(o).reveal;E?(ye.style.removeProperty("display"),ye.style.display=c?"flex":"",ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-95","persona-opacity-0"),le.classList.add("persona-scale-100","persona-opacity-100"),Ie?Ie.element.style.display="none":Ge&&(Ge.style.display="none")):(c?c&&(V==="overlay"||V==="push")&&!N?(ye.style.removeProperty("display"),ye.style.display="flex",ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ye.style.setProperty("display","none","important"),ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ye.style.display="",ye.classList.add("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100"),le.classList.add("persona-scale-95","persona-opacity-0")),Ie?Ie.element.style.display=c?"none":"":Ge&&(Ge.style.display=c?"none":""))},Bt=(c,g="user")=>{var N,V;if(!S()||E===c)return;let h=E;E=c,Zo();let y=(()=>{var Oe,tt,Ye,at,it,Pe,Re,qe,L,Me;let z=(tt=(Oe=o.launcher)==null?void 0:Oe.sidebarMode)!=null?tt:!1,O=(Ye=e.ownerDocument.defaultView)!=null?Ye:window,Ae=(it=(at=o.launcher)==null?void 0:at.mobileFullscreen)!=null?it:!0,ue=(Re=(Pe=o.launcher)==null?void 0:Pe.mobileBreakpoint)!=null?Re:640,ee=O.innerWidth<=ue,he=pn(o)&&Ae&&ee,Ee=k()&&((Me=(L=(qe=o.launcher)==null?void 0:qe.composerBar)==null?void 0:L.expandedSize)!=null?Me:"fullscreen")==="fullscreen";return z||Ae&&ee&&I||he||Ee})();if(E&&y){if(!Kt){let z=e.getRootNode(),O=z instanceof ShadowRoot?z.host:e.closest(".persona-host");O&&(Kt=ml(O,(V=(N=o.launcher)==null?void 0:N.zIndex)!=null?V:hn))}Gt||(Gt=gl(e.ownerDocument))}else E||(Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null);E&&(Rt(),Yo(!0));let P={open:E,source:g,timestamp:Date.now()};E&&!h?s.emit("widget:opened",P):!E&&h&&s.emit("widget:closed",P),s.emit("widget:state",{open:E,launcherEnabled:I,voiceActive:mt.active,streaming:T.isStreaming()})},Br=c=>{Vt(c?"stop":"send"),q&&(q.disabled=c),uo.buttons.forEach(g=>{g.disabled=c}),Ve.dataset.personaComposerStreaming=c?"true":"false",Ve.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=c)})},Hr=()=>{mt.active||pe&&pe.focus()};s.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Hr(),200)});let ms=()=>{var h,y,P,N,V,z,O,Ae,ue,ee,he;Dn.textContent=(y=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",Jn.textContent=(N=(P=o.copy)==null?void 0:P.welcomeSubtitle)!=null?N:"Ask anything about your account or products.",pe.placeholder=(z=(V=o.copy)==null?void 0:V.inputPlaceholder)!=null?z:"How can I help...";let c=K.querySelector("[data-persona-intro-card]");if(c){let Ee=((O=o.copy)==null?void 0:O.showWelcomeCard)!==!1;c.style.display=Ee?"":"none",Ee?(K.classList.remove("persona-gap-3"),K.classList.add("persona-gap-6")):(K.classList.remove("persona-gap-6"),K.classList.add("persona-gap-3"))}!((ue=(Ae=o.sendButton)==null?void 0:Ae.useIcon)!=null&&ue)&&!(T!=null&&T.isStreaming())&&(ae.textContent=(he=(ee=o.copy)==null?void 0:ee.sendButtonLabel)!=null?he:"Send"),pe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',pe.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{u(g=>({...g,sessionId:c}))}});let Ao=null,fa=()=>{Ao==null&&(Ao=setInterval(()=>{let c=_e.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Ao),Ao=null;return}let g=Date.now();c.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=za(g-y))})},100))};if(T=new ei(o,{onMessagesChanged(c){dr(_e,c,me),fa(),T&&(c.some(P=>P.role==="user")?uo.render([],T,pe,c):uo.render(o.suggestionChips,T,pe,c,o.suggestionChipsConfig)),Yo(!Kn),da(c);let g=[...c].reverse().find(y=>y.role==="user"),h=mt.lastUserMessageId;g&&g.id!==h&&(mt.lastUserMessageId=g.id,s.emit("user:message",g)),mt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),Wr(c),Do()},onStatusChanged(c){var y;let g=(y=o.statusIndicator)!=null?y:{};nt(ln,(P=>{var N,V,z,O;return P==="idle"?(N=g.idleText)!=null?N:fn.idle:P==="connecting"?(V=g.connectingText)!=null?V:fn.connecting:P==="connected"?(z=g.connectedText)!=null?z:fn.connected:P==="error"?(O=g.errorText)!=null?O:fn.error:fn[P]})(c),g,c)},onStreamingChanged(c){Kn=c,Br(c),T&&dr(_e,T.getMessages(),me),c||Yo(!0),Do()},onVoiceStatusChanged(c){var g,h;if(((h=(g=o.voiceRecognition)==null?void 0:g.provider)==null?void 0:h.type)==="runtype")switch(c){case"listening":break;case"processing":G(),W();break;case"speaking":G(),Z();break;default:c==="idle"&&T.isBargeInActive()?(G(),U(),q==null||q.setAttribute("aria-label","End voice session")):(mt.active=!1,G(),ro("system"),Rn());break}},onArtifactsState(c){Vn=c,zn(),Wr()}}),It.current=T,((zc=(Uc=o.voiceRecognition)==null?void 0:Uc.provider)==null?void 0:zc.type)==="runtype")try{T.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}o.clientToken&&T.initClientSession().catch(c=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(Y||o.onSSEEvent)&&T.setSSEEventCallback((c,g)=>{var h;(h=o.onSSEEvent)==null||h.call(o,c,g),xe==null||xe.processEvent(c,g),Y==null||Y.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(g)})}),l&&l.then(c=>{var g,h,y;c&&(c.metadata&&(d=Ol(c.metadata),M.syncFromMetadata()),(g=c.messages)!=null&&g.length&&T.hydrateMessages(c.messages),(h=c.artifacts)!=null&&h.length&&T.hydrateArtifacts(c.artifacts,(y=c.selectedArtifactId)!=null?y:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let gs=()=>{var g,h,y;!k()||E||!((y=(h=(g=o.launcher)==null?void 0:g.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||Bt(!0,"auto")},fs=c=>{var P;if(c.preventDefault(),T.isStreaming()){T.cancel(),xe==null||xe.reset(),Se==null||Se.update();return}let g=pe.value.trim(),h=(P=et==null?void 0:et.hasAttachments())!=null?P:!1;if(!g&&!h)return;gs();let y;h&&(y=[],y.push(...et.getContentParts()),g&&y.push(ll(g))),pe.value="",pe.style.height="auto",pr(),T.sendMessage(g,{contentParts:y}),h&&et.clearAttachments()},ha=()=>{var c;return((c=o.features)==null?void 0:c.composerHistory)!==!1},Dr={...oi},Fr=!1,pr=()=>{Dr={...oi}},ba=()=>T.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),ya=c=>{if(!pe)return;Fr=!0,pe.value=c,pe.dispatchEvent(new Event("input",{bubbles:!0})),Fr=!1;let g=pe.value.length;pe.setSelectionRange(g,g)},hs=()=>{Fr||pr()},bs=c=>{if(pe){if(ha()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=pe.selectionStart===0&&pe.selectionEnd===0,h=Du({direction:c.key==="ArrowUp"?"up":"down",history:ba(),currentValue:pe.value,atStart:g,state:Dr});if(Dr=h.state,h.handled){c.preventDefault(),h.value!==void 0&&ya(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(T.isStreaming()){c.preventDefault();return}pr(),c.preventDefault(),ae.click()}}},ys=c=>{c.key!=="Escape"||c.isComposing||T.isStreaming()&&c.composedPath().includes(ce)&&(T.cancel(),xe==null||xe.reset(),Se==null||Se.update(),pr(),c.preventDefault(),c.stopImmediatePropagation())},vs=async c=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!et)return;let g=nx(c.clipboardData);g.length!==0&&(c.preventDefault(),await et.handleFiles(g))},Cn=null,Gn=!1,Fo=null,rt=null,xs=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ur=(c="user")=>{var N,V,z,O,Ae,ue,ee;if(Gn||T.isStreaming())return;let g=xs();if(!g)return;Cn=new g;let y=(V=((N=o.voiceRecognition)!=null?N:{}).pauseDuration)!=null?V:2e3;Cn.continuous=!0,Cn.interimResults=!0,Cn.lang="en-US";let P=pe.value;Cn.onresult=he=>{let Ee="",Oe="";for(let Ye=0;Ye<he.results.length;Ye++){let at=he.results[Ye],it=at[0].transcript;at.isFinal?Ee+=it+" ":Oe=it}let tt=P+Ee+Oe;pe.value=tt,Fo&&clearTimeout(Fo),(Ee||Oe)&&(Fo=window.setTimeout(()=>{let Ye=pe.value.trim();Ye&&Cn&&Gn&&(bo(),pe.value="",pe.style.height="auto",T.sendMessage(Ye,{viaVoice:!0}))},y))},Cn.onerror=he=>{he.error!=="no-speech"&&bo()},Cn.onend=()=>{if(Gn){let he=pe.value.trim();he&&he!==P.trim()&&(pe.value="",pe.style.height="auto",T.sendMessage(he,{viaVoice:!0})),bo()}};try{if(Cn.start(),Gn=!0,mt.active=!0,c!=="system"&&(mt.manuallyDeactivated=!1),ro(c),Rn(),q){let he=(z=o.voiceRecognition)!=null?z:{};rt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(O=he.iconName)!=null?O:"mic",iconSize:parseFloat((ee=(ue=he.iconSize)!=null?ue:(Ae=o.sendButton)==null?void 0:Ae.size)!=null?ee:"40")||24};let Ee=he.recordingBackgroundColor,Oe=he.recordingIconColor,tt=he.recordingBorderColor;if(q.classList.add("persona-voice-recording"),q.style.backgroundColor=Ee!=null?Ee:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=Oe!=null?Oe:"var(--persona-voice-recording-indicator, #ffffff)",Oe){let Ye=q.querySelector("svg");Ye&&Ye.setAttribute("stroke",Oe)}tt&&(q.style.borderColor=tt),q.setAttribute("aria-label","Stop voice recognition")}}catch{bo("system")}},bo=(c="user")=>{if(Gn){if(Gn=!1,Fo&&(clearTimeout(Fo),Fo=null),Cn){try{Cn.stop()}catch{}Cn=null}if(mt.active=!1,ro(c),Rn(),q){if(q.classList.remove("persona-voice-recording"),rt){q.style.backgroundColor=rt.backgroundColor,q.style.color=rt.color,q.style.borderColor=rt.borderColor;let g=q.querySelector("svg");g&&g.setAttribute("stroke",rt.color||"currentColor"),rt=null}q.setAttribute("aria-label","Start voice recognition")}}},va=(c,g)=>{var at,it,Pe,Re,qe,L,Me,We;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((at=c==null?void 0:c.provider)==null?void 0:at.type)==="runtype";if(!(h||y))return null;let N=b("div","persona-send-button-wrapper"),V=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");V.type="button",V.setAttribute("aria-label","Start voice recognition");let z=(it=c==null?void 0:c.iconName)!=null?it:"mic",O=(Pe=g==null?void 0:g.size)!=null?Pe:"40px",Ae=(Re=c==null?void 0:c.iconSize)!=null?Re:O,ue=parseFloat(Ae)||24,ee=(qe=c==null?void 0:c.backgroundColor)!=null?qe:g==null?void 0:g.backgroundColor,he=(L=c==null?void 0:c.iconColor)!=null?L:g==null?void 0:g.textColor;V.style.width=Ae,V.style.height=Ae,V.style.minWidth=Ae,V.style.minHeight=Ae,V.style.fontSize="18px",V.style.lineHeight="1",he?V.style.color=he:V.style.color="var(--persona-text, #111827)";let Oe=Te(z,ue,he||"currentColor",1.5);Oe?V.appendChild(Oe):V.textContent="\u{1F3A4}",ee?V.style.backgroundColor=ee:V.style.backgroundColor="",c!=null&&c.borderWidth&&(V.style.borderWidth=c.borderWidth,V.style.borderStyle="solid"),c!=null&&c.borderColor&&(V.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(V.style.paddingLeft=c.paddingX,V.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(V.style.paddingTop=c.paddingY,V.style.paddingBottom=c.paddingY),N.appendChild(V);let tt=(Me=c==null?void 0:c.tooltipText)!=null?Me:"Start voice recognition";if(((We=c==null?void 0:c.showTooltip)!=null?We:!1)&&tt){let Ke=b("div","persona-send-button-tooltip");Ke.textContent=tt,N.appendChild(Ke)}return{micButton:V,micButtonWrapper:N}},er=()=>{var g,h,y,P,N;if(!q||rt)return;let c=(g=o.voiceRecognition)!=null?g:{};rt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(h=c.iconName)!=null?h:"mic",iconSize:parseFloat((N=(P=c.iconSize)!=null?P:(y=o.sendButton)==null?void 0:y.size)!=null?N:"40")||24}},je=(c,g)=>{var N,V,z,O,Ae;if(!q)return;let h=q.querySelector("svg");h&&h.remove();let y=(Ae=rt==null?void 0:rt.iconSize)!=null?Ae:parseFloat((O=(z=(N=o.voiceRecognition)==null?void 0:N.iconSize)!=null?z:(V=o.sendButton)==null?void 0:V.size)!=null?O:"40")||24,P=Te(c,y,g,1.5);P&&q.appendChild(P)},A=()=>{q&&q.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},U=()=>{var P;if(!q)return;er();let c=(P=o.voiceRecognition)!=null?P:{},g=c.recordingBackgroundColor,h=c.recordingIconColor,y=c.recordingBorderColor;if(A(),q.classList.add("persona-voice-recording"),q.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let N=q.querySelector("svg");N&&N.setAttribute("stroke",h)}y&&(q.style.borderColor=y),q.setAttribute("aria-label","Stop voice recognition")},W=()=>{var z,O,Ae,ue,ee,he,Ee,Oe;if(!q)return;er();let c=(z=o.voiceRecognition)!=null?z:{},g=T.getVoiceInterruptionMode(),h=(O=c.processingIconName)!=null?O:"loader",y=(ue=(Ae=c.processingIconColor)!=null?Ae:rt==null?void 0:rt.color)!=null?ue:"",P=(he=(ee=c.processingBackgroundColor)!=null?ee:rt==null?void 0:rt.backgroundColor)!=null?he:"",N=(Oe=(Ee=c.processingBorderColor)!=null?Ee:rt==null?void 0:rt.borderColor)!=null?Oe:"";A(),q.classList.add("persona-voice-processing"),q.style.backgroundColor=P,q.style.borderColor=N;let V=y||"currentColor";q.style.color=V,je(h,V),q.setAttribute("aria-label","Processing voice input"),g==="none"&&(q.style.cursor="default")},Z=()=>{var Ae,ue,ee,he,Ee,Oe,tt,Ye,at,it,Pe,Re;if(!q)return;er();let c=(Ae=o.voiceRecognition)!=null?Ae:{},g=T.getVoiceInterruptionMode(),h=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",y=(ue=c.speakingIconName)!=null?ue:h,P=(Oe=c.speakingIconColor)!=null?Oe:g==="barge-in"?(he=(ee=c.recordingIconColor)!=null?ee:rt==null?void 0:rt.color)!=null?he:"":(Ee=rt==null?void 0:rt.color)!=null?Ee:"",N=(at=c.speakingBackgroundColor)!=null?at:g==="barge-in"?(tt=c.recordingBackgroundColor)!=null?tt:"var(--persona-voice-recording-bg, #ef4444)":(Ye=rt==null?void 0:rt.backgroundColor)!=null?Ye:"",V=(Re=c.speakingBorderColor)!=null?Re:g==="barge-in"?(it=c.recordingBorderColor)!=null?it:"":(Pe=rt==null?void 0:rt.borderColor)!=null?Pe:"";A(),q.classList.add("persona-voice-speaking"),q.style.backgroundColor=N,q.style.borderColor=V;let z=P||"currentColor";q.style.color=z,je(y,z);let O=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";q.setAttribute("aria-label",O),g==="none"&&(q.style.cursor="default"),g==="barge-in"&&q.classList.add("persona-voice-recording")},G=()=>{var c,g,h;q&&(A(),rt&&(q.style.backgroundColor=(c=rt.backgroundColor)!=null?c:"",q.style.color=(g=rt.color)!=null?g:"",q.style.borderColor=(h=rt.borderColor)!=null?h:"",je(rt.iconName,rt.color||"currentColor"),rt=null),q.style.cursor="",q.setAttribute("aria-label","Start voice recognition"))},X=()=>{var c,g;if(((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let h=T.getVoiceStatus(),y=T.getVoiceInterruptionMode();if(y==="none"&&(h==="processing"||h==="speaking"))return;if(y==="cancel"&&(h==="processing"||h==="speaking")){T.stopVoicePlayback();return}if(T.isBargeInActive()){T.stopVoicePlayback(),T.deactivateBargeIn().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Rn(),ro("user"),G()});return}T.toggleVoice().then(()=>{mt.active=T.isVoiceActive(),mt.manuallyDeactivated=!T.isVoiceActive(),Rn(),ro("user"),T.isVoiceActive()?U():G()});return}if(Gn){let h=pe.value.trim();mt.manuallyDeactivated=!0,Rn(),bo("user"),h&&(pe.value="",pe.style.height="auto",T.sendMessage(h))}else mt.manuallyDeactivated=!1,Rn(),ur("user")};Fn=X,q&&(q.addEventListener("click",X),gt.push(()=>{var c,g;((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(T.isVoiceActive()&&T.toggleVoice(),G()):bo("system"),q&&q.removeEventListener("click",X)}));let Xe=s.on("assistant:complete",()=>{is&&(mt.active||mt.manuallyDeactivated||is==="assistant"&&!mt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!mt.active&&!mt.manuallyDeactivated&&(((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?T.toggleVoice().then(()=>{mt.active=T.isVoiceActive(),ro("auto"),T.isVoiceActive()&&U()}):ur("auto"))},600))});gt.push(Xe);let Ne=s.on("action:resubmit",()=>{setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)});gt.push(Ne);let Ze=()=>{Bt(!E,"user")},Ie=null,Ge=null;if(I&&!k()){let c=r.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:o,defaultRenderer:()=>qs(o,Ze).element,onToggle:Ze});g&&(Ge=g)}Ge||(Ie=qs(o,Ze))}Ie?e.appendChild(Ie.element):Ge&&e.appendChild(Ge),Zo(),uo.render(o.suggestionChips,T,pe,void 0,o.suggestionChipsConfig),ms(),Br(T.isStreaming()),Yo(!0),aa(),H&&(!I||k()?setTimeout(()=>Hr(),0):E&&setTimeout(()=>Hr(),200));let Rt=()=>{var O,Ae,ue,ee,he,Ee,Oe,tt,Ye,at,it,Pe,Re,qe,L,Me,We,Ke,Ce,Lt,st,Xt;if(k()){bt(),Zo();return}let c=pn(o),g=(Ae=(O=o.launcher)==null?void 0:O.sidebarMode)!=null?Ae:!1,h=c||g||((ee=(ue=o.launcher)==null?void 0:ue.fullHeight)!=null?ee:!1),y=(he=e.ownerDocument.defaultView)!=null?he:window,P=(Oe=(Ee=o.launcher)==null?void 0:Ee.mobileFullscreen)!=null?Oe:!0,N=(Ye=(tt=o.launcher)==null?void 0:tt.mobileBreakpoint)!=null?Ye:640,V=y.innerWidth<=N,z=P&&V&&I;try{if(z){po(),$r(e,o);return}if(x&&(x=!1,po(),$r(e,o)),!I&&!c){le.style.height="",le.style.width="";return}if(!g&&!c){let cn=(it=(at=o==null?void 0:o.launcher)==null?void 0:at.width)!=null?it:o==null?void 0:o.launcherWidth,Pt=cn!=null?cn:io;le.style.width=Pt,le.style.maxWidth=Pt}if(Co(),!h){let cn=y.innerHeight,Pt=64,An=(Re=(Pe=o.launcher)==null?void 0:Pe.heightOffset)!=null?Re:0,dn=Math.max(200,cn-Pt),Je=Math.min(640,dn),lt=Math.max(200,Je-An);le.style.height=`${lt}px`}}finally{if(bt(),Zo(),E&&I){let Pt=((qe=e.ownerDocument.defaultView)!=null?qe:window).innerWidth<=((Me=(L=o.launcher)==null?void 0:L.mobileBreakpoint)!=null?Me:640),An=(Ke=(We=o.launcher)==null?void 0:We.sidebarMode)!=null?Ke:!1,dn=(Lt=(Ce=o.launcher)==null?void 0:Ce.mobileFullscreen)!=null?Lt:!0,Je=pn(o)&&dn&&Pt,lt=An||dn&&Pt&&I||Je;if(lt&&!Gt){let Tn=e.getRootNode(),mn=Tn instanceof ShadowRoot?Tn.host:e.closest(".persona-host");mn&&!Kt&&(Kt=ml(mn,(Xt=(st=o.launcher)==null?void 0:st.zIndex)!=null?Xt:hn)),Gt=gl(e.ownerDocument)}else lt||(Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null)}}};Rt();let nn=(qc=e.ownerDocument.defaultView)!=null?qc:window;if(nn.addEventListener("resize",Rt),gt.push(()=>nn.removeEventListener("resize",Rt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{bt()});c.observe(Ve),gt.push(()=>c.disconnect())}fo=K.scrollTop;let Ct=K.scrollHeight,Mt=()=>{let c=K.scrollTop,g=K.scrollHeight,h=g<Ct;Ct=g;let{action:y,nextLastScrollTop:P}=si({following:go.isFollowing(),currentScrollTop:c,lastScrollTop:fo,nearBottom:Os(K,as),userScrollThreshold:ra,isAutoScrolling:Wo||lr||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(fo=P,y==="resume"){Go();return}y==="pause"&&cs()};K.addEventListener("scroll",Mt,{passive:!0}),gt.push(()=>K.removeEventListener("scroll",Mt));let on=c=>{let g=ai({following:go.isFollowing(),deltaY:c.deltaY,nearBottom:Os(K,as),resumeWhenNearBottom:!0});g==="pause"?cs():g==="resume"&&Go()};K.addEventListener("wheel",on,{passive:!0}),gt.push(()=>K.removeEventListener("wheel",on)),Tt.addEventListener("click",()=>{K.scrollTop=K.scrollHeight,fo=K.scrollTop,Go(),Yo(!0)}),gt.push(()=>Tt.remove()),gt.push(()=>{ls()});let un=()=>{ze&&(jn&&(ze.removeEventListener("click",jn),jn=null),S()?(ze.style.display="",jn=()=>{Bt(!1,"user")},ze.addEventListener("click",jn)):ze.style.display="none")};un(),(()=>{let{clearChatButton:c}=Be;c&&c.addEventListener("click",()=>{T.clearMessages(),mo.clear(),Go(),Jr(Be.composerOverlay);try{localStorage.removeItem(es),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${es}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==es)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}d={},M.syncFromMetadata(),Y==null||Y.clear(),xe==null||xe.reset(),Se==null||Se.update()})})(),Nt&&Nt.addEventListener("submit",fs),pe==null||pe.addEventListener("keydown",bs),pe==null||pe.addEventListener("input",hs),pe==null||pe.addEventListener("paste",vs);let Yt=(jc=e.ownerDocument)!=null?jc:document;Yt.addEventListener("keydown",ys,!0);let so="persona-attachment-drop-active",ws=0,Ui=()=>{ws=0,ce.classList.remove(so)},Or=()=>{var c;return((c=o.attachments)==null?void 0:c.enabled)===!0&&et!==null},Zl=c=>{!Ei(c.dataTransfer)||!Or()||(ws++,ws===1&&ce.classList.add(so))},ec=c=>{!Ei(c.dataTransfer)||!Or()||(ws--,ws<=0&&Ui())},tc=c=>{!Ei(c.dataTransfer)||!Or()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},nc=c=>{var h;if(!Ei(c.dataTransfer)||!Or())return;c.preventDefault(),c.stopPropagation(),Ui();let g=Array.from((h=c.dataTransfer.files)!=null?h:[]);g.length!==0&&et.handleFiles(g)},tr=!0;ce.addEventListener("dragenter",Zl,tr),ce.addEventListener("dragleave",ec,tr),e.addEventListener("dragover",tc,tr),e.addEventListener("drop",nc,tr);let xa=e.ownerDocument,oc=c=>{Or()&&c.preventDefault()},rc=c=>{Or()&&c.preventDefault()};xa.addEventListener("dragover",oc),xa.addEventListener("drop",rc),gt.push(()=>{Nt&&Nt.removeEventListener("submit",fs),pe==null||pe.removeEventListener("keydown",bs),pe==null||pe.removeEventListener("input",hs),pe==null||pe.removeEventListener("paste",vs),Yt.removeEventListener("keydown",ys,!0)}),gt.push(()=>{ce.removeEventListener("dragenter",Zl,tr),ce.removeEventListener("dragleave",ec,tr),e.removeEventListener("dragover",tc,tr),e.removeEventListener("drop",nc,tr),xa.removeEventListener("dragover",oc),xa.removeEventListener("drop",rc),Ui()}),gt.push(()=>{T.cancel()}),Ie?gt.push(()=>{Ie==null||Ie.destroy()}):Ge&&gt.push(()=>{Ge==null||Ge.remove()});let Zt={update(c){var en,To,No,wa,Ca,Sa,br,Aa,Cs,Zc,ed,td,nd,od,rd,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,bd,yd,vd,xd,wd,Cd,Sd,Ad,Td,kd,Ed,Md,Ld,Id,Rd,Pd,Wd,Bd,Hd,Dd,Fd,Od,Nd,_d,Vd,$d,Ud,zd,qd,jd,Kd,Gd,Yd,Xd,Qd,Jd,Zd,ep,tp,np,op,rp,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,bp,yp,vp,xp,wp,Cp,Sp,Ap,Tp,kp,Ep,Mp,Lp,Ip,Rp,Pp,Wp,Bp,Hp,Dp,Fp,Op,Np,_p,Vp,$p,Up,zp,qp,jp,Kp,Gp;let g=o.toolCall,h=o.messageActions,y=(en=o.layout)==null?void 0:en.messages,P=o.colorScheme,N=o.loadingIndicator,V=o.iterationDisplay,z=(To=o.features)==null?void 0:To.showReasoning,O=(No=o.features)==null?void 0:No.showToolCalls,Ae=(wa=o.features)==null?void 0:wa.toolCallDisplay,ue=(Ca=o.features)==null?void 0:Ca.reasoningDisplay;o={...o,...c},po(),$r(e,o),Ti(e,o),ki(e,o),zn(),o.colorScheme!==P&&Ko();let ee=Bl.getForInstance(o.plugins);r.length=0,r.push(...ee),I=(br=(Sa=o.launcher)==null?void 0:Sa.enabled)!=null?br:!0,R=(Cs=(Aa=o.launcher)==null?void 0:Aa.autoExpand)!=null?Cs:!1,se=(ed=(Zc=o.features)==null?void 0:Zc.showReasoning)!=null?ed:!0,ge=(nd=(td=o.features)==null?void 0:td.showToolCalls)!=null?nd:!0,be=(rd=(od=o.features)==null?void 0:od.scrollToBottom)!=null?rd:{},zt(),Ho();let he=ie;if(ie=(ad=(sd=o.features)==null?void 0:sd.showEventStreamToggle)!=null?ad:!1,ie&&!he){if(Y||(J=new Xs(ve),Y=new Ys(Le,J),xe=xe!=null?xe:new Qs,J.open().then(()=>Y==null?void 0:Y.restore()).catch(()=>{}),T.setSSEEventCallback((Q,vt)=>{var Ot;(Ot=o.onSSEEvent)==null||Ot.call(o,Q,vt),xe==null||xe.processEvent(Q,vt),Y.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Q,timestamp:Date.now(),payload:JSON.stringify(vt)})})),!ut&&De){let Q=(ld=(id=o.features)==null?void 0:id.eventStream)==null?void 0:ld.classNames,vt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(Q!=null&&Q.toggleButton?" "+Q.toggleButton:"");ut=b("button",vt),ut.style.width="28px",ut.style.height="28px",ut.style.color=Mn.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let Ot=Te("activity","18px","currentColor",1.5);Ot&&ut.appendChild(Ot);let ct=Be.clearChatButtonWrapper,kt=Be.closeButtonWrapper,rn=ct||kt;rn&&rn.parentNode===De?De.insertBefore(ut,rn):De.appendChild(ut),ut.addEventListener("click",()=>{de?On():vn()})}}else!ie&&he&&(On(),ut&&(ut.remove(),ut=null),Y==null||Y.clear(),J==null||J.destroy(),Y=null,J=null,xe==null||xe.reset(),xe=null);if(((cd=o.launcher)==null?void 0:cd.enabled)===!1&&Ie&&(Ie.destroy(),Ie=null),((dd=o.launcher)==null?void 0:dd.enabled)===!1&&Ge&&(Ge.remove(),Ge=null),((pd=o.launcher)==null?void 0:pd.enabled)!==!1&&!Ie&&!Ge){let Q=r.find(vt=>vt.renderLauncher);if(Q!=null&&Q.renderLauncher){let vt=Q.renderLauncher({config:o,defaultRenderer:()=>qs(o,Ze).element,onToggle:Ze});vt&&(Ge=vt,e.appendChild(Ge))}Ge||(Ie=qs(o,Ze),e.appendChild(Ie.element))}Ie&&Ie.update(o),ke&&((ud=o.launcher)==null?void 0:ud.title)!==void 0&&(ke.textContent=o.launcher.title),He&&((md=o.launcher)==null?void 0:md.subtitle)!==void 0&&(He.textContent=o.launcher.subtitle);let Ee=(gd=o.layout)==null?void 0:gd.header;if((Ee==null?void 0:Ee.layout)!==v&&De){let Q=Ee?mi(o,Ee,{showClose:S(),onClose:()=>Bt(!1,"user")}):Ar({config:o,showClose:S(),onClose:()=>Bt(!1,"user")});De.replaceWith(Q.header),De=Q.header,_=Q.iconHolder,ke=Q.headerTitle,He=Q.headerSubtitle,ze=Q.closeButton,v=Ee==null?void 0:Ee.layout}else if(Ee&&(_&&(_.style.display=Ee.showIcon===!1?"none":""),ke&&(ke.style.display=Ee.showTitle===!1?"none":""),He&&(He.style.display=Ee.showSubtitle===!1?"none":""),ze&&(ze.style.display=Ee.showCloseButton===!1?"none":""),Be.clearChatButtonWrapper)){let Q=Ee.showClearChat;if(Q!==void 0){Be.clearChatButtonWrapper.style.display=Q?"":"none";let{closeButtonWrapper:vt}=Be;vt&&!vt.classList.contains("persona-absolute")&&(Q?vt.classList.remove("persona-ml-auto"):vt.classList.add("persona-ml-auto"))}}let tt=((fd=o.layout)==null?void 0:fd.showHeader)!==!1;De&&(De.style.display=tt?"":"none");let Ye=((hd=o.layout)==null?void 0:hd.showFooter)!==!1;Ve&&(Ve.style.display=Ye?"":"none"),bt(),Ho(),I!==B?I?Bt(R,"auto"):(E=!0,Zo()):R!==D&&Bt(R,"auto"),D=R,B=I,Rt(),un();let Pe=JSON.stringify(c.toolCall)!==JSON.stringify(g),Re=JSON.stringify(o.messageActions)!==JSON.stringify(h),qe=JSON.stringify((bd=o.layout)==null?void 0:bd.messages)!==JSON.stringify(y),L=((yd=o.loadingIndicator)==null?void 0:yd.render)!==(N==null?void 0:N.render)||((vd=o.loadingIndicator)==null?void 0:vd.renderIdle)!==(N==null?void 0:N.renderIdle)||((xd=o.loadingIndicator)==null?void 0:xd.showBubble)!==(N==null?void 0:N.showBubble),Me=o.iterationDisplay!==V,We=((Cd=(wd=o.features)==null?void 0:wd.showReasoning)!=null?Cd:!0)!==(z!=null?z:!0)||((Ad=(Sd=o.features)==null?void 0:Sd.showToolCalls)!=null?Ad:!0)!==(O!=null?O:!0)||JSON.stringify((Td=o.features)==null?void 0:Td.toolCallDisplay)!==JSON.stringify(Ae)||JSON.stringify((kd=o.features)==null?void 0:kd.reasoningDisplay)!==JSON.stringify(ue);(Pe||Re||qe||L||Me||We)&&T&&(ss++,dr(_e,T.getMessages(),me));let Ce=(Ed=o.launcher)!=null?Ed:{},Lt=(Md=Ce.headerIconHidden)!=null?Md:!1,st=(Id=(Ld=o.layout)==null?void 0:Ld.header)==null?void 0:Id.showIcon,Xt=Lt||st===!1,cn=Ce.headerIconName,Pt=(Rd=Ce.headerIconSize)!=null?Rd:"48px";if(_){let Q=ce.querySelector(".persona-border-b-persona-divider"),vt=Q==null?void 0:Q.querySelector(".persona-flex-col");if(Xt)_.style.display="none",Q&&vt&&!Q.contains(vt)&&Q.insertBefore(vt,Q.firstChild);else{if(_.style.display="",_.style.height=Pt,_.style.width=Pt,Q&&vt&&(Q.contains(_)?_.nextSibling!==vt&&(_.remove(),Q.insertBefore(_,vt)):Q.insertBefore(_,vt)),cn){let ct=parseFloat(Pt)||24,kt=Te(cn,ct*.6,"#ffffff",2);kt?_.replaceChildren(kt):_.textContent=(Pd=Ce.agentIconText)!=null?Pd:"\u{1F4AC}"}else if(Ce.iconUrl){let ct=_.querySelector("img");if(ct)ct.src=Ce.iconUrl,ct.style.height=Pt,ct.style.width=Pt;else{let kt=document.createElement("img");kt.src=Ce.iconUrl,kt.alt="",kt.className="persona-rounded-xl persona-object-cover",kt.style.height=Pt,kt.style.width=Pt,_.replaceChildren(kt)}}else{let ct=_.querySelector("svg"),kt=_.querySelector("img");(ct||kt)&&_.replaceChildren(),_.textContent=(Wd=Ce.agentIconText)!=null?Wd:"\u{1F4AC}"}let Ot=_.querySelector("img");Ot&&(Ot.style.height=Pt,Ot.style.width=Pt)}}let An=(Hd=(Bd=o.layout)==null?void 0:Bd.header)==null?void 0:Hd.showTitle,dn=(Fd=(Dd=o.layout)==null?void 0:Dd.header)==null?void 0:Fd.showSubtitle;if(ke&&(ke.style.display=An===!1?"none":""),He&&(He.style.display=dn===!1?"none":""),ze){((Nd=(Od=o.layout)==null?void 0:Od.header)==null?void 0:Nd.showCloseButton)===!1?ze.style.display="none":ze.style.display="";let vt=(_d=Ce.closeButtonSize)!=null?_d:"32px",Ot=(Vd=Ce.closeButtonPlacement)!=null?Vd:"inline";ze.style.height=vt,ze.style.width=vt;let{closeButtonWrapper:ct}=Be,kt=Ot==="top-right",rn=ct==null?void 0:ct.classList.contains("persona-absolute");if(ct&&kt!==rn)if(ct.remove(),kt)ct.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ce.style.position="relative",ce.appendChild(ct);else{let pt=(Ud=($d=Ce.clearChat)==null?void 0:$d.placement)!=null?Ud:"inline",sn=(qd=(zd=Ce.clearChat)==null?void 0:zd.enabled)!=null?qd:!0;ct.className=sn&&pt==="inline"?"":"persona-ml-auto";let Hn=ce.querySelector(".persona-border-b-persona-divider");Hn&&Hn.appendChild(ct)}if(ze.style.color=Ce.closeButtonColor||Mn.actionIconColor,Ce.closeButtonBackgroundColor?(ze.style.backgroundColor=Ce.closeButtonBackgroundColor,ze.classList.remove("hover:persona-bg-gray-100")):(ze.style.backgroundColor="",ze.classList.add("hover:persona-bg-gray-100")),Ce.closeButtonBorderWidth||Ce.closeButtonBorderColor){let pt=Ce.closeButtonBorderWidth||"0px",sn=Ce.closeButtonBorderColor||"transparent";ze.style.border=`${pt} solid ${sn}`,ze.classList.remove("persona-border-none")}else ze.style.border="",ze.classList.add("persona-border-none");Ce.closeButtonBorderRadius?(ze.style.borderRadius=Ce.closeButtonBorderRadius,ze.classList.remove("persona-rounded-full")):(ze.style.borderRadius="",ze.classList.add("persona-rounded-full")),Ce.closeButtonPaddingX?(ze.style.paddingLeft=Ce.closeButtonPaddingX,ze.style.paddingRight=Ce.closeButtonPaddingX):(ze.style.paddingLeft="",ze.style.paddingRight=""),Ce.closeButtonPaddingY?(ze.style.paddingTop=Ce.closeButtonPaddingY,ze.style.paddingBottom=Ce.closeButtonPaddingY):(ze.style.paddingTop="",ze.style.paddingBottom="");let gn=(jd=Ce.closeButtonIconName)!=null?jd:"x",yo=(Kd=Ce.closeButtonIconText)!=null?Kd:"\xD7";ze.innerHTML="";let En=Te(gn,"28px","currentColor",1);En?ze.appendChild(En):ze.textContent=yo;let Qt=(Gd=Ce.closeButtonTooltipText)!=null?Gd:"Close chat",Xn=(Yd=Ce.closeButtonShowTooltip)!=null?Yd:!0;if(ze.setAttribute("aria-label",Qt),ct&&(ct._cleanupTooltip&&(ct._cleanupTooltip(),delete ct._cleanupTooltip),Xn&&Qt)){let pt=null,sn=()=>{if(pt||!ze)return;let yr=ze.ownerDocument,Ss=yr.body;if(!Ss)return;pt=Eo(yr,"div","persona-clear-chat-tooltip"),pt.textContent=Qt;let As=Eo(yr,"div");As.className="persona-clear-chat-tooltip-arrow",pt.appendChild(As);let vr=ze.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(or),pt.style.left=`${vr.left+vr.width/2}px`,pt.style.top=`${vr.top-8}px`,pt.style.transform="translate(-50%, -100%)",Ss.appendChild(pt)},Hn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};ct.addEventListener("mouseenter",sn),ct.addEventListener("mouseleave",Hn),ze.addEventListener("focus",sn),ze.addEventListener("blur",Hn),ct._cleanupTooltip=()=>{Hn(),ct&&(ct.removeEventListener("mouseenter",sn),ct.removeEventListener("mouseleave",Hn)),ze&&(ze.removeEventListener("focus",sn),ze.removeEventListener("blur",Hn))}}}let{clearChatButton:Je,clearChatButtonWrapper:lt}=Be;if(Je){let Q=(Xd=Ce.clearChat)!=null?Xd:{},vt=(Qd=Q.enabled)!=null?Qd:!0,Ot=(Zd=(Jd=o.layout)==null?void 0:Jd.header)==null?void 0:Zd.showClearChat,ct=Ot!==void 0?Ot:vt,kt=(ep=Q.placement)!=null?ep:"inline";if(lt){lt.style.display=ct?"":"none";let{closeButtonWrapper:rn}=Be;!k()&&rn&&!rn.classList.contains("persona-absolute")&&(ct?rn.classList.remove("persona-ml-auto"):rn.classList.add("persona-ml-auto"));let gn=kt==="top-right",yo=lt.classList.contains("persona-absolute");if(!k()&&gn!==yo&&ct){if(lt.remove(),gn)lt.className="persona-absolute persona-top-4 persona-z-50",lt.style.right="48px",ce.style.position="relative",ce.appendChild(lt);else{lt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",lt.style.right="";let Qt=ce.querySelector(".persona-border-b-persona-divider"),Xn=Be.closeButtonWrapper;Qt&&Xn&&Xn.parentElement===Qt?Qt.insertBefore(lt,Xn):Qt&&Qt.appendChild(lt)}let En=Be.closeButtonWrapper;En&&!En.classList.contains("persona-absolute")&&(gn?En.classList.add("persona-ml-auto"):En.classList.remove("persona-ml-auto"))}}if(ct){if(!k()){let pt=(tp=Q.size)!=null?tp:"32px";Je.style.height=pt,Je.style.width=pt}let rn=(np=Q.iconName)!=null?np:"refresh-cw",gn=(op=Q.iconColor)!=null?op:"";Je.style.color=gn||Mn.actionIconColor,Je.innerHTML="";let yo=k()?"14px":"20px",En=Te(rn,yo,"currentColor",2);if(En&&Je.appendChild(En),Q.backgroundColor?(Je.style.backgroundColor=Q.backgroundColor,Je.classList.remove("hover:persona-bg-gray-100")):(Je.style.backgroundColor="",Je.classList.add("hover:persona-bg-gray-100")),Q.borderWidth||Q.borderColor){let pt=Q.borderWidth||"0px",sn=Q.borderColor||"transparent";Je.style.border=`${pt} solid ${sn}`,Je.classList.remove("persona-border-none")}else Je.style.border="",Je.classList.add("persona-border-none");Q.borderRadius?(Je.style.borderRadius=Q.borderRadius,Je.classList.remove("persona-rounded-full")):(Je.style.borderRadius="",Je.classList.add("persona-rounded-full")),Q.paddingX?(Je.style.paddingLeft=Q.paddingX,Je.style.paddingRight=Q.paddingX):(Je.style.paddingLeft="",Je.style.paddingRight=""),Q.paddingY?(Je.style.paddingTop=Q.paddingY,Je.style.paddingBottom=Q.paddingY):(Je.style.paddingTop="",Je.style.paddingBottom="");let Qt=(rp=Q.tooltipText)!=null?rp:"Clear chat",Xn=(sp=Q.showTooltip)!=null?sp:!0;if(Je.setAttribute("aria-label",Qt),lt&&(lt._cleanupTooltip&&(lt._cleanupTooltip(),delete lt._cleanupTooltip),Xn&&Qt)){let pt=null,sn=()=>{if(pt||!Je)return;let yr=Je.ownerDocument,Ss=yr.body;if(!Ss)return;pt=Eo(yr,"div","persona-clear-chat-tooltip"),pt.textContent=Qt;let As=Eo(yr,"div");As.className="persona-clear-chat-tooltip-arrow",pt.appendChild(As);let vr=Je.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(or),pt.style.left=`${vr.left+vr.width/2}px`,pt.style.top=`${vr.top-8}px`,pt.style.transform="translate(-50%, -100%)",Ss.appendChild(pt)},Hn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};lt.addEventListener("mouseenter",sn),lt.addEventListener("mouseleave",Hn),Je.addEventListener("focus",sn),Je.addEventListener("blur",Hn),lt._cleanupTooltip=()=>{Hn(),lt&&(lt.removeEventListener("mouseenter",sn),lt.removeEventListener("mouseleave",Hn)),Je&&(Je.removeEventListener("focus",sn),Je.removeEventListener("blur",Hn))}}}}let Tn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Dl],mn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Js.message,Js.messageAndClick];M=Fl({parsers:Tn,handlers:mn,getSessionMetadata:f,updateSessionMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),me=Dm(o,M,j),T.updateConfig(o),dr(_e,T.getMessages(),me),uo.render(o.suggestionChips,T,pe,void 0,o.suggestionChipsConfig),ms(),Br(T.isStreaming());let mr=((ap=o.voiceRecognition)==null?void 0:ap.enabled)===!0,gr=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),fr=((lp=(ip=o.voiceRecognition)==null?void 0:ip.provider)==null?void 0:lp.type)==="runtype";if(mr&&(gr||fr))if(!q||!_t){let Q=va(o.voiceRecognition,o.sendButton);Q&&(q=Q.micButton,_t=Q.micButtonWrapper,At.insertBefore(_t,Ln),q.addEventListener("click",X),q.disabled=T.isStreaming())}else{let Q=(cp=o.voiceRecognition)!=null?cp:{},vt=(dp=o.sendButton)!=null?dp:{},Ot=(pp=Q.iconName)!=null?pp:"mic",ct=(up=vt.size)!=null?up:"40px",kt=(mp=Q.iconSize)!=null?mp:ct,rn=parseFloat(kt)||24;q.style.width=kt,q.style.height=kt,q.style.minWidth=kt,q.style.minHeight=kt;let gn=(fp=(gp=Q.iconColor)!=null?gp:vt.textColor)!=null?fp:"currentColor";q.innerHTML="";let yo=Te(Ot,rn,gn,2);yo?q.appendChild(yo):q.textContent="\u{1F3A4}";let En=(hp=Q.backgroundColor)!=null?hp:vt.backgroundColor;En?q.style.backgroundColor=En:q.style.backgroundColor="",gn?q.style.color=gn:q.style.color="var(--persona-text, #111827)",Q.borderWidth?(q.style.borderWidth=Q.borderWidth,q.style.borderStyle="solid"):(q.style.borderWidth="",q.style.borderStyle=""),Q.borderColor?q.style.borderColor=Q.borderColor:q.style.borderColor="",Q.paddingX?(q.style.paddingLeft=Q.paddingX,q.style.paddingRight=Q.paddingX):(q.style.paddingLeft="",q.style.paddingRight=""),Q.paddingY?(q.style.paddingTop=Q.paddingY,q.style.paddingBottom=Q.paddingY):(q.style.paddingTop="",q.style.paddingBottom="");let Qt=_t==null?void 0:_t.querySelector(".persona-send-button-tooltip"),Xn=(bp=Q.tooltipText)!=null?bp:"Start voice recognition";if(((yp=Q.showTooltip)!=null?yp:!1)&&Xn)if(Qt)Qt.textContent=Xn,Qt.style.display="";else{let sn=document.createElement("div");sn.className="persona-send-button-tooltip",sn.textContent=Xn,_t==null||_t.insertBefore(sn,q)}else Qt&&(Qt.style.display="none");_t.style.display="",q.disabled=T.isStreaming()}else q&&_t&&(_t.style.display="none",((xp=(vp=o.voiceRecognition)==null?void 0:vp.provider)==null?void 0:xp.type)==="runtype"?T.isVoiceActive()&&T.toggleVoice():Gn&&bo());if(((wp=o.attachments)==null?void 0:wp.enabled)===!0)if(!Ft||!Qe){let Q=(Cp=o.attachments)!=null?Cp:{},Ot=(Ap=((Sp=o.sendButton)!=null?Sp:{}).size)!=null?Ap:"40px";fe||(fe=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),fe.style.display="none",Nt.insertBefore(fe,pe)),oe||(oe=document.createElement("input"),oe.type="file",oe.accept=((Tp=Q.allowedTypes)!=null?Tp:_o).join(","),oe.multiple=((kp=Q.maxFiles)!=null?kp:4)>1,oe.style.display="none",oe.setAttribute("aria-label","Attach files"),Nt.insertBefore(oe,pe)),Ft=b("div","persona-send-button-wrapper"),Qe=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Qe.type="button",Qe.setAttribute("aria-label",(Ep=Q.buttonTooltipText)!=null?Ep:"Attach file");let ct=(Mp=Q.buttonIconName)!=null?Mp:"paperclip",kt=Ot,rn=parseFloat(kt)||40,gn=Math.round(rn*.6);Qe.style.width=kt,Qe.style.height=kt,Qe.style.minWidth=kt,Qe.style.minHeight=kt,Qe.style.fontSize="18px",Qe.style.lineHeight="1",Qe.style.backgroundColor="transparent",Qe.style.color="var(--persona-primary, #111827)",Qe.style.border="none",Qe.style.borderRadius="6px",Qe.style.transition="background-color 0.15s ease",Qe.addEventListener("mouseenter",()=>{Qe.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Qe.addEventListener("mouseleave",()=>{Qe.style.backgroundColor="transparent"});let yo=Te(ct,gn,"currentColor",1.5);yo?Qe.appendChild(yo):Qe.textContent="\u{1F4CE}",Qe.addEventListener("click",Xn=>{Xn.preventDefault(),oe==null||oe.click()}),Ft.appendChild(Qe);let En=(Lp=Q.buttonTooltipText)!=null?Lp:"Attach file",Qt=b("div","persona-send-button-tooltip");Qt.textContent=En,Ft.appendChild(Qt),ot.append(Ft),!et&&oe&&fe&&(et=Ds.fromConfig(Q),et.setPreviewsContainer(fe),oe.addEventListener("change",async()=>{et&&(oe!=null&&oe.files)&&(await et.handleFileSelect(oe.files),oe.value="")})),ce.querySelector(".persona-attachment-drop-overlay")||ce.appendChild(Fm(Q.dropOverlay))}else{Ft.style.display="";let Q=(Ip=o.attachments)!=null?Ip:{};oe&&(oe.accept=((Rp=Q.allowedTypes)!=null?Rp:_o).join(","),oe.multiple=((Pp=Q.maxFiles)!=null?Pp:4)>1),et&&et.updateConfig({allowedTypes:Q.allowedTypes,maxFileSize:Q.maxFileSize,maxFiles:Q.maxFiles})}else Ft&&(Ft.style.display="none"),et&&et.clearAttachments(),(Wp=ce.querySelector(".persona-attachment-drop-overlay"))==null||Wp.remove();let qt=(Bp=o.sendButton)!=null?Bp:{},hr=(Hp=qt.useIcon)!=null?Hp:!1,nr=(Dp=qt.iconText)!=null?Dp:"\u2191",ht=qt.iconName,Pn=(Fp=qt.tooltipText)!=null?Fp:"Send message",Oo=(Op=qt.showTooltip)!=null?Op:!1,kn=(Np=qt.size)!=null?Np:"40px",Wn=qt.backgroundColor,Ht=qt.textColor;if(hr){if(ae.style.width=kn,ae.style.height=kn,ae.style.minWidth=kn,ae.style.minHeight=kn,ae.style.fontSize="18px",ae.style.lineHeight="1",ae.innerHTML="",Ht?ae.style.color=Ht:ae.style.color="var(--persona-button-primary-fg, #ffffff)",ht){let Q=parseFloat(kn)||24,vt=(Ht==null?void 0:Ht.trim())||"currentColor",Ot=Te(ht,Q,vt,2);Ot?ae.appendChild(Ot):ae.textContent=nr}else ae.textContent=nr;ae.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Wn?(ae.style.backgroundColor=Wn,ae.classList.remove("persona-bg-persona-primary")):(ae.style.backgroundColor="",ae.classList.add("persona-bg-persona-primary"))}else ae.textContent=(Vp=(_p=o.copy)==null?void 0:_p.sendButtonLabel)!=null?Vp:"Send",ae.style.width="",ae.style.height="",ae.style.minWidth="",ae.style.minHeight="",ae.style.fontSize="",ae.style.lineHeight="",ae.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Wn?(ae.style.backgroundColor=Wn,ae.classList.remove("persona-bg-persona-accent")):ae.classList.add("persona-bg-persona-accent"),Ht?ae.style.color=Ht:ae.classList.add("persona-text-white");qt.borderWidth?(ae.style.borderWidth=qt.borderWidth,ae.style.borderStyle="solid"):(ae.style.borderWidth="",ae.style.borderStyle=""),qt.borderColor?ae.style.borderColor=qt.borderColor:ae.style.borderColor="",qt.paddingX?(ae.style.paddingLeft=qt.paddingX,ae.style.paddingRight=qt.paddingX):(ae.style.paddingLeft="",ae.style.paddingRight=""),qt.paddingY?(ae.style.paddingTop=qt.paddingY,ae.style.paddingBottom=qt.paddingY):(ae.style.paddingTop="",ae.style.paddingBottom="");let Ut=Ln==null?void 0:Ln.querySelector(".persona-send-button-tooltip");if(Oo&&Pn)if(Ut)Ut.textContent=Pn,Ut.style.display="";else{let Q=document.createElement("div");Q.className="persona-send-button-tooltip",Q.textContent=Pn,Ln==null||Ln.insertBefore(Q,ae)}else Ut&&(Ut.style.display="none");let Dt=(jp=($p=o.layout)==null?void 0:$p.contentMaxWidth)!=null?jp:k()?(qp=(zp=(Up=o.launcher)==null?void 0:Up.composerBar)==null?void 0:zp.contentMaxWidth)!=null?qp:"720px":void 0;Dt?(_e.style.maxWidth=Dt,_e.style.marginLeft="auto",_e.style.marginRight="auto",_e.style.width="100%",Nt&&(Nt.style.maxWidth=Dt,Nt.style.marginLeft="auto",Nt.style.marginRight="auto"),Et&&(Et.style.maxWidth=Dt,Et.style.marginLeft="auto",Et.style.marginRight="auto")):(_e.style.maxWidth="",_e.style.marginLeft="",_e.style.marginRight="",_e.style.width="",Nt&&(Nt.style.maxWidth="",Nt.style.marginLeft="",Nt.style.marginRight=""),Et&&(Et.style.maxWidth="",Et.style.marginLeft="",Et.style.marginRight=""));let jt=(Kp=o.statusIndicator)!=null?Kp:{},Bn=(Gp=jt.visible)!=null?Gp:!0;if(ln.style.display=Bn?"":"none",T){let Q=T.getStatus();nt(ln,(Ot=>{var ct,kt,rn,gn;return Ot==="idle"?(ct=jt.idleText)!=null?ct:fn.idle:Ot==="connecting"?(kt=jt.connectingText)!=null?kt:fn.connecting:Ot==="connected"?(rn=jt.connectedText)!=null?rn:fn.connected:Ot==="error"?(gn=jt.errorText)!=null?gn:fn.error:fn[Ot]})(Q),jt,Q)}ln.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Yn=jt.align==="left"?"persona-text-left":jt.align==="center"?"persona-text-center":"persona-text-right";ln.classList.add(Yn)},open(){S()&&Bt(!0,"api")},close(){S()&&Bt(!1,"api")},toggle(){S()&&Bt(!E,"api")},clearChat(){xn=!1,T.clearMessages(),mo.clear(),Go();try{localStorage.removeItem(es),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${es}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==es)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let g=i.clear();g instanceof Promise&&g.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}d={},M.syncFromMetadata(),Y==null||Y.clear(),xe==null||xe.reset(),Se==null||Se.update()},setMessage(c){return!pe||T.isStreaming()?!1:(!E&&S()&&Bt(!0,"system"),pe.value=c,pe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(T.isStreaming())return!1;let g=(c==null?void 0:c.trim())||pe.value.trim();return g?(!E&&S()&&Bt(!0,"system"),pe.value="",pe.style.height="auto",T.sendMessage(g),!0):!1},startVoiceRecognition(){var g,h;return T.isStreaming()?!1:((h=(g=o.voiceRecognition)==null?void 0:g.provider)==null?void 0:h.type)==="runtype"?(T.isVoiceActive()||(!E&&S()&&Bt(!0,"system"),mt.manuallyDeactivated=!1,Rn(),T.toggleVoice().then(()=>{mt.active=T.isVoiceActive(),ro("user"),T.isVoiceActive()&&U()})),!0):Gn?!0:xs()?(!E&&S()&&Bt(!0,"system"),mt.manuallyDeactivated=!1,Rn(),ur("user"),!0):!1},stopVoiceRecognition(){var c,g;return((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?T.isVoiceActive()?(T.toggleVoice().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Rn(),ro("user"),G()}),!0):!1:Gn?(mt.manuallyDeactivated=!0,Rn(),bo("user"),!0):!1},injectMessage(c){return!E&&S()&&Bt(!0,"system"),T.injectMessage(c)},injectAssistantMessage(c){!E&&S()&&Bt(!0,"system");let g=T.injectAssistantMessage(c);return F&&(F=!1,$&&(clearTimeout($),$=null),setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)),g},injectUserMessage(c){return!E&&S()&&Bt(!0,"system"),T.injectUserMessage(c)},injectSystemMessage(c){return!E&&S()&&Bt(!0,"system"),T.injectSystemMessage(c)},injectMessageBatch(c){return!E&&S()&&Bt(!0,"system"),T.injectMessageBatch(c)},injectComponentDirective(c){return!E&&S()&&Bt(!0,"system"),T.injectComponentDirective(c)},injectTestMessage(c){!E&&S()&&Bt(!0,"system"),T.injectTestEvent(c)},async connectStream(c,g){return T.connectStream(c,g)},__pushEventStreamEvent(c){Y&&(xe==null||xe.processEvent(c.type,c.payload),Y.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!ie||!Y||vn()},hideEventStream(){de&&On()},isEventStreamVisible(){return de},showArtifacts(){co(o)&&(xn=!1,zn(),yt==null||yt.setMobileOpen(!0))},hideArtifacts(){co(o)&&(xn=!0,zn())},upsertArtifact(c){return co(o)?(xn=!1,T.upsertArtifact(c)):null},selectArtifact(c){co(o)&&T.selectArtifact(c)},clearArtifacts(){co(o)&&T.clearArtifacts()},getArtifacts(){var c;return(c=T==null?void 0:T.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=T==null?void 0:T.getSelectedArtifactId())!=null?c:null},focusInput(){return I&&!E&&!k()||!pe?!1:(pe.focus(),!0)},async resolveApproval(c,g){let y=T.getMessages().find(P=>{var N;return P.variant==="approval"&&((N=P.approval)==null?void 0:N.id)===c});if(!(y!=null&&y.approval))throw new Error(`Approval not found: ${c}`);if(y.approval.toolType==="webmcp"){T.resolveWebMcpApproval(y.id,g);return}return T.resolveApproval(y.approval,g)},getMessages(){return T.getMessages()},getStatus(){return T.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){u(c)},on(c,g){return s.on(c,g)},off(c,g){s.off(c,g)},isOpen(){return S()&&E},isVoiceActive(){return mt.active},getState(){return{open:S()&&E,launcherEnabled:I,voiceActive:mt.active,streaming:T.isStreaming()}},showCSATFeedback(c){!E&&S()&&Bt(!0,"system");let g=_e.querySelector(".persona-feedback-container");g&&g.remove();let h=Wm({onSubmit:async(y,P)=>{var N;T.isClientTokenMode()&&await T.submitCSATFeedback(y,P),(N=c==null?void 0:c.onSubmit)==null||N.call(c,y,P)},onDismiss:c==null?void 0:c.onDismiss,...c});_e.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!E&&S()&&Bt(!0,"system");let g=_e.querySelector(".persona-feedback-container");g&&g.remove();let h=Bm({onSubmit:async(y,P)=>{var N;T.isClientTokenMode()&&await T.submitNPSFeedback(y,P),(N=c==null?void 0:c.onSubmit)==null||N.call(c,y,P)},onDismiss:c==null?void 0:c.onDismiss,...c});_e.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,g){return T.submitCSATFeedback(c,g)},async submitNPSFeedback(c,g){return T.submitNPSFeedback(c,g)},destroy(){Ao!=null&&(clearInterval(Ao),Ao=null),gt.forEach(c=>c()),ye.remove(),$e==null||$e.remove(),Ie==null||Ie.destroy(),Ge==null||Ge.remove(),jn&&ze.removeEventListener("click",jn)}};if((((Kc=n==null?void 0:n.debugTools)!=null?Kc:!1)||!!o.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:Zt,getMessages:Zt.getMessages,getStatus:Zt.getStatus,getMetadata:Zt.getPersistentMetadata,updateMetadata:Zt.updatePersistentMetadata,clearHistory:()=>Zt.clearChat(),setVoiceActive:h=>h?Zt.startVoiceRecognition():Zt.stopVoiceRecognition()};window.AgentWidgetBrowser=g,gt.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&Zt.focusInput()};if(window.addEventListener("persona:focusInput",g),gt.push(()=>{window.removeEventListener("persona:focusInput",g)}),ie){let z=Ae=>{let ue=Ae.detail;(!(ue!=null&&ue.instanceId)||ue.instanceId===c)&&Zt.showEventStream()},O=Ae=>{let ue=Ae.detail;(!(ue!=null&&ue.instanceId)||ue.instanceId===c)&&Zt.hideEventStream()};window.addEventListener("persona:showEventStream",z),window.addEventListener("persona:hideEventStream",O),gt.push(()=>{window.removeEventListener("persona:showEventStream",z),window.removeEventListener("persona:hideEventStream",O)})}let h=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&Zt.showArtifacts()},y=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&Zt.hideArtifacts()},P=z=>{let O=z.detail;O!=null&&O.instanceId&&O.instanceId!==c||O!=null&&O.artifact&&Zt.upsertArtifact(O.artifact)},N=z=>{let O=z.detail;O!=null&&O.instanceId&&O.instanceId!==c||typeof(O==null?void 0:O.id)=="string"&&Zt.selectArtifact(O.id)},V=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&Zt.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",P),window.addEventListener("persona:selectArtifact",N),window.addEventListener("persona:clearArtifacts",V),gt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",P),window.removeEventListener("persona:selectArtifact",N),window.removeEventListener("persona:clearArtifacts",V)})}let ao=ox(o.persistState);if(ao&&S()){let c=rx(ao.storage),g=`${ao.keyPrefix}widget-open`,h=`${ao.keyPrefix}widget-voice`,y=`${ao.keyPrefix}widget-voice-mode`;if(c){let P=((Gc=ao.persist)==null?void 0:Gc.openState)&&c.getItem(g)==="true",N=((Yc=ao.persist)==null?void 0:Yc.voiceState)&&c.getItem(h)==="true",V=((Xc=ao.persist)==null?void 0:Xc.voiceState)&&c.getItem(y)==="true";if(P&&setTimeout(()=>{Zt.open(),setTimeout(()=>{var z;if(N||V)Zt.startVoiceRecognition();else if((z=ao.persist)!=null&&z.focusInput){let O=e.querySelector("textarea");O&&O.focus()}},100)},0),(Qc=ao.persist)!=null&&Qc.openState&&(s.on("widget:opened",()=>{c.setItem(g,"true")}),s.on("widget:closed",()=>{c.setItem(g,"false")})),(Jc=ao.persist)!=null&&Jc.voiceState&&(s.on("voice:state",z=>{c.setItem(h,z.active?"true":"false")}),s.on("user:message",z=>{c.setItem(y,z.viaVoice?"true":"false")})),ao.clearOnChatClear){let z=()=>{c.removeItem(g),c.removeItem(h),c.removeItem(y)},O=()=>z();window.addEventListener("persona:clear-chat",O),gt.push(()=>{window.removeEventListener("persona:clear-chat",O)})}}}return p&&S()&&setTimeout(()=>{Zt.open()},0),Do(),Zt};var sx=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},Nm=(e,t)=>{var o,r;let n=(r=(o=t==null?void 0:t.launcher)==null?void 0:o.enabled)!=null?r:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},$l=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},_m=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",$l(e)},Nl=e=>{e.style.transition=""},_l=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform=""},Vl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Mi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},ax=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},ix=(e,t,n,o,r,s)=>{let a=s?t:e;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},Vm=(e,t,n,o,r,s,a)=>{var w,C,M,I,R,H;let i=Mo(s),d=i.reveal==="push";ax(e,t,n,o,d),ix(e,t,n,o,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,p=(C=(w=s==null?void 0:s.launcher)==null?void 0:w.mobileFullscreen)!=null?C:!0,m=(I=(M=s==null?void 0:s.launcher)==null?void 0:M.mobileBreakpoint)!=null?I:640,f=l!=null?l.innerWidth<=m:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),_l(t),Nl(o),_m(o),Vl(n),Mi(r,o),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String((H=(R=s==null?void 0:s.launcher)==null?void 0:R.zIndex)!=null?H:hn),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),_m(o),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",_l(t),Nl(o),Vl(n),Mi(r,o);let D=i.animate?"transform 180ms ease":"none",B=i.side==="right"?"translateX(100%)":"translateX(-100%)",v=a?"translateX(0)":B;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=D,o.style.transform=v,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",i.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Nl(o),$l(o),Mi(r,o);let D=sx(i.width,e.clientWidth),B=Math.max(0,e.clientWidth),v=i.animate?"transform 180ms ease":"none",x=i.side==="right"?a?`translateX(-${D}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${D}px)`;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${B+D}px`,t.style.transition=v,t.style.transform=x,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${B}px`,n.style.maxWidth=`${B}px`,n.style.minWidth=`${B}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.position="relative",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",_l(t),$l(o),Vl(n),Mi(r,o);let D=i.reveal==="emerge";D?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let B=a?i.width:"0px",v=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",x=!a;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${B}`,o.style.width=B,o.style.maxWidth=B,o.style.minWidth=B,o.style.minHeight="0",o.style.position="relative",o.style.overflow=D||x?"hidden":"visible",o.style.transition=v,D&&(o.style.alignItems=i.side==="right"?"flex-start":"flex-end",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.boxSizing="border-box")}},lx=(e,t)=>{let n=e.ownerDocument.createElement("div");return Nm(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Nm(n,o)},destroy(){n.remove()}}},cx=(e,t)=>{var R,H,D,B;let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),p=n.createElement("div"),m=(H=(R=t==null?void 0:t.launcher)==null?void 0:R.enabled)==null||H?(B=(D=t==null?void 0:t.launcher)==null?void 0:D.autoExpand)!=null?B:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",l.appendChild(p),o.insertBefore(a,e),d.appendChild(e);let f=null,u=()=>{f==null||f.disconnect(),f=null},w=()=>{u(),Mo(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Vm(a,i,d,l,p,t,m)}),f.observe(a))},C=()=>{Vm(a,i,d,l,p,t,m),w()},M=a.ownerDocument.defaultView,I=()=>{C()};return M==null||M.addEventListener("resize",I),Mo(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),C(),{mode:"docked",host:p,shell:a,syncWidgetState(v){let x=v.launcherEnabled?v.open:!0;m!==x&&(m=x,C())},updateConfig(v){var x,k;t=v,((k=(x=t==null?void 0:t.launcher)==null?void 0:x.enabled)!=null?k:!0)===!1&&(m=!0),C()},destroy(){M==null||M.removeEventListener("resize",I),u(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},$m=(e,t)=>pn(t)?cx(e,t):lx(e,t);var ts={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Ul=.15,zl=1.5,Li="persona-preview-shell-theme",Um={load:()=>null,save:()=>{},clear:()=>{}},zm=["How do I get started?","Pricing & plans","Talk to support"];function Ii(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function qm(e){return e==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function ql(e){let t=qm(e);return`* { box-sizing: border-box; }
107
+ `}if(!y&&!c){let gt="max-height: -moz-available !important; max-height: stretch !important;",it=g?"":"padding-top: 1.25em !important;",kt=g?"":`z-index: ${(cn=(gn=o.launcher)==null?void 0:gn.zIndex)!=null?cn:wn} !important;`;Ae.style.cssText+=gt+it+kt}Qe()};bo(),Kr(e,o),Ri(e,o),Pi(e,o);let yt=[];yt.push(()=>{document.removeEventListener("keydown",Ko)});let Yt=null,Xt=null;yt.push(()=>{Yt==null||Yt(),Yt=null,Xt==null||Xt(),Xt=null}),_n&&yt.push(()=>{_n==null||_n.disconnect(),_n=null}),yt.push(()=>{kn==null||kn(),kn=null,Do(),Dt&&(Dt.remove(),Dt=null),St==null||St.element.style.removeProperty("width"),St==null||St.element.style.removeProperty("maxWidth")}),ke&&yt.push(()=>{Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),le==null||le.destroy(),le=null,K==null||K.destroy(),K=null,j=null});let qn=null,Xo=()=>{qn&&(qn(),qn=null),o.colorScheme==="auto"&&(qn=cu(()=>{Kr(e,o)}))};Xo(),yt.push(()=>{qn&&(qn(),qn=null)});let so=(Kc=o.features)==null?void 0:Kc.streamAnimation;if(so!=null&&so.type&&so.type!=="none"){let c=Gs(so.type,so.plugins);c&&(vl(c,e),yt.push(()=>tm(e)))}let yo=Em(Bt),jn=null,V,ao=!1,ve=Yu(),Kn=new Map,io=new Map,vo=new Map,us=0,xo=li(),wo=0,Co=null,Fo=!1,pr=!1,ua=4,ms=24,ma=80,Dr=new Map,bt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},gs=(Yc=(Gc=o.voiceRecognition)==null?void 0:Gc.autoResume)!=null?Yc:!1,lo=c=>{s.emit("voice:state",{active:bt.active,source:c,timestamp:Date.now()})},Wn=()=>{u(c=>({...c,voiceState:{active:bt.active,timestamp:Date.now(),manuallyDeactivated:bt.manuallyDeactivated}}))},ga=()=>{var y,M;if(((y=o.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=zl(d.voiceState),g=!!c.active,h=Number((M=c.timestamp)!=null?M:0);bt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-h<hx&&setTimeout(()=>{var F,O;bt.active||(bt.manuallyDeactivated=!1,((O=(F=o.voiceRecognition)==null?void 0:F.provider)==null?void 0:O.type)==="runtype"?V.toggleVoice().then(()=>{bt.active=V.isVoiceActive(),lo("restore"),V.isVoiceActive()&&R()}):fr("restore"))},1e3)},fa=()=>V?Xm(V.getMessages()).filter(c=>!c.__skipPersist):[];function Fr(c){if(!(i!=null&&i.save))return;let h={messages:c?Xm(c):V?fa():[],metadata:d,artifacts:Vn.artifacts,selectedArtifactId:Vn.selectedId};try{let y=i.save(h);y instanceof Promise&&y.catch(M=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",M)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let Oo=null,ha=()=>Ae.querySelector("#persona-scroll-container")||X,ur=()=>{Oo!==null&&(cancelAnimationFrame(Oo),Oo=null),Fo=!1},fs=()=>{Co!==null&&(cancelAnimationFrame(Co),Co=null),pr=!1,ur()},No=()=>{if(!Sn()||te){Pt.parentNode&&Pt.remove(),Pt.style.display="none";return}Pt.parentNode!==ue&&ue.appendChild(Pt),Ct();let c=qs(X)>0;Pt.style.display=xo.isFollowing()||!c?"none":""},hs=()=>{xo.pause()&&(fs(),No())},Qo=()=>{xo.resume(),No()},Jo=(c=!1)=>{xo.isFollowing()&&(!c&&!ao||(Co!==null&&(cancelAnimationFrame(Co),Co=null),pr=!0,Co=requestAnimationFrame(()=>{Co=null,pr=!1,xo.isFollowing()&&ba(ha(),c?220:140)})))},ba=(c,g=500)=>{let h=c.scrollTop,y=qs(c),M=y-h;if(Math.abs(M)<1){wo=c.scrollTop;return}if(Math.abs(M)>=ma){ur(),Fo=!0,c.scrollTop=y,wo=c.scrollTop,Fo=!1;return}ur();let F=performance.now();Fo=!0;let O=D=>1-Math.pow(1-D,3),z=D=>{if(!xo.isFollowing()){ur();return}let Te=qs(c);Te!==y&&(y=Te,M=y-h);let me=D-F,Z=Math.min(me/g,1),Se=O(Z),Le=h+M*Se;c.scrollTop=Le,wo=c.scrollTop,Z<1?Oo=requestAnimationFrame(z):(c.scrollTop=y,wo=c.scrollTop,Oo=null,Fo=!1)};Oo=requestAnimationFrame(z)},ya=c=>{let g=new Map;c.forEach(h=>{let y=Dr.get(h.id);g.set(h.id,{streaming:h.streaming,role:h.role}),!y&&h.role==="assistant"&&s.emit("assistant:message",h),h.role==="assistant"&&(y!=null&&y.streaming)&&h.streaming===!1&&s.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(y?h.approval.status!=="pending"&&s.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):s.emit("approval:requested",{approval:h.approval,message:h}))}),Dr.clear(),g.forEach((h,y)=>{Dr.set(y,h)})},mr=(c,g,h)=>{var dt,Pe,Re,qe,Qe,vt;let y=document.createElement("div"),F=(()=>{var De;let B=r.find(ne=>ne.renderLoadingIndicator);if(B!=null&&B.renderLoadingIndicator)return B.renderLoadingIndicator;if((De=o.loadingIndicator)!=null&&De.render)return o.loadingIndicator.render})(),O=(B,De)=>De==null?!1:typeof De=="string"?(B.textContent=De,!0):(B.appendChild(De),!0),z=new Set,D=new Set,Te=r.some(B=>B.renderAskUserQuestion),me=[],Z=[],Se=o.enableComponentStreaming!==!1,Le=r.some(B=>B.renderApproval)&&o.approval!==!1,Ve=[];if(g.forEach(B=>{var wt,Xn,on,uo,Qn,hr,zr,qr,Gt,br,rr,sr,$o,yr;z.add(B.id);let De=Te&&Lr(B),ne=Le&&B.variant==="approval"&&!!B.approval,et=!De&&B.role==="assistant"&&!B.variant&&Se&&jm(B);if(!ne&&vo.has(B.id)){let tt=c.querySelector(`#wrapper-${B.id}`);tt==null||tt.removeAttribute("data-preserve-runtime"),vo.delete(B.id)}if(!et&&io.has(B.id)){let tt=c.querySelector(`#wrapper-${B.id}`);tt==null||tt.removeAttribute("data-preserve-runtime"),io.delete(B.id)}let Nt=Lr(B)?`:${(wt=B.agentMetadata)!=null&&wt.askUserQuestionAnswered?"a":"u"}:${(Xn=B.agentMetadata)!=null&&Xn.askUserQuestionAnswers?Object.keys(B.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ot=Gu(B,us)+Nt,zt=De||ne||et?null:Xu(ve,B.id,Ot);if(zt){y.appendChild(zt.cloneNode(!0)),Lr(B)&&((on=B.toolCall)!=null&&on.id)&&((uo=B.agentMetadata)==null?void 0:uo.awaitingLocalTool)===!0&&!((Qn=B.agentMetadata)!=null&&Qn.askUserQuestionAnswered)&&(D.add(B.toolCall.id),ki(B,o,We.composerOverlay));return}let at=null,ln=r.find(tt=>!!(B.variant==="reasoning"&&tt.renderReasoning||B.variant==="tool"&&tt.renderToolCall||!B.variant&&tt.renderMessage)),Yn=(hr=o.layout)==null?void 0:hr.messages;if(Lr(B)&&((zr=B.agentMetadata)==null?void 0:zr.askUserQuestionAnswered)===!0){Kn.delete(B.id);let tt=c.querySelector(`#wrapper-${B.id}`);tt==null||tt.removeAttribute("data-preserve-runtime");return}if(Lr(B)&&((Gt=(qr=o.features)==null?void 0:qr.askUserQuestion)==null?void 0:Gt.enabled)!==!1){let tt=r.find(yn=>typeof yn.renderAskUserQuestion=="function");if(tt&&Mt.current){let yn=Kn.get(B.id),gn=yn!==Ot,cn=null;if(gn){let{payload:kt,complete:Bn}=os(B),Zt=B.id,Io=()=>{var rn;return(rn=Mt.current)==null?void 0:rn.getMessages().find(Mn=>Mn.id===Zt)};cn=tt.renderAskUserQuestion({message:B,payload:kt,complete:Bn,resolve:rn=>{var mo;let Mn=Io();Mn&&((mo=Mt.current)==null||mo.resolveAskUserQuestion(Mn,rn))},dismiss:()=>{var Mn,mo,vr;let rn=Io();(Mn=rn==null?void 0:rn.agentMetadata)!=null&&Mn.awaitingLocalTool&&((mo=Mt.current)==null||mo.markAskUserQuestionResolved(rn),(vr=Mt.current)==null||vr.resolveAskUserQuestion(rn,"(dismissed)"))},config:o})}let gt=yn!=null;if(gn&&cn===null&&!gt){((br=B.agentMetadata)==null?void 0:br.awaitingLocalTool)===!0&&!((rr=B.agentMetadata)!=null&&rr.askUserQuestionAnswered)&&(D.add(B.toolCall.id),ki(B,o,We.composerOverlay));return}let it=document.createElement("div");it.className="persona-flex",it.id=`wrapper-${B.id}`,it.setAttribute("data-wrapper-id",B.id),it.setAttribute("data-ask-plugin-stub","true"),it.setAttribute("data-preserve-runtime","true"),y.appendChild(it),me.push({messageId:B.id,fingerprint:Ot,bubble:cn});return}else{((sr=B.agentMetadata)==null?void 0:sr.awaitingLocalTool)===!0&&!(($o=B.agentMetadata)!=null&&$o.askUserQuestionAnswered)&&(D.add(B.toolCall.id),ki(B,o,We.composerOverlay));return}}else if(ne){let tt=r.find(gt=>typeof gt.renderApproval=="function"),gn=vo.get(B.id)!==Ot,cn=null;if(gn&&(tt!=null&&tt.renderApproval)){let gt=B.id,it=(kt,Bn)=>{var Io,rn,Mn;let Zt=(Io=Mt.current)==null?void 0:Io.getMessages().find(mo=>mo.id===gt);Zt!=null&&Zt.approval&&(Zt.approval.toolType==="webmcp"?(rn=Mt.current)==null||rn.resolveWebMcpApproval(Zt.id,kt):(Mn=Mt.current)==null||Mn.resolveApproval(Zt.approval,kt,Bn))};cn=tt.renderApproval({message:B,defaultRenderer:()=>Li(B,o),config:o,approve:kt=>it("approved",kt),deny:kt=>it("denied",kt)})}if(gn&&cn===null){let gt=c.querySelector(`#wrapper-${B.id}`);gt==null||gt.removeAttribute("data-preserve-runtime"),vo.delete(B.id),at=Li(B,o)}else{let gt=document.createElement("div");gt.className="persona-flex",gt.id=`wrapper-${B.id}`,gt.setAttribute("data-wrapper-id",B.id),gt.setAttribute("data-approval-plugin-stub","true"),gt.setAttribute("data-preserve-runtime","true"),y.appendChild(gt),Ve.push({messageId:B.id,fingerprint:Ot,bubble:cn});return}}else if(ln)if(B.variant==="reasoning"&&B.reasoning&&ln.renderReasoning){if(!ge)return;at=ln.renderReasoning({message:B,defaultRenderer:()=>kl(B,o),config:o})}else if(B.variant==="tool"&&B.toolCall&&ln.renderToolCall){if(!se)return;at=ln.renderToolCall({message:B,defaultRenderer:()=>El(B,o),config:o})}else ln.renderMessage&&(at=ln.renderMessage({message:B,defaultRenderer:()=>{let tt=Tl(B,h,Yn,o.messageActions,ee,{loadingIndicatorRenderer:F,widgetConfig:o});return B.role!=="user"&&Ol(tt,B,o,V),tt},config:o}));if(!at&&et){let tt=Km(B);if(tt){let yn=io.get(B.id),gn=yn!==Ot,cn=o.wrapComponentDirectiveInBubble!==!1,gt=null;if(gn){let it=zm(tt,{config:o,message:B,transform:h});if(it)if(cn){let kt=document.createElement("div");if(kt.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),kt.id=`bubble-${B.id}`,kt.setAttribute("data-message-id",B.id),B.content&&B.content.trim()){let Bn=document.createElement("div");Bn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Bn.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),kt.appendChild(Bn)}kt.appendChild(it),gt=kt}else{let kt=document.createElement("div");if(kt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",kt.id=`bubble-${B.id}`,kt.setAttribute("data-message-id",B.id),kt.setAttribute("data-persona-component-directive","true"),B.content&&B.content.trim()){let Bn=document.createElement("div");Bn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Bn.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),kt.appendChild(Bn)}kt.appendChild(it),gt=kt}}if(gt||yn!=null){let it=document.createElement("div");it.className="persona-flex",it.id=`wrapper-${B.id}`,it.setAttribute("data-wrapper-id",B.id),it.setAttribute("data-component-directive-stub","true"),it.setAttribute("data-preserve-runtime","true"),cn||it.classList.add("persona-w-full"),y.appendChild(it),Z.push({messageId:B.id,fingerprint:Ot,bubble:gt});return}}}if(!at)if(B.variant==="reasoning"&&B.reasoning){if(!ge)return;at=kl(B,o)}else if(B.variant==="tool"&&B.toolCall){if(!se)return;at=El(B,o)}else if(B.variant==="approval"&&B.approval){if(o.approval===!1)return;at=Li(B,o)}else{let tt=(yr=o.layout)==null?void 0:yr.messages;tt!=null&&tt.renderUserMessage&&B.role==="user"?at=tt.renderUserMessage({message:B,config:o,streaming:!!B.streaming}):tt!=null&&tt.renderAssistantMessage&&B.role==="assistant"?at=tt.renderAssistantMessage({message:B,config:o,streaming:!!B.streaming}):at=Tl(B,h,tt,o.messageActions,ee,{loadingIndicatorRenderer:F,widgetConfig:o}),B.role!=="user"&&at&&Ol(at,B,o,V)}let Ke=document.createElement("div");Ke.className="persona-flex",Ke.id=`wrapper-${B.id}`,Ke.setAttribute("data-wrapper-id",B.id),B.role==="user"&&Ke.classList.add("persona-justify-end"),(at==null?void 0:at.getAttribute("data-persona-component-directive"))==="true"&&Ke.classList.add("persona-w-full"),Ke.appendChild(at),Qu(ve,B.id,Ot,Ke),y.appendChild(Ke)}),We.composerOverlay&&We.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(De=>{let ne=De.getAttribute("data-persona-ask-sheet-for");ne&&!D.has(ne)&&ss(We.composerOverlay,ne)}),(Pe=(dt=o.features)==null?void 0:dt.toolCallDisplay)!=null&&Pe.grouped){let B=[],De=[];g.forEach(ne=>{if(ne.variant==="tool"&&ne.toolCall&&se){De.push(ne);return}De.length>1&&B.push(De),De=[]}),De.length>1&&B.push(De),B.forEach((ne,et)=>{var wt,Xn;let Nt=ne.map(on=>Array.from(y.children).find(uo=>uo instanceof HTMLElement&&uo.getAttribute("data-wrapper-id")===on.id)).filter(on=>!!on);if(Nt.length<2)return;let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id=`wrapper-tool-group-${et}-${ne[0].id}`,Ot.setAttribute("data-wrapper-id",`tool-group-${et}-${ne[0].id}`);let zt=document.createElement("div");zt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",zt.setAttribute("data-persona-tool-group","true");let at=document.createElement("div");at.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let ln=`Called ${ne.length} tools`,Yn=(Xn=(wt=o.toolCall)==null?void 0:wt.renderGroupedSummary)==null?void 0:Xn.call(wt,{messages:ne,toolCalls:ne.map(on=>on.toolCall).filter(on=>!!on),defaultSummary:ln,config:o});O(at,Yn)||(at.textContent=ln);let Ke=document.createElement("div");Ke.className="persona-tool-group-stack persona-flex persona-flex-col",zt.append(at,Ke),Ot.appendChild(zt),Nt[0].before(Ot),Nt.forEach((on,uo)=>{let Qn=document.createElement("div");Qn.className="persona-tool-group-item persona-relative",Qn.setAttribute("data-persona-tool-group-item","true"),uo<Nt.length-1&&Qn.setAttribute("data-persona-tool-group-connector","true"),Qn.appendChild(on),Ke.appendChild(Qn)})})}Ju(ve,z);let ot=g.some(B=>B.role==="assistant"&&B.streaming),je=g[g.length-1],mt=(je==null?void 0:je.role)==="assistant"&&!je.streaming&&je.variant!=="approval";if(ao&&g.some(B=>B.role==="user")&&!ot&&!mt){let B={config:o,streaming:!0,location:"standalone",defaultRenderer:ta},De=r.find(et=>et.renderLoadingIndicator),ne=null;if(De!=null&&De.renderLoadingIndicator&&(ne=De.renderLoadingIndicator(B)),ne===null&&((Re=o.loadingIndicator)!=null&&Re.render)&&(ne=o.loadingIndicator.render(B)),ne===null&&(ne=ta()),ne){let et=document.createElement("div"),Nt=((qe=o.loadingIndicator)==null?void 0:qe.showBubble)!==!1;et.className=Nt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),et.setAttribute("data-typing-indicator","true"),et.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",et.appendChild(ne);let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id="wrapper-typing-indicator",Ot.setAttribute("data-wrapper-id","typing-indicator"),Ot.appendChild(et),y.appendChild(Ot)}}if(!ao&&g.length>0){let B=g[g.length-1],De={config:o,lastMessage:B,messageCount:g.length},ne=r.find(Nt=>Nt.renderIdleIndicator),et=null;if(ne!=null&&ne.renderIdleIndicator&&(et=ne.renderIdleIndicator(De)),et===null&&((Qe=o.loadingIndicator)!=null&&Qe.renderIdle)&&(et=o.loadingIndicator.renderIdle(De)),et){let Nt=document.createElement("div"),Ot=((vt=o.loadingIndicator)==null?void 0:vt.showBubble)!==!1;Nt.className=Ot?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Nt.setAttribute("data-idle-indicator","true"),Nt.appendChild(et);let zt=document.createElement("div");zt.className="persona-flex",zt.id="wrapper-idle-indicator",zt.setAttribute("data-wrapper-id","idle-indicator"),zt.appendChild(Nt),y.appendChild(zt)}}if(ai(c,y),me.length>0)for(let{messageId:B,fingerprint:De,bubble:ne}of me){let et=c.querySelector(`#wrapper-${B}`);et&&ne!==null&&(et.replaceChildren(ne),et.setAttribute("data-bubble-fp",De),Kn.set(B,De))}if(Kn.size>0)for(let B of Kn.keys())z.has(B)||Kn.delete(B);if(Z.length>0)for(let{messageId:B,fingerprint:De,bubble:ne}of Z){let et=c.querySelector(`#wrapper-${B}`);et&&ne!==null&&(et.replaceChildren(ne),et.setAttribute("data-bubble-fp",De),io.set(B,De))}if(io.size>0)for(let B of io.keys())z.has(B)||io.delete(B);if(Ve.length>0)for(let{messageId:B,fingerprint:De,bubble:ne}of Ve){let et=c.querySelector(`#wrapper-${B}`);et&&ne!==null&&(et.replaceChildren(ne),et.setAttribute("data-bubble-fp",De),vo.set(B,De))}if(vo.size>0)for(let B of vo.keys())z.has(B)||vo.delete(B)},Zo=null,va=()=>{var h;if(Zo)return;let c=y=>{let M=y.composedPath();M.includes(Ae)||$e&&M.includes($e)||Ft(!1,"user")};Zo=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},bs=()=>{var g;if(!Zo)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("pointerdown",Zo,!0),Zo=null};yt.push(()=>bs());let er=null,xa=()=>{var h;if(er)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Ft(!1,"user"))};er=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},ys=()=>{var g;if(!er)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("keydown",er,!0),er=null};yt.push(()=>ys());let tr=!1,vs=new Set,wa=()=>{var g,h,y,M;let c=(y=(h=(g=o.launcher)==null?void 0:g.composerBar)==null?void 0:h.peek)==null?void 0:y.streamAnimation;return c||((M=o.features)==null?void 0:M.streamAnimation)},_o=()=>{var mt,dt,Pe,Re;if(!k())return;let c=We.peekBanner,g=We.peekTextNode;if(!c||!g)return;if(A){c.classList.remove("persona-pill-peek--visible");return}let h=(mt=V==null?void 0:V.getMessages())!=null?mt:[],y;for(let qe=h.length-1;qe>=0;qe--){let Qe=h[qe];if(Qe.role==="assistant"&&Qe.content){y=Qe;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let M=y.content,F=!!y.streaming,O=wa(),z=pi(O),D=z.type!=="none"?Gs(z.type,O==null?void 0:O.plugins):null,Te=((dt=D==null?void 0:D.isAnimating)==null?void 0:dt.call(D,y))===!0,me=D!==null&&(F||Te);me&&D&&!vs.has(D.name)&&(vl(D,e),vs.add(D.name));let Z=me&&(D!=null&&D.containerClass)?D.containerClass:null,Se=(Pe=g.dataset.personaPeekStreamClass)!=null?Pe:null;Se&&Se!==Z&&(g.classList.remove(Se),delete g.dataset.personaPeekStreamClass),Z&&Se!==Z&&(g.classList.add(Z),g.dataset.personaPeekStreamClass=Z),me?(g.style.setProperty("--persona-stream-step",`${z.speed}ms`),g.style.setProperty("--persona-stream-duration",`${z.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Le=me?ui(M,z.buffer,D,y,F):M;if(me&&z.placeholder==="skeleton"&&F&&(!Le||!Le.trim())){let qe=document.createElement("div"),Qe=Xs();Qe.classList.add("persona-pill-peek__skeleton"),qe.appendChild(Qe),ai(g,qe)}else{let qe=Math.max(0,Le.length-100),Qe=Le.length>100?Le.slice(-100):Le,vt=Ds(Qe);if(!me||!D){let B=Le.length>100?`\u2026${Qe}`:Qe;g.textContent!==B&&(g.textContent=B)}else{let B=vt;(D.wrap==="char"||D.wrap==="word")&&(B=Ys(vt,D.wrap,`peek-${y.id}`,{skipTags:D.skipTags,startIndex:qe}));let De=document.createElement("div");if(De.innerHTML=B,D.useCaret&&Qe.length>0){let ne=mi(),et=De.querySelectorAll(".persona-stream-char, .persona-stream-word"),Nt=et[et.length-1];Nt!=null&&Nt.parentNode?Nt.parentNode.insertBefore(ne,Nt.nextSibling):De.appendChild(ne)}ai(g,De),(Re=D.onAfterRender)==null||Re.call(D,{container:g,bubble:c,messageId:y.id,message:y,speed:z.speed,duration:z.duration})}}let je=ao||tr;c.classList.toggle("persona-pill-peek--visible",je)};if(k()){let c=We.peekBanner;if(c){let y=M=>{M.preventDefault(),M.stopPropagation(),Ft(!0,"user")};c.addEventListener("pointerdown",y),yt.push(()=>{c.removeEventListener("pointerdown",y)})}let g=()=>{tr||(tr=!0,_o())},h=()=>{tr&&(tr=!1,_o())};pe.addEventListener("pointerenter",g),pe.addEventListener("pointerleave",h),yt.push(()=>{pe.removeEventListener("pointerenter",g),pe.removeEventListener("pointerleave",h)}),$e&&($e.addEventListener("pointerenter",g),$e.addEventListener("pointerleave",h),yt.push(()=>{$e.removeEventListener("pointerenter",g),$e.removeEventListener("pointerleave",h)}))}let Ca=c=>{var Se,Le,Ve,ot,je,mt,dt,Pe;let g=(Le=(Se=o.launcher)==null?void 0:Se.composerBar)!=null?Le:{},h=(Ve=g.expandedSize)!=null?Ve:"anchored",y=(ot=g.bottomOffset)!=null?ot:"16px",M=g.collapsedMaxWidth,F=(je=g.expandedMaxWidth)!=null?je:"880px",O=(mt=g.expandedTopOffset)!=null?mt:"5vh",z=(dt=g.modalMaxWidth)!=null?dt:"880px",D=(Pe=g.modalMaxHeight)!=null?Pe:"min(90vh, 800px)",Te="calc(100vw - 32px)",me="var(--persona-pill-area-height, 80px)",Z=Ae.style;if(Z.left="",Z.right="",Z.top="",Z.bottom="",Z.transform="",Z.width="",Z.maxWidth="",Z.height="",Z.maxHeight="",$e){let Re=$e.style;Re.bottom=y,Re.width=M!=null?M:""}if(c&&h!=="fullscreen"){if(h==="modal"){Z.top="50%",Z.left="50%",Z.transform="translate(-50%, -50%)",Z.bottom="auto",Z.right="auto",Z.width=z,Z.maxWidth=Te,Z.maxHeight=D,Z.height=D;return}Z.left="50%",Z.transform="translateX(-50%)",Z.bottom=`calc(${y} + ${me})`,Z.top=O,Z.width=F,Z.maxWidth=Te}},nr=()=>{var D,Te,me,Z,Se,Le,Ve,ot;if(!S())return;if(k()){let mt=(me=((Te=(D=o.launcher)==null?void 0:D.composerBar)!=null?Te:{}).expandedSize)!=null?me:"anchored",dt=A?"expanded":"collapsed";Ae.dataset.state=dt,Ae.dataset.expandedSize=mt,$e&&($e.dataset.state=dt,$e.dataset.expandedSize=mt),Ae.style.removeProperty("display"),Ae.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Ca(A),ue.style.display=A?"flex":"none",bo(),A?(va(),xa()):(bs(),ys()),_o();return}let c=hn(o),g=(Z=e.ownerDocument.defaultView)!=null?Z:window,h=(Le=(Se=o.launcher)==null?void 0:Se.mobileBreakpoint)!=null?Le:640,y=(ot=(Ve=o.launcher)==null?void 0:Ve.mobileFullscreen)!=null?ot:!0,M=g.innerWidth<=h,F=y&&M&&L,O=Wo(o).reveal;A?(Ae.style.removeProperty("display"),Ae.style.display=c?"flex":"",Ae.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-95","persona-opacity-0"),pe.classList.add("persona-scale-100","persona-opacity-100"),Xe?Xe.element.style.display="none":Ze&&(Ze.style.display="none")):(c?c&&(O==="overlay"||O==="push")&&!F?(Ae.style.removeProperty("display"),Ae.style.display="flex",Ae.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ae.style.setProperty("display","none","important"),Ae.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ae.style.display="",Ae.classList.add("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-100","persona-opacity-100"),pe.classList.add("persona-scale-95","persona-opacity-0")),Xe?Xe.element.style.display=c?"none":"":Ze&&(Ze.style.display=c?"none":""))},Ft=(c,g="user")=>{var F,O;if(!S()||A===c)return;let h=A;A=c,nr();let y=(()=>{var Ve,ot,je,mt,dt,Pe,Re,qe,Qe,vt;let z=(ot=(Ve=o.launcher)==null?void 0:Ve.sidebarMode)!=null?ot:!1,D=(je=e.ownerDocument.defaultView)!=null?je:window,Te=(dt=(mt=o.launcher)==null?void 0:mt.mobileFullscreen)!=null?dt:!0,me=(Re=(Pe=o.launcher)==null?void 0:Pe.mobileBreakpoint)!=null?Re:640,Z=D.innerWidth<=me,Se=hn(o)&&Te&&Z,Le=k()&&((vt=(Qe=(qe=o.launcher)==null?void 0:qe.composerBar)==null?void 0:Qe.expandedSize)!=null?vt:"fullscreen")==="fullscreen";return z||Te&&Z&&L||Se||Le})();if(A&&y){if(!Yt){let z=e.getRootNode(),D=z instanceof ShadowRoot?z.host:e.closest(".persona-host");D&&(Yt=xl(D,(O=(F=o.launcher)==null?void 0:F.zIndex)!=null?O:wn))}Xt||(Xt=wl(e.ownerDocument))}else A||(Yt==null||Yt(),Yt=null,Xt==null||Xt(),Xt=null);A&&(Qt(),Jo(!0));let M={open:A,source:g,timestamp:Date.now()};A&&!h?s.emit("widget:opened",M):!A&&h&&s.emit("widget:closed",M),s.emit("widget:state",{open:A,launcherEnabled:L,voiceActive:bt.active,streaming:V.isStreaming()})},Or=c=>{qt(c?"stop":"send"),q&&(q.disabled=c),yo.buttons.forEach(g=>{g.disabled=c}),_e.dataset.personaComposerStreaming=c?"true":"false",_e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=c)})},Nr=()=>{bt.active||he&&he.focus()};s.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Nr(),200)});let xs=()=>{var h,y,M,F,O,z,D,Te,me,Z,Se;Dn.textContent=(y=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",eo.textContent=(F=(M=o.copy)==null?void 0:M.welcomeSubtitle)!=null?F:"Ask anything about your account or products.",he.placeholder=(z=(O=o.copy)==null?void 0:O.inputPlaceholder)!=null?z:"How can I help...";let c=X.querySelector("[data-persona-intro-card]");if(c){let Le=((D=o.copy)==null?void 0:D.showWelcomeCard)!==!1;c.style.display=Le?"":"none",Le?(X.classList.remove("persona-gap-3"),X.classList.add("persona-gap-6")):(X.classList.remove("persona-gap-6"),X.classList.add("persona-gap-3"))}!((me=(Te=o.sendButton)==null?void 0:Te.useIcon)!=null&&me)&&!(V!=null&&V.isStreaming())&&(ce.textContent=(Se=(Z=o.copy)==null?void 0:Z.sendButtonLabel)!=null?Se:"Send"),he.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',he.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{u(g=>({...g,sessionId:c}))}});let Lo=null,Sa=()=>{Lo==null&&(Lo=setInterval(()=>{let c=Ne.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Lo),Lo=null;return}let g=Date.now();c.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=Ga(g-y))})},100))};if(V=new ri(o,{onMessagesChanged(c){mr(Ne,c,fe),Sa(),V&&(c.some(M=>M.role==="user")?yo.render([],V,he,c):yo.render(o.suggestionChips,V,he,c,o.suggestionChipsConfig)),Jo(!ao),ya(c);let g=[...c].reverse().find(y=>y.role==="user"),h=bt.lastUserMessageId;g&&g.id!==h&&(bt.lastUserMessageId=g.id,s.emit("user:message",g)),bt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),Fr(c),_o()},onStatusChanged(c){var y;let g=(y=o.statusIndicator)!=null?y:{};rt(mn,(M=>{var F,O,z,D;return M==="idle"?(F=g.idleText)!=null?F:xn.idle:M==="connecting"?(O=g.connectingText)!=null?O:xn.connecting:M==="connected"?(z=g.connectedText)!=null?z:xn.connected:M==="error"?(D=g.errorText)!=null?D:xn.error:xn[M]})(c),g,c)},onStreamingChanged(c){ao=c,Or(c),V&&mr(Ne,V.getMessages(),fe),c||Jo(!0),_o()},onVoiceStatusChanged(c){var g,h;if(((h=(g=o.voiceRecognition)==null?void 0:g.provider)==null?void 0:h.type)==="runtype")switch(c){case"listening":break;case"processing":Y(),J();break;case"speaking":Y(),ie();break;default:c==="idle"&&V.isBargeInActive()?(Y(),R(),q==null||q.setAttribute("aria-label","End voice session")):(bt.active=!1,Y(),lo("system"),Wn());break}},onArtifactsState(c){Vn=c,zn(),Fr()}}),Mt.current=V,((Qc=(Xc=o.voiceRecognition)==null?void 0:Xc.provider)==null?void 0:Qc.type)==="runtype")try{V.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}o.clientToken&&V.initClientSession().catch(c=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(K||o.onSSEEvent)&&V.setSSEEventCallback((c,g)=>{var h;(h=o.onSSEEvent)==null||h.call(o,c,g),ye==null||ye.processEvent(c,g),K==null||K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(g)})}),l&&l.then(c=>{var g,h,y;c&&(c.metadata&&(d=zl(c.metadata),E.syncFromMetadata()),(g=c.messages)!=null&&g.length&&V.hydrateMessages(c.messages),(h=c.artifacts)!=null&&h.length&&V.hydrateArtifacts(c.artifacts,(y=c.selectedArtifactId)!=null?y:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let ws=()=>{var g,h,y;!k()||A||!((y=(h=(g=o.launcher)==null?void 0:g.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||Ft(!0,"auto")},Cs=c=>{var M;if(c.preventDefault(),V.isStreaming()){V.cancel(),ye==null||ye.reset(),le==null||le.update();return}let g=he.value.trim(),h=(M=nt==null?void 0:nt.hasAttachments())!=null?M:!1;if(!g&&!h)return;ws();let y;h&&(y=[],y.push(...nt.getContentParts()),g&&y.push(fl(g))),he.value="",he.style.height="auto",gr(),V.sendMessage(g,{contentParts:y}),h&&nt.clearAttachments()},Aa=()=>{var c;return((c=o.features)==null?void 0:c.composerHistory)!==!1},_r={...ii},Vr=!1,gr=()=>{_r={...ii}},Ta=()=>V.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),ka=c=>{if(!he)return;Vr=!0,he.value=c,he.dispatchEvent(new Event("input",{bubbles:!0})),Vr=!1;let g=he.value.length;he.setSelectionRange(g,g)},Ss=()=>{Vr||gr()},As=c=>{if(he){if(Aa()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=he.selectionStart===0&&he.selectionEnd===0,h=Ku({direction:c.key==="ArrowUp"?"up":"down",history:Ta(),currentValue:he.value,atStart:g,state:_r});if(_r=h.state,h.handled){c.preventDefault(),h.value!==void 0&&ka(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(V.isStreaming()){c.preventDefault();return}gr(),c.preventDefault(),ce.click()}}},Ts=c=>{c.key!=="Escape"||c.isComposing||V.isStreaming()&&c.composedPath().includes(ue)&&(V.cancel(),ye==null||ye.reset(),le==null||le.update(),gr(),c.preventDefault(),c.stopImmediatePropagation())},ks=async c=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!nt)return;let g=yx(c.clipboardData);g.length!==0&&(c.preventDefault(),await nt.handleFiles(g))},En=null,Gn=!1,Vo=null,lt=null,Es=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,fr=(c="user")=>{var F,O,z,D,Te,me,Z;if(Gn||V.isStreaming())return;let g=Es();if(!g)return;En=new g;let y=(O=((F=o.voiceRecognition)!=null?F:{}).pauseDuration)!=null?O:2e3;En.continuous=!0,En.interimResults=!0,En.lang="en-US";let M=he.value;En.onresult=Se=>{let Le="",Ve="";for(let je=0;je<Se.results.length;je++){let mt=Se.results[je],dt=mt[0].transcript;mt.isFinal?Le+=dt+" ":Ve=dt}let ot=M+Le+Ve;he.value=ot,Vo&&clearTimeout(Vo),(Le||Ve)&&(Vo=window.setTimeout(()=>{let je=he.value.trim();je&&En&&Gn&&(So(),he.value="",he.style.height="auto",V.sendMessage(je,{viaVoice:!0}))},y))},En.onerror=Se=>{Se.error!=="no-speech"&&So()},En.onend=()=>{if(Gn){let Se=he.value.trim();Se&&Se!==M.trim()&&(he.value="",he.style.height="auto",V.sendMessage(Se,{viaVoice:!0})),So()}};try{if(En.start(),Gn=!0,bt.active=!0,c!=="system"&&(bt.manuallyDeactivated=!1),lo(c),Wn(),q){let Se=(z=o.voiceRecognition)!=null?z:{};lt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(D=Se.iconName)!=null?D:"mic",iconSize:parseFloat((Z=(me=Se.iconSize)!=null?me:(Te=o.sendButton)==null?void 0:Te.size)!=null?Z:"40")||24};let Le=Se.recordingBackgroundColor,Ve=Se.recordingIconColor,ot=Se.recordingBorderColor;if(q.classList.add("persona-voice-recording"),q.style.backgroundColor=Le!=null?Le:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=Ve!=null?Ve:"var(--persona-voice-recording-indicator, #ffffff)",Ve){let je=q.querySelector("svg");je&&je.setAttribute("stroke",Ve)}ot&&(q.style.borderColor=ot),q.setAttribute("aria-label","Stop voice recognition")}}catch{So("system")}},So=(c="user")=>{if(Gn){if(Gn=!1,Vo&&(clearTimeout(Vo),Vo=null),En){try{En.stop()}catch{}En=null}if(bt.active=!1,lo(c),Wn(),q){if(q.classList.remove("persona-voice-recording"),lt){q.style.backgroundColor=lt.backgroundColor,q.style.color=lt.color,q.style.borderColor=lt.borderColor;let g=q.querySelector("svg");g&&g.setAttribute("stroke",lt.color||"currentColor"),lt=null}q.setAttribute("aria-label","Start voice recognition")}}},$r=(c,g)=>{var mt,dt,Pe,Re,qe,Qe,vt,B;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((mt=c==null?void 0:c.provider)==null?void 0:mt.type)==="runtype";if(!(h||y))return null;let F=b("div","persona-send-button-wrapper"),O=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");O.type="button",O.setAttribute("aria-label","Start voice recognition");let z=(dt=c==null?void 0:c.iconName)!=null?dt:"mic",D=(Pe=g==null?void 0:g.size)!=null?Pe:"40px",Te=(Re=c==null?void 0:c.iconSize)!=null?Re:D,me=parseFloat(Te)||24,Z=(qe=c==null?void 0:c.backgroundColor)!=null?qe:g==null?void 0:g.backgroundColor,Se=(Qe=c==null?void 0:c.iconColor)!=null?Qe:g==null?void 0:g.textColor;O.style.width=Te,O.style.height=Te,O.style.minWidth=Te,O.style.minHeight=Te,O.style.fontSize="18px",O.style.lineHeight="1",Se?O.style.color=Se:O.style.color="var(--persona-text, #111827)";let Ve=Ee(z,me,Se||"currentColor",1.5);Ve?O.appendChild(Ve):O.textContent="\u{1F3A4}",Z?O.style.backgroundColor=Z:O.style.backgroundColor="",c!=null&&c.borderWidth&&(O.style.borderWidth=c.borderWidth,O.style.borderStyle="solid"),c!=null&&c.borderColor&&(O.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(O.style.paddingLeft=c.paddingX,O.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(O.style.paddingTop=c.paddingY,O.style.paddingBottom=c.paddingY),F.appendChild(O);let ot=(vt=c==null?void 0:c.tooltipText)!=null?vt:"Start voice recognition";if(((B=c==null?void 0:c.showTooltip)!=null?B:!1)&&ot){let De=b("div","persona-send-button-tooltip");De.textContent=ot,F.appendChild(De)}return{micButton:O,micButtonWrapper:F}},Ge=()=>{var g,h,y,M,F;if(!q||lt)return;let c=(g=o.voiceRecognition)!=null?g:{};lt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(h=c.iconName)!=null?h:"mic",iconSize:parseFloat((F=(M=c.iconSize)!=null?M:(y=o.sendButton)==null?void 0:y.size)!=null?F:"40")||24}},T=(c,g)=>{var F,O,z,D,Te;if(!q)return;let h=q.querySelector("svg");h&&h.remove();let y=(Te=lt==null?void 0:lt.iconSize)!=null?Te:parseFloat((D=(z=(F=o.voiceRecognition)==null?void 0:F.iconSize)!=null?z:(O=o.sendButton)==null?void 0:O.size)!=null?D:"40")||24,M=Ee(c,y,g,1.5);M&&q.appendChild(M)},U=()=>{q&&q.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},R=()=>{var M;if(!q)return;Ge();let c=(M=o.voiceRecognition)!=null?M:{},g=c.recordingBackgroundColor,h=c.recordingIconColor,y=c.recordingBorderColor;if(U(),q.classList.add("persona-voice-recording"),q.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let F=q.querySelector("svg");F&&F.setAttribute("stroke",h)}y&&(q.style.borderColor=y),q.setAttribute("aria-label","Stop voice recognition")},J=()=>{var z,D,Te,me,Z,Se,Le,Ve;if(!q)return;Ge();let c=(z=o.voiceRecognition)!=null?z:{},g=V.getVoiceInterruptionMode(),h=(D=c.processingIconName)!=null?D:"loader",y=(me=(Te=c.processingIconColor)!=null?Te:lt==null?void 0:lt.color)!=null?me:"",M=(Se=(Z=c.processingBackgroundColor)!=null?Z:lt==null?void 0:lt.backgroundColor)!=null?Se:"",F=(Ve=(Le=c.processingBorderColor)!=null?Le:lt==null?void 0:lt.borderColor)!=null?Ve:"";U(),q.classList.add("persona-voice-processing"),q.style.backgroundColor=M,q.style.borderColor=F;let O=y||"currentColor";q.style.color=O,T(h,O),q.setAttribute("aria-label","Processing voice input"),g==="none"&&(q.style.cursor="default")},ie=()=>{var Te,me,Z,Se,Le,Ve,ot,je,mt,dt,Pe,Re;if(!q)return;Ge();let c=(Te=o.voiceRecognition)!=null?Te:{},g=V.getVoiceInterruptionMode(),h=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",y=(me=c.speakingIconName)!=null?me:h,M=(Ve=c.speakingIconColor)!=null?Ve:g==="barge-in"?(Se=(Z=c.recordingIconColor)!=null?Z:lt==null?void 0:lt.color)!=null?Se:"":(Le=lt==null?void 0:lt.color)!=null?Le:"",F=(mt=c.speakingBackgroundColor)!=null?mt:g==="barge-in"?(ot=c.recordingBackgroundColor)!=null?ot:"var(--persona-voice-recording-bg, #ef4444)":(je=lt==null?void 0:lt.backgroundColor)!=null?je:"",O=(Re=c.speakingBorderColor)!=null?Re:g==="barge-in"?(dt=c.recordingBorderColor)!=null?dt:"":(Pe=lt==null?void 0:lt.borderColor)!=null?Pe:"";U(),q.classList.add("persona-voice-speaking"),q.style.backgroundColor=F,q.style.borderColor=O;let z=M||"currentColor";q.style.color=z,T(y,z);let D=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";q.setAttribute("aria-label",D),g==="none"&&(q.style.cursor="default"),g==="barge-in"&&q.classList.add("persona-voice-recording")},Y=()=>{var c,g,h;q&&(U(),lt&&(q.style.backgroundColor=(c=lt.backgroundColor)!=null?c:"",q.style.color=(g=lt.color)!=null?g:"",q.style.borderColor=(h=lt.borderColor)!=null?h:"",T(lt.iconName,lt.color||"currentColor"),lt=null),q.style.cursor="",q.setAttribute("aria-label","Start voice recognition"))},Ie=()=>{var c,g;if(((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let h=V.getVoiceStatus(),y=V.getVoiceInterruptionMode();if(y==="none"&&(h==="processing"||h==="speaking"))return;if(y==="cancel"&&(h==="processing"||h==="speaking")){V.stopVoicePlayback();return}if(V.isBargeInActive()){V.stopVoicePlayback(),V.deactivateBargeIn().then(()=>{bt.active=!1,bt.manuallyDeactivated=!0,Wn(),lo("user"),Y()});return}V.toggleVoice().then(()=>{bt.active=V.isVoiceActive(),bt.manuallyDeactivated=!V.isVoiceActive(),Wn(),lo("user"),V.isVoiceActive()?R():Y()});return}if(Gn){let h=he.value.trim();bt.manuallyDeactivated=!0,Wn(),So("user"),h&&(he.value="",he.style.height="auto",V.sendMessage(h))}else bt.manuallyDeactivated=!1,Wn(),fr("user")};Fn=Ie,q&&(q.addEventListener("click",Ie),yt.push(()=>{var c,g;((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(V.isVoiceActive()&&V.toggleVoice(),Y()):So("system"),q&&q.removeEventListener("click",Ie)}));let Oe=s.on("assistant:complete",()=>{gs&&(bt.active||bt.manuallyDeactivated||gs==="assistant"&&!bt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!bt.active&&!bt.manuallyDeactivated&&(((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?V.toggleVoice().then(()=>{bt.active=V.isVoiceActive(),lo("auto"),V.isVoiceActive()&&R()}):fr("auto"))},600))});yt.push(Oe);let ct=s.on("action:resubmit",()=>{setTimeout(()=>{V&&!V.isStreaming()&&V.continueConversation()},100)});yt.push(ct);let Ye=()=>{Ft(!A,"user")},Xe=null,Ze=null;if(L&&!k()){let c=r.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:o,defaultRenderer:()=>Zs(o,Ye).element,onToggle:Ye});g&&(Ze=g)}Ze||(Xe=Zs(o,Ye))}Xe?e.appendChild(Xe.element):Ze&&e.appendChild(Ze),nr(),yo.render(o.suggestionChips,V,he,void 0,o.suggestionChipsConfig),xs(),Or(V.isStreaming()),Jo(!0),ga(),P&&(!L||k()?setTimeout(()=>Nr(),0):A&&setTimeout(()=>Nr(),200));let Qt=()=>{var D,Te,me,Z,Se,Le,Ve,ot,je,mt,dt,Pe,Re,qe,Qe,vt,B,De,ne,et,Nt,Ot;if(k()){Ct(),nr();return}let c=hn(o),g=(Te=(D=o.launcher)==null?void 0:D.sidebarMode)!=null?Te:!1,h=c||g||((Z=(me=o.launcher)==null?void 0:me.fullHeight)!=null?Z:!1),y=(Se=e.ownerDocument.defaultView)!=null?Se:window,M=(Ve=(Le=o.launcher)==null?void 0:Le.mobileFullscreen)!=null?Ve:!0,F=(je=(ot=o.launcher)==null?void 0:ot.mobileBreakpoint)!=null?je:640,O=y.innerWidth<=F,z=M&&O&&L;try{if(z){bo(),Kr(e,o);return}if(w&&(w=!1,bo(),Kr(e,o)),!L&&!c){pe.style.height="",pe.style.width="";return}if(!g&&!c){let zt=(dt=(mt=o==null?void 0:o.launcher)==null?void 0:mt.width)!=null?dt:o==null?void 0:o.launcherWidth,at=zt!=null?zt:go;pe.style.width=at,pe.style.maxWidth=at}if(Mo(),!h){let zt=y.innerHeight,at=64,ln=(Re=(Pe=o.launcher)==null?void 0:Pe.heightOffset)!=null?Re:0,Yn=Math.max(200,zt-at),Ke=Math.min(640,Yn),wt=Math.max(200,Ke-ln);pe.style.height=`${wt}px`}}finally{if(Ct(),nr(),A&&L){let at=((qe=e.ownerDocument.defaultView)!=null?qe:window).innerWidth<=((vt=(Qe=o.launcher)==null?void 0:Qe.mobileBreakpoint)!=null?vt:640),ln=(De=(B=o.launcher)==null?void 0:B.sidebarMode)!=null?De:!1,Yn=(et=(ne=o.launcher)==null?void 0:ne.mobileFullscreen)!=null?et:!0,Ke=hn(o)&&Yn&&at,wt=ln||Yn&&at&&L||Ke;if(wt&&!Xt){let Xn=e.getRootNode(),on=Xn instanceof ShadowRoot?Xn.host:e.closest(".persona-host");on&&!Yt&&(Yt=xl(on,(Ot=(Nt=o.launcher)==null?void 0:Nt.zIndex)!=null?Ot:wn)),Xt=wl(e.ownerDocument)}else wt||(Yt==null||Yt(),Yt=null,Xt==null||Xt(),Xt=null)}}};Qt();let Lt=(Jc=e.ownerDocument.defaultView)!=null?Jc:window;if(Lt.addEventListener("resize",Qt),yt.push(()=>Lt.removeEventListener("resize",Qt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Ct()});c.observe(_e),yt.push(()=>c.disconnect())}wo=X.scrollTop;let Ht=X.scrollHeight,an=()=>{let c=X.scrollTop,g=X.scrollHeight,h=g<Ht;Ht=g;let{action:y,nextLastScrollTop:M}=ci({following:xo.isFollowing(),currentScrollTop:c,lastScrollTop:wo,nearBottom:js(X,ms),userScrollThreshold:ua,isAutoScrolling:Fo||pr||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(wo=M,y==="resume"){Qo();return}y==="pause"&&hs()};X.addEventListener("scroll",an,{passive:!0}),yt.push(()=>X.removeEventListener("scroll",an));let bn=c=>{let g=di({following:xo.isFollowing(),deltaY:c.deltaY,nearBottom:js(X,ms),resumeWhenNearBottom:!0});g==="pause"?hs():g==="resume"&&Qo()};X.addEventListener("wheel",bn,{passive:!0}),yt.push(()=>X.removeEventListener("wheel",bn)),Pt.addEventListener("click",()=>{X.scrollTop=X.scrollHeight,wo=X.scrollTop,Qo(),Jo(!0)}),yt.push(()=>Pt.remove()),yt.push(()=>{fs()});let fn=()=>{ze&&(jn&&(ze.removeEventListener("click",jn),jn=null),S()?(ze.style.display="",jn=()=>{Ft(!1,"user")},ze.addEventListener("click",jn)):ze.style.display="none")};fn(),(()=>{let{clearChatButton:c}=We;c&&c.addEventListener("click",()=>{V.clearMessages(),ve.clear(),Qo(),ss(We.composerOverlay);try{localStorage.removeItem(is),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${is}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==is)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}d={},E.syncFromMetadata(),K==null||K.clear(),ye==null||ye.reset(),le==null||le.update()})})(),$t&&$t.addEventListener("submit",Cs),he==null||he.addEventListener("keydown",As),he==null||he.addEventListener("input",Ss),he==null||he.addEventListener("paste",ks);let co=(Zc=e.ownerDocument)!=null?Zc:document;co.addEventListener("keydown",Ts,!0);let sc="persona-attachment-drop-active",Ms=0,Yi=()=>{Ms=0,ue.classList.remove(sc)},Ur=()=>{var c;return((c=o.attachments)==null?void 0:c.enabled)===!0&&nt!==null},ac=c=>{!Wi(c.dataTransfer)||!Ur()||(Ms++,Ms===1&&ue.classList.add(sc))},ic=c=>{!Wi(c.dataTransfer)||!Ur()||(Ms--,Ms<=0&&Yi())},lc=c=>{!Wi(c.dataTransfer)||!Ur()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},cc=c=>{var h;if(!Wi(c.dataTransfer)||!Ur())return;c.preventDefault(),c.stopPropagation(),Yi();let g=Array.from((h=c.dataTransfer.files)!=null?h:[]);g.length!==0&&nt.handleFiles(g)},or=!0;ue.addEventListener("dragenter",ac,or),ue.addEventListener("dragleave",ic,or),e.addEventListener("dragover",lc,or),e.addEventListener("drop",cc,or);let Ea=e.ownerDocument,dc=c=>{Ur()&&c.preventDefault()},pc=c=>{Ur()&&c.preventDefault()};Ea.addEventListener("dragover",dc),Ea.addEventListener("drop",pc),yt.push(()=>{$t&&$t.removeEventListener("submit",Cs),he==null||he.removeEventListener("keydown",As),he==null||he.removeEventListener("input",Ss),he==null||he.removeEventListener("paste",ks),co.removeEventListener("keydown",Ts,!0)}),yt.push(()=>{ue.removeEventListener("dragenter",ac,or),ue.removeEventListener("dragleave",ic,or),e.removeEventListener("dragover",lc,or),e.removeEventListener("drop",cc,or),Ea.removeEventListener("dragover",dc),Ea.removeEventListener("drop",pc),Yi()}),yt.push(()=>{V.cancel()}),Xe?yt.push(()=>{Xe==null||Xe.destroy()}):Ze&&yt.push(()=>{Ze==null||Ze.remove()});let nn={update(c){var Zt,Io,rn,Mn,mo,vr,xr,Ma,Ls,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,bd,yd,vd,xd,wd,Cd,Sd,Ad,Td,kd,Ed,Md,Ld,Id,Rd,Pd,Wd,Bd,Hd,Dd,Fd,Od,Nd,_d,Vd,$d,Ud,zd,qd,jd,Kd,Gd,Yd,Xd,Qd,Jd,Zd,ep,tp,np,op,rp,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,bp,yp,vp,xp,wp,Cp,Sp,Ap,Tp,kp,Ep,Mp,Lp,Ip,Rp,Pp,Wp,Bp,Hp,Dp,Fp,Op,Np,_p,Vp,$p,Up,zp,qp,jp,Kp,Gp,Yp,Xp,Qp,Jp,Zp,eu,tu;let g=o.toolCall,h=o.messageActions,y=(Zt=o.layout)==null?void 0:Zt.messages,M=o.colorScheme,F=o.loadingIndicator,O=o.iterationDisplay,z=(Io=o.features)==null?void 0:Io.showReasoning,D=(rn=o.features)==null?void 0:rn.showToolCalls,Te=(Mn=o.features)==null?void 0:Mn.toolCallDisplay,me=(mo=o.features)==null?void 0:mo.reasoningDisplay;o={...o,...c},bo(),Kr(e,o),Ri(e,o),Pi(e,o),zn(),o.colorScheme!==M&&Xo();let Z=_l.getForInstance(o.plugins);r.length=0,r.push(...Z),L=(xr=(vr=o.launcher)==null?void 0:vr.enabled)!=null?xr:!0,I=(Ls=(Ma=o.launcher)==null?void 0:Ma.autoExpand)!=null?Ls:!1,ge=(id=(ad=o.features)==null?void 0:ad.showReasoning)!=null?id:!0,se=(cd=(ld=o.features)==null?void 0:ld.showToolCalls)!=null?cd:!0,be=(pd=(dd=o.features)==null?void 0:dd.scrollToBottom)!=null?pd:{},Kt(),No();let Se=ke;if(ke=(md=(ud=o.features)==null?void 0:ud.showEventStreamToggle)!=null?md:!1,ke&&!Se){if(K||(j=new ra(xe),K=new oa(de,j),ye=ye!=null?ye:new sa,j.open().then(()=>K==null?void 0:K.restore()).catch(()=>{}),V.setSSEEventCallback((Q,At)=>{var Vt;(Vt=o.onSSEEvent)==null||Vt.call(o,Q,At),ye==null||ye.processEvent(Q,At),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Q,timestamp:Date.now(),payload:JSON.stringify(At)})})),!ht&&He){let Q=(fd=(gd=o.features)==null?void 0:gd.eventStream)==null?void 0:fd.classNames,At="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(Q!=null&&Q.toggleButton?" "+Q.toggleButton:"");ht=b("button",At),ht.style.width="28px",ht.style.height="28px",ht.style.color=In.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let Vt=Ee("activity","18px","currentColor",1.5);Vt&&ht.appendChild(Vt);let pt=We.clearChatButtonWrapper,Wt=We.closeButtonWrapper,dn=pt||Wt;dn&&dn.parentNode===He?He.insertBefore(ht,dn):He.appendChild(ht),ht.addEventListener("click",()=>{te?On():An()})}}else!ke&&Se&&(On(),ht&&(ht.remove(),ht=null),K==null||K.clear(),j==null||j.destroy(),K=null,j=null,ye==null||ye.reset(),ye=null);if(((hd=o.launcher)==null?void 0:hd.enabled)===!1&&Xe&&(Xe.destroy(),Xe=null),((bd=o.launcher)==null?void 0:bd.enabled)===!1&&Ze&&(Ze.remove(),Ze=null),((yd=o.launcher)==null?void 0:yd.enabled)!==!1&&!Xe&&!Ze){let Q=r.find(At=>At.renderLauncher);if(Q!=null&&Q.renderLauncher){let At=Q.renderLauncher({config:o,defaultRenderer:()=>Zs(o,Ye).element,onToggle:Ye});At&&(Ze=At,e.appendChild(Ze))}Ze||(Xe=Zs(o,Ye),e.appendChild(Xe.element))}Xe&&Xe.update(o),Me&&((vd=o.launcher)==null?void 0:vd.title)!==void 0&&(Me.textContent=o.launcher.title),Be&&((xd=o.launcher)==null?void 0:xd.subtitle)!==void 0&&(Be.textContent=o.launcher.subtitle);let Le=(wd=o.layout)==null?void 0:wd.header;if((Le==null?void 0:Le.layout)!==x&&He){let Q=Le?bi(o,Le,{showClose:S(),onClose:()=>Ft(!1,"user")}):Mr({config:o,showClose:S(),onClose:()=>Ft(!1,"user")});He.replaceWith(Q.header),He=Q.header,_=Q.iconHolder,Me=Q.headerTitle,Be=Q.headerSubtitle,ze=Q.closeButton,x=Le==null?void 0:Le.layout}else if(Le&&(_&&(_.style.display=Le.showIcon===!1?"none":""),Me&&(Me.style.display=Le.showTitle===!1?"none":""),Be&&(Be.style.display=Le.showSubtitle===!1?"none":""),ze&&(ze.style.display=Le.showCloseButton===!1?"none":""),We.clearChatButtonWrapper)){let Q=Le.showClearChat;if(Q!==void 0){We.clearChatButtonWrapper.style.display=Q?"":"none";let{closeButtonWrapper:At}=We;At&&!At.classList.contains("persona-absolute")&&(Q?At.classList.remove("persona-ml-auto"):At.classList.add("persona-ml-auto"))}}let ot=((Cd=o.layout)==null?void 0:Cd.showHeader)!==!1;He&&(He.style.display=ot?"":"none");let je=((Sd=o.layout)==null?void 0:Sd.showFooter)!==!1;_e&&(_e.style.display=je?"":"none"),Ct(),No(),L!==W?L?Ft(I,"auto"):(A=!0,nr()):I!==H&&Ft(I,"auto"),H=I,W=L,Qt(),fn();let Pe=JSON.stringify(c.toolCall)!==JSON.stringify(g),Re=JSON.stringify(o.messageActions)!==JSON.stringify(h),qe=JSON.stringify((Ad=o.layout)==null?void 0:Ad.messages)!==JSON.stringify(y),Qe=((Td=o.loadingIndicator)==null?void 0:Td.render)!==(F==null?void 0:F.render)||((kd=o.loadingIndicator)==null?void 0:kd.renderIdle)!==(F==null?void 0:F.renderIdle)||((Ed=o.loadingIndicator)==null?void 0:Ed.showBubble)!==(F==null?void 0:F.showBubble),vt=o.iterationDisplay!==O,B=((Ld=(Md=o.features)==null?void 0:Md.showReasoning)!=null?Ld:!0)!==(z!=null?z:!0)||((Rd=(Id=o.features)==null?void 0:Id.showToolCalls)!=null?Rd:!0)!==(D!=null?D:!0)||JSON.stringify((Pd=o.features)==null?void 0:Pd.toolCallDisplay)!==JSON.stringify(Te)||JSON.stringify((Wd=o.features)==null?void 0:Wd.reasoningDisplay)!==JSON.stringify(me);(Pe||Re||qe||Qe||vt||B)&&V&&(us++,mr(Ne,V.getMessages(),fe));let ne=(Bd=o.launcher)!=null?Bd:{},et=(Hd=ne.headerIconHidden)!=null?Hd:!1,Nt=(Fd=(Dd=o.layout)==null?void 0:Dd.header)==null?void 0:Fd.showIcon,Ot=et||Nt===!1,zt=ne.headerIconName,at=(Od=ne.headerIconSize)!=null?Od:"48px";if(_){let Q=ue.querySelector(".persona-border-b-persona-divider"),At=Q==null?void 0:Q.querySelector(".persona-flex-col");if(Ot)_.style.display="none",Q&&At&&!Q.contains(At)&&Q.insertBefore(At,Q.firstChild);else{if(_.style.display="",_.style.height=at,_.style.width=at,Q&&At&&(Q.contains(_)?_.nextSibling!==At&&(_.remove(),Q.insertBefore(_,At)):Q.insertBefore(_,At)),zt){let pt=parseFloat(at)||24,Wt=Ee(zt,pt*.6,"#ffffff",2);Wt?_.replaceChildren(Wt):_.textContent=(Nd=ne.agentIconText)!=null?Nd:"\u{1F4AC}"}else if(ne.iconUrl){let pt=_.querySelector("img");if(pt)pt.src=ne.iconUrl,pt.style.height=at,pt.style.width=at;else{let Wt=document.createElement("img");Wt.src=ne.iconUrl,Wt.alt="",Wt.className="persona-rounded-xl persona-object-cover",Wt.style.height=at,Wt.style.width=at,_.replaceChildren(Wt)}}else{let pt=_.querySelector("svg"),Wt=_.querySelector("img");(pt||Wt)&&_.replaceChildren(),_.textContent=(_d=ne.agentIconText)!=null?_d:"\u{1F4AC}"}let Vt=_.querySelector("img");Vt&&(Vt.style.height=at,Vt.style.width=at)}}let ln=($d=(Vd=o.layout)==null?void 0:Vd.header)==null?void 0:$d.showTitle,Yn=(zd=(Ud=o.layout)==null?void 0:Ud.header)==null?void 0:zd.showSubtitle;if(Me&&(Me.style.display=ln===!1?"none":""),Be&&(Be.style.display=Yn===!1?"none":""),ze){((jd=(qd=o.layout)==null?void 0:qd.header)==null?void 0:jd.showCloseButton)===!1?ze.style.display="none":ze.style.display="";let At=(Kd=ne.closeButtonSize)!=null?Kd:"32px",Vt=(Gd=ne.closeButtonPlacement)!=null?Gd:"inline";ze.style.height=At,ze.style.width=At;let{closeButtonWrapper:pt}=We,Wt=Vt==="top-right",dn=pt==null?void 0:pt.classList.contains("persona-absolute");if(pt&&Wt!==dn)if(pt.remove(),Wt)pt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ue.style.position="relative",ue.appendChild(pt);else{let ft=(Xd=(Yd=ne.clearChat)==null?void 0:Yd.placement)!=null?Xd:"inline",pn=(Jd=(Qd=ne.clearChat)==null?void 0:Qd.enabled)!=null?Jd:!0;pt.className=pn&&ft==="inline"?"":"persona-ml-auto";let Hn=ue.querySelector(".persona-border-b-persona-divider");Hn&&Hn.appendChild(pt)}if(ze.style.color=ne.closeButtonColor||In.actionIconColor,ne.closeButtonBackgroundColor?(ze.style.backgroundColor=ne.closeButtonBackgroundColor,ze.classList.remove("hover:persona-bg-gray-100")):(ze.style.backgroundColor="",ze.classList.add("hover:persona-bg-gray-100")),ne.closeButtonBorderWidth||ne.closeButtonBorderColor){let ft=ne.closeButtonBorderWidth||"0px",pn=ne.closeButtonBorderColor||"transparent";ze.style.border=`${ft} solid ${pn}`,ze.classList.remove("persona-border-none")}else ze.style.border="",ze.classList.add("persona-border-none");ne.closeButtonBorderRadius?(ze.style.borderRadius=ne.closeButtonBorderRadius,ze.classList.remove("persona-rounded-full")):(ze.style.borderRadius="",ze.classList.add("persona-rounded-full")),ne.closeButtonPaddingX?(ze.style.paddingLeft=ne.closeButtonPaddingX,ze.style.paddingRight=ne.closeButtonPaddingX):(ze.style.paddingLeft="",ze.style.paddingRight=""),ne.closeButtonPaddingY?(ze.style.paddingTop=ne.closeButtonPaddingY,ze.style.paddingBottom=ne.closeButtonPaddingY):(ze.style.paddingTop="",ze.style.paddingBottom="");let vn=(Zd=ne.closeButtonIconName)!=null?Zd:"x",Ao=(ep=ne.closeButtonIconText)!=null?ep:"\xD7";ze.innerHTML="";let Ln=Ee(vn,"28px","currentColor",1);Ln?ze.appendChild(Ln):ze.textContent=Ao;let Jt=(tp=ne.closeButtonTooltipText)!=null?tp:"Close chat",Jn=(np=ne.closeButtonShowTooltip)!=null?np:!0;if(ze.setAttribute("aria-label",Jt),pt&&(pt._cleanupTooltip&&(pt._cleanupTooltip(),delete pt._cleanupTooltip),Jn&&Jt)){let ft=null,pn=()=>{if(ft||!ze)return;let wr=ze.ownerDocument,Is=wr.body;if(!Is)return;ft=Po(wr,"div","persona-clear-chat-tooltip"),ft.textContent=Jt;let Rs=Po(wr,"div");Rs.className="persona-clear-chat-tooltip-arrow",ft.appendChild(Rs);let Cr=ze.getBoundingClientRect();ft.style.position="fixed",ft.style.zIndex=String(ar),ft.style.left=`${Cr.left+Cr.width/2}px`,ft.style.top=`${Cr.top-8}px`,ft.style.transform="translate(-50%, -100%)",Is.appendChild(ft)},Hn=()=>{ft&&ft.parentNode&&(ft.parentNode.removeChild(ft),ft=null)};pt.addEventListener("mouseenter",pn),pt.addEventListener("mouseleave",Hn),ze.addEventListener("focus",pn),ze.addEventListener("blur",Hn),pt._cleanupTooltip=()=>{Hn(),pt&&(pt.removeEventListener("mouseenter",pn),pt.removeEventListener("mouseleave",Hn)),ze&&(ze.removeEventListener("focus",pn),ze.removeEventListener("blur",Hn))}}}let{clearChatButton:Ke,clearChatButtonWrapper:wt}=We;if(Ke){let Q=(op=ne.clearChat)!=null?op:{},At=(rp=Q.enabled)!=null?rp:!0,Vt=(ap=(sp=o.layout)==null?void 0:sp.header)==null?void 0:ap.showClearChat,pt=Vt!==void 0?Vt:At,Wt=(ip=Q.placement)!=null?ip:"inline";if(wt){wt.style.display=pt?"":"none";let{closeButtonWrapper:dn}=We;!k()&&dn&&!dn.classList.contains("persona-absolute")&&(pt?dn.classList.remove("persona-ml-auto"):dn.classList.add("persona-ml-auto"));let vn=Wt==="top-right",Ao=wt.classList.contains("persona-absolute");if(!k()&&vn!==Ao&&pt){if(wt.remove(),vn)wt.className="persona-absolute persona-top-4 persona-z-50",wt.style.right="48px",ue.style.position="relative",ue.appendChild(wt);else{wt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",wt.style.right="";let Jt=ue.querySelector(".persona-border-b-persona-divider"),Jn=We.closeButtonWrapper;Jt&&Jn&&Jn.parentElement===Jt?Jt.insertBefore(wt,Jn):Jt&&Jt.appendChild(wt)}let Ln=We.closeButtonWrapper;Ln&&!Ln.classList.contains("persona-absolute")&&(vn?Ln.classList.add("persona-ml-auto"):Ln.classList.remove("persona-ml-auto"))}}if(pt){if(!k()){let ft=(lp=Q.size)!=null?lp:"32px";Ke.style.height=ft,Ke.style.width=ft}let dn=(cp=Q.iconName)!=null?cp:"refresh-cw",vn=(dp=Q.iconColor)!=null?dp:"";Ke.style.color=vn||In.actionIconColor,Ke.innerHTML="";let Ao=k()?"14px":"20px",Ln=Ee(dn,Ao,"currentColor",2);if(Ln&&Ke.appendChild(Ln),Q.backgroundColor?(Ke.style.backgroundColor=Q.backgroundColor,Ke.classList.remove("hover:persona-bg-gray-100")):(Ke.style.backgroundColor="",Ke.classList.add("hover:persona-bg-gray-100")),Q.borderWidth||Q.borderColor){let ft=Q.borderWidth||"0px",pn=Q.borderColor||"transparent";Ke.style.border=`${ft} solid ${pn}`,Ke.classList.remove("persona-border-none")}else Ke.style.border="",Ke.classList.add("persona-border-none");Q.borderRadius?(Ke.style.borderRadius=Q.borderRadius,Ke.classList.remove("persona-rounded-full")):(Ke.style.borderRadius="",Ke.classList.add("persona-rounded-full")),Q.paddingX?(Ke.style.paddingLeft=Q.paddingX,Ke.style.paddingRight=Q.paddingX):(Ke.style.paddingLeft="",Ke.style.paddingRight=""),Q.paddingY?(Ke.style.paddingTop=Q.paddingY,Ke.style.paddingBottom=Q.paddingY):(Ke.style.paddingTop="",Ke.style.paddingBottom="");let Jt=(pp=Q.tooltipText)!=null?pp:"Clear chat",Jn=(up=Q.showTooltip)!=null?up:!0;if(Ke.setAttribute("aria-label",Jt),wt&&(wt._cleanupTooltip&&(wt._cleanupTooltip(),delete wt._cleanupTooltip),Jn&&Jt)){let ft=null,pn=()=>{if(ft||!Ke)return;let wr=Ke.ownerDocument,Is=wr.body;if(!Is)return;ft=Po(wr,"div","persona-clear-chat-tooltip"),ft.textContent=Jt;let Rs=Po(wr,"div");Rs.className="persona-clear-chat-tooltip-arrow",ft.appendChild(Rs);let Cr=Ke.getBoundingClientRect();ft.style.position="fixed",ft.style.zIndex=String(ar),ft.style.left=`${Cr.left+Cr.width/2}px`,ft.style.top=`${Cr.top-8}px`,ft.style.transform="translate(-50%, -100%)",Is.appendChild(ft)},Hn=()=>{ft&&ft.parentNode&&(ft.parentNode.removeChild(ft),ft=null)};wt.addEventListener("mouseenter",pn),wt.addEventListener("mouseleave",Hn),Ke.addEventListener("focus",pn),Ke.addEventListener("blur",Hn),wt._cleanupTooltip=()=>{Hn(),wt&&(wt.removeEventListener("mouseenter",pn),wt.removeEventListener("mouseleave",Hn)),Ke&&(Ke.removeEventListener("focus",pn),Ke.removeEventListener("blur",Hn))}}}}let Xn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[$l],on=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[aa.message,aa.messageAndClick];E=Ul({parsers:Xn,handlers:on,getSessionMetadata:f,updateSessionMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),fe=Qm(o,E,G),V.updateConfig(o),mr(Ne,V.getMessages(),fe),yo.render(o.suggestionChips,V,he,void 0,o.suggestionChipsConfig),xs(),Or(V.isStreaming());let uo=((mp=o.voiceRecognition)==null?void 0:mp.enabled)===!0,Qn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),hr=((fp=(gp=o.voiceRecognition)==null?void 0:gp.provider)==null?void 0:fp.type)==="runtype";if(uo&&(Qn||hr))if(!q||!Ut){let Q=$r(o.voiceRecognition,o.sendButton);Q&&(q=Q.micButton,Ut=Q.micButtonWrapper,Rt.insertBefore(Ut,Rn),q.addEventListener("click",Ie),q.disabled=V.isStreaming())}else{let Q=(hp=o.voiceRecognition)!=null?hp:{},At=(bp=o.sendButton)!=null?bp:{},Vt=(yp=Q.iconName)!=null?yp:"mic",pt=(vp=At.size)!=null?vp:"40px",Wt=(xp=Q.iconSize)!=null?xp:pt,dn=parseFloat(Wt)||24;q.style.width=Wt,q.style.height=Wt,q.style.minWidth=Wt,q.style.minHeight=Wt;let vn=(Cp=(wp=Q.iconColor)!=null?wp:At.textColor)!=null?Cp:"currentColor";q.innerHTML="";let Ao=Ee(Vt,dn,vn,2);Ao?q.appendChild(Ao):q.textContent="\u{1F3A4}";let Ln=(Sp=Q.backgroundColor)!=null?Sp:At.backgroundColor;Ln?q.style.backgroundColor=Ln:q.style.backgroundColor="",vn?q.style.color=vn:q.style.color="var(--persona-text, #111827)",Q.borderWidth?(q.style.borderWidth=Q.borderWidth,q.style.borderStyle="solid"):(q.style.borderWidth="",q.style.borderStyle=""),Q.borderColor?q.style.borderColor=Q.borderColor:q.style.borderColor="",Q.paddingX?(q.style.paddingLeft=Q.paddingX,q.style.paddingRight=Q.paddingX):(q.style.paddingLeft="",q.style.paddingRight=""),Q.paddingY?(q.style.paddingTop=Q.paddingY,q.style.paddingBottom=Q.paddingY):(q.style.paddingTop="",q.style.paddingBottom="");let Jt=Ut==null?void 0:Ut.querySelector(".persona-send-button-tooltip"),Jn=(Ap=Q.tooltipText)!=null?Ap:"Start voice recognition";if(((Tp=Q.showTooltip)!=null?Tp:!1)&&Jn)if(Jt)Jt.textContent=Jn,Jt.style.display="";else{let pn=document.createElement("div");pn.className="persona-send-button-tooltip",pn.textContent=Jn,Ut==null||Ut.insertBefore(pn,q)}else Jt&&(Jt.style.display="none");Ut.style.display="",q.disabled=V.isStreaming()}else q&&Ut&&(Ut.style.display="none",((Ep=(kp=o.voiceRecognition)==null?void 0:kp.provider)==null?void 0:Ep.type)==="runtype"?V.isVoiceActive()&&V.toggleVoice():Gn&&So());if(((Mp=o.attachments)==null?void 0:Mp.enabled)===!0)if(!_t||!Je){let Q=(Lp=o.attachments)!=null?Lp:{},Vt=(Rp=((Ip=o.sendButton)!=null?Ip:{}).size)!=null?Rp:"40px";we||(we=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),we.style.display="none",$t.insertBefore(we,he)),re||(re=document.createElement("input"),re.type="file",re.accept=((Pp=Q.allowedTypes)!=null?Pp:Uo).join(","),re.multiple=((Wp=Q.maxFiles)!=null?Wp:4)>1,re.style.display="none",re.setAttribute("aria-label","Attach files"),$t.insertBefore(re,he)),_t=b("div","persona-send-button-wrapper"),Je=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Je.type="button",Je.setAttribute("aria-label",(Bp=Q.buttonTooltipText)!=null?Bp:"Attach file");let pt=(Hp=Q.buttonIconName)!=null?Hp:"paperclip",Wt=Vt,dn=parseFloat(Wt)||40,vn=Math.round(dn*.6);Je.style.width=Wt,Je.style.height=Wt,Je.style.minWidth=Wt,Je.style.minHeight=Wt,Je.style.fontSize="18px",Je.style.lineHeight="1",Je.style.backgroundColor="transparent",Je.style.color="var(--persona-primary, #111827)",Je.style.border="none",Je.style.borderRadius="6px",Je.style.transition="background-color 0.15s ease",Je.addEventListener("mouseenter",()=>{Je.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Je.addEventListener("mouseleave",()=>{Je.style.backgroundColor="transparent"});let Ao=Ee(pt,vn,"currentColor",1.5);Ao?Je.appendChild(Ao):Je.textContent="\u{1F4CE}",Je.addEventListener("click",Jn=>{Jn.preventDefault(),re==null||re.click()}),_t.appendChild(Je);let Ln=(Dp=Q.buttonTooltipText)!=null?Dp:"Attach file",Jt=b("div","persona-send-button-tooltip");Jt.textContent=Ln,_t.appendChild(Jt),st.append(_t),!nt&&re&&we&&(nt=zs.fromConfig(Q),nt.setPreviewsContainer(we),re.addEventListener("change",async()=>{nt&&(re!=null&&re.files)&&(await nt.handleFileSelect(re.files),re.value="")})),ue.querySelector(".persona-attachment-drop-overlay")||ue.appendChild(Jm(Q.dropOverlay))}else{_t.style.display="";let Q=(Fp=o.attachments)!=null?Fp:{};re&&(re.accept=((Op=Q.allowedTypes)!=null?Op:Uo).join(","),re.multiple=((Np=Q.maxFiles)!=null?Np:4)>1),nt&&nt.updateConfig({allowedTypes:Q.allowedTypes,maxFileSize:Q.maxFileSize,maxFiles:Q.maxFiles})}else _t&&(_t.style.display="none"),nt&&nt.clearAttachments(),(_p=ue.querySelector(".persona-attachment-drop-overlay"))==null||_p.remove();let Gt=(Vp=o.sendButton)!=null?Vp:{},br=($p=Gt.useIcon)!=null?$p:!1,rr=(Up=Gt.iconText)!=null?Up:"\u2191",sr=Gt.iconName,$o=(zp=Gt.tooltipText)!=null?zp:"Send message",yr=(qp=Gt.showTooltip)!=null?qp:!1,tt=(jp=Gt.size)!=null?jp:"40px",yn=Gt.backgroundColor,gn=Gt.textColor;if(br){if(ce.style.width=tt,ce.style.height=tt,ce.style.minWidth=tt,ce.style.minHeight=tt,ce.style.fontSize="18px",ce.style.lineHeight="1",ce.innerHTML="",gn?ce.style.color=gn:ce.style.color="var(--persona-button-primary-fg, #ffffff)",sr){let Q=parseFloat(tt)||24,At=(gn==null?void 0:gn.trim())||"currentColor",Vt=Ee(sr,Q,At,2);Vt?ce.appendChild(Vt):ce.textContent=rr}else ce.textContent=rr;ce.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",yn?(ce.style.backgroundColor=yn,ce.classList.remove("persona-bg-persona-primary")):(ce.style.backgroundColor="",ce.classList.add("persona-bg-persona-primary"))}else ce.textContent=(Gp=(Kp=o.copy)==null?void 0:Kp.sendButtonLabel)!=null?Gp:"Send",ce.style.width="",ce.style.height="",ce.style.minWidth="",ce.style.minHeight="",ce.style.fontSize="",ce.style.lineHeight="",ce.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",yn?(ce.style.backgroundColor=yn,ce.classList.remove("persona-bg-persona-accent")):ce.classList.add("persona-bg-persona-accent"),gn?ce.style.color=gn:ce.classList.add("persona-text-white");Gt.borderWidth?(ce.style.borderWidth=Gt.borderWidth,ce.style.borderStyle="solid"):(ce.style.borderWidth="",ce.style.borderStyle=""),Gt.borderColor?ce.style.borderColor=Gt.borderColor:ce.style.borderColor="",Gt.paddingX?(ce.style.paddingLeft=Gt.paddingX,ce.style.paddingRight=Gt.paddingX):(ce.style.paddingLeft="",ce.style.paddingRight=""),Gt.paddingY?(ce.style.paddingTop=Gt.paddingY,ce.style.paddingBottom=Gt.paddingY):(ce.style.paddingTop="",ce.style.paddingBottom="");let cn=Rn==null?void 0:Rn.querySelector(".persona-send-button-tooltip");if(yr&&$o)if(cn)cn.textContent=$o,cn.style.display="";else{let Q=document.createElement("div");Q.className="persona-send-button-tooltip",Q.textContent=$o,Rn==null||Rn.insertBefore(Q,ce)}else cn&&(cn.style.display="none");let gt=(Zp=(Yp=o.layout)==null?void 0:Yp.contentMaxWidth)!=null?Zp:k()?(Jp=(Qp=(Xp=o.launcher)==null?void 0:Xp.composerBar)==null?void 0:Qp.contentMaxWidth)!=null?Jp:"720px":void 0;gt?(Ne.style.maxWidth=gt,Ne.style.marginLeft="auto",Ne.style.marginRight="auto",Ne.style.width="100%",$t&&($t.style.maxWidth=gt,$t.style.marginLeft="auto",$t.style.marginRight="auto"),Bt&&(Bt.style.maxWidth=gt,Bt.style.marginLeft="auto",Bt.style.marginRight="auto")):(Ne.style.maxWidth="",Ne.style.marginLeft="",Ne.style.marginRight="",Ne.style.width="",$t&&($t.style.maxWidth="",$t.style.marginLeft="",$t.style.marginRight=""),Bt&&(Bt.style.maxWidth="",Bt.style.marginLeft="",Bt.style.marginRight=""));let it=(eu=o.statusIndicator)!=null?eu:{},kt=(tu=it.visible)!=null?tu:!0;if(mn.style.display=kt?"":"none",V){let Q=V.getStatus();rt(mn,(Vt=>{var pt,Wt,dn,vn;return Vt==="idle"?(pt=it.idleText)!=null?pt:xn.idle:Vt==="connecting"?(Wt=it.connectingText)!=null?Wt:xn.connecting:Vt==="connected"?(dn=it.connectedText)!=null?dn:xn.connected:Vt==="error"?(vn=it.errorText)!=null?vn:xn.error:xn[Vt]})(Q),it,Q)}mn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Bn=it.align==="left"?"persona-text-left":it.align==="center"?"persona-text-center":"persona-text-right";mn.classList.add(Bn)},open(){S()&&Ft(!0,"api")},close(){S()&&Ft(!1,"api")},toggle(){S()&&Ft(!A,"api")},clearChat(){Tn=!1,V.clearMessages(),ve.clear(),Qo();try{localStorage.removeItem(is),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${is}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==is)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let g=i.clear();g instanceof Promise&&g.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}d={},E.syncFromMetadata(),K==null||K.clear(),ye==null||ye.reset(),le==null||le.update()},setMessage(c){return!he||V.isStreaming()?!1:(!A&&S()&&Ft(!0,"system"),he.value=c,he.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(V.isStreaming())return!1;let g=(c==null?void 0:c.trim())||he.value.trim();return g?(!A&&S()&&Ft(!0,"system"),he.value="",he.style.height="auto",V.sendMessage(g),!0):!1},startVoiceRecognition(){var g,h;return V.isStreaming()?!1:((h=(g=o.voiceRecognition)==null?void 0:g.provider)==null?void 0:h.type)==="runtype"?(V.isVoiceActive()||(!A&&S()&&Ft(!0,"system"),bt.manuallyDeactivated=!1,Wn(),V.toggleVoice().then(()=>{bt.active=V.isVoiceActive(),lo("user"),V.isVoiceActive()&&R()})),!0):Gn?!0:Es()?(!A&&S()&&Ft(!0,"system"),bt.manuallyDeactivated=!1,Wn(),fr("user"),!0):!1},stopVoiceRecognition(){var c,g;return((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?V.isVoiceActive()?(V.toggleVoice().then(()=>{bt.active=!1,bt.manuallyDeactivated=!0,Wn(),lo("user"),Y()}),!0):!1:Gn?(bt.manuallyDeactivated=!0,Wn(),So("user"),!0):!1},injectMessage(c){return!A&&S()&&Ft(!0,"system"),V.injectMessage(c)},injectAssistantMessage(c){!A&&S()&&Ft(!0,"system");let g=V.injectAssistantMessage(c);return N&&(N=!1,$&&(clearTimeout($),$=null),setTimeout(()=>{V&&!V.isStreaming()&&V.continueConversation()},100)),g},injectUserMessage(c){return!A&&S()&&Ft(!0,"system"),V.injectUserMessage(c)},injectSystemMessage(c){return!A&&S()&&Ft(!0,"system"),V.injectSystemMessage(c)},injectMessageBatch(c){return!A&&S()&&Ft(!0,"system"),V.injectMessageBatch(c)},injectComponentDirective(c){return!A&&S()&&Ft(!0,"system"),V.injectComponentDirective(c)},injectTestMessage(c){!A&&S()&&Ft(!0,"system"),V.injectTestEvent(c)},async connectStream(c,g){return V.connectStream(c,g)},__pushEventStreamEvent(c){K&&(ye==null||ye.processEvent(c.type,c.payload),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!ke||!K||An()},hideEventStream(){te&&On()},isEventStreamVisible(){return te},showArtifacts(){ho(o)&&(Tn=!1,zn(),St==null||St.setMobileOpen(!0))},hideArtifacts(){ho(o)&&(Tn=!0,zn())},upsertArtifact(c){return ho(o)?(Tn=!1,V.upsertArtifact(c)):null},selectArtifact(c){ho(o)&&V.selectArtifact(c)},clearArtifacts(){ho(o)&&V.clearArtifacts()},getArtifacts(){var c;return(c=V==null?void 0:V.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=V==null?void 0:V.getSelectedArtifactId())!=null?c:null},focusInput(){return L&&!A&&!k()||!he?!1:(he.focus(),!0)},async resolveApproval(c,g,h){let M=V.getMessages().find(F=>{var O;return F.variant==="approval"&&((O=F.approval)==null?void 0:O.id)===c});if(!(M!=null&&M.approval))throw new Error(`Approval not found: ${c}`);if(M.approval.toolType==="webmcp"){V.resolveWebMcpApproval(M.id,g);return}return V.resolveApproval(M.approval,g,h)},getMessages(){return V.getMessages()},getStatus(){return V.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){u(c)},on(c,g){return s.on(c,g)},off(c,g){s.off(c,g)},isOpen(){return S()&&A},isVoiceActive(){return bt.active},getState(){return{open:S()&&A,launcherEnabled:L,voiceActive:bt.active,streaming:V.isStreaming()}},showCSATFeedback(c){!A&&S()&&Ft(!0,"system");let g=Ne.querySelector(".persona-feedback-container");g&&g.remove();let h=Gm({onSubmit:async(y,M)=>{var F;V.isClientTokenMode()&&await V.submitCSATFeedback(y,M),(F=c==null?void 0:c.onSubmit)==null||F.call(c,y,M)},onDismiss:c==null?void 0:c.onDismiss,...c});Ne.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!A&&S()&&Ft(!0,"system");let g=Ne.querySelector(".persona-feedback-container");g&&g.remove();let h=Ym({onSubmit:async(y,M)=>{var F;V.isClientTokenMode()&&await V.submitNPSFeedback(y,M),(F=c==null?void 0:c.onSubmit)==null||F.call(c,y,M)},onDismiss:c==null?void 0:c.onDismiss,...c});Ne.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,g){return V.submitCSATFeedback(c,g)},async submitNPSFeedback(c,g){return V.submitNPSFeedback(c,g)},destroy(){Lo!=null&&(clearInterval(Lo),Lo=null),yt.forEach(c=>c()),Ae.remove(),$e==null||$e.remove(),Xe==null||Xe.destroy(),Ze==null||Ze.remove(),jn&&ze.removeEventListener("click",jn)}};if((((ed=n==null?void 0:n.debugTools)!=null?ed:!1)||!!o.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:nn,getMessages:nn.getMessages,getStatus:nn.getStatus,getMetadata:nn.getPersistentMetadata,updateMetadata:nn.updatePersistentMetadata,clearHistory:()=>nn.clearChat(),setVoiceActive:h=>h?nn.startVoiceRecognition():nn.stopVoiceRecognition()};window.AgentWidgetBrowser=g,yt.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=z=>{let D=z.detail;(!(D!=null&&D.instanceId)||D.instanceId===c)&&nn.focusInput()};if(window.addEventListener("persona:focusInput",g),yt.push(()=>{window.removeEventListener("persona:focusInput",g)}),ke){let z=Te=>{let me=Te.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&nn.showEventStream()},D=Te=>{let me=Te.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&nn.hideEventStream()};window.addEventListener("persona:showEventStream",z),window.addEventListener("persona:hideEventStream",D),yt.push(()=>{window.removeEventListener("persona:showEventStream",z),window.removeEventListener("persona:hideEventStream",D)})}let h=z=>{let D=z.detail;(!(D!=null&&D.instanceId)||D.instanceId===c)&&nn.showArtifacts()},y=z=>{let D=z.detail;(!(D!=null&&D.instanceId)||D.instanceId===c)&&nn.hideArtifacts()},M=z=>{let D=z.detail;D!=null&&D.instanceId&&D.instanceId!==c||D!=null&&D.artifact&&nn.upsertArtifact(D.artifact)},F=z=>{let D=z.detail;D!=null&&D.instanceId&&D.instanceId!==c||typeof(D==null?void 0:D.id)=="string"&&nn.selectArtifact(D.id)},O=z=>{let D=z.detail;(!(D!=null&&D.instanceId)||D.instanceId===c)&&nn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",M),window.addEventListener("persona:selectArtifact",F),window.addEventListener("persona:clearArtifacts",O),yt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",M),window.removeEventListener("persona:selectArtifact",F),window.removeEventListener("persona:clearArtifacts",O)})}let po=vx(o.persistState);if(po&&S()){let c=xx(po.storage),g=`${po.keyPrefix}widget-open`,h=`${po.keyPrefix}widget-voice`,y=`${po.keyPrefix}widget-voice-mode`;if(c){let M=((td=po.persist)==null?void 0:td.openState)&&c.getItem(g)==="true",F=((nd=po.persist)==null?void 0:nd.voiceState)&&c.getItem(h)==="true",O=((od=po.persist)==null?void 0:od.voiceState)&&c.getItem(y)==="true";if(M&&setTimeout(()=>{nn.open(),setTimeout(()=>{var z;if(F||O)nn.startVoiceRecognition();else if((z=po.persist)!=null&&z.focusInput){let D=e.querySelector("textarea");D&&D.focus()}},100)},0),(rd=po.persist)!=null&&rd.openState&&(s.on("widget:opened",()=>{c.setItem(g,"true")}),s.on("widget:closed",()=>{c.setItem(g,"false")})),(sd=po.persist)!=null&&sd.voiceState&&(s.on("voice:state",z=>{c.setItem(h,z.active?"true":"false")}),s.on("user:message",z=>{c.setItem(y,z.viaVoice?"true":"false")})),po.clearOnChatClear){let z=()=>{c.removeItem(g),c.removeItem(h),c.removeItem(y)},D=()=>z();window.addEventListener("persona:clear-chat",D),yt.push(()=>{window.removeEventListener("persona:clear-chat",D)})}}}return m&&S()&&setTimeout(()=>{nn.open()},0),_o(),nn};var wx=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},eg=(e,t)=>{var o,r;let n=(r=(o=t==null?void 0:t.launcher)==null?void 0:o.enabled)!=null?r:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},Gl=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},tg=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Gl(e)},ql=e=>{e.style.transition=""},jl=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform=""},Kl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Bi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Cx=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},Sx=(e,t,n,o,r,s)=>{let a=s?t:e;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},ng=(e,t,n,o,r,s,a)=>{var C,v,E,L,I,P;let i=Wo(s),d=i.reveal==="push";Cx(e,t,n,o,d),Sx(e,t,n,o,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,m=(v=(C=s==null?void 0:s.launcher)==null?void 0:C.mobileFullscreen)!=null?v:!0,p=(L=(E=s==null?void 0:s.launcher)==null?void 0:E.mobileBreakpoint)!=null?L:640,f=l!=null?l.innerWidth<=p:!1;if(m&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),jl(t),ql(o),tg(o),Kl(n),Bi(r,o),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String((P=(I=s==null?void 0:s.launcher)==null?void 0:I.zIndex)!=null?P:wn),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),tg(o),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",jl(t),ql(o),Kl(n),Bi(r,o);let H=i.animate?"transform 180ms ease":"none",W=i.side==="right"?"translateX(100%)":"translateX(-100%)",x=a?"translateX(0)":W;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=H,o.style.transform=x,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",i.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",ql(o),Gl(o),Bi(r,o);let H=wx(i.width,e.clientWidth),W=Math.max(0,e.clientWidth),x=i.animate?"transform 180ms ease":"none",w=i.side==="right"?a?`translateX(-${H}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${H}px)`;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${W+H}px`,t.style.transition=x,t.style.transform=w,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${W}px`,n.style.maxWidth=`${W}px`,n.style.minWidth=`${W}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.position="relative",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",jl(t),Gl(o),Kl(n),Bi(r,o);let H=i.reveal==="emerge";H?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let W=a?i.width:"0px",x=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",w=!a;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${W}`,o.style.width=W,o.style.maxWidth=W,o.style.minWidth=W,o.style.minHeight="0",o.style.position="relative",o.style.overflow=H||w?"hidden":"visible",o.style.transition=x,H&&(o.style.alignItems=i.side==="right"?"flex-start":"flex-end",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.boxSizing="border-box")}},Ax=(e,t)=>{let n=e.ownerDocument.createElement("div");return eg(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){eg(n,o)},destroy(){n.remove()}}},Tx=(e,t)=>{var I,P,H,W;let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),m=n.createElement("div"),p=(P=(I=t==null?void 0:t.launcher)==null?void 0:I.enabled)==null||P?(W=(H=t==null?void 0:t.launcher)==null?void 0:H.autoExpand)!=null?W:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",m.dataset.personaDockRole="host",l.appendChild(m),o.insertBefore(a,e),d.appendChild(e);let f=null,u=()=>{f==null||f.disconnect(),f=null},C=()=>{u(),Wo(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{ng(a,i,d,l,m,t,p)}),f.observe(a))},v=()=>{ng(a,i,d,l,m,t,p),C()},E=a.ownerDocument.defaultView,L=()=>{v()};return E==null||E.addEventListener("resize",L),Wo(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),v(),{mode:"docked",host:m,shell:a,syncWidgetState(x){let w=x.launcherEnabled?x.open:!0;p!==w&&(p=w,v())},updateConfig(x){var w,k;t=x,((k=(w=t==null?void 0:t.launcher)==null?void 0:w.enabled)!=null?k:!0)===!1&&(p=!0),v()},destroy(){E==null||E.removeEventListener("resize",L),u(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},og=(e,t)=>hn(t)?Tx(e,t):Ax(e,t);var ls={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Yl=.15,Xl=1.5,Hi="persona-preview-shell-theme",rg={load:()=>null,save:()=>{},clear:()=>{}},sg=["How do I get started?","Pricing & plans","Talk to support"];function Di(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function ag(e){return e==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function Ql(e){let t=ag(e);return`* { box-sizing: border-box; }
108
108
  html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
109
109
  html { color-scheme: ${e}; }
110
110
  body { font-family: system-ui, sans-serif; background: ${t.pageBg}; }
@@ -128,7 +128,7 @@ _Details: ${n.message}_`:o}var ei=class e{constructor(t={},n){this.config=t;this
128
128
  .preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
129
129
  .preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
130
130
  .preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${t.cardBg}; box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
131
- .preview-workspace-card.short { height: 96px; }`}function jl(e,t){let n=e.contentDocument;if(!(n!=null&&n.documentElement))return;let o=n.getElementById(Li);o||(o=n.createElement("style"),o.id=Li,n.head.appendChild(o)),o.textContent=ql(t)}var jm=`
131
+ .preview-workspace-card.short { height: 96px; }`}function Jl(e,t){let n=e.contentDocument;if(!(n!=null&&n.documentElement))return;let o=n.getElementById(Hi);o||(o=n.createElement("style"),o.id=Hi,n.head.appendChild(o)),o.textContent=Ql(t)}var ig=`
132
132
  <div class="preview-iframe-mock" aria-hidden="true">
133
133
  <div class="preview-iframe-chrome">
134
134
  <span class="preview-iframe-dot"></span>
@@ -147,7 +147,7 @@ _Details: ${n.message}_`:o}var ei=class e{constructor(t={},n){this.config=t;this
147
147
  <div class="preview-iframe-line body"></div>
148
148
  <div class="preview-iframe-line body"></div>
149
149
  </div>
150
- </div>`,Km=`
150
+ </div>`,lg=`
151
151
  <div class="preview-workspace-content-shell" aria-hidden="true">
152
152
  <div class="preview-iframe-line hero"></div>
153
153
  <div class="preview-iframe-line body"></div>
@@ -160,8 +160,8 @@ _Details: ${n.message}_`:o}var ei=class e{constructor(t={},n){this.config=t;this
160
160
  <div class="preview-workspace-card short"></div>
161
161
  <div class="preview-workspace-card short"></div>
162
162
  </div>
163
- </div>`;function Kl(e,t,n,o){let r=`
164
- ${jm}
163
+ </div>`;function Zl(e,t,n,o){let r=`
164
+ ${ig}
165
165
  <div style="position:fixed;inset:0;z-index:9999;"><div id="${e}" data-mount-id="${e}"></div></div>`,s=`
166
166
  <div class="preview-workspace-shell">
167
167
  <div class="preview-workspace-topbar">
@@ -173,7 +173,7 @@ _Details: ${n.message}_`:o}var ei=class e{constructor(t={},n){this.config=t;this
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
- ${Km}
176
+ ${lg}
177
177
  </div>
178
178
  </div>
179
179
  </div>`;return`<!DOCTYPE html>
@@ -181,19 +181,19 @@ _Details: ${n.message}_`:o}var ei=class e{constructor(t={},n){this.config=t;this
181
181
  <head>
182
182
  <meta charset="UTF-8">
183
183
  <meta name="viewport" content="width=device-width, initial-scale=1">
184
- <link rel="stylesheet" href="${Ii(o)}">
185
- <style id="${Li}">${ql(t)}</style>
184
+ <link rel="stylesheet" href="${Di(o)}">
185
+ <style id="${Hi}">${Ql(t)}</style>
186
186
  </head>
187
187
  <body>
188
188
  ${n?s:r}
189
189
  </body>
190
- </html>`}var dx={"user-message":"User message","assistant-message":"Assistant message","assistant-code-block":"Assistant \u2014 code block","assistant-markdown-table":"Assistant \u2014 markdown table","assistant-image":"Assistant \u2014 image","reasoning-streaming":"Reasoning (streaming)","reasoning-complete":"Reasoning (complete)","tool-running":"Tool call (running)","tool-complete":"Tool call (complete)"};function px(e){return dx[e]}function Gl(e,t=0){let n=new Date(Date.now()-Math.max(0,60-t)*1e3).toISOString(),o=`${e}-${t}`;switch(e){case"user-message":return{id:`preview-seq-user-${o}`,role:"user",content:"Can you continue with the next step?",createdAt:n};case"assistant-message":return{id:`preview-seq-assistant-${o}`,role:"assistant",content:"Absolutely. I can keep going and explain what happens next.",createdAt:n};case"assistant-code-block":return{id:`preview-seq-assistant-code-${o}`,role:"assistant",content:["Here's how you'd wire up a streaming animation:","","```ts","import { createAgentExperience } from '@runtypelabs/persona';","","createAgentExperience(el, {"," features: {",' streamAnimation: { type: "letter-rise", speed: 120 },'," },","});","```","","Swap the `type` value to try the other presets."].join(`
190
+ </html>`}var kx={"user-message":"User message","assistant-message":"Assistant message","assistant-code-block":"Assistant \u2014 code block","assistant-markdown-table":"Assistant \u2014 markdown table","assistant-image":"Assistant \u2014 image","reasoning-streaming":"Reasoning (streaming)","reasoning-complete":"Reasoning (complete)","tool-running":"Tool call (running)","tool-complete":"Tool call (complete)","approval-request":"Approval request"};function Ex(e){return kx[e]}function ec(e,t=0){let n=new Date(Date.now()-Math.max(0,60-t)*1e3).toISOString(),o=`${e}-${t}`;switch(e){case"user-message":return{id:`preview-seq-user-${o}`,role:"user",content:"Can you continue with the next step?",createdAt:n};case"assistant-message":return{id:`preview-seq-assistant-${o}`,role:"assistant",content:"Absolutely. I can keep going and explain what happens next.",createdAt:n};case"assistant-code-block":return{id:`preview-seq-assistant-code-${o}`,role:"assistant",content:["Here's how you'd wire up a streaming animation:","","```ts","import { createAgentExperience } from '@runtypelabs/persona';","","createAgentExperience(el, {"," features: {",' streamAnimation: { type: "letter-rise", speed: 120 },'," },","});","```","","Swap the `type` value to try the other presets."].join(`
191
191
  `),createdAt:n};case"assistant-markdown-table":return{id:`preview-seq-assistant-table-${o}`,role:"assistant",content:["Here are the built-in streaming animations at a glance:","","| Preset | Wrap unit | Best for |","| ------------ | --------- | --------------------------- |","| Typewriter | Character | Classic terminal feel |","| Letter rise | Character | Soft, staggered entrance |","| Word fade | Word | Longer-form assistant replies |","| Pop bubble | Bubble | Short, punchy affirmations |"].join(`
192
192
  `),createdAt:n};case"assistant-image":return{id:`preview-seq-assistant-image-${o}`,role:"assistant",content:["Here's the reference diagram you asked for \u2014 let me know if you'd like a different view:","","![Stream animation reference](https://placehold.co/320x200/png?text=Stream+Animation)","","The gradient shows how per-unit delays stagger across the reply."].join(`
193
- `),createdAt:n};case"reasoning-streaming":return{id:`preview-seq-reasoning-stream-${o}`,role:"assistant",content:"",createdAt:n,streaming:!0,variant:"reasoning",reasoning:{id:`preview-reasoning-stream-${o}`,status:"streaming",chunks:["Thinking through the next step in the workflow..."]}};case"reasoning-complete":return{id:`preview-seq-reasoning-complete-${o}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"reasoning",reasoning:{id:`preview-reasoning-complete-${o}`,status:"complete",chunks:["Reviewed the requirements and finalized the reasoning output."],durationMs:1200}};case"tool-complete":return{id:`preview-seq-tool-complete-${o}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"tool",toolCall:{id:`preview-tool-complete-${o}`,name:"Create build instructions",status:"complete",chunks:["Prepared the build instructions and validated the inputs."],result:{ok:!0},duration:420}};default:return{id:`preview-seq-tool-running-${o}`,role:"assistant",content:"",createdAt:n,streaming:!0,variant:"tool",toolCall:{id:`preview-tool-running-${o}`,name:"Get platform documentation",status:"running",chunks:["Fetching the relevant platform documentation..."]}}}}function ux(e,t){return[...e,Gl(t,e.length)]}function Gm(e){return e==="assistant-message"||e==="assistant-code-block"||e==="assistant-markdown-table"||e==="assistant-image"}function mx(e,t,n){var d,l;let o=Gl(e,t);if(!Gm(e)||typeof o.content!="string")return[{message:o,delayMs:0,done:!0}];let r=Math.max(1,(d=n==null?void 0:n.chunkSize)!=null?d:24),s=Math.max(0,(l=n==null?void 0:n.delayMs)!=null?l:42),a=o.content,i=[];i.push({message:{...o,content:"",streaming:!0},delayMs:0,done:!1});for(let p=r;p<a.length;p+=r)i.push({message:{...o,content:a.slice(0,p),streaming:!0},delayMs:s,done:!1});return i.push({message:{...o,content:a,streaming:!1},delayMs:s,done:!0}),i}var gx=()=>[{id:"preview-adv-1",role:"user",content:"Can you create the product and gather the docs?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-adv-2",role:"assistant",content:"",createdAt:new Date(Date.now()-15e4).toISOString(),streaming:!0,variant:"reasoning",reasoning:{id:"preview-reasoning",status:"streaming",chunks:["Now let me get the Persona embed documentation and builtin tools catalog."]}},{id:"preview-adv-3",role:"assistant",content:"",createdAt:new Date(Date.now()-12e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-1",name:"Load tools",status:"running",chunks:["Loaded tools, used Runtype integration"]}},{id:"preview-adv-4",role:"assistant",content:"",createdAt:new Date(Date.now()-9e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-2",name:"Get platform documentation",status:"running",chunks:["Get platform documentation"]}},{id:"preview-adv-5",role:"assistant",content:"I loaded the tools and fetched the docs. Next I can assemble the product details.",createdAt:new Date(Date.now()-3e4).toISOString()}],fx=e=>{var t,n,o,r,s,a,i,d;return!!((n=(t=e==null?void 0:e.features)==null?void 0:t.toolCallDisplay)!=null&&n.activePreview||(r=(o=e==null?void 0:e.features)==null?void 0:o.toolCallDisplay)!=null&&r.grouped||(a=(s=e==null?void 0:e.features)==null?void 0:s.toolCallDisplay)!=null&&a.collapsedMode&&e.features.toolCallDisplay.collapsedMode!=="tool-call"||(d=(i=e==null?void 0:e.features)==null?void 0:i.reasoningDisplay)!=null&&d.activePreview)};function Ym(e,t,n=[]){return e==="home"?[{id:"preview-home-1",role:"assistant",content:"Hi there! How can we help today?",createdAt:new Date().toISOString()}]:e==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:e==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:e==="conversation"&&fx(t)?[...gx(),...n]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...n]}function Yl(e,t,n=[]){var s,a;let o={...e.launcher,enabled:!0,autoExpand:t!=="minimized"},r={...e,launcher:o,suggestionChips:t==="home"?(s=e.suggestionChips)!=null&&s.length?e.suggestionChips:zm:e.suggestionChips,initialMessages:Ym(t,e,n),storageAdapter:Um};return t==="artifact"&&(r.features={...r.features,artifacts:{...(a=r.features)==null?void 0:a.artifacts,enabled:!0}}),r}function Lr(e,t){var s,a,i,d;let n=e.theme?tn(e.theme,{validate:!1}):tn(),o=(s=e.scene)!=null?s:"conversation",r={...St,...e.config,theme:n,darkTheme:e.darkTheme,colorScheme:(i=t!=null?t:(a=e.config)==null?void 0:a.colorScheme)!=null?i:"light"};return Yl(r,o,(d=e.appendedMessages)!=null?d:[])}function hx(e,t,n){var a,i,d;let o=e.theme?tn(e.theme,{validate:!1}):tn(),r=(a=e.scene)!=null?a:"conversation",s={...St,...e.config,theme:o,darkTheme:e.darkTheme,colorScheme:(d=n!=null?n:(i=e.config)==null?void 0:i.colorScheme)!=null?d:"light"};return Yl(s,r,t)}function Xm(e){var o,r,s,a,i;let t=(o=e.compareMode)!=null?o:"off",n=(r=e.shellMode)!=null?r:"light";if(t==="themes")return[{mountId:"preview-light",label:"Light",config:Lr(e,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Lr(e,"dark"),shellMode:"dark"}];if(t==="baseline"&&(e.baselineConfig||e.baselineTheme)){let d={...e,config:(s=e.baselineConfig)!=null?s:e.config,theme:(a=e.baselineTheme)!=null?a:e.theme,darkTheme:(i=e.baselineDarkTheme)!=null?i:e.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:Lr(d,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Lr(e,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Lr(e,n),shellMode:n}]}function bx(e,t){let n={...t},o=[],r=[],s=null,a=!1,i=1,d=1,l=0;function p(){var R;return(R=n.device)!=null?R:"desktop"}function m(){var R;return(R=n.zoom)!=null?R:i}function f(){var E,F;let R=getComputedStyle(e),H=parseFloat(R.paddingLeft)+parseFloat(R.paddingRight),D=parseFloat(R.paddingTop)+parseFloat(R.paddingBottom),B=40,v=((E=n.compareMode)!=null?E:"off")!=="off",x=(e.clientWidth-H-B)/(v?2:1),k=e.clientHeight-D-B;if(x<=0||k<=0)return 1;let S=(F=ts[p()])!=null?F:ts.desktop;return Math.min(x/S.w,k/S.h,1)}function u(){var D,B,v;i=f();let R=Math.max(Ul,Math.min(zl,m()));d=R;let H=Array.from(e.querySelectorAll(".preview-iframe-wrapper"));for(let x of H){let k=(D=x.dataset.device)!=null?D:"desktop",S=(B=ts[k])!=null?B:ts.desktop;x.style.width=`${S.w*R}px`,x.style.height=`${S.h*R}px`,k==="mobile"&&(x.style.borderRadius=`${32*R}px`);let E=x.querySelector("iframe");E&&(E.style.width=`${S.w}px`,E.style.height=`${S.h}px`,E.style.transformOrigin="top left",E.style.transition="none",E.style.transform=`scale(${R})`)}(v=n.onScaleChange)==null||v.call(n,R)}function w(){var R;(R=n.onBeforeDestroy)==null||R.call(n);for(let H of o)H.destroy();for(let H of r)H();o=[],r=[]}function C(){return Array.from(e.querySelectorAll("iframe[data-mount-id]"))}function M(){var ge,ie,be,Fe;if(a)return;w();let R=++l,H=Xm(n),D=p(),B=((ge=n.compareMode)!=null?ge:"off")!=="off",v=((ie=n.scene)!=null?ie:"conversation")==="minimized",x=(be=n.widgetCssPath)!=null?be:"/widget-dist/widget.css",k=(Fe=n.buildSrcdoc)!=null?Fe:Kl,S=D==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",E=ve=>`<div class="${S}" data-mount-id="${ve.mountId}" data-device="${D}" data-shell-mode="${ve.shellMode}">
194
- ${B?`<div class="preview-frame-meta"><span class="preview-frame-label">${Ii(ve.label)}</span></div>`:""}
195
- <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${ve.mountId}"></iframe>
196
- </div>`,F=B?`<div class="preview-compare-grid">${H.map(ve=>`<div class="preview-compare-cell">${E(ve)}</div>`).join("")}</div>`:`<div class="preview-single">${E(H[0])}</div>`;n.morphContainer?n.morphContainer(e,F):e.innerHTML=F,u();let $=C(),j=0,me=$.length,se=()=>{var J,Le,Y,xe,Se;if(a||R!==l)return;for(let de of $){let we=de.dataset.mountId;if(!we||!de.contentDocument)continue;let Ue=H.find(ye=>ye.mountId===we);if(!Ue)continue;let te=()=>{},ne=pn(Ue.config),re=ne?(()=>{var K;let ye=(K=de.contentDocument)==null?void 0:K.getElementById(`preview-content-${we}`);if(!ye)return null;let le=$m(ye,Ue.config),$e=de.contentDocument.createElement("div");$e.id=we,$e.style.height="100%",$e.style.display="flex",$e.style.flexDirection="column",$e.style.flex="1",$e.style.minHeight="0",le.host.appendChild($e);let Be=()=>le.syncWidgetState(nt.getState()),ce=te;return te=()=>{le.destroy(),ce()},$e.__syncDock=Be,$e.__hostLayout=le,$e})():de.contentDocument.getElementById(we);if(!re)continue;let nt=Om(re,Ue.config);if(o.push(nt),ne&&re.__syncDock){let ye=re.__syncDock,le=nt.on("widget:opened",ye),$e=nt.on("widget:closed",ye),Be=te;te=()=>{le(),$e(),Be()},ye()}r.push(te),v&&nt.close()}if(((J=n.scene)!=null?J:"conversation")==="artifact"||(xe=(Y=(Le=n.config)==null?void 0:Le.features)==null?void 0:Y.artifacts)!=null&&xe.enabled)for(let de of o)de.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
193
+ `),createdAt:n};case"reasoning-streaming":return{id:`preview-seq-reasoning-stream-${o}`,role:"assistant",content:"",createdAt:n,streaming:!0,variant:"reasoning",reasoning:{id:`preview-reasoning-stream-${o}`,status:"streaming",chunks:["Thinking through the next step in the workflow..."]}};case"reasoning-complete":return{id:`preview-seq-reasoning-complete-${o}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"reasoning",reasoning:{id:`preview-reasoning-complete-${o}`,status:"complete",chunks:["Reviewed the requirements and finalized the reasoning output."],durationMs:1200}};case"approval-request":{let r=`preview-approval-${o}`;return{id:`approval-${r}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"approval",approval:{id:r,status:"pending",agentId:"preview-agent",executionId:`preview-exec-${o}`,toolName:"add_to_cart",description:"Add the selected item to the shopping cart. Approve to let the assistant continue.",parameters:{items:[{productEntityId:129,quantity:1}]}}}}case"tool-complete":return{id:`preview-seq-tool-complete-${o}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"tool",toolCall:{id:`preview-tool-complete-${o}`,name:"Create build instructions",status:"complete",chunks:["Prepared the build instructions and validated the inputs."],result:{ok:!0},duration:420}};default:return{id:`preview-seq-tool-running-${o}`,role:"assistant",content:"",createdAt:n,streaming:!0,variant:"tool",toolCall:{id:`preview-tool-running-${o}`,name:"Get platform documentation",status:"running",chunks:["Fetching the relevant platform documentation..."]}}}}function Mx(e,t){return[...e,ec(t,e.length)]}function cg(e){return e==="assistant-message"||e==="assistant-code-block"||e==="assistant-markdown-table"||e==="assistant-image"}function Lx(e,t,n){var d,l;let o=ec(e,t);if(!cg(e)||typeof o.content!="string")return[{message:o,delayMs:0,done:!0}];let r=Math.max(1,(d=n==null?void 0:n.chunkSize)!=null?d:24),s=Math.max(0,(l=n==null?void 0:n.delayMs)!=null?l:42),a=o.content,i=[];i.push({message:{...o,content:"",streaming:!0},delayMs:0,done:!1});for(let m=r;m<a.length;m+=r)i.push({message:{...o,content:a.slice(0,m),streaming:!0},delayMs:s,done:!1});return i.push({message:{...o,content:a,streaming:!1},delayMs:s,done:!0}),i}var Ix=()=>[{id:"preview-adv-1",role:"user",content:"Can you create the product and gather the docs?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-adv-2",role:"assistant",content:"",createdAt:new Date(Date.now()-15e4).toISOString(),streaming:!0,variant:"reasoning",reasoning:{id:"preview-reasoning",status:"streaming",chunks:["Now let me get the Persona embed documentation and builtin tools catalog."]}},{id:"preview-adv-3",role:"assistant",content:"",createdAt:new Date(Date.now()-12e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-1",name:"Load tools",status:"running",chunks:["Loaded tools, used Runtype integration"]}},{id:"preview-adv-4",role:"assistant",content:"",createdAt:new Date(Date.now()-9e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-2",name:"Get platform documentation",status:"running",chunks:["Get platform documentation"]}},{id:"preview-adv-5",role:"assistant",content:"I loaded the tools and fetched the docs. Next I can assemble the product details.",createdAt:new Date(Date.now()-3e4).toISOString()}],Rx=e=>{var t,n,o,r,s,a,i,d;return!!((n=(t=e==null?void 0:e.features)==null?void 0:t.toolCallDisplay)!=null&&n.activePreview||(r=(o=e==null?void 0:e.features)==null?void 0:o.toolCallDisplay)!=null&&r.grouped||(a=(s=e==null?void 0:e.features)==null?void 0:s.toolCallDisplay)!=null&&a.collapsedMode&&e.features.toolCallDisplay.collapsedMode!=="tool-call"||(d=(i=e==null?void 0:e.features)==null?void 0:i.reasoningDisplay)!=null&&d.activePreview)};function dg(e,t,n=[]){return e==="home"?[{id:"preview-home-1",role:"assistant",content:"Hi there! How can we help today?",createdAt:new Date().toISOString()}]:e==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:e==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:e==="conversation"&&Rx(t)?[...Ix(),...n]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...n]}function tc(e,t,n=[]){var s,a;let o={...e.launcher,enabled:!0,autoExpand:t!=="minimized"},r={...e,launcher:o,suggestionChips:t==="home"?(s=e.suggestionChips)!=null&&s.length?e.suggestionChips:sg:e.suggestionChips,initialMessages:dg(t,e,n),storageAdapter:rg};return t==="artifact"&&(r.features={...r.features,artifacts:{...(a=r.features)==null?void 0:a.artifacts,enabled:!0}}),r}function Wr(e,t){var s,a,i,d;let n=e.theme?sn(e.theme,{validate:!1}):sn(),o=(s=e.scene)!=null?s:"conversation",r={...It,...e.config,theme:n,darkTheme:e.darkTheme,colorScheme:(i=t!=null?t:(a=e.config)==null?void 0:a.colorScheme)!=null?i:"light"};return tc(r,o,(d=e.appendedMessages)!=null?d:[])}function Px(e,t,n){var a,i,d;let o=e.theme?sn(e.theme,{validate:!1}):sn(),r=(a=e.scene)!=null?a:"conversation",s={...It,...e.config,theme:o,darkTheme:e.darkTheme,colorScheme:(d=n!=null?n:(i=e.config)==null?void 0:i.colorScheme)!=null?d:"light"};return tc(s,r,t)}function pg(e){var o,r,s,a,i;let t=(o=e.compareMode)!=null?o:"off",n=(r=e.shellMode)!=null?r:"light";if(t==="themes")return[{mountId:"preview-light",label:"Light",config:Wr(e,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Wr(e,"dark"),shellMode:"dark"}];if(t==="baseline"&&(e.baselineConfig||e.baselineTheme)){let d={...e,config:(s=e.baselineConfig)!=null?s:e.config,theme:(a=e.baselineTheme)!=null?a:e.theme,darkTheme:(i=e.baselineDarkTheme)!=null?i:e.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:Wr(d,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Wr(e,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Wr(e,n),shellMode:n}]}function Wx(e,t){let n={...t},o=[],r=[],s=null,a=!1,i=1,d=1,l=0;function m(){var I;return(I=n.device)!=null?I:"desktop"}function p(){var I;return(I=n.zoom)!=null?I:i}function f(){var A,N;let I=getComputedStyle(e),P=parseFloat(I.paddingLeft)+parseFloat(I.paddingRight),H=parseFloat(I.paddingTop)+parseFloat(I.paddingBottom),W=40,x=((A=n.compareMode)!=null?A:"off")!=="off",w=(e.clientWidth-P-W)/(x?2:1),k=e.clientHeight-H-W;if(w<=0||k<=0)return 1;let S=(N=ls[m()])!=null?N:ls.desktop;return Math.min(w/S.w,k/S.h,1)}function u(){var H,W,x;i=f();let I=Math.max(Yl,Math.min(Xl,p()));d=I;let P=Array.from(e.querySelectorAll(".preview-iframe-wrapper"));for(let w of P){let k=(H=w.dataset.device)!=null?H:"desktop",S=(W=ls[k])!=null?W:ls.desktop;w.style.width=`${S.w*I}px`,w.style.height=`${S.h*I}px`,k==="mobile"&&(w.style.borderRadius=`${32*I}px`);let A=w.querySelector("iframe");A&&(A.style.width=`${S.w}px`,A.style.height=`${S.h}px`,A.style.transformOrigin="top left",A.style.transition="none",A.style.transform=`scale(${I})`)}(x=n.onScaleChange)==null||x.call(n,I)}function C(){var I;(I=n.onBeforeDestroy)==null||I.call(n);for(let P of o)P.destroy();for(let P of r)P();o=[],r=[]}function v(){return Array.from(e.querySelectorAll("iframe[data-mount-id]"))}function E(){var se,ke,be,Fe;if(a)return;C();let I=++l,P=pg(n),H=m(),W=((se=n.compareMode)!=null?se:"off")!=="off",x=((ke=n.scene)!=null?ke:"conversation")==="minimized",w=(be=n.widgetCssPath)!=null?be:"/widget-dist/widget.css",k=(Fe=n.buildSrcdoc)!=null?Fe:Zl,S=H==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",A=xe=>`<div class="${S}" data-mount-id="${xe.mountId}" data-device="${H}" data-shell-mode="${xe.shellMode}">
194
+ ${W?`<div class="preview-frame-meta"><span class="preview-frame-label">${Di(xe.label)}</span></div>`:""}
195
+ <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${xe.mountId}"></iframe>
196
+ </div>`,N=W?`<div class="preview-compare-grid">${P.map(xe=>`<div class="preview-compare-cell">${A(xe)}</div>`).join("")}</div>`:`<div class="preview-single">${A(P[0])}</div>`;n.morphContainer?n.morphContainer(e,N):e.innerHTML=N,u();let $=v(),G=0,fe=$.length,ge=()=>{var j,de,K,ye,le;if(a||I!==l)return;for(let te of $){let Ce=te.dataset.mountId;if(!Ce||!te.contentDocument)continue;let Ue=P.find(Ae=>Ae.mountId===Ce);if(!Ue)continue;let ee=()=>{},oe=hn(Ue.config),ae=oe?(()=>{var X;let Ae=(X=te.contentDocument)==null?void 0:X.getElementById(`preview-content-${Ce}`);if(!Ae)return null;let pe=og(Ae,Ue.config),$e=te.contentDocument.createElement("div");$e.id=Ce,$e.style.height="100%",$e.style.display="flex",$e.style.flexDirection="column",$e.style.flex="1",$e.style.minHeight="0",pe.host.appendChild($e);let We=()=>pe.syncWidgetState(rt.getState()),ue=ee;return ee=()=>{pe.destroy(),ue()},$e.__syncDock=We,$e.__hostLayout=pe,$e})():te.contentDocument.getElementById(Ce);if(!ae)continue;let rt=Zm(ae,Ue.config);if(o.push(rt),oe&&ae.__syncDock){let Ae=ae.__syncDock,pe=rt.on("widget:opened",Ae),$e=rt.on("widget:closed",Ae),We=ee;ee=()=>{pe(),$e(),We()},Ae()}r.push(ee),x&&rt.close()}if(((j=n.scene)!=null?j:"conversation")==="artifact"||(ye=(K=(de=n.config)==null?void 0:de.features)==null?void 0:K.artifacts)!=null&&ye.enabled)for(let te of o)te.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
197
197
 
198
198
  This is a preview of the artifact sidebar.
199
199
 
@@ -201,4 +201,4 @@ This is a preview of the artifact sidebar.
201
201
 
202
202
  - Markdown rendering
203
203
  - Document toolbar
204
- - Resizable panes`});(Se=n.onAfterMount)==null||Se.call(n,{iframes:$,controllers:[...o]})};for(let ve of $){let J=ve.dataset.mountId;if(!J)continue;let Le=H.find(Y=>Y.mountId===J);Le&&(ve.addEventListener("load",()=>{j++,j>=me&&se()},{once:!0}),ve.srcdoc=k(J,Le.shellMode,pn(Le.config),x))}me===0&&se()}function I(){var D;if(a)return;let R=Xm(n);if(o.length!==R.length){M();return}if(R.some(B=>{let v=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${B.mountId}"]`);return!v||v.dataset.shellMode!==B.shellMode})){M();return}o.forEach((B,v)=>{var x;B.update(R[v].config),((x=n.scene)!=null?x:"conversation")==="minimized"&&B.close()});for(let B of R){let v=e.querySelector(`iframe[data-mount-id="${B.mountId}"]`);v&&jl(v,B.shellMode)}(D=n.onAfterUpdate)==null||D.call(n,{iframes:C(),controllers:[...o]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||u()}),s.observe(e)),M(),{update(R){if(a)return;let H=R.device!==void 0&&R.device!==n.device||R.scene!==void 0&&R.scene!==n.scene||R.compareMode!==void 0&&R.compareMode!==n.compareMode||R.widgetCssPath!==void 0&&R.widgetCssPath!==n.widgetCssPath;n={...n,...R},H?M():I()},destroy(){a||(a=!0,w(),s==null||s.disconnect(),e.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},u())},getIframes(){return C()},getScale(){return d},setZoom(R){a||(n={...n,zoom:R},u())}}}function Vo(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}var Pi={black:"#000000",white:"#ffffff",red:"#ff0000",green:"#008000",lime:"#00ff00",blue:"#0000ff",yellow:"#ffff00",cyan:"#00ffff",aqua:"#00ffff",magenta:"#ff00ff",fuchsia:"#ff00ff",silver:"#c0c0c0",gray:"#808080",grey:"#808080",maroon:"#800000",olive:"#808000",purple:"#800080",teal:"#008080",navy:"#000080",orange:"#ffa500",pink:"#ffc0cb",hotpink:"#ff69b4",gold:"#ffd700",indigo:"#4b0082",violet:"#ee82ee",brown:"#a52a2a",beige:"#f5f5dc",ivory:"#fffff0",khaki:"#f0e68c",coral:"#ff7f50",salmon:"#fa8072",tomato:"#ff6347",crimson:"#dc143c",turquoise:"#40e0d0",lavender:"#e6e6fa",plum:"#dda0dd",orchid:"#da70d6",tan:"#d2b48c",chocolate:"#d2691e",sienna:"#a0522d",slategray:"#708090",slategrey:"#708090",steelblue:"#4682b4",royalblue:"#4169e1",dodgerblue:"#1e90ff",skyblue:"#87ceeb",lightblue:"#add8e6",midnightblue:"#191970",forestgreen:"#228b22",seagreen:"#2e8b57",limegreen:"#32cd32",olivedrab:"#6b8e23",darkgreen:"#006400",emerald:"#50c878",mint:"#3eb489",goldenrod:"#daa520",firebrick:"#b22222",darkred:"#8b0000",indianred:"#cd5c5c",deeppink:"#ff1493",mediumpurple:"#9370db",rebeccapurple:"#663399",darkviolet:"#9400d3",slateblue:"#6a5acd",cornflowerblue:"#6495ed",teal2:"#008080",charcoal:"#36454f",graphite:"#3b3b3b",transparent:"transparent"},yx=/^rgba?\(\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*(,\s*(0|1|0?\.\d+|\d{1,3}%)\s*)?\)$/;function vx(e){return yx.test(e)}function ns(e){if(typeof e!="string"||e.trim()==="")throw new Error('Color must be a non-empty string (e.g. "#2563eb" or "blue").');let t=e.trim().toLowerCase(),n=Pi[t];if(n)return n;let o=ks(t);if(Yi(o)||o==="transparent"||vx(o))return o;throw new Error(`"${e}" is not a recognized color. Pass a hex value like "#ef4444" or a CSS color name (e.g. ${Object.keys(Pi).slice(0,6).join(", ")}).`)}var Wi=Ma.map(e=>e==="gray"?"neutral":e),xx={...Object.fromEntries(Wi.map(e=>[e,e])),gray:"neutral",grey:"neutral"};function Bi(e,t=!0){let n=String(e!=null?e:"").trim().toLowerCase(),o=xx[n];if(!o||!t&&o==="neutral"){let r=t?"primary, secondary, accent, neutral":"primary, secondary, accent";throw new Error(`Unknown color family "${e}". Valid families: ${r}.`)}return o}function Hi(e){let t=String(e!=null?e:"solid").trim().toLowerCase();if(t==="solid"||t==="soft")return t;throw new Error(`Unknown intensity "${e}". Valid intensities: solid, soft.`)}function Di(e){let t=String(e!=null?e:"").trim().toLowerCase();if(t==="light"||t==="dark"||t==="auto")return t;if(t==="system")return"auto";throw new Error(`Unknown color scheme "${e}". Valid: light, dark, auto.`)}var wx={sharp:"sharp",square:"sharp",none:"sharp",default:"default",normal:"default",rounded:"rounded",round:"rounded",soft:"rounded",pill:"pill",circle:"pill",full:"pill"};function Fi(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=wx[t];if(!n)throw new Error(`Unknown roundness "${e}". Valid: sharp, default, rounded, pill.`);return n}function Oi(e){if(typeof e=="number"&&Number.isFinite(e))return`${e}px`;if(typeof e=="string"&&e.trim()!==""){let t=e.trim();if(t==="9999px"||/^(100%|9999px)$/.test(t))return"9999px";let n=Ki(t);return Gi(n.value,n.unit)}throw new Error('Radius must be a number (px) or a CSS length string like "0.5rem".')}function Ni(e){for(let t of zr){let n=t.fields.find(o=>o.id===e);if(n!=null&&n.options){let o={};for(let r of n.options){let s=r.value.split(".").pop();s&&(o[s]=r.value)}return o}}return{}}var Qm=Ni("typo-font-family"),Zs=Ni("typo-font-size"),ea=Ni("typo-font-weight"),Ri=Ni("typo-line-height"),Jm={...Qm,monospace:Qm.mono},Zm={...Zs,small:Zs.sm,md:Zs.base,medium:Zs.base,large:Zs.lg},eg={...ea,400:ea.normal,500:ea.medium,600:ea.semibold,700:ea.bold},tg={...Ri,"1.25":Ri.tight,"1.5":Ri.normal,"1.625":Ri.relaxed};function ng(e,t,n){let o=String(e!=null?e:"").trim().toLowerCase(),r=t[o];if(!r){let s=[...new Set(Object.values(t).map(a=>a.split(".").pop()))].join(", ");throw new Error(`Unknown ${n} "${e}". Valid: ${s}.`)}return r}var og="theme.palette.radius.";function Cx(){var t;let e={pill:{sm:"9999px",md:"9999px",lg:"9999px",xl:"9999px",full:"9999px"}};for(let n of zr)for(let o of(t=n.presets)!=null?t:[]){let r=o.id.match(/^radius-(\w+)$/);if(!r)continue;let s={};for(let[a,i]of Object.entries(o.values))a.startsWith(og)&&typeof i=="string"&&(s[a.slice(og.length)]=i);e[r[1]]=s}return e}var na=Cx(),rg=["sm","md","lg","xl","full"];function Vi(e,t,n="theme",o=0){if(o>6)return null;let r=e.get(`${n}.${t}`);return typeof r!="string"||r===""?n==="darkTheme"?Vi(e,t,"theme",o):null:r.startsWith("#")||r.startsWith("rgb")||r==="transparent"?r:r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components.")?Vi(e,r,n,o+1):null}function _i(e,t){let n=e.get(t);if(typeof n!="string")return"unknown";let o=n.split(".");return o[o.length-1]||String(n)}function os(e){return e.replace(/^role-/,"")}function Sx(e){for(let[t,n]of Object.entries(na))if(rg.every(o=>e[o]===n[o]))return t;return"custom"}function Ir(e){var o,r;let t={};for(let s of rg)t[s]=String((o=e.get(`theme.palette.radius.${s}`))!=null?o:"");let n={};for(let s of wr)n[os(s.roleId)]=Zi(a=>e.get(`theme.${a}`),s);return{brand:{primary:Xl(e.get("theme.palette.colors.primary.500")),secondary:Xl(e.get("theme.palette.colors.secondary.500")),accent:Xl(e.get("theme.palette.colors.accent.500"))},roles:n,typography:{fontFamily:_i(e,"theme.semantic.typography.fontFamily"),fontSize:_i(e,"theme.semantic.typography.fontSize"),fontWeight:_i(e,"theme.semantic.typography.fontWeight"),lineHeight:_i(e,"theme.semantic.typography.lineHeight")},roundness:{style:Sx(t),radius:t},colorScheme:String((r=e.get("colorScheme"))!=null?r:"light"),history:{index:e.getHistoryIndex(),canUndo:e.canUndo(),canRedo:e.canRedo()}}}function Xl(e){return typeof e=="string"&&e!==""?e:null}var ta=[{key:"user-message",label:"User message text",fg:"components.message.user.text",bg:"components.message.user.background"},{key:"assistant-message",label:"Assistant message text",fg:"components.message.assistant.text",bg:"components.message.assistant.background"},{key:"header",label:"Header title",fg:"components.header.titleForeground",bg:"components.header.background"},{key:"primary-button",label:"Primary button label",fg:"components.button.primary.foreground",bg:"components.button.primary.background"},{key:"input",label:"Input placeholder",fg:"components.input.placeholder",bg:"components.input.background"},{key:"link",label:"Link text",fg:"components.markdown.link.foreground",bg:"semantic.colors.background"},{key:"scroll",label:"Scroll-to-bottom icon",fg:"components.scrollToBottom.foreground",bg:"components.scrollToBottom.background"},{key:"body",label:"Body text on background",fg:"semantic.colors.text",bg:"semantic.colors.background"},{key:"surface",label:"Body text on surface",fg:"semantic.colors.text",bg:"semantic.colors.surface"}];function sg(e){let t=new Set(e.targets.map(n=>n.path));return ta.filter(n=>t.has(n.fg)||t.has(n.bg)).map(n=>n.key)}var Ax={AA:4.5,AAA:7};function Tx(e){return Math.round(e*100)/100}function kx(e,t,n,o,r){let s=e.get(`${r}.${t}`);if(typeof s!="string")return null;let a=s.match(/^palette\.colors\.(\w+)\.(\d+)$/);if(!a)return null;let i=a[1],d=Ur.indexOf(a[2]),l=null,p=1/0;return Ur.forEach((m,f)=>{let u=e.get(`${r}.palette.colors.${i}.${m}`);if(!(typeof u!="string"||!(u.startsWith("#")||u.startsWith("rgb")))&&Ea(u,n)>=o){let w=d>=0?Math.abs(f-d):f;w<p&&(p=w,l=`palette.colors.${i}.${m}`)}}),l}function oa(e,t="AA",n="both",o){let r=Ax[t],s=n==="both"?["light","dark"]:[n],a=o?ta.filter(d=>o.includes(d.key)):ta,i=[];for(let d of s){let l=d==="light"?"theme":"darkTheme";for(let p of a){let m=Vi(e,p.fg,l),f=Vi(e,p.bg,l);if(!m||!f)continue;let u=Tx(Ea(m,f)),w=u>=r,C={pair:p.key,label:p.label,variant:d,fg:m,bg:f,ratio:u,threshold:r,passes:w};if(!w){let M=kx(e,p.fg,f,r,l);M&&(C.suggestion=M)}i.push(C)}}return{level:t,checks:i,failures:i.filter(d=>!d.passes)}}function rs(e,t,n="light",o="AA"){return t.length===0?[]:oa(e,o,n,t).failures.map(s=>({code:"contrast",pair:s.pair,variant:s.variant,ratio:s.ratio,threshold:s.threshold,message:`${s.label} (${s.variant}) has a contrast ratio of ${s.ratio}:1, below the ${o} threshold of ${s.threshold}:1${s.suggestion?`. Try ${s.suggestion} for the foreground.`:"."}`}))}var an={};for(let e of wr){let t=os(e.roleId);an[t]=e,an[e.roleId]=e}Object.assign(an,{surface:an.surfaces,background:an.surfaces,backgrounds:an.surfaces,user:an["user-messages"],"user-message":an["user-messages"],assistant:an["assistant-messages"],"assistant-message":an["assistant-messages"],actions:an["primary-actions"],buttons:an["primary-actions"],composer:an.input,links:an["links-focus"],focus:an["links-focus"],border:an.borders,dividers:an.borders,scroll:an["scroll-to-bottom"]});function Ex(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=an[t];if(!n){let o=wr.map(r=>os(r.roleId)).join(", ");throw new Error(`Unknown role "${e}". Valid roles: ${o}.`)}return n}function ag(){let e=new Map,t=n=>{for(let o of n)for(let r of o.fields)e.has(r.id)||e.set(r.id,r)};for(let n of tl)t(n.sections);for(let n of Na)t(n.sections);return e}var Mx={voice:"voiceRecognition.enabled",artifacts:"features.artifacts.enabled",attachments:"attachments.enabled",toolCalls:"features.showToolCalls",reasoning:"features.showReasoning",feedback:"messageActions.enabled"},Lx={avatars:"layout.messages.avatar.show",timestamps:"layout.messages.timestamp.show",showHeader:"layout.showHeader",messageStyle:"layout.messages.layout"},Ql=["bottom-right","bottom-left","top-right","top-left"],Jl=["bubble","flat","minimal"],Ix={title:"copy.welcomeTitle",subtitle:"copy.welcomeSubtitle",placeholder:"copy.inputPlaceholder",sendLabel:"copy.sendButtonLabel"};function ig(e,t){var B;let n=(B=t==null?void 0:t.editTarget)!=null?B:"both",o=null,r=v=>v&&typeof v=="object"?v:{},s=(v,x,k=n)=>{let S={};return(k==="light"||k==="both")&&(S[`theme.${v}`]=x),(k==="dark"||k==="both")&&(S[`darkTheme.${v}`]=x),S},a=v=>{if(n==="both")return v;let x={};for(let[k,S]of Object.entries(v))(n==="light"&&k.startsWith("theme.")||n==="dark"&&k.startsWith("darkTheme."))&&(x[k]=S);return x},i=()=>n==="dark"?"dark":"light",d=(v,x=[])=>Vo({ok:!0,summary:Ir(e),warnings:x,applied:v});return[{name:"get_theme_overview",title:"Get current theme & what is editable",description:"Read the current widget theme (brand colors, per-role color assignments, typography, roundness, color scheme, undo/redo state), the available presets, and the high-level levers you can change. Call this FIRST before editing.",annotations:{readOnlyHint:!0},inputSchema:{type:"object",properties:{verbosity:{type:"string",enum:["summary","full"],description:"Use 'full' to also include the field-id index for set_theme_fields."}},additionalProperties:!1},execute(v){let{verbosity:x}=r(v),k={summary:Ir(e),availableRoles:wr.map(S=>({role:os(S.roleId),helper:S.helper})),availableFamilies:Wi,presets:Ms.map(S=>{var E;return{id:S.id,name:S.name,description:S.description,tags:(E=S.tags)!=null?E:[]}}),tools:[{tool:"set_brand_colors",hint:"Recolor the palette (primary/secondary/accent) \u2014 auto-generates shade scales."},{tool:"assign_color_role",hint:"Recolor a region (header, user/assistant messages, actions, input, links, borders, surfaces, scroll) with a family + intensity."},{tool:"set_typography",hint:"Set font family, size, weight, line height."},{tool:"set_roundness",hint:"Set corner roundness (sharp/default/rounded/pill) or granular radii."},{tool:"set_color_scheme",hint:"Set light/dark/auto and which variant edits target."},{tool:"apply_preset",hint:"Apply a complete built-in preset."},{tool:"configure_widget",hint:"Toggle launcher position, features, and layout."},{tool:"set_copy_and_suggestions",hint:"Set welcome copy, placeholder, and suggestion chips."},{tool:"set_theme_fields",hint:"Advanced escape hatch: set any field by id or dot-path."},{tool:"check_contrast",hint:"Audit WCAG contrast across key text/background pairs."},{tool:"manage_session",hint:"Undo, redo, reset, or export the theme."}]};return x==="full"&&(o!=null||(o=ag()),k.fieldIndex=Array.from(o.values()).map(S=>{var E;return{id:S.id,path:S.path,type:S.type,label:S.label,options:(E=S.options)==null?void 0:E.map(F=>F.value)}})),Vo(k)}},{name:"set_brand_colors",title:"Set brand colors",description:'Set one or more brand colors (primary, secondary, accent). Each color auto-generates a full 50\u2013950 shade scale and applies to the light and dark themes (per the current edit target). Accepts hex ("#2563eb", "2563eb", "#18f"), rgb()/rgba() ("rgb(37, 99, 235)"), or CSS color names ("blue", "slateblue").',inputSchema:{type:"object",properties:{primary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},secondary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},accent:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."}},additionalProperties:!1},execute(v){let x=r(v),k=["primary","secondary","accent"],S={},E={};for(let $ of k){if(x[$]===void 0)continue;let j=ns(x[$]);E[$]=j;let me=Qi(j);for(let se of Ur){let ge=me[se];ge!==void 0&&Object.assign(S,s(`palette.colors.${$}.${se}`,ge))}}if(Object.keys(E).length===0)throw new Error("Provide at least one of: primary, secondary, accent.");e.setBatch(S);let F=rs(e,["primary-button","user-message"],i());return d(E,F)}},{name:"assign_color_role",title:"Assign a color family to an interface role",description:"Recolor a semantic region of the widget by choosing a palette family and intensity. One call writes all related tokens (background, text, border, icon) consistently. Roles: header, user-messages, assistant-messages, primary-actions, input, links, borders, surfaces, scroll-to-bottom. Families: primary, secondary, accent, neutral. Intensity: solid (bold) or soft (tinted).",inputSchema:{type:"object",properties:{role:{type:"string",description:'Interface role, e.g. "header" or "user-messages".'},family:{type:"string",enum:Wi},intensity:{type:"string",enum:["solid","soft"],description:"Defaults to 'solid'."}},required:["role","family"],additionalProperties:!1},execute(v){let x=r(v),k=Ex(x.role),S=Bi(x.family,!0),E=Hi(x.intensity),F=a(Oa(S,E,k)),$=Object.keys(F).length;e.setBatch(F);let j=rs(e,sg(k),i());return d({role:os(k.roleId),family:S,intensity:E,tokensWritten:$},j)}},{name:"set_typography",title:"Set typography",description:"Set font family, base size, weight, and line height in one call. fontFamily: sans|serif|mono. fontSize: xs|sm|base|lg|xl. fontWeight: normal|medium|semibold|bold (or 400\u2013700). lineHeight: tight|normal|relaxed (or 1.25/1.5/1.625).",inputSchema:{type:"object",properties:{fontFamily:{type:"string"},fontSize:{type:"string"},fontWeight:{type:["string","number"]},lineHeight:{type:["string","number"]}},additionalProperties:!1},execute(v){let x=r(v),k={},S={},E=(F,$)=>{var me;if(x[F]===void 0)return;let j=ng(x[F],$,F);S[F]=(me=j.split(".").pop())!=null?me:j,Object.assign(k,s(`semantic.typography.${F}`,j))};if(E("fontFamily",Jm),E("fontSize",Zm),E("fontWeight",eg),E("lineHeight",tg),Object.keys(S).length===0)throw new Error("Provide at least one of: fontFamily, fontSize, fontWeight, lineHeight.");return e.setBatch(k),d(S)}},{name:"set_roundness",title:"Set corner roundness",description:"Set overall corner roundness with a keyword (sharp, default, rounded, pill) which maps the full radius scale, OR pass granular radius values. Provide at least one of `style` or `radius`.",inputSchema:{type:"object",properties:{style:{type:"string",enum:["sharp","default","rounded","pill"]},radius:{type:"object",description:"Granular overrides (px number or CSS length).",properties:{sm:{type:["string","number"]},md:{type:["string","number"]},lg:{type:["string","number"]},xl:{type:["string","number"]},full:{type:["string","number"]}},additionalProperties:!1}},additionalProperties:!1},execute(v){let x=r(v),k={},S={};if(x.style!==void 0){let E=Fi(x.style);S.style=E;for(let[F,$]of Object.entries(na[E]))Object.assign(k,s(`palette.radius.${F}`,$))}if(x.radius!==void 0){let E=r(x.radius),F={};for(let $ of["sm","md","lg","xl","full"]){if(E[$]===void 0)continue;let j=Oi(E[$]);F[$]=j,Object.assign(k,s(`palette.radius.${$}`,j))}S.radius=F}if(Object.keys(k).length===0)throw new Error("Provide `style` (sharp|default|rounded|pill) or a `radius` object.");return e.setBatch(k),d(S)}},{name:"set_color_scheme",title:"Set color scheme",description:"Set the shipped widget color scheme (light, dark, or auto/follow-system). Optionally set `editTarget` to choose which theme variant subsequent styling edits write to (light, dark, or both \u2014 default both).",inputSchema:{type:"object",properties:{scheme:{type:"string",enum:["light","dark","auto"]},editTarget:{type:"string",enum:["light","dark","both"]}},additionalProperties:!1},execute(v){let x=r(v),k={};if(x.scheme!==void 0){let S=Di(x.scheme);e.set("colorScheme",S),k.scheme=S}if(x.editTarget!==void 0){let S=String(x.editTarget).trim().toLowerCase();if(S!=="light"&&S!=="dark"&&S!=="both")throw new Error(`Unknown editTarget "${x.editTarget}". Valid: light, dark, both.`);n=S,k.editTarget=S}if(Object.keys(k).length===0)throw new Error("Provide `scheme` and/or `editTarget`.");return Vo({ok:!0,summary:Ir(e),warnings:[],applied:k,editTarget:n})}},{name:"apply_preset",title:"Apply a built-in theme preset",description:"Apply a complete built-in preset, replacing theme tokens. Call get_theme_overview to list preset ids.",inputSchema:{type:"object",properties:{presetId:{type:"string"}},required:["presetId"],additionalProperties:!1},execute(v){let{presetId:x}=r(v),k=nl(String(x!=null?x:""));if(!k){let $=Ms.map(j=>j.id).join(", ");throw new Error(`Unknown preset "${x}". Valid presets: ${$}.`)}let S=tn(k.theme,{validate:!1}),E={...e.getConfig()};k.darkTheme&&(E.darkTheme=tn(k.darkTheme,{validate:!1})),k.toolCall&&(E.toolCall=k.toolCall),e.setFullConfig(E,S);let F=rs(e,["body","assistant-message"],"light");return d({appliedPreset:{id:k.id,name:k.name}},F)}},{name:"configure_widget",title:"Configure launcher, features, and layout",description:"Toggle non-theme widget configuration. launcherPosition: bottom-right|bottom-left|top-right|top-left. features: { voice, artifacts, attachments, toolCalls, reasoning, feedback } booleans. layout: { avatars, timestamps, showHeader } booleans and messageStyle: bubble|flat|minimal.",inputSchema:{type:"object",properties:{launcherPosition:{type:"string",enum:Ql},features:{type:"object",properties:{voice:{type:"boolean"},artifacts:{type:"boolean"},attachments:{type:"boolean"},toolCalls:{type:"boolean"},reasoning:{type:"boolean"},feedback:{type:"boolean"}},additionalProperties:!1},layout:{type:"object",properties:{avatars:{type:"boolean"},timestamps:{type:"boolean"},showHeader:{type:"boolean"},messageStyle:{type:"string",enum:Jl}},additionalProperties:!1}},additionalProperties:!1},execute(v){var $,j,me;let x=r(v),k={},S={};if(x.launcherPosition!==void 0){let se=String(x.launcherPosition);if(!Ql.includes(se))throw new Error(`Unknown launcherPosition "${se}". Valid: ${Ql.join(", ")}.`);k["launcher.position"]=se,S.launcherPosition=se}let E=r(x.features);for(let[se,ge]of Object.entries(Mx))E[se]!==void 0&&(k[ge]=!!E[se],($=S.features)!=null||(S.features={}),S.features[se]=!!E[se]);let F=r(x.layout);for(let[se,ge]of Object.entries(Lx))if(F[se]!==void 0)if(se==="messageStyle"){let ie=String(F[se]);if(!Jl.includes(ie))throw new Error(`Unknown messageStyle "${ie}". Valid: ${Jl.join(", ")}.`);k[ge]=ie,(j=S.layout)!=null||(S.layout={}),S.layout[se]=ie}else k[ge]=!!F[se],(me=S.layout)!=null||(S.layout={}),S.layout[se]=!!F[se];if(Object.keys(k).length===0)throw new Error("Provide launcherPosition, features, and/or layout.");return e.setBatch(k),d(S)}},{name:"set_copy_and_suggestions",title:"Set welcome copy and suggestion chips",description:"Set the widget welcome copy and suggestion chips. title/subtitle are the welcome card text; placeholder is the input placeholder; sendLabel is the send button label; suggestions is an array of suggestion-chip strings (replaces the existing list).",inputSchema:{type:"object",properties:{title:{type:"string"},subtitle:{type:"string"},placeholder:{type:"string"},sendLabel:{type:"string"},suggestions:{type:"array",items:{type:"string"}}},additionalProperties:!1},execute(v){let x=r(v),k={},S={};for(let[E,F]of Object.entries(Ix))x[E]!==void 0&&(k[F]=String(x[E]),S[E]=String(x[E]));if(x.suggestions!==void 0){if(!Array.isArray(x.suggestions))throw new Error("`suggestions` must be an array of strings.");let E=x.suggestions.filter(F=>typeof F=="string");k.suggestionChips=E,S.suggestions=E}if(Object.keys(k).length===0)throw new Error("Provide at least one of: title, subtitle, placeholder, sendLabel, suggestions.");return e.setBatch(k),d(S)}},{name:"set_theme_fields",title:"Set theme fields by id or path (advanced)",description:'Advanced escape hatch: set individual editor fields by field id (see get_theme_overview verbosity:"full") \u2014 theme field ids follow the current edit target (light/dark/both) \u2014 or by raw dot-path (theme.* / darkTheme.* / a config path), which is written as-is. Use only when a higher-level tool does not cover the need. Values are validated against the field metadata.',inputSchema:{type:"object",properties:{updates:{type:"array",items:{type:"object",properties:{field:{type:"string",description:"Field id or dot-path."},value:{type:["string","number","boolean"]}},required:["field","value"],additionalProperties:!1}}},required:["updates"],additionalProperties:!1},execute(v){var F;let{updates:x}=r(v);if(!Array.isArray(x)||x.length===0)throw new Error("`updates` must be a non-empty array of { field, value }.");o!=null||(o=ag());let k={},S=[];for(let $ of x){let j=r($),me=String((F=j.field)!=null?F:"");try{let se=o.get(me),ge=se?se.path:me;if(!se&&!/^(theme|darkTheme)\.|\./.test(ge))throw new Error(`Unknown field "${me}". Pass a known field id or a dot-path (e.g. theme.palette.radius.md).`);let ie=Rx(se,j.value);if(se&&ge.startsWith("theme.")){let be=s(ge.slice(6),ie);Object.assign(k,be),S.push({field:me,resolvedPath:Object.keys(be),ok:!0})}else k[ge]=ie,S.push({field:me,resolvedPath:ge,ok:!0})}catch(se){S.push({field:me,ok:!1,error:se.message})}}let E=S.filter($=>$.ok);return Object.keys(k).length>0&&e.setBatch(k),Vo({ok:E.length>0,summary:Ir(e),warnings:[],applied:{updates:S}})}},{name:"check_contrast",title:"Check accessibility contrast",description:"Run WCAG contrast checks over the key text/background pairs (message text, header title, input/body text, primary button). Returns each ratio, whether it passes, and a suggested foreground shade for failures.",annotations:{readOnlyHint:!0},inputSchema:{type:"object",properties:{level:{type:"string",enum:["AA","AAA"],description:"Defaults to 'AA'."},variant:{type:"string",enum:["light","dark","both"],description:"Defaults to 'both'."}},additionalProperties:!1},execute(v){let x=r(v),k=x.level==="AAA"?"AAA":"AA",S=x.variant==="light"||x.variant==="dark"?x.variant:"both",E=oa(e,k,S);return Vo({level:E.level,passing:E.checks.length-E.failures.length,total:E.checks.length,checks:E.checks,failures:E.failures})}},{name:"manage_session",title:"Undo, redo, reset, or export the theme",description:'Session action. "undo"/"redo" step through edit history; "reset" restores defaults; "export" returns the embeddable theme snapshot (config + theme JSON) with no side effects.',inputSchema:{type:"object",properties:{action:{type:"string",enum:["undo","redo","reset","export"]}},required:["action"],additionalProperties:!1},execute(v){let{action:x}=r(v);switch(x){case"undo":return e.undo(),d({action:"undo"});case"redo":return e.redo(),d({action:"redo"});case"reset":return e.resetToDefaults(),d({action:"reset"});case"export":return Vo({ok:!0,snapshot:e.exportSnapshot()});default:throw new Error(`Unknown action "${x}". Valid: undo, redo, reset, export.`)}}}]}function Rx(e,t){if(!e)return t;switch(e.type){case"color":return e.parseValue?e.parseValue(ns(t)):ns(t);case"toggle":return typeof t=="boolean"?t:t==="true"||t===1;case"slider":{let n=Number(t);if(!Number.isFinite(n))throw new Error(`"${e.id}" expects a number.`);if(e.slider){let{min:o,max:r}=e.slider;if(n<o||n>r)throw new Error(`"${e.id}" must be between ${o} and ${r}.`)}return e.parseValue?e.parseValue(n):n}case"select":{let n=String(t);if(e.options&&!e.options.some(o=>o.value===n))throw new Error(`"${e.id}" must be one of: ${e.options.map(o=>o.value).join(", ")}.`);return e.parseValue?e.parseValue(n):n}default:return e.parseValue?e.parseValue(t):t}}export{bu as ADVANCED_TOKENS_SECTION,wr as ALL_ROLES,tl as ALL_TABS,mu as BRAND_PALETTE_SECTION,vu as BUILT_IN_PRESETS,Og as COLORS_SECTIONS,Ji as COLOR_FAMILIES,du as COMPONENTS_SECTIONS,cu as COMPONENT_COLOR_SECTIONS,lu as COMPONENT_SHAPE_SECTIONS,pu as CONFIGURE_SECTIONS,Na as CONFIGURE_SUB_GROUPS,ta as CONTRAST_PAIRS,Pi as CSS_NAMED_COLORS,ts as DEVICE_DIMENSIONS,zm as HOME_SUGGESTION_CHIPS,fu as INTERFACE_ROLES_SECTION,jm as MOCK_BROWSER_CONTENT,Km as MOCK_WORKSPACE_CONTENT,Dg as PALETTE_SECTION,Um as PREVIEW_STORAGE_ADAPTER,na as RADIUS_PRESETS,Pa as ROLE_ASSISTANT_MESSAGES,Fa as ROLE_BORDERS,Ma as ROLE_FAMILIES,Sg as ROLE_FAMILY_LABELS,Ia as ROLE_HEADER,Ha as ROLE_INPUT,ko as ROLE_INTENSITIES,Da as ROLE_LINKS_FOCUS,Wa as ROLE_PRIMARY_ACTIONS,Ba as ROLE_SCROLL_TO_BOTTOM,La as ROLE_SURFACES,Ra as ROLE_USER_MESSAGES,Fg as SEMANTIC_COLORS_SECTION,Ur as SHADE_KEYS,Li as SHELL_STYLE_ID,hu as STATUS_COLORS_SECTION,gu as STATUS_PALETTE_SECTION,zr as STYLE_SECTIONS,wf as STYLE_SECTIONS_V2,Ms as THEME_EDITOR_PRESETS,uu as THEME_SECTION,ji as ThemeEditorState,zl as ZOOM_MAX,Ul as ZOOM_MIN,ux as appendPreviewTranscriptEntry,Yl as applySceneConfig,jl as applyShellTheme,Lr as buildPreviewConfig,hx as buildPreviewConfigWithMessages,ql as buildShellCss,Kl as buildSrcdoc,Ir as buildSummary,mx as buildTranscriptStreamFrames,ns as coerceColor,Bi as coerceFamily,Hi as coerceIntensity,Oi as coerceRadius,Fi as coerceRoundnessStyle,Di as coerceScheme,xg as convertFromPx,vg as convertToPx,Ym as createPreviewMessages,Gl as createPreviewTranscriptEntry,ig as createThemeEditorTools,bx as createThemePreview,Zi as detectRoleAssignment,Ii as escapeHtml,Sf as findSection,Gi as formatCssValue,Qi as generateColorScale,px as getPreviewTranscriptPresetLabel,qm as getShellPalette,nl as getThemeEditorPreset,ou as hexToHsl,ru as hslToHex,Yi as isValidHex,ks as normalizeColorValue,wg as paletteColorPath,Ki as parseCssValue,Gm as presetStreamsText,rs as quickContrastWarnings,Oa as resolveRoleAssignment,su as resolveThemeColorPath,Xi as rgbToHex,oa as runContrastChecks,Af as scopeSection,Cg as tokenRefDisplayName,Vo as toolResult,Ea as wcagContrastRatio};
204
+ - Resizable panes`});(le=n.onAfterMount)==null||le.call(n,{iframes:$,controllers:[...o]})};for(let xe of $){let j=xe.dataset.mountId;if(!j)continue;let de=P.find(K=>K.mountId===j);de&&(xe.addEventListener("load",()=>{G++,G>=fe&&ge()},{once:!0}),xe.srcdoc=k(j,de.shellMode,hn(de.config),w))}fe===0&&ge()}function L(){var H;if(a)return;let I=pg(n);if(o.length!==I.length){E();return}if(I.some(W=>{let x=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${W.mountId}"]`);return!x||x.dataset.shellMode!==W.shellMode})){E();return}o.forEach((W,x)=>{var w;W.update(I[x].config),((w=n.scene)!=null?w:"conversation")==="minimized"&&W.close()});for(let W of I){let x=e.querySelector(`iframe[data-mount-id="${W.mountId}"]`);x&&Jl(x,W.shellMode)}(H=n.onAfterUpdate)==null||H.call(n,{iframes:v(),controllers:[...o]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||u()}),s.observe(e)),E(),{update(I){if(a)return;let P=I.device!==void 0&&I.device!==n.device||I.scene!==void 0&&I.scene!==n.scene||I.compareMode!==void 0&&I.compareMode!==n.compareMode||I.widgetCssPath!==void 0&&I.widgetCssPath!==n.widgetCssPath;n={...n,...I},P?E():L()},destroy(){a||(a=!0,C(),s==null||s.disconnect(),e.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},u())},getIframes(){return v()},getScale(){return d},setZoom(I){a||(n={...n,zoom:I},u())}}}function zo(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}var Oi={black:"#000000",white:"#ffffff",red:"#ff0000",green:"#008000",lime:"#00ff00",blue:"#0000ff",yellow:"#ffff00",cyan:"#00ffff",aqua:"#00ffff",magenta:"#ff00ff",fuchsia:"#ff00ff",silver:"#c0c0c0",gray:"#808080",grey:"#808080",maroon:"#800000",olive:"#808000",purple:"#800080",teal:"#008080",navy:"#000080",orange:"#ffa500",pink:"#ffc0cb",hotpink:"#ff69b4",gold:"#ffd700",indigo:"#4b0082",violet:"#ee82ee",brown:"#a52a2a",beige:"#f5f5dc",ivory:"#fffff0",khaki:"#f0e68c",coral:"#ff7f50",salmon:"#fa8072",tomato:"#ff6347",crimson:"#dc143c",turquoise:"#40e0d0",lavender:"#e6e6fa",plum:"#dda0dd",orchid:"#da70d6",tan:"#d2b48c",chocolate:"#d2691e",sienna:"#a0522d",slategray:"#708090",slategrey:"#708090",steelblue:"#4682b4",royalblue:"#4169e1",dodgerblue:"#1e90ff",skyblue:"#87ceeb",lightblue:"#add8e6",midnightblue:"#191970",forestgreen:"#228b22",seagreen:"#2e8b57",limegreen:"#32cd32",olivedrab:"#6b8e23",darkgreen:"#006400",emerald:"#50c878",mint:"#3eb489",goldenrod:"#daa520",firebrick:"#b22222",darkred:"#8b0000",indianred:"#cd5c5c",deeppink:"#ff1493",mediumpurple:"#9370db",rebeccapurple:"#663399",darkviolet:"#9400d3",slateblue:"#6a5acd",cornflowerblue:"#6495ed",teal2:"#008080",charcoal:"#36454f",graphite:"#3b3b3b",transparent:"transparent"},Bx=/^rgba?\(\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*(,\s*(0|1|0?\.\d+|\d{1,3}%)\s*)?\)$/;function Hx(e){return Bx.test(e)}function cs(e){if(typeof e!="string"||e.trim()==="")throw new Error('Color must be a non-empty string (e.g. "#2563eb" or "blue").');let t=e.trim().toLowerCase(),n=Oi[t];if(n)return n;let o=Ws(t);if(tl(o)||o==="transparent"||Hx(o))return o;throw new Error(`"${e}" is not a recognized color. Pass a hex value like "#ef4444" or a CSS color name (e.g. ${Object.keys(Oi).slice(0,6).join(", ")}).`)}var Ni=Pa.map(e=>e==="gray"?"neutral":e),Dx={...Object.fromEntries(Ni.map(e=>[e,e])),gray:"neutral",grey:"neutral"};function _i(e,t=!0){let n=String(e!=null?e:"").trim().toLowerCase(),o=Dx[n];if(!o||!t&&o==="neutral"){let r=t?"primary, secondary, accent, neutral":"primary, secondary, accent";throw new Error(`Unknown color family "${e}". Valid families: ${r}.`)}return o}function Vi(e){let t=String(e!=null?e:"solid").trim().toLowerCase();if(t==="solid"||t==="soft")return t;throw new Error(`Unknown intensity "${e}". Valid intensities: solid, soft.`)}function $i(e){let t=String(e!=null?e:"").trim().toLowerCase();if(t==="light"||t==="dark"||t==="auto")return t;if(t==="system")return"auto";throw new Error(`Unknown color scheme "${e}". Valid: light, dark, auto.`)}var Fx={sharp:"sharp",square:"sharp",none:"sharp",default:"default",normal:"default",rounded:"rounded",round:"rounded",soft:"rounded",pill:"pill",circle:"pill",full:"pill"};function Ui(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=Fx[t];if(!n)throw new Error(`Unknown roundness "${e}". Valid: sharp, default, rounded, pill.`);return n}function zi(e){if(typeof e=="number"&&Number.isFinite(e))return`${e}px`;if(typeof e=="string"&&e.trim()!==""){let t=e.trim();if(t==="9999px"||/^(100%|9999px)$/.test(t))return"9999px";let n=Zi(t);return el(n.value,n.unit)}throw new Error('Radius must be a number (px) or a CSS length string like "0.5rem".')}function qi(e){for(let t of Xr){let n=t.fields.find(o=>o.id===e);if(n!=null&&n.options){let o={};for(let r of n.options){let s=r.value.split(".").pop();s&&(o[s]=r.value)}return o}}return{}}var ug=qi("typo-font-family"),ia=qi("typo-font-size"),la=qi("typo-font-weight"),Fi=qi("typo-line-height"),mg={...ug,monospace:ug.mono},gg={...ia,small:ia.sm,md:ia.base,medium:ia.base,large:ia.lg},fg={...la,400:la.normal,500:la.medium,600:la.semibold,700:la.bold},hg={...Fi,"1.25":Fi.tight,"1.5":Fi.normal,"1.625":Fi.relaxed};function bg(e,t,n){let o=String(e!=null?e:"").trim().toLowerCase(),r=t[o];if(!r){let s=[...new Set(Object.values(t).map(a=>a.split(".").pop()))].join(", ");throw new Error(`Unknown ${n} "${e}". Valid: ${s}.`)}return r}var yg="theme.palette.radius.";function Ox(){var t;let e={pill:{sm:"9999px",md:"9999px",lg:"9999px",xl:"9999px",full:"9999px"}};for(let n of Xr)for(let o of(t=n.presets)!=null?t:[]){let r=o.id.match(/^radius-(\w+)$/);if(!r)continue;let s={};for(let[a,i]of Object.entries(o.values))a.startsWith(yg)&&typeof i=="string"&&(s[a.slice(yg.length)]=i);e[r[1]]=s}return e}var da=Ox(),vg=["sm","md","lg","xl","full"];function Ki(e,t,n="theme",o=0){if(o>6)return null;let r=e.get(`${n}.${t}`);return typeof r!="string"||r===""?n==="darkTheme"?Ki(e,t,"theme",o):null:r.startsWith("#")||r.startsWith("rgb")||r==="transparent"?r:r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components.")?Ki(e,r,n,o+1):null}function ji(e,t){let n=e.get(t);if(typeof n!="string")return"unknown";let o=n.split(".");return o[o.length-1]||String(n)}function ds(e){return e.replace(/^role-/,"")}function Nx(e){for(let[t,n]of Object.entries(da))if(vg.every(o=>e[o]===n[o]))return t;return"custom"}function Br(e){var o,r;let t={};for(let s of vg)t[s]=String((o=e.get(`theme.palette.radius.${s}`))!=null?o:"");let n={};for(let s of Ar)n[ds(s.roleId)]=sl(a=>e.get(`theme.${a}`),s);return{brand:{primary:nc(e.get("theme.palette.colors.primary.500")),secondary:nc(e.get("theme.palette.colors.secondary.500")),accent:nc(e.get("theme.palette.colors.accent.500"))},roles:n,typography:{fontFamily:ji(e,"theme.semantic.typography.fontFamily"),fontSize:ji(e,"theme.semantic.typography.fontSize"),fontWeight:ji(e,"theme.semantic.typography.fontWeight"),lineHeight:ji(e,"theme.semantic.typography.lineHeight")},roundness:{style:Nx(t),radius:t},colorScheme:String((r=e.get("colorScheme"))!=null?r:"light"),history:{index:e.getHistoryIndex(),canUndo:e.canUndo(),canRedo:e.canRedo()}}}function nc(e){return typeof e=="string"&&e!==""?e:null}var ca=[{key:"user-message",label:"User message text",fg:"components.message.user.text",bg:"components.message.user.background"},{key:"assistant-message",label:"Assistant message text",fg:"components.message.assistant.text",bg:"components.message.assistant.background"},{key:"header",label:"Header title",fg:"components.header.titleForeground",bg:"components.header.background"},{key:"primary-button",label:"Primary button label",fg:"components.button.primary.foreground",bg:"components.button.primary.background"},{key:"input",label:"Input placeholder",fg:"components.input.placeholder",bg:"components.input.background"},{key:"link",label:"Link text",fg:"components.markdown.link.foreground",bg:"semantic.colors.background"},{key:"scroll",label:"Scroll-to-bottom icon",fg:"components.scrollToBottom.foreground",bg:"components.scrollToBottom.background"},{key:"body",label:"Body text on background",fg:"semantic.colors.text",bg:"semantic.colors.background"},{key:"surface",label:"Body text on surface",fg:"semantic.colors.text",bg:"semantic.colors.surface"}];function xg(e){let t=new Set(e.targets.map(n=>n.path));return ca.filter(n=>t.has(n.fg)||t.has(n.bg)).map(n=>n.key)}var _x={AA:4.5,AAA:7};function Vx(e){return Math.round(e*100)/100}function $x(e,t,n,o,r){let s=e.get(`${r}.${t}`);if(typeof s!="string")return null;let a=s.match(/^palette\.colors\.(\w+)\.(\d+)$/);if(!a)return null;let i=a[1],d=Gr.indexOf(a[2]),l=null,m=1/0;return Gr.forEach((p,f)=>{let u=e.get(`${r}.palette.colors.${i}.${p}`);if(!(typeof u!="string"||!(u.startsWith("#")||u.startsWith("rgb")))&&Ra(u,n)>=o){let C=d>=0?Math.abs(f-d):f;C<m&&(m=C,l=`palette.colors.${i}.${p}`)}}),l}function pa(e,t="AA",n="both",o){let r=_x[t],s=n==="both"?["light","dark"]:[n],a=o?ca.filter(d=>o.includes(d.key)):ca,i=[];for(let d of s){let l=d==="light"?"theme":"darkTheme";for(let m of a){let p=Ki(e,m.fg,l),f=Ki(e,m.bg,l);if(!p||!f)continue;let u=Vx(Ra(p,f)),C=u>=r,v={pair:m.key,label:m.label,variant:d,fg:p,bg:f,ratio:u,threshold:r,passes:C};if(!C){let E=$x(e,m.fg,f,r,l);E&&(v.suggestion=E)}i.push(v)}}return{level:t,checks:i,failures:i.filter(d=>!d.passes)}}function ps(e,t,n="light",o="AA"){return t.length===0?[]:pa(e,o,n,t).failures.map(s=>({code:"contrast",pair:s.pair,variant:s.variant,ratio:s.ratio,threshold:s.threshold,message:`${s.label} (${s.variant}) has a contrast ratio of ${s.ratio}:1, below the ${o} threshold of ${s.threshold}:1${s.suggestion?`. Try ${s.suggestion} for the foreground.`:"."}`}))}var un={};for(let e of Ar){let t=ds(e.roleId);un[t]=e,un[e.roleId]=e}Object.assign(un,{surface:un.surfaces,background:un.surfaces,backgrounds:un.surfaces,user:un["user-messages"],"user-message":un["user-messages"],assistant:un["assistant-messages"],"assistant-message":un["assistant-messages"],actions:un["primary-actions"],buttons:un["primary-actions"],composer:un.input,links:un["links-focus"],focus:un["links-focus"],border:un.borders,dividers:un.borders,scroll:un["scroll-to-bottom"]});function Ux(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=un[t];if(!n){let o=Ar.map(r=>ds(r.roleId)).join(", ");throw new Error(`Unknown role "${e}". Valid roles: ${o}.`)}return n}function wg(){let e=new Map,t=n=>{for(let o of n)for(let r of o.fields)e.has(r.id)||e.set(r.id,r)};for(let n of ll)t(n.sections);for(let n of Ua)t(n.sections);return e}var zx={voice:"voiceRecognition.enabled",artifacts:"features.artifacts.enabled",attachments:"attachments.enabled",toolCalls:"features.showToolCalls",reasoning:"features.showReasoning",feedback:"messageActions.enabled"},qx={avatars:"layout.messages.avatar.show",timestamps:"layout.messages.timestamp.show",showHeader:"layout.showHeader",messageStyle:"layout.messages.layout"},oc=["bottom-right","bottom-left","top-right","top-left"],rc=["bubble","flat","minimal"],jx={title:"copy.welcomeTitle",subtitle:"copy.welcomeSubtitle",placeholder:"copy.inputPlaceholder",sendLabel:"copy.sendButtonLabel"};function Cg(e,t){var W;let n=(W=t==null?void 0:t.editTarget)!=null?W:"both",o=null,r=x=>x&&typeof x=="object"?x:{},s=(x,w,k=n)=>{let S={};return(k==="light"||k==="both")&&(S[`theme.${x}`]=w),(k==="dark"||k==="both")&&(S[`darkTheme.${x}`]=w),S},a=x=>{if(n==="both")return x;let w={};for(let[k,S]of Object.entries(x))(n==="light"&&k.startsWith("theme.")||n==="dark"&&k.startsWith("darkTheme."))&&(w[k]=S);return w},i=()=>n==="dark"?"dark":"light",d=(x,w=[])=>zo({ok:!0,summary:Br(e),warnings:w,applied:x});return[{name:"get_theme_overview",title:"Get current theme & what is editable",description:"Read the current widget theme (brand colors, per-role color assignments, typography, roundness, color scheme, undo/redo state), the available presets, and the high-level levers you can change. Call this FIRST before editing.",annotations:{readOnlyHint:!0},inputSchema:{type:"object",properties:{verbosity:{type:"string",enum:["summary","full"],description:"Use 'full' to also include the field-id index for set_theme_fields."}},additionalProperties:!1},execute(x){let{verbosity:w}=r(x),k={summary:Br(e),availableRoles:Ar.map(S=>({role:ds(S.roleId),helper:S.helper})),availableFamilies:Ni,presets:Hs.map(S=>{var A;return{id:S.id,name:S.name,description:S.description,tags:(A=S.tags)!=null?A:[]}}),tools:[{tool:"set_brand_colors",hint:"Recolor the palette (primary/secondary/accent) \u2014 auto-generates shade scales."},{tool:"assign_color_role",hint:"Recolor a region (header, user/assistant messages, actions, input, links, borders, surfaces, scroll) with a family + intensity."},{tool:"set_typography",hint:"Set font family, size, weight, line height."},{tool:"set_roundness",hint:"Set corner roundness (sharp/default/rounded/pill) or granular radii."},{tool:"set_color_scheme",hint:"Set light/dark/auto and which variant edits target."},{tool:"apply_preset",hint:"Apply a complete built-in preset."},{tool:"configure_widget",hint:"Toggle launcher position, features, and layout."},{tool:"set_copy_and_suggestions",hint:"Set welcome copy, placeholder, and suggestion chips."},{tool:"set_theme_fields",hint:"Advanced escape hatch: set any field by id or dot-path."},{tool:"check_contrast",hint:"Audit WCAG contrast across key text/background pairs."},{tool:"manage_session",hint:"Undo, redo, reset, or export the theme."}]};return w==="full"&&(o!=null||(o=wg()),k.fieldIndex=Array.from(o.values()).map(S=>{var A;return{id:S.id,path:S.path,type:S.type,label:S.label,options:(A=S.options)==null?void 0:A.map(N=>N.value)}})),zo(k)}},{name:"set_brand_colors",title:"Set brand colors",description:'Set one or more brand colors (primary, secondary, accent). Each color auto-generates a full 50\u2013950 shade scale and applies to the light and dark themes (per the current edit target). Accepts hex ("#2563eb", "2563eb", "#18f"), rgb()/rgba() ("rgb(37, 99, 235)"), or CSS color names ("blue", "slateblue").',inputSchema:{type:"object",properties:{primary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},secondary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},accent:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."}},additionalProperties:!1},execute(x){let w=r(x),k=["primary","secondary","accent"],S={},A={};for(let $ of k){if(w[$]===void 0)continue;let G=cs(w[$]);A[$]=G;let fe=ol(G);for(let ge of Gr){let se=fe[ge];se!==void 0&&Object.assign(S,s(`palette.colors.${$}.${ge}`,se))}}if(Object.keys(A).length===0)throw new Error("Provide at least one of: primary, secondary, accent.");e.setBatch(S);let N=ps(e,["primary-button","user-message"],i());return d(A,N)}},{name:"assign_color_role",title:"Assign a color family to an interface role",description:"Recolor a semantic region of the widget by choosing a palette family and intensity. One call writes all related tokens (background, text, border, icon) consistently. Roles: header, user-messages, assistant-messages, primary-actions, input, links, borders, surfaces, scroll-to-bottom. Families: primary, secondary, accent, neutral. Intensity: solid (bold) or soft (tinted).",inputSchema:{type:"object",properties:{role:{type:"string",description:'Interface role, e.g. "header" or "user-messages".'},family:{type:"string",enum:Ni},intensity:{type:"string",enum:["solid","soft"],description:"Defaults to 'solid'."}},required:["role","family"],additionalProperties:!1},execute(x){let w=r(x),k=Ux(w.role),S=_i(w.family,!0),A=Vi(w.intensity),N=a($a(S,A,k)),$=Object.keys(N).length;e.setBatch(N);let G=ps(e,xg(k),i());return d({role:ds(k.roleId),family:S,intensity:A,tokensWritten:$},G)}},{name:"set_typography",title:"Set typography",description:"Set font family, base size, weight, and line height in one call. fontFamily: sans|serif|mono. fontSize: xs|sm|base|lg|xl. fontWeight: normal|medium|semibold|bold (or 400\u2013700). lineHeight: tight|normal|relaxed (or 1.25/1.5/1.625).",inputSchema:{type:"object",properties:{fontFamily:{type:"string"},fontSize:{type:"string"},fontWeight:{type:["string","number"]},lineHeight:{type:["string","number"]}},additionalProperties:!1},execute(x){let w=r(x),k={},S={},A=(N,$)=>{var fe;if(w[N]===void 0)return;let G=bg(w[N],$,N);S[N]=(fe=G.split(".").pop())!=null?fe:G,Object.assign(k,s(`semantic.typography.${N}`,G))};if(A("fontFamily",mg),A("fontSize",gg),A("fontWeight",fg),A("lineHeight",hg),Object.keys(S).length===0)throw new Error("Provide at least one of: fontFamily, fontSize, fontWeight, lineHeight.");return e.setBatch(k),d(S)}},{name:"set_roundness",title:"Set corner roundness",description:"Set overall corner roundness with a keyword (sharp, default, rounded, pill) which maps the full radius scale, OR pass granular radius values. Provide at least one of `style` or `radius`.",inputSchema:{type:"object",properties:{style:{type:"string",enum:["sharp","default","rounded","pill"]},radius:{type:"object",description:"Granular overrides (px number or CSS length).",properties:{sm:{type:["string","number"]},md:{type:["string","number"]},lg:{type:["string","number"]},xl:{type:["string","number"]},full:{type:["string","number"]}},additionalProperties:!1}},additionalProperties:!1},execute(x){let w=r(x),k={},S={};if(w.style!==void 0){let A=Ui(w.style);S.style=A;for(let[N,$]of Object.entries(da[A]))Object.assign(k,s(`palette.radius.${N}`,$))}if(w.radius!==void 0){let A=r(w.radius),N={};for(let $ of["sm","md","lg","xl","full"]){if(A[$]===void 0)continue;let G=zi(A[$]);N[$]=G,Object.assign(k,s(`palette.radius.${$}`,G))}S.radius=N}if(Object.keys(k).length===0)throw new Error("Provide `style` (sharp|default|rounded|pill) or a `radius` object.");return e.setBatch(k),d(S)}},{name:"set_color_scheme",title:"Set color scheme",description:"Set the shipped widget color scheme (light, dark, or auto/follow-system). Optionally set `editTarget` to choose which theme variant subsequent styling edits write to (light, dark, or both \u2014 default both).",inputSchema:{type:"object",properties:{scheme:{type:"string",enum:["light","dark","auto"]},editTarget:{type:"string",enum:["light","dark","both"]}},additionalProperties:!1},execute(x){let w=r(x),k={};if(w.scheme!==void 0){let S=$i(w.scheme);e.set("colorScheme",S),k.scheme=S}if(w.editTarget!==void 0){let S=String(w.editTarget).trim().toLowerCase();if(S!=="light"&&S!=="dark"&&S!=="both")throw new Error(`Unknown editTarget "${w.editTarget}". Valid: light, dark, both.`);n=S,k.editTarget=S}if(Object.keys(k).length===0)throw new Error("Provide `scheme` and/or `editTarget`.");return zo({ok:!0,summary:Br(e),warnings:[],applied:k,editTarget:n})}},{name:"apply_preset",title:"Apply a built-in theme preset",description:"Apply a complete built-in preset, replacing theme tokens. Call get_theme_overview to list preset ids.",inputSchema:{type:"object",properties:{presetId:{type:"string"}},required:["presetId"],additionalProperties:!1},execute(x){let{presetId:w}=r(x),k=cl(String(w!=null?w:""));if(!k){let $=Hs.map(G=>G.id).join(", ");throw new Error(`Unknown preset "${w}". Valid presets: ${$}.`)}let S=sn(k.theme,{validate:!1}),A={...e.getConfig()};k.darkTheme&&(A.darkTheme=sn(k.darkTheme,{validate:!1})),k.toolCall&&(A.toolCall=k.toolCall),e.setFullConfig(A,S);let N=ps(e,["body","assistant-message"],"light");return d({appliedPreset:{id:k.id,name:k.name}},N)}},{name:"configure_widget",title:"Configure launcher, features, and layout",description:"Toggle non-theme widget configuration. launcherPosition: bottom-right|bottom-left|top-right|top-left. features: { voice, artifacts, attachments, toolCalls, reasoning, feedback } booleans. layout: { avatars, timestamps, showHeader } booleans and messageStyle: bubble|flat|minimal.",inputSchema:{type:"object",properties:{launcherPosition:{type:"string",enum:oc},features:{type:"object",properties:{voice:{type:"boolean"},artifacts:{type:"boolean"},attachments:{type:"boolean"},toolCalls:{type:"boolean"},reasoning:{type:"boolean"},feedback:{type:"boolean"}},additionalProperties:!1},layout:{type:"object",properties:{avatars:{type:"boolean"},timestamps:{type:"boolean"},showHeader:{type:"boolean"},messageStyle:{type:"string",enum:rc}},additionalProperties:!1}},additionalProperties:!1},execute(x){var $,G,fe;let w=r(x),k={},S={};if(w.launcherPosition!==void 0){let ge=String(w.launcherPosition);if(!oc.includes(ge))throw new Error(`Unknown launcherPosition "${ge}". Valid: ${oc.join(", ")}.`);k["launcher.position"]=ge,S.launcherPosition=ge}let A=r(w.features);for(let[ge,se]of Object.entries(zx))A[ge]!==void 0&&(k[se]=!!A[ge],($=S.features)!=null||(S.features={}),S.features[ge]=!!A[ge]);let N=r(w.layout);for(let[ge,se]of Object.entries(qx))if(N[ge]!==void 0)if(ge==="messageStyle"){let ke=String(N[ge]);if(!rc.includes(ke))throw new Error(`Unknown messageStyle "${ke}". Valid: ${rc.join(", ")}.`);k[se]=ke,(G=S.layout)!=null||(S.layout={}),S.layout[ge]=ke}else k[se]=!!N[ge],(fe=S.layout)!=null||(S.layout={}),S.layout[ge]=!!N[ge];if(Object.keys(k).length===0)throw new Error("Provide launcherPosition, features, and/or layout.");return e.setBatch(k),d(S)}},{name:"set_copy_and_suggestions",title:"Set welcome copy and suggestion chips",description:"Set the widget welcome copy and suggestion chips. title/subtitle are the welcome card text; placeholder is the input placeholder; sendLabel is the send button label; suggestions is an array of suggestion-chip strings (replaces the existing list).",inputSchema:{type:"object",properties:{title:{type:"string"},subtitle:{type:"string"},placeholder:{type:"string"},sendLabel:{type:"string"},suggestions:{type:"array",items:{type:"string"}}},additionalProperties:!1},execute(x){let w=r(x),k={},S={};for(let[A,N]of Object.entries(jx))w[A]!==void 0&&(k[N]=String(w[A]),S[A]=String(w[A]));if(w.suggestions!==void 0){if(!Array.isArray(w.suggestions))throw new Error("`suggestions` must be an array of strings.");let A=w.suggestions.filter(N=>typeof N=="string");k.suggestionChips=A,S.suggestions=A}if(Object.keys(k).length===0)throw new Error("Provide at least one of: title, subtitle, placeholder, sendLabel, suggestions.");return e.setBatch(k),d(S)}},{name:"set_theme_fields",title:"Set theme fields by id or path (advanced)",description:'Advanced escape hatch: set individual editor fields by field id (see get_theme_overview verbosity:"full") \u2014 theme field ids follow the current edit target (light/dark/both) \u2014 or by raw dot-path (theme.* / darkTheme.* / a config path), which is written as-is. Use only when a higher-level tool does not cover the need. Values are validated against the field metadata.',inputSchema:{type:"object",properties:{updates:{type:"array",items:{type:"object",properties:{field:{type:"string",description:"Field id or dot-path."},value:{type:["string","number","boolean"]}},required:["field","value"],additionalProperties:!1}}},required:["updates"],additionalProperties:!1},execute(x){var N;let{updates:w}=r(x);if(!Array.isArray(w)||w.length===0)throw new Error("`updates` must be a non-empty array of { field, value }.");o!=null||(o=wg());let k={},S=[];for(let $ of w){let G=r($),fe=String((N=G.field)!=null?N:"");try{let ge=o.get(fe),se=ge?ge.path:fe;if(!ge&&!/^(theme|darkTheme)\.|\./.test(se))throw new Error(`Unknown field "${fe}". Pass a known field id or a dot-path (e.g. theme.palette.radius.md).`);let ke=Kx(ge,G.value);if(ge&&se.startsWith("theme.")){let be=s(se.slice(6),ke);Object.assign(k,be),S.push({field:fe,resolvedPath:Object.keys(be),ok:!0})}else k[se]=ke,S.push({field:fe,resolvedPath:se,ok:!0})}catch(ge){S.push({field:fe,ok:!1,error:ge.message})}}let A=S.filter($=>$.ok);return Object.keys(k).length>0&&e.setBatch(k),zo({ok:A.length>0,summary:Br(e),warnings:[],applied:{updates:S}})}},{name:"check_contrast",title:"Check accessibility contrast",description:"Run WCAG contrast checks over the key text/background pairs (message text, header title, input/body text, primary button). Returns each ratio, whether it passes, and a suggested foreground shade for failures.",annotations:{readOnlyHint:!0},inputSchema:{type:"object",properties:{level:{type:"string",enum:["AA","AAA"],description:"Defaults to 'AA'."},variant:{type:"string",enum:["light","dark","both"],description:"Defaults to 'both'."}},additionalProperties:!1},execute(x){let w=r(x),k=w.level==="AAA"?"AAA":"AA",S=w.variant==="light"||w.variant==="dark"?w.variant:"both",A=pa(e,k,S);return zo({level:A.level,passing:A.checks.length-A.failures.length,total:A.checks.length,checks:A.checks,failures:A.failures})}},{name:"manage_session",title:"Undo, redo, reset, or export the theme",description:'Session action. "undo"/"redo" step through edit history; "reset" restores defaults; "export" returns the embeddable theme snapshot (config + theme JSON) with no side effects.',inputSchema:{type:"object",properties:{action:{type:"string",enum:["undo","redo","reset","export"]}},required:["action"],additionalProperties:!1},execute(x){let{action:w}=r(x);switch(w){case"undo":return e.undo(),d({action:"undo"});case"redo":return e.redo(),d({action:"redo"});case"reset":return e.resetToDefaults(),d({action:"reset"});case"export":return zo({ok:!0,snapshot:e.exportSnapshot()});default:throw new Error(`Unknown action "${w}". Valid: undo, redo, reset, export.`)}}}]}function Kx(e,t){if(!e)return t;switch(e.type){case"color":return e.parseValue?e.parseValue(cs(t)):cs(t);case"toggle":return typeof t=="boolean"?t:t==="true"||t===1;case"slider":{let n=Number(t);if(!Number.isFinite(n))throw new Error(`"${e.id}" expects a number.`);if(e.slider){let{min:o,max:r}=e.slider;if(n<o||n>r)throw new Error(`"${e.id}" must be between ${o} and ${r}.`)}return e.parseValue?e.parseValue(n):n}case"select":{let n=String(t);if(e.options&&!e.options.some(o=>o.value===n))throw new Error(`"${e.id}" must be one of: ${e.options.map(o=>o.value).join(", ")}.`);return e.parseValue?e.parseValue(n):n}default:return e.parseValue?e.parseValue(t):t}}export{Tu as ADVANCED_TOKENS_SECTION,Ar as ALL_ROLES,ll as ALL_TABS,wu as BRAND_PALETTE_SECTION,Eu as BUILT_IN_PRESETS,Zg as COLORS_SECTIONS,rl as COLOR_FAMILIES,yu as COMPONENTS_SECTIONS,bu as COMPONENT_COLOR_SECTIONS,hu as COMPONENT_SHAPE_SECTIONS,vu as CONFIGURE_SECTIONS,Ua as CONFIGURE_SUB_GROUPS,ca as CONTRAST_PAIRS,Oi as CSS_NAMED_COLORS,ls as DEVICE_DIMENSIONS,sg as HOME_SUGGESTION_CHIPS,Su as INTERFACE_ROLES_SECTION,ig as MOCK_BROWSER_CONTENT,lg as MOCK_WORKSPACE_CONTENT,Qg as PALETTE_SECTION,rg as PREVIEW_STORAGE_ADAPTER,da as RADIUS_PRESETS,Da as ROLE_ASSISTANT_MESSAGES,Va as ROLE_BORDERS,Pa as ROLE_FAMILIES,Og as ROLE_FAMILY_LABELS,Ba as ROLE_HEADER,Na as ROLE_INPUT,Ro as ROLE_INTENSITIES,_a as ROLE_LINKS_FOCUS,Fa as ROLE_PRIMARY_ACTIONS,Oa as ROLE_SCROLL_TO_BOTTOM,Wa as ROLE_SURFACES,Ha as ROLE_USER_MESSAGES,Jg as SEMANTIC_COLORS_SECTION,Gr as SHADE_KEYS,Hi as SHELL_STYLE_ID,Au as STATUS_COLORS_SECTION,Cu as STATUS_PALETTE_SECTION,Xr as STYLE_SECTIONS,Ff as STYLE_SECTIONS_V2,Hs as THEME_EDITOR_PRESETS,xu as THEME_SECTION,Ji as ThemeEditorState,Xl as ZOOM_MAX,Yl as ZOOM_MIN,Mx as appendPreviewTranscriptEntry,tc as applySceneConfig,Jl as applyShellTheme,Wr as buildPreviewConfig,Px as buildPreviewConfigWithMessages,Ql as buildShellCss,Zl as buildSrcdoc,Br as buildSummary,Lx as buildTranscriptStreamFrames,cs as coerceColor,_i as coerceFamily,Vi as coerceIntensity,zi as coerceRadius,Ui as coerceRoundnessStyle,$i as coerceScheme,Hg as convertFromPx,Bg as convertToPx,dg as createPreviewMessages,ec as createPreviewTranscriptEntry,Cg as createThemeEditorTools,Wx as createThemePreview,sl as detectRoleAssignment,Di as escapeHtml,Nf as findSection,el as formatCssValue,ol as generateColorScale,Ex as getPreviewTranscriptPresetLabel,ag as getShellPalette,cl as getThemeEditorPreset,du as hexToHsl,pu as hslToHex,tl as isValidHex,Ws as normalizeColorValue,Dg as paletteColorPath,Zi as parseCssValue,cg as presetStreamsText,ps as quickContrastWarnings,$a as resolveRoleAssignment,uu as resolveThemeColorPath,nl as rgbToHex,pa as runContrastChecks,_f as scopeSection,Fg as tokenRefDisplayName,zo as toolResult,Ra as wcagContrastRatio};