@runtypelabs/persona 3.29.1 → 3.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -2547
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/{types-B_Qazlm4.d.cts → types-quh7NmYD.d.cts} +9 -0
- package/dist/animations/{types-B_Qazlm4.d.ts → types-quh7NmYD.d.ts} +9 -0
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/codegen.cjs +6 -6
- package/dist/codegen.js +4 -4
- package/dist/index.cjs +50 -50
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +164 -7
- package/dist/index.d.ts +164 -7
- package/dist/index.global.js +60 -60
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +49 -49
- package/dist/index.js.map +1 -1
- package/dist/launcher.global.js +2 -2
- package/dist/launcher.global.js.map +1 -1
- package/dist/plugin-kit.cjs +1 -0
- package/dist/plugin-kit.d.cts +98 -0
- package/dist/plugin-kit.d.ts +98 -0
- package/dist/plugin-kit.js +1 -0
- package/dist/smart-dom-reader.d.cts +157 -4
- package/dist/smart-dom-reader.d.ts +157 -4
- package/dist/theme-editor.cjs +40 -40
- package/dist/theme-editor.d.cts +161 -6
- package/dist/theme-editor.d.ts +161 -6
- package/dist/theme-editor.js +40 -40
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.d.cts +2 -0
- package/dist/theme-reference.d.ts +2 -0
- package/dist/theme-reference.js +1 -1
- package/dist/widget.css +19 -0
- package/package.json +8 -2
- package/src/client.ts +6 -0
- package/src/components/approval-bubble.test.ts +320 -0
- package/src/components/approval-bubble.ts +190 -20
- package/src/components/launcher.ts +6 -3
- package/src/components/panel.ts +7 -1
- package/src/components/tool-bubble.test.ts +39 -0
- package/src/components/tool-bubble.ts +4 -0
- package/src/defaults.ts +14 -0
- package/src/generated/runtype-openapi-contract.ts +4 -0
- package/src/index-core.ts +1 -0
- package/src/plugin-kit.test.ts +230 -0
- package/src/plugin-kit.ts +294 -0
- package/src/plugins/types.ts +49 -2
- package/src/session.test.ts +161 -0
- package/src/session.ts +41 -3
- package/src/styles/widget.css +19 -0
- package/src/theme-editor/preview-utils.test.ts +10 -0
- package/src/theme-editor/preview-utils.ts +29 -1
- package/src/theme-editor/sections.test.ts +17 -0
- package/src/theme-editor/sections.ts +31 -0
- package/src/theme-reference.ts +2 -2
- package/src/types/theme.ts +2 -0
- package/src/types.ts +109 -2
- package/src/ui.approval-plugin.test.ts +204 -0
- package/src/ui.scroll.test.ts +383 -0
- package/src/ui.ts +539 -56
- package/src/utils/auto-follow.test.ts +91 -0
- package/src/utils/auto-follow.ts +68 -0
- package/src/utils/theme.test.ts +6 -2
- package/src/utils/theme.ts +0 -8
- package/src/utils/tokens.ts +6 -1
- package/src/webmcp-bridge.test.ts +66 -0
- package/src/webmcp-bridge.ts +49 -0
package/dist/theme-editor.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
var Xp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ks(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];Xp(s)&&Xp(r)?n[o]=ks(s,r):n[o]=r}return n}var io="min(440px, calc(100vw - 24px))",Ea="440px",St={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:io,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Qp(e,t){if(!(!e&&!t))return e?t?ks(e,t):e:t}function Jp(e){var t,n,o,r,s,a,i,d,l,m,u,g,p,w,S,M,I,L,H,D,W;return e?{...St,...e,theme:Qp(St.theme,e.theme),darkTheme:Qp(St.darkTheme,e.darkTheme),launcher:{...St.launcher,...e.launcher,dock:{...(t=St.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(o=St.launcher)==null?void 0:o.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...St.copy,...e.copy},sendButton:{...St.sendButton,...e.sendButton},statusIndicator:{...St.statusIndicator,...e.statusIndicator},voiceRecognition:{...St.voiceRecognition,...e.voiceRecognition},features:(()=>{var be,Oe,ve,Q,Le,Y,xe,Se;let v=(be=St.features)==null?void 0:be.artifacts,x=(Oe=e.features)==null?void 0:Oe.artifacts,k=(ve=St.features)==null?void 0:ve.scrollToBottom,C=(Q=e.features)==null?void 0:Q.scrollToBottom,T=(Le=St.features)==null?void 0:Le.streamAnimation,F=(Y=e.features)==null?void 0:Y.streamAnimation,$=(xe=St.features)==null?void 0:xe.askUserQuestion,j=(Se=e.features)==null?void 0:Se.askUserQuestion,me=v===void 0&&x===void 0?void 0:{...v,...x,layout:{...v==null?void 0:v.layout,...x==null?void 0:x.layout}},se=k===void 0&&C===void 0?void 0:{...k,...C},fe=T===void 0&&F===void 0?void 0:{...T,...F},ie=$===void 0&&j===void 0?void 0:{...$,...j,styles:{...$==null?void 0:$.styles,...j==null?void 0:j.styles}};return{...St.features,...e.features,...se!==void 0?{scrollToBottom:se}:{},...me!==void 0?{artifacts:me}:{},...fe!==void 0?{streamAnimation:fe}:{},...ie!==void 0?{askUserQuestion:ie}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:St.suggestionChips,suggestionChipsConfig:{...St.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...St.layout,...e.layout,header:{...(a=St.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=St.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(u=(m=St.layout)==null?void 0:m.messages)==null?void 0:u.avatar,...(p=(g=e.layout)==null?void 0:g.messages)==null?void 0:p.avatar},timestamp:{...(S=(w=St.layout)==null?void 0:w.messages)==null?void 0:S.timestamp,...(I=(M=e.layout)==null?void 0:M.messages)==null?void 0:I.timestamp}},slots:{...(L=St.layout)==null?void 0:L.slots,...(H=e.layout)==null?void 0:H.slots}},markdown:{...St.markdown,...e.markdown,options:{...(D=St.markdown)==null?void 0:D.options,...(W=e.markdown)==null?void 0:W.options}},messageActions:{...St.messageActions,...e.messageActions}}:St}var pf={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},uf={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},mf={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:io,maxWidth:Ea,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Vr(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Vr(e,o):o}function Zp(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let i=`${r}.${s}`;if(typeof a=="string"){let d=Vr(e,a);d!==void 0&&(t[i]={path:i,value:d,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function ff(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function eu(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=eu(s,r):n[o]=r}return n}function gf(e,t){return t?eu(e,t):e}function tn(e,t={}){var r,s,a,i,d,l,m,u,g,p,w,S,M;let n={palette:pf,semantic:uf,components:mf},o={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(m=e==null?void 0:e.semantic)==null?void 0:m.colors,interactive:{...n.semantic.colors.interactive,...(g=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:g.interactive},feedback:{...n.semantic.colors.feedback,...(w=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:w.feedback}},spacing:{...n.semantic.spacing,...(S=e==null?void 0:e.semantic)==null?void 0:S.spacing},typography:{...n.semantic.typography,...(M=e==null?void 0:e.semantic)==null?void 0:M.typography}},components:gf(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let I=ff(o);if(!I.valid)throw new Error(`Theme validation failed: ${I.errors.map(L=>L.message).join(", ")}`)}if(t.plugins)for(let I of t.plugins)o=I.transform(o);return o}function tu(e){var S,M,I,L,H,D,W,v,x,k,C,T,F,$,j,me,se,fe,ie,be,Oe,ve,Q,Le,Y,xe,Se,de,we,ze,te,ne,re,nt,ye,le,Ue,He,ce,G,Ve,Et,pe,ae,Ln,Nt,ln,Dn,Jn,qe,_,ke,De,Fe,$e,dt,ot,At,Vt,q,_t,Qe,Ft,oe,ge,xt,$t,Jt,yn,Tt,wt,gt,bt,zt,et,Fn,Zn,vn,On,ut,wo,Nn,ir,In,Rr,$o,Lo,yt,_n,Vn,xn,It,eo,to,$n,Uo,Io,zo,Un,Wt,wn,no,qo,Ro,jo,Co,zn,po,ft,Kt,Gt,qn,Ko,oo,uo,jn;let t=Zp(e),n={};for(let[E,Kn]of Object.entries(t)){let mo=E.replace(/\./g,"-");n[`--persona-${mo}`]=Kn.value}n["--persona-primary"]=(S=n["--persona-semantic-colors-primary"])!=null?S:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(M=n["--persona-semantic-colors-secondary"])!=null?M:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(I=n["--persona-semantic-colors-accent"])!=null?I:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(L=n["--persona-semantic-colors-surface"])!=null?L:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(H=n["--persona-semantic-colors-background"])!=null?H:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(D=n["--persona-semantic-colors-container"])!=null?D:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(W=n["--persona-semantic-colors-text"])!=null?W:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(v=n["--persona-semantic-colors-text-muted"])!=null?v:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(x=n["--persona-semantic-colors-text-inverse"])!=null?x:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(k=n["--persona-semantic-colors-border"])!=null?k:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(C=n["--persona-semantic-colors-divider"])!=null?C:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(T=n["--persona-components-voice-recording-indicator"])!=null?T:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(F=n["--persona-components-voice-recording-background"])!=null?F:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=($=n["--persona-components-voice-processing-icon"])!=null?$:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(j=n["--persona-components-voice-speaking-icon"])!=null?j:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(me=n["--persona-components-approval-requested-background"])!=null?me:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(se=n["--persona-components-approval-requested-border"])!=null?se:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(fe=n["--persona-components-approval-requested-text"])!=null?fe:n["--persona-palette-colors-gray-900"],n["--persona-approval-approve-bg"]=(ie=n["--persona-components-approval-approve-background"])!=null?ie:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(be=n["--persona-components-approval-deny-background"])!=null?be:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Oe=n["--persona-components-attachment-image-background"])!=null?Oe:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(ve=n["--persona-components-attachment-image-border"])!=null?ve:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(Q=n["--persona-semantic-typography-fontFamily"])!=null?Q:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(Le=n["--persona-semantic-typography-fontSize"])!=null?Le:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(Y=n["--persona-semantic-typography-fontWeight"])!=null?Y:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(xe=n["--persona-semantic-typography-lineHeight"])!=null?xe:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(Se=n["--persona-palette-radius-sm"])!=null?Se:"0.125rem",n["--persona-radius-md"]=(de=n["--persona-palette-radius-md"])!=null?de:"0.375rem",n["--persona-radius-lg"]=(we=n["--persona-palette-radius-lg"])!=null?we:"0.5rem",n["--persona-radius-xl"]=(ze=n["--persona-palette-radius-xl"])!=null?ze:"0.75rem",n["--persona-radius-full"]=(te=n["--persona-palette-radius-full"])!=null?te:"9999px",n["--persona-launcher-radius"]=(re=(ne=n["--persona-components-launcher-borderRadius"])!=null?ne:n["--persona-palette-radius-full"])!=null?re:"9999px",n["--persona-launcher-bg"]=(nt=n["--persona-components-launcher-background"])!=null?nt:n["--persona-primary"],n["--persona-launcher-fg"]=(ye=n["--persona-components-launcher-foreground"])!=null?ye:n["--persona-text-inverse"],n["--persona-launcher-border"]=(le=n["--persona-components-launcher-border"])!=null?le:n["--persona-border"],n["--persona-button-primary-bg"]=(Ue=n["--persona-components-button-primary-background"])!=null?Ue:n["--persona-primary"],n["--persona-button-primary-fg"]=(He=n["--persona-components-button-primary-foreground"])!=null?He:n["--persona-text-inverse"],n["--persona-button-radius"]=(G=(ce=n["--persona-components-button-primary-borderRadius"])!=null?ce:n["--persona-palette-radius-full"])!=null?G:"9999px",n["--persona-panel-radius"]=(Et=(Ve=n["--persona-components-panel-borderRadius"])!=null?Ve:n["--persona-radius-xl"])!=null?Et:"0.75rem",n["--persona-panel-border"]=(pe=n["--persona-components-panel-border"])!=null?pe:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Ln=(ae=n["--persona-components-panel-shadow"])!=null?ae:n["--persona-palette-shadows-xl"])!=null?Ln:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-input-radius"]=(ln=(Nt=n["--persona-components-input-borderRadius"])!=null?Nt:n["--persona-radius-lg"])!=null?ln:"0.5rem",n["--persona-message-user-radius"]=(Jn=(Dn=n["--persona-components-message-user-borderRadius"])!=null?Dn:n["--persona-radius-lg"])!=null?Jn:"0.5rem",n["--persona-message-assistant-radius"]=(_=(qe=n["--persona-components-message-assistant-borderRadius"])!=null?qe:n["--persona-radius-lg"])!=null?_:"0.5rem",n["--persona-header-bg"]=(ke=n["--persona-components-header-background"])!=null?ke:n["--persona-surface"],n["--persona-header-border"]=(De=n["--persona-components-header-border"])!=null?De:n["--persona-divider"],n["--persona-header-icon-bg"]=(Fe=n["--persona-components-header-iconBackground"])!=null?Fe:n["--persona-primary"],n["--persona-header-icon-fg"]=($e=n["--persona-components-header-iconForeground"])!=null?$e:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(dt=n["--persona-components-header-titleForeground"])!=null?dt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(ot=n["--persona-components-header-subtitleForeground"])!=null?ot:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(At=n["--persona-components-header-actionIconForeground"])!=null?At:n["--persona-muted"];let o=(Vt=e.components)==null?void 0:Vt.header;o!=null&&o.shadow&&(n["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom);let r=(q=e.components)==null?void 0:q.introCard;n["--persona-intro-card-bg"]=(_t=n["--persona-components-introCard-background"])!=null?_t:n["--persona-surface"],n["--persona-intro-card-radius"]=(Qe=n["--persona-components-introCard-borderRadius"])!=null?Qe:"1rem",n["--persona-intro-card-padding"]=(Ft=n["--persona-components-introCard-padding"])!=null?Ft:"1.5rem",n["--persona-intro-card-shadow"]=(ge=(oe=r==null?void 0:r.shadow)!=null?oe:n["--persona-components-introCard-shadow"])!=null?ge:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(xt=n["--persona-components-input-background"])!=null?xt:n["--persona-surface"],n["--persona-input-placeholder"]=($t=n["--persona-components-input-placeholder"])!=null?$t:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Jt=n["--persona-components-message-user-background"])!=null?Jt:n["--persona-accent"],n["--persona-message-user-text"]=(yn=n["--persona-components-message-user-text"])!=null?yn:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Tt=n["--persona-components-message-user-shadow"])!=null?Tt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(wt=n["--persona-components-message-assistant-background"])!=null?wt:n["--persona-surface"],n["--persona-message-assistant-text"]=(gt=n["--persona-components-message-assistant-text"])!=null?gt:n["--persona-text"],n["--persona-message-assistant-border"]=(bt=n["--persona-components-message-assistant-border"])!=null?bt:n["--persona-border"],n["--persona-message-assistant-shadow"]=(zt=n["--persona-components-message-assistant-shadow"])!=null?zt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(Fn=(et=n["--persona-components-scrollToBottom-background"])!=null?et:n["--persona-button-primary-bg"])!=null?Fn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(vn=(Zn=n["--persona-components-scrollToBottom-foreground"])!=null?Zn:n["--persona-button-primary-fg"])!=null?vn:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(On=n["--persona-components-scrollToBottom-border"])!=null?On:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(ut=n["--persona-components-scrollToBottom-size"])!=null?ut:"40px",n["--persona-scroll-to-bottom-radius"]=(ir=(Nn=(wo=n["--persona-components-scrollToBottom-borderRadius"])!=null?wo:n["--persona-button-radius"])!=null?Nn:n["--persona-radius-full"])!=null?ir:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Rr=(In=n["--persona-components-scrollToBottom-shadow"])!=null?In:n["--persona-palette-shadows-sm"])!=null?Rr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=($o=n["--persona-components-scrollToBottom-padding"])!=null?$o:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Lo=n["--persona-components-scrollToBottom-gap"])!=null?Lo:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(_n=(yt=n["--persona-components-scrollToBottom-fontSize"])!=null?yt:n["--persona-palette-typography-fontSize-sm"])!=null?_n:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Vn=n["--persona-components-scrollToBottom-iconSize"])!=null?Vn:"14px",n["--persona-tool-bubble-shadow"]=(xn=n["--persona-components-toolBubble-shadow"])!=null?xn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(It=n["--persona-components-reasoningBubble-shadow"])!=null?It:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(eo=n["--persona-components-composer-shadow"])!=null?eo:"none",n["--persona-md-inline-code-bg"]=(to=n["--persona-components-markdown-inlineCode-background"])!=null?to:n["--persona-container"],n["--persona-md-inline-code-color"]=($n=n["--persona-components-markdown-inlineCode-foreground"])!=null?$n:n["--persona-text"],n["--persona-md-link-color"]=(Io=(Uo=n["--persona-components-markdown-link-foreground"])!=null?Uo:n["--persona-accent"])!=null?Io:"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let l=n["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(n["--persona-md-prose-font-family"]=l),n["--persona-md-code-block-bg"]=(zo=n["--persona-components-markdown-codeBlock-background"])!=null?zo:n["--persona-container"],n["--persona-md-code-block-border-color"]=(Un=n["--persona-components-markdown-codeBlock-borderColor"])!=null?Un:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Wt=n["--persona-components-markdown-codeBlock-textColor"])!=null?Wt:"inherit",n["--persona-md-table-header-bg"]=(wn=n["--persona-components-markdown-table-headerBackground"])!=null?wn:n["--persona-container"],n["--persona-md-table-border-color"]=(no=n["--persona-components-markdown-table-borderColor"])!=null?no:n["--persona-border"],n["--persona-md-hr-color"]=(qo=n["--persona-components-markdown-hr-color"])!=null?qo:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Ro=n["--persona-components-markdown-blockquote-borderColor"])!=null?Ro:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(jo=n["--persona-components-markdown-blockquote-background"])!=null?jo:"transparent",n["--persona-md-blockquote-text-color"]=(Co=n["--persona-components-markdown-blockquote-textColor"])!=null?Co:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(zn=n["--persona-components-collapsibleWidget-container"])!=null?zn:n["--persona-surface"],n["--cw-surface"]=(po=n["--persona-components-collapsibleWidget-surface"])!=null?po:n["--persona-surface"],n["--cw-border"]=(ft=n["--persona-components-collapsibleWidget-border"])!=null?ft:n["--persona-border"],n["--persona-message-border"]=(Kt=n["--persona-components-message-border"])!=null?Kt:n["--persona-border"];let m=e.components,u=m==null?void 0:m.iconButton;u&&(u.background&&(n["--persona-icon-btn-bg"]=u.background),u.border&&(n["--persona-icon-btn-border"]=u.border),u.color&&(n["--persona-icon-btn-color"]=u.color),u.padding&&(n["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(n["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(n["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(n["--persona-icon-btn-active-border"]=u.activeBorder));let g=m==null?void 0:m.labelButton;g&&(g.background&&(n["--persona-label-btn-bg"]=g.background),g.border&&(n["--persona-label-btn-border"]=g.border),g.color&&(n["--persona-label-btn-color"]=g.color),g.padding&&(n["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(n["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(n["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(n["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(n["--persona-label-btn-gap"]=g.gap));let p=m==null?void 0:m.toggleGroup;p&&(p.gap&&(n["--persona-toggle-group-gap"]=p.gap),p.borderRadius&&(n["--persona-toggle-group-radius"]=p.borderRadius));let w=m==null?void 0:m.artifact;if(w!=null&&w.toolbar){let E=w.toolbar;E.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=E.iconHoverColor),E.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=E.iconHoverBackground),E.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=E.iconPadding),E.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=E.iconBorderRadius),E.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=E.iconBorder),E.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=E.toggleGroupGap),E.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=E.toggleBorderRadius),E.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=E.copyBackground),E.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=E.copyBorder),E.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=E.copyColor),E.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=E.copyBorderRadius),E.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=E.copyPadding),E.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=E.copyMenuBackground,n["--persona-dropdown-bg"]=(Gt=n["--persona-dropdown-bg"])!=null?Gt:E.copyMenuBackground),E.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=E.copyMenuBorder,n["--persona-dropdown-border"]=(qn=n["--persona-dropdown-border"])!=null?qn:E.copyMenuBorder),E.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=E.copyMenuShadow,n["--persona-dropdown-shadow"]=(Ko=n["--persona-dropdown-shadow"])!=null?Ko:E.copyMenuShadow),E.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=E.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(oo=n["--persona-dropdown-radius"])!=null?oo:E.copyMenuBorderRadius),E.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=E.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(uo=n["--persona-dropdown-item-hover-bg"])!=null?uo:E.copyMenuItemHoverBackground),E.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=E.iconBackground),E.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=E.toolbarBorder)}if(w!=null&&w.tab){let E=w.tab;E.background&&(n["--persona-artifact-tab-bg"]=E.background),E.activeBackground&&(n["--persona-artifact-tab-active-bg"]=E.activeBackground),E.activeBorder&&(n["--persona-artifact-tab-active-border"]=E.activeBorder),E.borderRadius&&(n["--persona-artifact-tab-radius"]=E.borderRadius),E.textColor&&(n["--persona-artifact-tab-color"]=E.textColor),E.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=E.hoverBackground),E.listBackground&&(n["--persona-artifact-tab-list-bg"]=E.listBackground),E.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=E.listBorderColor),E.listPadding&&(n["--persona-artifact-tab-list-padding"]=E.listPadding)}if(w!=null&&w.pane){let E=w.pane;if(E.toolbarBackground){let Kn=(jn=Vr(e,E.toolbarBackground))!=null?jn:E.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Kn}}return n}var hf={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},nu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},ji=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},bf=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":ji()},yf=e=>bf(e),vf=e=>tn(e),xf=e=>{var n;let t=tn(void 0,{validate:!1});return tn({...e,palette:{...t.palette,colors:{...hf.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Ma=e=>{let t=yf(e),n=nu(e==null?void 0:e.theme),o=nu(e==null?void 0:e.darkTheme);return t==="dark"?xf(ks(n!=null?n:{},o!=null?o:{})):vf(n)},wf=e=>tu(e),$r=(e,t)=>{var s;let n=Ma(t),o=wf(n);for(let[a,i]of Object.entries(o))e.style.setProperty(a,i);let r=(s=t==null?void 0:t.toolCall)==null?void 0:s.shadow;r!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",r.trim()===""?"none":r)},ou=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(ji())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(ji());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};function Ki(e,t){let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return o}function xr(e,t,n){var i;let o=t.split(".");if(o.length===1)return{...e,[o[0]]:n};let[r,...s]=o,a=e;return{...a,[r]:xr((i=a==null?void 0:a[r])!=null?i:{},s.join("."),n)}}var Gi=class{constructor(t,n,o){this.listeners=[];this.history=[];this.historyIndex=-1;this.suppressHistory=!1;var s;let r=(s=o==null?void 0:o.mergeDefaults)!=null?s:!0;this.config=r?{...St,...n}:n!=null?n:St,this.theme=tn(t,{validate:!1}),this.syncThemeIntoConfig(),this.pushHistorySnapshot(this.exportSnapshot(),!0)}get(t){var n;return t.startsWith("theme.")?Ki(this.theme,t.replace("theme.","")):t.startsWith("darkTheme.")?Ki((n=this.config.darkTheme)!=null?n:{},t.replace("darkTheme.","")):Ki(this.config,t)}getTheme(){return this.theme}getConfig(){return this.config}set(t,n){var o;if(t.startsWith("theme.")){let r=t.replace("theme.","");this.theme=xr(this.theme,r,n),this.syncThemeIntoConfig()}else if(t.startsWith("darkTheme.")){let r=t.replace("darkTheme.",""),s=(o=this.config.darkTheme)!=null?o:tn();this.config={...this.config,darkTheme:xr(s,r,n)}}else this.config=xr(this.config,t,n);this.recordHistory(),this.notifyListeners()}setBatch(t){var s;let n=!1,o=!1,r=!1;for(let[a,i]of Object.entries(t))if(a.startsWith("theme.")){let d=a.replace("theme.","");this.theme=xr(this.theme,d,i),n=!0}else if(a.startsWith("darkTheme.")){let d=a.replace("darkTheme.",""),l=(s=this.config.darkTheme)!=null?s:tn();this.config={...this.config,darkTheme:xr(l,d,i)},o=!0}else this.config=xr(this.config,a,i),r=!0;n&&this.syncThemeIntoConfig(),(n||o||r)&&(this.recordHistory(),this.notifyListeners())}setTheme(t){this.theme=t,this.syncThemeIntoConfig(),this.recordHistory(),this.notifyListeners()}setFullConfig(t,n){this.config={...t},n&&(this.theme=n),this.syncThemeIntoConfig(),this.recordHistory(),this.notifyListeners()}importSnapshot(t){var r,s;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Snapshot must be a JSON object");let n=t;if("config"in n||"theme"in n||n.version===2){let a=(r=n.config)!=null?r:this.config,i=tn((s=n.theme)!=null?s:this.theme,{validate:!1});this.setFullConfig(a,i);return}let o=tn(n,{validate:!1});this.setTheme(o)}resetToDefaults(){this.config={...St},this.theme=tn(),this.syncThemeIntoConfig(),this.history=[],this.historyIndex=-1,this.pushHistorySnapshot(this.exportSnapshot()),this.notifyListeners()}canUndo(){return this.historyIndex>0}canRedo(){return this.historyIndex>=0&&this.historyIndex<this.history.length-1}getHistoryLength(){return this.history.length}getHistoryIndex(){return this.historyIndex}undo(){this.canUndo()&&(this.historyIndex-=1,this.restoreSnapshot(this.history[this.historyIndex]))}redo(){this.canRedo()&&(this.historyIndex+=1,this.restoreSnapshot(this.history[this.historyIndex]))}exportSnapshot(){return{version:2,config:{...this.config,theme:void 0},theme:this.theme}}onChange(t){return this.listeners.push(t),()=>{let n=this.listeners.indexOf(t);n>=0&&this.listeners.splice(n,1)}}syncThemeIntoConfig(){this.config={...this.config,theme:this.theme}}notifyListeners(){for(let t of this.listeners)t(this.config,this.theme)}recordHistory(){this.pushHistorySnapshot(this.exportSnapshot())}pushHistorySnapshot(t,n=!1){if(this.suppressHistory)return;let o=JSON.stringify(t),r=this.historyIndex>=0&&this.history[this.historyIndex]?JSON.stringify(this.history[this.historyIndex]):null;if(n&&this.historyIndex>=0){this.history[this.historyIndex]=t;return}o!==r&&(this.history=this.history.slice(0,this.historyIndex+1),this.history.push(t),this.historyIndex=this.history.length-1)}restoreSnapshot(t){this.suppressHistory=!0,this.config=t.config,this.theme=tn(t.theme,{validate:!1}),this.syncThemeIntoConfig(),this.suppressHistory=!1,this.notifyListeners()}};function Yi(e){let t=e.trim();if(t==="9999px")return{value:100,unit:"px"};let n=t.match(/^([\d.]+)(px|rem)$/);if(!n){let o=parseFloat(t);return{value:isNaN(o)?0:o,unit:"px"}}return{value:parseFloat(n[1]),unit:n[2]}}function Xi(e,t){return t==="rem"?`${e}rem`:`${e}px`}function Cf(e,t){return t==="rem"?e*16:e}function Sf(e,t){return t==="rem"?e/16:e}function Es(e){if(!e)return"#000000";let t=e.trim().toLowerCase();return t==="transparent"?"transparent":t.startsWith("rgba")||t.startsWith("rgb")?t:t.startsWith("#")?t.length===4?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:t:`#${t}`}function Qi(e){return/^#[0-9A-Fa-f]{6}$/.test(e)}function Ji(e){let t=e.trim().toLowerCase().match(/^rgba?\(([^)]+)\)$/);if(!t)return null;let n=t[1].split(",").map(d=>d.trim());if(n.length<3)return null;let o=d=>{let l=d.endsWith("%"),m=parseFloat(l?d.slice(0,-1):d);return Number.isFinite(m)?Math.max(0,Math.min(255,Math.round(l?m/100*255:m))):NaN},r=o(n[0]),s=o(n[1]),a=o(n[2]);if(!Number.isFinite(r)||!Number.isFinite(s)||!Number.isFinite(a))return null;let i=d=>d.toString(16).padStart(2,"0");return`#${i(r)}${i(s)}${i(a)}`}function La(e,t){let n=s=>{var l;let a=Es(s),i=a.startsWith("rgb")?(l=Ji(a))!=null?l:"#000000":a,d=[1,3,5].map(m=>{let u=parseInt(i.slice(m,m+2),16)/255;return u<=.03928?u/12.92:Math.pow((u+.055)/1.055,2.4)});return .2126*d[0]+.7152*d[1]+.0722*d[2]},o=n(e),r=n(t);return(Math.max(o,r)+.05)/(Math.min(o,r)+.05)}function ru(e){var g;let t=Es(e),n=t.startsWith("rgb")?(g=Ji(t))!=null?g:"#000000":t,o=parseInt(n.slice(1,3),16)/255,r=parseInt(n.slice(3,5),16)/255,s=parseInt(n.slice(5,7),16)/255,a=Math.max(o,r,s),i=Math.min(o,r,s),d=(a+i)/2;if(a===i)return{h:0,s:0,l:d};let l=a-i,m=d>.5?l/(2-a-i):l/(a+i),u;switch(a){case o:u=((r-s)/l+(r<s?6:0))/6;break;case r:u=((s-o)/l+2)/6;break;default:u=((o-r)/l+4)/6;break}return{h:u*360,s:m,l:d}}function su(e,t,n){let o=(e%360+360)%360,r=(1-Math.abs(2*n-1))*t,s=r*(1-Math.abs(o/60%2-1)),a=n-r/2,i,d,l;o<60?[i,d,l]=[r,s,0]:o<120?[i,d,l]=[s,r,0]:o<180?[i,d,l]=[0,r,s]:o<240?[i,d,l]=[0,s,r]:o<300?[i,d,l]=[s,0,r]:[i,d,l]=[r,0,s];let m=u=>{let g=Math.round((u+a)*255).toString(16);return g.length===1?"0"+g:g};return`#${m(i)}${m(d)}${m(l)}`}function Zi(e){let{h:t,s:n,l:o}=ru(e),r={50:.97,100:.94,200:.87,300:.77,400:.64,500:o,600:Math.max(.05,o-.1),700:Math.max(.05,o-.2),800:Math.max(.05,o-.28),900:Math.max(.05,o-.35),950:Math.max(.03,o-.42)},s={50:Math.min(1,n*.85),100:Math.min(1,n*.9),200:Math.min(1,n*.95),300:n,400:n,500:n,600:Math.min(1,n*1.05),700:Math.min(1,n*1.05),800:Math.min(1,n*1),900:Math.min(1,n*.95),950:Math.min(1,n*.9)},a={};for(let[i,d]of Object.entries(r)){let l=s[i];a[i]=su(t,l,d)}return a}var Ur=["50","100","200","300","400","500","600","700","800","900","950"],el=["primary","secondary","accent","gray","success","warning","error","info"];function Af(e,t){return`palette.colors.${e}.${t}`}function au(e,t,n=0){if(n>5)return"#cbd5e1";let o=e(t);return typeof o!="string"?"#cbd5e1":o.startsWith("#")||o.startsWith("rgb")||o==="transparent"?o:o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components.")?au(e,`theme.${o}`,n+1):"#cbd5e1"}function Tf(e){if(!e.startsWith("palette.")&&!e.startsWith("semantic."))return e;let t=e.split(".");if(t[0]==="palette"&&t[1]==="colors"){let n=t[2],o=t[3];return`${n.charAt(0).toUpperCase()+n.slice(1)} ${o}`}return t[0]==="semantic"?t.slice(1).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):t[t.length-1]}var ko=[{id:"solid",label:"Solid"},{id:"soft",label:"Soft"}],Ia=["primary","secondary","accent","gray"],kf={primary:"Primary",secondary:"Secondary",accent:"Accent",gray:"Neutral"},Ra={roleId:"role-surfaces",helper:"Page and panel backgrounds",previewZone:"container",intensities:ko,targets:[{path:"semantic.colors.background",kind:"background"},{path:"semantic.colors.surface",kind:"background"},{path:"semantic.colors.container",kind:"background"}]},Pa={roleId:"role-header",helper:"Widget header bar",previewZone:"header",intensities:ko,targets:[{path:"components.header.background",kind:"background"},{path:"components.header.border",kind:"border"},{path:"components.header.iconBackground",kind:"accent"},{path:"components.header.iconForeground",kind:"foreground"},{path:"components.header.titleForeground",kind:"accent"},{path:"components.header.subtitleForeground",kind:"foreground"},{path:"components.header.actionIconForeground",kind:"foreground"}]},Wa={roleId:"role-user-messages",helper:"User chat bubbles",previewZone:"user-message",intensities:ko,targets:[{path:"components.message.user.background",kind:"background"},{path:"components.message.user.text",kind:"foreground"}]},Ba={roleId:"role-assistant-messages",helper:"Assistant chat bubbles",previewZone:"assistant-message",intensities:ko,targets:[{path:"components.message.assistant.background",kind:"background"},{path:"components.message.assistant.text",kind:"foreground"}]},Ha={roleId:"role-primary-actions",helper:"Send button and primary buttons",intensities:ko,targets:[{path:"components.button.primary.background",kind:"background"},{path:"components.button.primary.foreground",kind:"foreground"},{path:"semantic.colors.interactive.default",kind:"accent"},{path:"semantic.colors.interactive.hover",kind:"accent"}]},Da={roleId:"role-scroll-to-bottom",helper:"Scroll-to-bottom affordances in transcript and event stream",intensities:ko,targets:[{path:"components.scrollToBottom.background",kind:"background"},{path:"components.scrollToBottom.foreground",kind:"foreground"},{path:"components.scrollToBottom.border",kind:"border"}]},Fa={roleId:"role-input",helper:"Message input field",previewZone:"composer",intensities:ko,targets:[{path:"components.input.background",kind:"background"},{path:"components.input.placeholder",kind:"foreground"},{path:"components.input.focus.border",kind:"accent"},{path:"components.input.focus.ring",kind:"accent"}]},Oa={roleId:"role-links-focus",helper:"Links, focus rings, and interactive highlights",intensities:ko,targets:[{path:"semantic.colors.accent",kind:"accent"},{path:"semantic.colors.interactive.focus",kind:"accent"},{path:"semantic.colors.interactive.active",kind:"accent"},{path:"components.markdown.link.foreground",kind:"accent"}]},Na={roleId:"role-borders",helper:"Borders, dividers, and separators",intensities:ko,targets:[{path:"semantic.colors.border",kind:"border"},{path:"semantic.colors.divider",kind:"border"}]},wr=[Ra,Pa,Wa,Ba,Ha,Da,Fa,Oa,Na];function _a(e,t,n){let o={},r=e==="neutral"?"gray":e;for(let s of n.targets){let a=Ef(r,t,s,n.roleId);o[`theme.${s.path}`]=a,o[`darkTheme.${s.path}`]=a}if(n.roleId==="role-primary-actions"){let s=t==="solid"?`palette.colors.${r}.700`:`palette.colors.${r}.200`;o["theme.semantic.colors.interactive.hover"]=s,o["darkTheme.semantic.colors.interactive.hover"]=s}return o}function Ef(e,t,n,o){let r=t==="solid";if(o==="role-header")return Mf(e,r,n);if(o==="role-input")return Lf(e,r,n);switch(n.kind){case"background":return r?`palette.colors.${e}.500`:`palette.colors.${e}.${e==="gray"?"50":"100"}`;case"foreground":return r?`palette.colors.${e==="gray"?"gray":e}.50`:`palette.colors.${e==="gray"?"gray":e}.900`;case"border":return r?`palette.colors.${e}.600`:`palette.colors.${e}.200`;case"accent":return r?`palette.colors.${e}.600`:`palette.colors.${e}.400`}}function Mf(e,t,n){let o=n.path;return o.endsWith(".background")?t?`palette.colors.${e}.500`:`palette.colors.${e}.${e==="gray"?"50":"100"}`:o.endsWith(".border")?t?`palette.colors.${e}.600`:`palette.colors.${e}.200`:o.endsWith(".iconBackground")?t?`palette.colors.${e}.${e==="gray"?"700":"600"}`:`palette.colors.${e}.500`:o.endsWith(".iconForeground")?t?`palette.colors.${e}.50`:`palette.colors.${e}.50`:o.endsWith(".titleForeground")?t?`palette.colors.${e}.50`:`palette.colors.${e}.${e==="gray"?"900":"700"}`:o.endsWith(".subtitleForeground")?t?`palette.colors.${e}.200`:`palette.colors.${e}.500`:o.endsWith(".actionIconForeground")?t?`palette.colors.${e}.200`:`palette.colors.${e}.500`:`palette.colors.${e}.500`}function Lf(e,t,n){let o=n.path;return o.endsWith(".background")?t?`palette.colors.${e}.${e==="gray"?"100":"50"}`:`palette.colors.${e}.50`:o.endsWith(".placeholder")?`palette.colors.${e}.400`:o.endsWith(".border")||o.endsWith(".ring")?t?`palette.colors.${e}.500`:`palette.colors.${e}.400`:`palette.colors.${e}.500`}var If=/^palette\.colors\.(\w+)\.(\d+)$/;function tl(e,t){var i,d;let n=(i=t.targets.find(l=>l.kind==="background"))!=null?i:t.targets[0];if(!n)return null;let r=String((d=e(n.path))!=null?d:"").match(If);if(!r)return null;let s=r[1],a=Ia.includes(s)?s:null;if(!a)return null;for(let l of["solid","soft"]){let m=_a(a,l,t);if(t.targets.every(g=>{var w;return String((w=e(g.path))!=null?w:"")===m[`theme.${g.path}`]}))return{family:a,intensity:l}}return null}var Rf={id:"theme-mode",title:"Runtime Theme",description:"Controls how the shipped widget picks light or dark mode.",collapsed:!1,fields:[{id:"theme-mode",label:"Runtime Theme",description:"Always Light, Always Dark, or follow the visitor system preference",type:"select",path:"colorScheme",defaultValue:"auto",options:[{value:"light",label:"Light"},{value:"dark",label:"Dark"},{value:"auto",label:"Follow System"}]}]},Pf={id:"brand-colors",title:"Brand Colors",description:"Pick your brand colors. A full shade scale is generated automatically for both light and dark themes.",collapsed:!1,fields:[{id:"brand-primary",label:"Primary",description:"Main brand color for buttons, links, and accents",type:"color",path:"theme.palette.colors.primary.500",defaultValue:"#171717"},{id:"brand-secondary",label:"Secondary",description:"Supporting brand color",type:"color",path:"theme.palette.colors.secondary.500",defaultValue:"#7c3aed"},{id:"brand-accent",label:"Accent",description:"Highlight and decorative color",type:"color",path:"theme.palette.colors.accent.500",defaultValue:"#06b6d4"}]},Wf={id:"chat-colors",title:"Chat Colors",description:"Customize the main colors of the chat interface.",collapsed:!0,fields:[{id:"chat-header-bg",label:"Header Background",type:"token-ref",path:"theme.components.header.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"chat-header-icon-bg",label:"Header Icon Background",type:"token-ref",path:"theme.components.header.iconBackground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-header-icon-fg",label:"Header Icon Color",type:"token-ref",path:"theme.components.header.iconForeground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"chat-header-title-fg",label:"Header Title Color",type:"token-ref",path:"theme.components.header.titleForeground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-header-subtitle-fg",label:"Header Subtitle Color",type:"token-ref",path:"theme.components.header.subtitleForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"chat-header-action-icons-fg",label:"Header Button Icons",type:"token-ref",path:"theme.components.header.actionIconForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"chat-msg-user-bg",label:"User Message Background",type:"token-ref",path:"theme.components.message.user.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-msg-user-text",label:"User Message Text",type:"token-ref",path:"theme.components.message.user.text",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"chat-msg-assistant-bg",label:"Assistant Message Background",type:"token-ref",path:"theme.components.message.assistant.background",defaultValue:"semantic.colors.container",tokenRef:{tokenType:"color"}},{id:"chat-msg-assistant-text",label:"Assistant Message Text",type:"token-ref",path:"theme.components.message.assistant.text",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},Bf={id:"typography",title:"Typography",collapsed:!0,fields:[{id:"typo-font-family",label:"Font Family",type:"select",path:"theme.semantic.typography.fontFamily",defaultValue:"palette.typography.fontFamily.sans",options:[{value:"palette.typography.fontFamily.sans",label:"Sans Serif"},{value:"palette.typography.fontFamily.serif",label:"Serif"},{value:"palette.typography.fontFamily.mono",label:"Monospace"}]},{id:"typo-font-size",label:"Base Font Size",type:"select",path:"theme.semantic.typography.fontSize",defaultValue:"palette.typography.fontSize.base",options:[{value:"palette.typography.fontSize.xs",label:"Extra Small (0.75rem)"},{value:"palette.typography.fontSize.sm",label:"Small (0.875rem)"},{value:"palette.typography.fontSize.base",label:"Base (1rem)"},{value:"palette.typography.fontSize.lg",label:"Large (1.125rem)"},{value:"palette.typography.fontSize.xl",label:"Extra Large (1.25rem)"}]},{id:"typo-font-weight",label:"Font Weight",type:"select",path:"theme.semantic.typography.fontWeight",defaultValue:"palette.typography.fontWeight.normal",options:[{value:"palette.typography.fontWeight.normal",label:"Normal (400)"},{value:"palette.typography.fontWeight.medium",label:"Medium (500)"},{value:"palette.typography.fontWeight.semibold",label:"Semibold (600)"},{value:"palette.typography.fontWeight.bold",label:"Bold (700)"}]},{id:"typo-line-height",label:"Line Height",type:"select",path:"theme.semantic.typography.lineHeight",defaultValue:"palette.typography.lineHeight.normal",options:[{value:"palette.typography.lineHeight.tight",label:"Tight (1.25)"},{value:"palette.typography.lineHeight.normal",label:"Normal (1.5)"},{value:"palette.typography.lineHeight.relaxed",label:"Relaxed (1.625)"}]}]},Hf={id:"launcher-style",title:"Launcher",description:"Control launcher appearance.",collapsed:!0,fields:[{id:"style-launcher-size",label:"Launcher Size",type:"slider",path:"theme.components.launcher.size",defaultValue:"60px",slider:{min:32,max:80,step:2}},{id:"style-launcher-shape",label:"Launcher Shape",type:"select",path:"theme.components.launcher.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Rounded Square"},{value:"palette.radius.lg",label:"Rounded"},{value:"palette.radius.xl",label:"Very Rounded"},{value:"palette.radius.full",label:"Circle"}]},{id:"style-launcher-shadow",label:"Launcher Shadow",type:"select",path:"theme.components.launcher.shadow",defaultValue:"palette.shadows.lg",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},Df={id:"shape",title:"Shape",description:"Control the corner roundness across the widget.",collapsed:!0,fields:[{id:"radius-sm",label:"Small",type:"slider",path:"theme.palette.radius.sm",defaultValue:"0.125rem",slider:{min:0,max:16,step:1}},{id:"radius-md",label:"Medium",type:"slider",path:"theme.palette.radius.md",defaultValue:"0.375rem",slider:{min:0,max:24,step:1}},{id:"radius-lg",label:"Large",type:"slider",path:"theme.palette.radius.lg",defaultValue:"0.5rem",slider:{min:0,max:32,step:1}},{id:"radius-xl",label:"Extra Large",type:"slider",path:"theme.palette.radius.xl",defaultValue:"0.75rem",slider:{min:0,max:48,step:1}},{id:"radius-full",label:"Full",type:"slider",path:"theme.palette.radius.full",defaultValue:"9999px",slider:{min:0,max:100,step:1,isRadiusFull:!0}}],presets:[{id:"radius-default",label:"Default",values:{"theme.palette.radius.sm":"0.125rem","theme.palette.radius.md":"0.375rem","theme.palette.radius.lg":"0.5rem","theme.palette.radius.xl":"0.75rem","theme.palette.radius.full":"9999px"}},{id:"radius-sharp",label:"Sharp",values:{"theme.palette.radius.sm":"1px","theme.palette.radius.md":"2px","theme.palette.radius.lg":"3px","theme.palette.radius.xl":"4px","theme.palette.radius.full":"4px"}},{id:"radius-rounded",label:"Rounded",values:{"theme.palette.radius.sm":"0.5rem","theme.palette.radius.md":"0.75rem","theme.palette.radius.lg":"1rem","theme.palette.radius.xl":"1.5rem","theme.palette.radius.full":"9999px"}}]},Ff={id:"shadows",title:"Shadows",collapsed:!0,fields:[{id:"shadow-sm",label:"Small",type:"text",path:"theme.palette.shadows.sm",defaultValue:"0 1px 2px 0 rgb(0 0 0 / 0.05)"},{id:"shadow-md",label:"Medium",type:"text",path:"theme.palette.shadows.md",defaultValue:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)"},{id:"shadow-lg",label:"Large",type:"text",path:"theme.palette.shadows.lg",defaultValue:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)"},{id:"shadow-xl",label:"Extra Large",type:"text",path:"theme.palette.shadows.xl",defaultValue:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)"}]},Of={id:"widget-style",title:"Widget Surface",description:"Adjust the main panel and message bubble treatment.",collapsed:!0,fields:[{id:"style-panel-radius",label:"Panel Corner Radius",type:"select",path:"theme.components.panel.borderRadius",defaultValue:"palette.radius.xl",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"style-panel-shadow",label:"Panel Shadow",type:"select",path:"theme.components.panel.shadow",defaultValue:"palette.shadows.xl",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]},{id:"style-msg-user-radius",label:"User Message Radius",type:"select",path:"theme.components.message.user.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"style-msg-assistant-radius",label:"Assistant Message Radius",type:"select",path:"theme.components.message.assistant.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},zr=[Pf,Wf,Hf,Bf,Rf,Df,Ff,Of];function iu(){return{id:"brand-palette",title:"Brand Palette",description:"Define your color palette. Edit the base color (500) to auto-generate the full scale.",collapsed:!1,fields:el.map(t=>({id:`palette-${t}`,label:`${t.charAt(0).toUpperCase()+t.slice(1)}`,description:`${t} color palette (edit shade 500, auto-generate scale)`,type:"color-scale",path:`theme.palette.colors.${t}`,colorScale:{colorFamily:t}}))}}var lu={id:"semantic-colors",title:"Semantic Colors",description:"Map intents to palette colors.",collapsed:!0,fields:[{id:"sem-primary",label:"Primary",description:"Main brand/action color",type:"token-ref",path:"theme.semantic.colors.primary",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sem-secondary",label:"Secondary",description:"Secondary actions",type:"token-ref",path:"theme.semantic.colors.secondary",defaultValue:"palette.colors.gray.500",tokenRef:{tokenType:"color"}},{id:"sem-accent",label:"Accent",description:"Accent/highlight color",type:"token-ref",path:"theme.semantic.colors.accent",defaultValue:"palette.colors.primary.600",tokenRef:{tokenType:"color"}},{id:"sem-surface",label:"Surface",description:"Primary surface background",type:"token-ref",path:"theme.semantic.colors.surface",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-background",label:"Background",description:"Page/widget background",type:"token-ref",path:"theme.semantic.colors.background",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-container",label:"Container",description:"Container/card background",type:"token-ref",path:"theme.semantic.colors.container",defaultValue:"palette.colors.gray.100",tokenRef:{tokenType:"color"}},{id:"sem-text",label:"Text",description:"Primary text color",type:"token-ref",path:"theme.semantic.colors.text",defaultValue:"palette.colors.gray.900",tokenRef:{tokenType:"color"}},{id:"sem-text-muted",label:"Text Muted",description:"Secondary/muted text",type:"token-ref",path:"theme.semantic.colors.textMuted",defaultValue:"palette.colors.gray.500",tokenRef:{tokenType:"color"}},{id:"sem-text-inverse",label:"Text Inverse",description:"Text on dark backgrounds",type:"token-ref",path:"theme.semantic.colors.textInverse",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-border",label:"Border",description:"Default border color",type:"token-ref",path:"theme.semantic.colors.border",defaultValue:"palette.colors.gray.200",tokenRef:{tokenType:"color"}},{id:"sem-divider",label:"Divider",description:"Divider/separator color",type:"token-ref",path:"theme.semantic.colors.divider",defaultValue:"palette.colors.gray.200",tokenRef:{tokenType:"color"}},{id:"sem-interactive-default",label:"Interactive Default",type:"token-ref",path:"theme.semantic.colors.interactive.default",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sem-interactive-hover",label:"Interactive Hover",type:"token-ref",path:"theme.semantic.colors.interactive.hover",defaultValue:"palette.colors.primary.600",tokenRef:{tokenType:"color"}},{id:"sem-interactive-focus",label:"Interactive Focus",type:"token-ref",path:"theme.semantic.colors.interactive.focus",defaultValue:"palette.colors.primary.700",tokenRef:{tokenType:"color"}},{id:"sem-interactive-active",label:"Interactive Active",type:"token-ref",path:"theme.semantic.colors.interactive.active",defaultValue:"palette.colors.primary.800",tokenRef:{tokenType:"color"}},{id:"sem-interactive-disabled",label:"Interactive Disabled",type:"token-ref",path:"theme.semantic.colors.interactive.disabled",defaultValue:"palette.colors.gray.300",tokenRef:{tokenType:"color"}},{id:"sem-feedback-success",label:"Success",type:"token-ref",path:"theme.semantic.colors.feedback.success",defaultValue:"palette.colors.success.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-warning",label:"Warning",type:"token-ref",path:"theme.semantic.colors.feedback.warning",defaultValue:"palette.colors.warning.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-error",label:"Error",type:"token-ref",path:"theme.semantic.colors.feedback.error",defaultValue:"palette.colors.error.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-info",label:"Info",type:"token-ref",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}}]},Nf=iu(),_f=lu,Vf=[iu(),lu],$f={id:"comp-panel",title:"Panel",collapsed:!1,fields:[{id:"panel-width",label:"Width",type:"text",path:"theme.components.panel.width",defaultValue:io},{id:"panel-max-width",label:"Max Width",type:"text",path:"theme.components.panel.maxWidth",defaultValue:Ea},{id:"panel-height",label:"Height",type:"text",path:"theme.components.panel.height",defaultValue:"600px"},{id:"panel-max-height",label:"Max Height",type:"text",path:"theme.components.panel.maxHeight",defaultValue:"calc(100vh - 80px)"},{id:"panel-border-radius",label:"Border Radius",type:"select",path:"theme.components.panel.borderRadius",defaultValue:"palette.radius.xl",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"panel-shadow",label:"Shadow",type:"select",path:"theme.components.panel.shadow",defaultValue:"palette.shadows.xl",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},Uf={id:"comp-launcher",title:"Launcher",collapsed:!0,fields:[{id:"launcher-size",label:"Size",type:"slider",path:"theme.components.launcher.size",defaultValue:"60px",slider:{min:32,max:80,step:2}},{id:"launcher-icon-size",label:"Icon Size",type:"slider",path:"theme.components.launcher.iconSize",defaultValue:"28px",slider:{min:16,max:48,step:2}},{id:"launcher-border-radius",label:"Border Radius",type:"select",path:"theme.components.launcher.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"},{value:"palette.radius.full",label:"Full (Circle)"}]},{id:"launcher-shadow",label:"Shadow",type:"select",path:"theme.components.launcher.shadow",defaultValue:"palette.shadows.lg",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},zf={id:"comp-message-shape",title:"Message Shape",collapsed:!0,fields:[{id:"msg-user-radius",label:"User Bubble Radius",type:"select",path:"theme.components.message.user.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"msg-assistant-radius",label:"Assistant Bubble Radius",type:"select",path:"theme.components.message.assistant.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},qf={id:"comp-input-shape",title:"Input Shape",collapsed:!0,fields:[{id:"input-radius",label:"Border Radius",type:"select",path:"theme.components.input.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},jf={id:"comp-button-shape",title:"Button Shape",collapsed:!0,fields:[{id:"btn-primary-radius",label:"Primary Radius",type:"select",path:"theme.components.button.primary.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.full",label:"Full"}]}]},Kf={id:"comp-header-colors",title:"Header Colors",collapsed:!0,fields:[{id:"header-bg",label:"Background",type:"token-ref",path:"theme.components.header.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"header-icon-bg",label:"Icon background",type:"token-ref",path:"theme.components.header.iconBackground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"header-icon-fg",label:"Icon color",type:"token-ref",path:"theme.components.header.iconForeground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"header-title-fg",label:"Title color",type:"token-ref",path:"theme.components.header.titleForeground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"header-subtitle-fg",label:"Subtitle color",type:"token-ref",path:"theme.components.header.subtitleForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"header-action-icons-fg",label:"Clear / close icons",type:"token-ref",path:"theme.components.header.actionIconForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"header-border",label:"Border",type:"token-ref",path:"theme.components.header.border",defaultValue:"semantic.colors.border",tokenRef:{tokenType:"color"}}]},Gf={id:"comp-message-colors",title:"Message Colors",collapsed:!0,fields:[{id:"msg-user-bg",label:"User Bubble Background",type:"token-ref",path:"theme.components.message.user.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"msg-user-text",label:"User Bubble Text",type:"token-ref",path:"theme.components.message.user.text",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"msg-assistant-bg",label:"Assistant Bubble Background",type:"token-ref",path:"theme.components.message.assistant.background",defaultValue:"semantic.colors.container",tokenRef:{tokenType:"color"}},{id:"msg-assistant-text",label:"Assistant Bubble Text",type:"token-ref",path:"theme.components.message.assistant.text",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},Yf={id:"comp-input-colors",title:"Input Colors",collapsed:!0,fields:[{id:"input-bg",label:"Background",type:"token-ref",path:"theme.components.input.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"input-placeholder",label:"Placeholder Color",type:"token-ref",path:"theme.components.input.placeholder",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"input-focus-border",label:"Focus Border",type:"token-ref",path:"theme.components.input.focus.border",defaultValue:"semantic.colors.interactive.focus",tokenRef:{tokenType:"color"}},{id:"input-focus-ring",label:"Focus Ring",type:"token-ref",path:"theme.components.input.focus.ring",defaultValue:"semantic.colors.interactive.focus",tokenRef:{tokenType:"color"}}]},Xf={id:"comp-button-colors",title:"Button Colors",collapsed:!0,fields:[{id:"btn-primary-bg",label:"Primary Background",type:"token-ref",path:"theme.components.button.primary.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"btn-primary-fg",label:"Primary Foreground",type:"token-ref",path:"theme.components.button.primary.foreground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"btn-secondary-bg",label:"Secondary Background",type:"token-ref",path:"theme.components.button.secondary.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"btn-secondary-fg",label:"Secondary Foreground",type:"token-ref",path:"theme.components.button.secondary.foreground",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}},{id:"btn-ghost-bg",label:"Ghost Background",type:"color",path:"theme.components.button.ghost.background",defaultValue:"transparent"},{id:"btn-ghost-fg",label:"Ghost Foreground",type:"token-ref",path:"theme.components.button.ghost.foreground",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},Qf={id:"scroll-to-bottom-style",title:"Scroll To Bottom",description:"Style the floating jump-to-latest affordance.",collapsed:!0,fields:[{id:"scroll-bottom-bg",label:"Background",type:"token-ref",path:"theme.components.scrollToBottom.background",defaultValue:"components.button.primary.background",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-fg",label:"Foreground",type:"token-ref",path:"theme.components.scrollToBottom.foreground",defaultValue:"components.button.primary.foreground",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-border",label:"Border",type:"token-ref",path:"theme.components.scrollToBottom.border",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-size",label:"Size",type:"text",path:"theme.components.scrollToBottom.size",defaultValue:"40px"},{id:"scroll-bottom-radius",label:"Border Radius",type:"select",path:"theme.components.scrollToBottom.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"},{value:"palette.radius.full",label:"Full"}]},{id:"scroll-bottom-shadow",label:"Shadow",type:"select",path:"theme.components.scrollToBottom.shadow",defaultValue:"palette.shadows.sm",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]},{id:"scroll-bottom-padding",label:"Padding",type:"text",path:"theme.components.scrollToBottom.padding",defaultValue:"0.5rem 0.875rem"},{id:"scroll-bottom-gap",label:"Gap",type:"text",path:"theme.components.scrollToBottom.gap",defaultValue:"0.5rem"},{id:"scroll-bottom-font-size",label:"Font Size",type:"text",path:"theme.components.scrollToBottom.fontSize",defaultValue:"0.875rem"},{id:"scroll-bottom-icon-size",label:"Icon Size",type:"text",path:"theme.components.scrollToBottom.iconSize",defaultValue:"14px"}]},cu=[$f,Uf,zf,qf,jf],du=[Kf,Gf,Yf,Xf,Qf],pu=[...cu,...du],nl=1024*1024,Jf=["What can you help me with?","Tell me about your features","How does this work?"],Ms={images:["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],"images-pdf":["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf"],"images-text-pdf":["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf","text/plain","text/markdown","text/csv","application/json"],all:["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"]};function Zf(e){return Number(e)*nl}function eg(e){let t=Number(e);return Number.isFinite(t)?t>1024?String(Math.round(t/nl)):String(t):"10"}function tg(e){var t;return(t=Ms[String(e)])!=null?t:Ms.images}function ng(e){let t=Array.isArray(e)?e:Ms.images,n=[...new Set(t)].sort();for(let[o,r]of Object.entries(Ms)){let s=[...r].sort();if(n.length===s.length&&n.every((a,i)=>a===s[i]))return o}return n.some(o=>o.startsWith("application/vnd")||o==="application/msword")?"all":n.some(o=>o==="text/plain"||o==="text/markdown"||o==="text/csv")?"images-text-pdf":n.includes("application/pdf")?"images-pdf":"images"}var og={id:"copy",title:"Content & Copy",collapsed:!1,fields:[{id:"copy-show-welcome-card",label:"Show Welcome Card",type:"toggle",path:"copy.showWelcomeCard",defaultValue:!0},{id:"copy-welcome-title",label:"Welcome Title",type:"text",path:"copy.welcomeTitle",defaultValue:"Hello \u{1F44B}"},{id:"copy-welcome-subtitle",label:"Welcome Subtitle",type:"text",path:"copy.welcomeSubtitle",defaultValue:"Ask anything about your account or products."},{id:"copy-placeholder",label:"Input Placeholder",type:"text",path:"copy.inputPlaceholder",defaultValue:"Type your message\u2026"},{id:"copy-send-label",label:"Send Button Label",type:"text",path:"copy.sendButtonLabel",defaultValue:"Send"}]},rg={id:"suggestions",title:"Suggestion Chips",description:"Configure chip content and styling.",collapsed:!0,fields:[{id:"suggestions-list",label:"Suggestions",description:"Add, edit, and remove chips directly.",type:"chip-list",path:"suggestionChips",defaultValue:Jf}]},sg={id:"general-layout",title:"Layout Basics",collapsed:!0,fields:[{id:"layout-show-header",label:"Show Header",type:"toggle",path:"layout.showHeader",defaultValue:!0},{id:"layout-show-footer",label:"Show Footer",type:"toggle",path:"layout.showFooter",defaultValue:!0},{id:"layout-content-max-width",label:"Content Max Width",description:"Max width for messages + composer",type:"text",path:"layout.contentMaxWidth",defaultValue:""}]},ag={id:"header-layout",title:"Header",collapsed:!0,fields:[{id:"layout-header",label:"Header Layout",type:"select",path:"layout.header.layout",defaultValue:"default",options:[{value:"default",label:"Default"},{value:"minimal",label:"Minimal"}]},{id:"layout-show-icon",label:"Show Header Icon",type:"toggle",path:"layout.header.showIcon",defaultValue:!0},{id:"layout-show-title",label:"Show Header Title",type:"toggle",path:"layout.header.showTitle",defaultValue:!0},{id:"layout-show-subtitle",label:"Show Header Subtitle",type:"toggle",path:"layout.header.showSubtitle",defaultValue:!0},{id:"layout-show-close",label:"Show Close Button",type:"toggle",path:"layout.header.showCloseButton",defaultValue:!0},{id:"layout-show-clear",label:"Show Clear Chat",type:"toggle",path:"layout.header.showClearChat",defaultValue:!0}]},ig={id:"messages-layout",title:"Messages",collapsed:!0,fields:[{id:"layout-messages",label:"Messages Layout",type:"select",path:"layout.messages.layout",defaultValue:"bubble",options:[{value:"bubble",label:"Bubble"},{value:"flat",label:"Flat"},{value:"minimal",label:"Minimal"}]},{id:"layout-group",label:"Group Consecutive",type:"toggle",path:"layout.messages.groupConsecutive",defaultValue:!1},{id:"layout-avatar-show",label:"Show Avatars",type:"toggle",path:"layout.messages.avatar.show",defaultValue:!1},{id:"layout-avatar-pos",label:"Avatar Position",type:"select",path:"layout.messages.avatar.position",defaultValue:"left",options:[{value:"left",label:"Left"},{value:"right",label:"Right"}]},{id:"layout-avatar-user",label:"User Avatar URL",type:"text",path:"layout.messages.avatar.userAvatar",defaultValue:""},{id:"layout-avatar-assistant",label:"Assistant Avatar URL",type:"text",path:"layout.messages.avatar.assistantAvatar",defaultValue:""},{id:"layout-timestamp-show",label:"Show Timestamps",type:"toggle",path:"layout.messages.timestamp.show",defaultValue:!1},{id:"layout-timestamp-pos",label:"Timestamp Position",type:"select",path:"layout.messages.timestamp.position",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"below",label:"Below"}]}]},lg={id:"message-actions",title:"Message Actions",collapsed:!0,fields:[{id:"msg-actions-enabled",label:"Enabled",type:"toggle",path:"messageActions.enabled",defaultValue:!0},{id:"msg-actions-copy",label:"Show Copy",type:"toggle",path:"messageActions.showCopy",defaultValue:!0},{id:"msg-actions-upvote",label:"Show Upvote",type:"toggle",path:"messageActions.showUpvote",defaultValue:!0},{id:"msg-actions-downvote",label:"Show Downvote",type:"toggle",path:"messageActions.showDownvote",defaultValue:!0},{id:"msg-actions-visibility",label:"Visibility",type:"select",path:"messageActions.visibility",defaultValue:"hover",options:[{value:"hover",label:"On Hover"},{value:"always",label:"Always Visible"}]},{id:"msg-actions-align",label:"Alignment",type:"select",path:"messageActions.align",defaultValue:"right",options:[{value:"left",label:"Left"},{value:"right",label:"Right"}]},{id:"msg-actions-layout",label:"Layout",type:"select",path:"messageActions.layout",defaultValue:"pill-inside",options:[{value:"pill-inside",label:"Pill"},{value:"row-inside",label:"Row"}]}]},cg={id:"launcher-basics",title:"Launcher",collapsed:!0,fields:[{id:"launch-enabled",label:"Enabled",type:"toggle",path:"launcher.enabled",defaultValue:!0},{id:"launch-mount-mode",label:"Mount Mode",type:"select",path:"launcher.mountMode",defaultValue:"floating",options:[{value:"floating",label:"Floating"},{value:"docked",label:"Docked"}]},{id:"launch-position",label:"Position",type:"select",path:"launcher.position",defaultValue:"bottom-right",options:[{value:"bottom-right",label:"Bottom Right"},{value:"bottom-left",label:"Bottom Left"},{value:"top-right",label:"Top Right"},{value:"top-left",label:"Top Left"}]},{id:"launch-width",label:"Width",type:"text",path:"launcher.width",defaultValue:io},{id:"launch-auto-expand",label:"Auto Expand",type:"toggle",path:"launcher.autoExpand",defaultValue:!1},{id:"launch-title",label:"Title",type:"text",path:"launcher.title",defaultValue:"Chat Assistant"},{id:"launch-subtitle",label:"Subtitle",type:"text",path:"launcher.subtitle",defaultValue:"Here to help you get answers fast"}]},dg={id:"launcher-advanced",title:"Launcher Advanced",collapsed:!0,fields:[{id:"launch-dock-side",label:"Dock Side",type:"select",path:"launcher.dock.side",defaultValue:"right",options:[{value:"right",label:"Right"},{value:"left",label:"Left"}]},{id:"launch-dock-width",label:"Dock Width",type:"text",path:"launcher.dock.width",defaultValue:"420px"},{id:"launch-dock-animate",label:"Dock Animate",type:"toggle",path:"launcher.dock.animate",defaultValue:!0},{id:"launch-dock-reveal",label:"Dock Reveal",type:"select",path:"launcher.dock.reveal",defaultValue:"resize",options:[{value:"resize",label:"Resize"},{value:"overlay",label:"Overlay"},{value:"push",label:"Push"},{value:"emerge",label:"Emerge"}]},{id:"launch-text-hidden",label:"Hide Text",type:"toggle",path:"launcher.textHidden",defaultValue:!1},{id:"launch-icon-text",label:"Agent Icon Text",type:"text",path:"launcher.agentIconText",defaultValue:"\u{1F4AC}"},{id:"launch-icon-name",label:"Agent Icon Name (Lucide)",type:"text",path:"launcher.agentIconName",defaultValue:"bot"},{id:"launch-icon-hidden",label:"Hide Agent Icon",type:"toggle",path:"launcher.agentIconHidden",defaultValue:!1},{id:"launch-icon-size",label:"Agent Icon Size",type:"slider",path:"launcher.agentIconSize",defaultValue:"40px",slider:{min:16,max:72,step:2}},{id:"launch-icon-url",label:"Icon Image URL",description:"Custom image URL (overrides emoji/lucide)",type:"text",path:"launcher.iconUrl",defaultValue:""},{id:"launch-header-icon-name",label:"Header Icon Name (Lucide)",type:"text",path:"launcher.headerIconName",defaultValue:"bot"},{id:"launch-header-icon-size",label:"Header Icon Size",type:"slider",path:"launcher.headerIconSize",defaultValue:"48px",slider:{min:24,max:80,step:2}},{id:"launch-header-icon-hidden",label:"Hide Header Icon",type:"toggle",path:"launcher.headerIconHidden",defaultValue:!1},{id:"launch-full-height",label:"Full Height",type:"toggle",path:"launcher.fullHeight",defaultValue:!1},{id:"launch-sidebar",label:"Sidebar Mode",type:"toggle",path:"launcher.sidebarMode",defaultValue:!1},{id:"launch-sidebar-width",label:"Sidebar Width",type:"text",path:"launcher.sidebarWidth",defaultValue:"420px"},{id:"launch-mobile-fullscreen",label:"Mobile Fullscreen",description:"Fullscreen on mobile devices",type:"toggle",path:"launcher.mobileFullscreen",defaultValue:!0},{id:"launch-mobile-breakpoint",label:"Mobile Breakpoint (px)",type:"text",path:"launcher.mobileBreakpoint",defaultValue:640,formatValue:e=>String(e!=null?e:640),parseValue:e=>Number(e)},{id:"launch-height-offset",label:"Height Offset (px)",type:"text",path:"launcher.heightOffset",defaultValue:0,formatValue:e=>String(e!=null?e:0),parseValue:e=>Number(e)},{id:"launch-collapsed-max-width",label:"Collapsed Max Width",description:"Max width of launcher pill when closed",type:"text",path:"launcher.collapsedMaxWidth",defaultValue:""},{id:"launch-cta-text",label:"CTA Icon Text",type:"text",path:"launcher.callToActionIconText",defaultValue:"\u2197"},{id:"launch-cta-name",label:"CTA Icon Name",type:"text",path:"launcher.callToActionIconName",defaultValue:""},{id:"launch-cta-hidden",label:"Hide CTA Icon",type:"toggle",path:"launcher.callToActionIconHidden",defaultValue:!1},{id:"launch-cta-size",label:"CTA Icon Size",type:"slider",path:"launcher.callToActionIconSize",defaultValue:"32px",slider:{min:16,max:64,step:2}},{id:"launch-cta-padding",label:"CTA Icon Padding",type:"slider",path:"launcher.callToActionIconPadding",defaultValue:"5px",slider:{min:0,max:24,step:1}},{id:"launch-cta-bg",label:"CTA Icon Background",type:"color",path:"launcher.callToActionIconBackgroundColor",defaultValue:""}]},pg={id:"send-button",title:"Send Button",collapsed:!0,fields:[{id:"send-use-icon",label:"Use Icon",type:"toggle",path:"sendButton.useIcon",defaultValue:!1},{id:"send-icon-text",label:"Icon Text",type:"text",path:"sendButton.iconText",defaultValue:"\u2191"},{id:"send-icon-name",label:"Icon Name (Lucide)",type:"text",path:"sendButton.iconName",defaultValue:""},{id:"send-size",label:"Size",type:"slider",path:"sendButton.size",defaultValue:"40px",slider:{min:24,max:64,step:2}},{id:"send-border-width",label:"Border Width",type:"slider",path:"sendButton.borderWidth",defaultValue:"0px",slider:{min:0,max:10,step:1}},{id:"send-padding-x",label:"Padding X",type:"slider",path:"sendButton.paddingX",defaultValue:"10px",slider:{min:0,max:32,step:1}},{id:"send-padding-y",label:"Padding Y",type:"slider",path:"sendButton.paddingY",defaultValue:"6px",slider:{min:0,max:32,step:1}},{id:"send-show-tooltip",label:"Show Tooltip",type:"toggle",path:"sendButton.showTooltip",defaultValue:!1},{id:"send-tooltip-text",label:"Tooltip Text",type:"text",path:"sendButton.tooltipText",defaultValue:"Send message"}]},ug={id:"close-button",title:"Close Button",collapsed:!0,fields:[{id:"close-size",label:"Size",type:"slider",path:"launcher.closeButtonSize",defaultValue:"32px",slider:{min:16,max:64,step:1}},{id:"close-placement",label:"Placement",type:"select",path:"launcher.closeButtonPlacement",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"top-right",label:"Top Right"}]},{id:"close-border-width",label:"Border Width",type:"slider",path:"launcher.closeButtonBorderWidth",defaultValue:"0px",slider:{min:0,max:8,step:1}},{id:"close-border-radius",label:"Border Radius",type:"slider",path:"launcher.closeButtonBorderRadius",defaultValue:"50%",slider:{min:0,max:100,step:1,isRadiusFull:!0}},{id:"close-icon-name",label:"Icon Name",type:"text",path:"launcher.closeButtonIconName",defaultValue:"x"},{id:"close-icon-text",label:"Icon Text",type:"text",path:"launcher.closeButtonIconText",defaultValue:"\xD7"},{id:"close-show-tooltip",label:"Show Tooltip",type:"toggle",path:"launcher.closeButtonShowTooltip",defaultValue:!0},{id:"close-tooltip-text",label:"Tooltip Text",type:"text",path:"launcher.closeButtonTooltipText",defaultValue:"Close chat"}]},mg={id:"clear-chat",title:"Clear Chat Button",collapsed:!0,fields:[{id:"clear-enabled",label:"Enabled",type:"toggle",path:"launcher.clearChat.enabled",defaultValue:!0},{id:"clear-placement",label:"Placement",type:"select",path:"launcher.clearChat.placement",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"top-right",label:"Top Right"}]},{id:"clear-icon-name",label:"Icon Name",type:"text",path:"launcher.clearChat.iconName",defaultValue:"refresh-cw"},{id:"clear-size",label:"Size",type:"slider",path:"launcher.clearChat.size",defaultValue:"32px",slider:{min:16,max:64,step:1}},{id:"clear-show-tooltip",label:"Show Tooltip",type:"toggle",path:"launcher.clearChat.showTooltip",defaultValue:!0},{id:"clear-tooltip-text",label:"Tooltip Text",type:"text",path:"launcher.clearChat.tooltipText",defaultValue:"Clear chat"}]},fg={id:"status-indicator",title:"Status Indicator",collapsed:!0,fields:[{id:"status-visible",label:"Visible",type:"toggle",path:"statusIndicator.visible",defaultValue:!0},{id:"status-align",label:"Alignment",type:"select",path:"statusIndicator.align",defaultValue:"right",options:[{value:"left",label:"Left"},{value:"center",label:"Center"},{value:"right",label:"Right"}]},{id:"status-idle-text",label:"Idle Text",type:"text",path:"statusIndicator.idleText",defaultValue:"Online"},{id:"status-connecting-text",label:"Connecting Text",type:"text",path:"statusIndicator.connectingText",defaultValue:"Connecting\u2026"},{id:"status-connected-text",label:"Connected Text",type:"text",path:"statusIndicator.connectedText",defaultValue:"Streaming\u2026"},{id:"status-error-text",label:"Error Text",type:"text",path:"statusIndicator.errorText",defaultValue:"Offline"}]},gg={id:"features",title:"Features",collapsed:!0,fields:[{id:"feat-voice",label:"Voice Recognition",description:"Enable voice input",type:"toggle",path:"voiceRecognition.enabled",defaultValue:!1},{id:"feat-auto-focus",label:"Auto Focus Input",description:"Focus input after panel opens",type:"toggle",path:"autoFocusInput",defaultValue:!1},{id:"feat-scroll-bottom-enabled",label:"Scroll To Bottom",description:"Show a jump-to-latest affordance when the user scrolls away from new content",type:"toggle",path:"features.scrollToBottom.enabled",defaultValue:!0},{id:"feat-scroll-bottom-icon",label:"Scroll To Bottom Icon",type:"text",path:"features.scrollToBottom.iconName",defaultValue:"arrow-down"},{id:"feat-scroll-bottom-label",label:"Scroll To Bottom Label",description:"Leave empty for icon-only mode",type:"text",path:"features.scrollToBottom.label",defaultValue:""}]},hg={id:"stream-animation",title:"Stream Animation",description:"Control how assistant text appears while streaming.",collapsed:!0,fields:[{id:"stream-anim-type",label:"Animation",description:"Reveal effect applied to each assistant reply as it streams.",type:"select",path:"features.streamAnimation.type",defaultValue:"none",options:[{value:"none",label:"None"},{value:"typewriter",label:"Typewriter"},{value:"word-fade",label:"Word fade"},{value:"letter-rise",label:"Letter rise"},{value:"glyph-cycle",label:"Glyph cycle"},{value:"wipe",label:"Wipe"},{value:"pop-bubble",label:"Pop bubble"}]},{id:"stream-anim-placeholder",label:"Pre-first-token Placeholder",description:"What to show before the first token arrives.",type:"select",path:"features.streamAnimation.placeholder",defaultValue:"none",options:[{value:"none",label:"Typing indicator (default)"},{value:"skeleton",label:"Skeleton shimmer"}]},{id:"stream-anim-buffer",label:"Content Buffering",description:"Trim in-progress units so only complete words/lines reveal.",type:"select",path:"features.streamAnimation.buffer",defaultValue:"none",options:[{value:"none",label:"None \u2014 stream every character"},{value:"word",label:"Word \u2014 hold until whitespace"},{value:"line",label:"Line \u2014 hold until newline"}]},{id:"stream-anim-speed",label:"Per-unit Duration (ms)",description:"Animation length for each character or word.",type:"select",path:"features.streamAnimation.speed",defaultValue:120,options:[{value:"40",label:"40ms \u2014 snappy"},{value:"80",label:"80ms"},{value:"120",label:"120ms (default)"},{value:"200",label:"200ms"},{value:"320",label:"320ms"},{value:"480",label:"480ms \u2014 slow"}],formatValue:e=>String(e!=null?e:120),parseValue:e=>Number(e)},{id:"stream-anim-duration",label:"Container Duration (ms)",description:"Length of container-level effects (pop-bubble, custom plugins).",type:"select",path:"features.streamAnimation.duration",defaultValue:1800,options:[{value:"600",label:"600ms"},{value:"1200",label:"1200ms"},{value:"1800",label:"1800ms (default)"},{value:"2400",label:"2400ms"},{value:"3600",label:"3600ms \u2014 slow"}],formatValue:e=>String(e!=null?e:1800),parseValue:e=>Number(e)}]},bg={id:"attachments-config",title:"Attachments",collapsed:!0,fields:[{id:"attach-enabled",label:"Enabled",type:"toggle",path:"attachments.enabled",defaultValue:!1},{id:"attach-max-files",label:"Max Files",type:"select",path:"attachments.maxFiles",defaultValue:4,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"4",label:"4"},{value:"6",label:"6"},{value:"8",label:"8"},{value:"10",label:"10"}],formatValue:e=>String(e!=null?e:4),parseValue:e=>Number(e)},{id:"attach-max-size",label:"Max File Size (MB)",type:"select",path:"attachments.maxFileSize",defaultValue:10*nl,options:[{value:"1",label:"1 MB"},{value:"5",label:"5 MB"},{value:"10",label:"10 MB"},{value:"25",label:"25 MB"},{value:"50",label:"50 MB"}],formatValue:eg,parseValue:Zf},{id:"attach-types",label:"Allowed File Types",type:"select",path:"attachments.allowedTypes",defaultValue:Ms.images,options:[{value:"images",label:"Images only"},{value:"images-pdf",label:"Images + PDF"},{value:"images-text-pdf",label:"Images + text + PDF"},{value:"all",label:"All supported types"}],formatValue:ng,parseValue:tg}]},yg={id:"artifacts-config",title:"Artifacts",collapsed:!0,fields:[{id:"art-enabled",label:"Enabled",description:"Show artifact sidebar for documents and components",type:"toggle",path:"features.artifacts.enabled",defaultValue:!1},{id:"art-appearance",label:"Pane Appearance",type:"select",path:"features.artifacts.layout.paneAppearance",defaultValue:"panel",options:[{value:"panel",label:"Panel (bordered)"},{value:"seamless",label:"Seamless"}]}]},vg={id:"artifacts-customization",title:"Artifact Customization",collapsed:!0,fields:[{id:"art-toolbar",label:"Toolbar Preset",type:"select",path:"features.artifacts.layout.toolbarPreset",defaultValue:"default",options:[{value:"default",label:"Default"},{value:"document",label:"Document"}]},{id:"art-pane-width",label:"Pane Width",description:"CSS width (e.g. 40%, 28rem)",type:"text",path:"features.artifacts.layout.paneWidth",defaultValue:"40%"},{id:"art-pane-max-width",label:"Pane Max Width",type:"text",path:"features.artifacts.layout.paneMaxWidth",defaultValue:"28rem"},{id:"art-split-gap",label:"Split Gap",type:"text",path:"features.artifacts.layout.splitGap",defaultValue:"0.5rem"},{id:"art-pane-bg",label:"Pane Background",type:"color",path:"features.artifacts.layout.paneBackground",defaultValue:""},{id:"art-unified",label:"Unified Split Chrome",description:"Wrap chat and artifact in a single container",type:"toggle",path:"features.artifacts.layout.unifiedSplitChrome",defaultValue:!1},{id:"art-resizable",label:"Resizable",description:"Allow dragging the pane divider",type:"toggle",path:"features.artifacts.layout.resizable",defaultValue:!1},{id:"art-expand-panel",label:"Expand Panel When Open",description:"Widen the launcher panel to fit artifacts",type:"toggle",path:"features.artifacts.layout.expandLauncherPanelWhenOpen",defaultValue:!0}]},xg={id:"api-integration",title:"API & Integration",description:"Runtime and integration options.",collapsed:!0,fields:[{id:"dev-api-url",label:"API URL",type:"text",path:"apiUrl",defaultValue:""},{id:"dev-flow",label:"Flow ID",type:"text",path:"flowId",defaultValue:""},{id:"dev-parser",label:"Stream Parser",type:"select",path:"parserType",defaultValue:"plain",options:[{value:"plain",label:"Plain Text"},{value:"json",label:"JSON"},{value:"regex-json",label:"Regex JSON"},{value:"xml",label:"XML"}]}]},wg={id:"debug-inspection",title:"Debug & Inspection",collapsed:!0,fields:[{id:"dev-reasoning",label:"Show Reasoning",description:"Display AI reasoning steps",type:"toggle",path:"features.showReasoning",defaultValue:!1},{id:"dev-tool-calls",label:"Show Tool Calls",description:"Display tool call details",type:"toggle",path:"features.showToolCalls",defaultValue:!1},{id:"dev-tool-collapsed-mode",label:"Tool Call Summary",description:"Choose what collapsed tool rows show by default",type:"select",path:"features.toolCallDisplay.collapsedMode",defaultValue:"tool-call",options:[{value:"tool-call",label:"Tool Call"},{value:"tool-name",label:"Tool Name"},{value:"tool-preview",label:"Tool Preview"}]},{id:"dev-tool-active-preview",label:"Tool Preview While Active",description:"Show a lightweight preview in collapsed active tool rows",type:"toggle",path:"features.toolCallDisplay.activePreview",defaultValue:!1},{id:"dev-tool-preview-lines",label:"Tool Preview Lines",type:"select",path:"features.toolCallDisplay.previewMaxLines",defaultValue:3,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"3",label:"3"},{value:"4",label:"4"},{value:"5",label:"5"}],formatValue:e=>String(e!=null?e:3),parseValue:e=>Number(e)},{id:"dev-tool-active-min-height",label:"Tool Active Min Height",description:"CSS min-height for collapsed active tool rows (e.g. 5rem)",type:"text",path:"features.toolCallDisplay.activeMinHeight",defaultValue:""},{id:"dev-tool-expandable",label:"Tool Calls Expandable",description:"Allow expanding tool call rows to see full details",type:"toggle",path:"features.toolCallDisplay.expandable",defaultValue:!0},{id:"dev-tool-grouped",label:"Group Sequential Tool Calls",description:"Render consecutive tool rows inside a grouped container",type:"toggle",path:"features.toolCallDisplay.grouped",defaultValue:!1},{id:"dev-reasoning-expandable",label:"Reasoning Expandable",description:"Allow expanding reasoning rows to see full details",type:"toggle",path:"features.reasoningDisplay.expandable",defaultValue:!0},{id:"dev-reasoning-active-preview",label:"Reasoning Preview While Active",description:"Show a lightweight preview in collapsed active reasoning rows",type:"toggle",path:"features.reasoningDisplay.activePreview",defaultValue:!1},{id:"dev-reasoning-preview-lines",label:"Reasoning Preview Lines",type:"select",path:"features.reasoningDisplay.previewMaxLines",defaultValue:3,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"3",label:"3"},{value:"4",label:"4"},{value:"5",label:"5"}],formatValue:e=>String(e!=null?e:3),parseValue:e=>Number(e)},{id:"dev-reasoning-active-min-height",label:"Reasoning Active Min Height",description:"CSS min-height for collapsed active reasoning rows (e.g. 5rem)",type:"text",path:"features.reasoningDisplay.activeMinHeight",defaultValue:""},{id:"dev-debug",label:"Debug Mode",description:"Show debug information",type:"toggle",path:"debug",defaultValue:!1}]},Cg={id:"markdown",title:"Markdown Options",collapsed:!0,fields:[{id:"md-gfm",label:"GitHub Flavored Markdown",type:"toggle",path:"markdown.options.gfm",defaultValue:!0},{id:"md-breaks",label:"Line Breaks",type:"toggle",path:"markdown.options.breaks",defaultValue:!0},{id:"md-header-ids",label:"Header IDs",type:"toggle",path:"markdown.options.headerIds",defaultValue:!1},{id:"md-pedantic",label:"Pedantic Mode",type:"toggle",path:"markdown.options.pedantic",defaultValue:!1},{id:"md-silent",label:"Silent",type:"toggle",path:"markdown.options.silent",defaultValue:!1},{id:"md-disable-styles",label:"Disable Default Styles",type:"toggle",path:"markdown.disableDefaultStyles",defaultValue:!1}]},Va=[{label:"Content",sections:[og,rg]},{label:"Layout",sections:[sg,ag,ig,lg]},{label:"Widget",sections:[cg,dg,pg,ug,mg,fg]},{label:"Features",sections:[gg,hg,bg,yg,vg]},{label:"Developer",collapsedByDefault:!0,sections:[xg,wg,Cg]}],uu=Va.flatMap(e=>e.sections),mu={id:"theme-mode-v2",title:"Theme",description:"Choose how the interface adapts across light and dark mode.",collapsed:!1,fields:[{id:"color-mode",label:"Color Mode",type:"select",path:"colorScheme",defaultValue:"auto",options:[{value:"auto",label:"Auto"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}]}]},fu={id:"brand-palette-v2",title:"Brand Palette",description:"Set your brand, accent, and neutral colors. These are used to generate the interface theme.",collapsed:!1,fields:[{id:"bp-primary",label:"Primary",description:"Main brand color",type:"color",path:"theme.palette.colors.primary.500",defaultValue:"#171717"},{id:"bp-secondary",label:"Secondary",description:"Supporting brand color",type:"color",path:"theme.palette.colors.secondary.500",defaultValue:"#8b5cf6"},{id:"bp-accent",label:"Accent",description:"Highlight and decorative color",type:"color",path:"theme.palette.colors.accent.500",defaultValue:"#06b6d4"},{id:"bp-neutral",label:"Neutral",description:"Backgrounds, text, and borders",type:"color",path:"theme.palette.colors.gray.500",defaultValue:"#6b7280"}]},gu={id:"status-palette",title:"Status Palette",description:"Colors for system feedback states.",collapsed:!0,fields:[{id:"sp-success",label:"Success",type:"color",path:"theme.palette.colors.success.500",defaultValue:"#22c55e"},{id:"sp-warning",label:"Warning",type:"color",path:"theme.palette.colors.warning.500",defaultValue:"#eab308"},{id:"sp-error",label:"Error",type:"color",path:"theme.palette.colors.error.500",defaultValue:"#ef4444"},{id:"sp-notice",label:"Notice",description:"Info and notice states",type:"color",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500"}]},hu={id:"interface-roles",title:"Interface Roles",description:"Control where brand and neutral colors appear across the interface.",collapsed:!1,fields:[{id:"role-surfaces",label:"Background Surfaces",type:"role-assignment",path:"theme.semantic.colors.background",roleAssignment:Ra},{id:"role-header",label:"Header",type:"role-assignment",path:"theme.components.header.background",roleAssignment:Pa},{id:"role-user-messages",label:"User Messages",type:"role-assignment",path:"theme.components.message.user.background",roleAssignment:Wa},{id:"role-assistant-messages",label:"Assistant Messages",type:"role-assignment",path:"theme.components.message.assistant.background",roleAssignment:Ba},{id:"role-primary-actions",label:"Primary Actions",type:"role-assignment",path:"theme.components.button.primary.background",roleAssignment:Ha},{id:"role-scroll-to-bottom",label:"Scroll To Bottom",type:"role-assignment",path:"theme.components.scrollToBottom.background",roleAssignment:Da},{id:"role-input",label:"Input Field",type:"role-assignment",path:"theme.components.input.background",roleAssignment:Fa},{id:"role-links-focus",label:"Links & Focus",type:"role-assignment",path:"theme.semantic.colors.accent",roleAssignment:Oa},{id:"role-borders",label:"Borders & Dividers",type:"role-assignment",path:"theme.semantic.colors.border",roleAssignment:Na}]},bu={id:"status-colors",title:"Status Colors",description:"Used for system states like success, warning, notice, and error.",collapsed:!0,fields:[{id:"sc-notice",label:"Notice",type:"token-ref",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sc-success",label:"Success",type:"token-ref",path:"theme.semantic.colors.feedback.success",defaultValue:"palette.colors.success.500",tokenRef:{tokenType:"color"}},{id:"sc-warning",label:"Warning",type:"token-ref",path:"theme.semantic.colors.feedback.warning",defaultValue:"palette.colors.warning.500",tokenRef:{tokenType:"color"}},{id:"sc-error",label:"Error",type:"token-ref",path:"theme.semantic.colors.feedback.error",defaultValue:"palette.colors.error.500",tokenRef:{tokenType:"color"}}]},yu={id:"advanced-tokens",title:"Advanced Tokens",description:"Override individual semantic and component values when you need precise control.",collapsed:!0,fields:[]},Sg=[mu,fu,gu,hu,bu,yu],ol=[{id:"style",label:"Style",sections:zr},{id:"design-system",label:"Design System",sections:pu},{id:"configure",label:"Configure",sections:uu}];function vu(e,t){return e.startsWith("theme.")?e.replace(/^theme\./,`${t}.`):e}function Ag(e,t,n){return{...e,id:`${n}-${e.id}`,path:vu(e.path,t)}}function Tg(e,t){let n=e.find(o=>o.id===t);if(!n)throw new Error(`Section "${t}" not found in definitions`);return n}function kg(e,t,n,o=e.collapsed){var a;let r=n==="light"?"Light":"Dark",s=n==="light"?"Applies when the widget is in light mode.":"Applies when the widget is in dark mode.";return{...e,id:`${n}-${e.id}`,title:`${r} ${e.title}`,description:e.description?`${s} ${e.description}`:s,collapsed:o,fields:e.fields.map(i=>Ag(i,t,n)),presets:(a=e.presets)==null?void 0:a.map(i=>({...i,id:`${n}-${i.id}`,values:Object.fromEntries(Object.entries(i.values).map(([d,l])=>[vu(d,t),l]))}))}}var xu=[{id:"default-light",name:"Default Light",description:"Clean monochrome light theme",theme:{components:{artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}}},preview:{primary:"#171717",surface:"#ffffff",accent:"#0f0f0f"},tags:["light"]},{id:"default-dark",name:"Default Dark",description:"Monochrome dark theme",theme:{palette:{colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},semantic:{colors:{primary:"palette.colors.primary.400",secondary:"palette.colors.gray.400",accent:"palette.colors.primary.500",surface:"palette.colors.gray.800",background:"palette.colors.gray.900",container:"palette.colors.gray.800",text:"palette.colors.gray.100",textMuted:"palette.colors.gray.400",textInverse:"palette.colors.gray.900",border:"palette.colors.gray.700",divider:"palette.colors.gray.700",interactive:{default:"palette.colors.primary.400",hover:"palette.colors.primary.300",focus:"palette.colors.primary.500",active:"palette.colors.primary.600",disabled:"palette.colors.gray.600"},feedback:{success:"palette.colors.success.400",warning:"palette.colors.warning.400",error:"palette.colors.error.400",info:"palette.colors.primary.400"}}}},preview:{primary:"#171717",surface:"#1f2937",accent:"#0f0f0f"},tags:["dark"]},{id:"high-contrast",name:"High Contrast",description:"Maximum contrast for accessibility",theme:{semantic:{colors:{primary:"palette.colors.primary.700",secondary:"palette.colors.gray.700",accent:"palette.colors.primary.800",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.200",text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.400",divider:"palette.colors.gray.400",interactive:{default:"palette.colors.primary.700",hover:"palette.colors.primary.800",focus:"palette.colors.primary.900",active:"palette.colors.primary.950",disabled:"palette.colors.gray.400"},feedback:{success:"palette.colors.success.700",warning:"palette.colors.warning.700",error:"palette.colors.error.700",info:"palette.colors.primary.700"}}}},preview:{primary:"#0a0a0a",surface:"#f9fafb",accent:"#050505"},tags:["light","high-contrast","accessibility"]}],Ls=[...xu];function rl(e){return Ls.find(t=>t.id===e)}import{Marked as Eg}from"marked";var Mg=e=>{if(e)return e},sl=e=>{var r,s;let t=e==null?void 0:e.markedOptions,n=new Eg({gfm:(r=t==null?void 0:t.gfm)!=null?r:!0,breaks:(s=t==null?void 0:t.breaks)!=null?s:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),o=Mg(e==null?void 0:e.renderer);return o&&n.use({renderer:o}),a=>n.parse(a)},$a=e=>e?sl({markedOptions:e.options,renderer:e.renderer}):sl(),ew=sl();var Is=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");import Lg from"dompurify";var Ig={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},Rg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Pg=()=>{let e=Lg(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(t,n)=>{if(n.attrName==="src"||n.attrName==="href"){let o=n.attrValue;o.toLowerCase().startsWith("data:")&&!Rg.test(o)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,Ig)},Ua=e=>e===!1?null:typeof e=="function"?e:Pg();var al="webmcp:",za={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function Cu(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var o,r;return[n.name,(o=n.description)!=null?o:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(r=n.origin)!=null?r:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${Wg(t.join(""))}`}function wu(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function Wg(e){let t=wu(e,0).toString(36),n=wu(e,2654435761).toString(36);return`${t}.${n}`}var qa=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return za.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",r),[]}let o=typeof location!="undefined"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=Dg(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return vo("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let p=typeof document!="undefined"&&!!document.modelContext;return vo(p?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=Bg(t),a;try{a=await r.getTools()}catch(p){let w=p instanceof Error?p.message:String(p);return vo(`Failed to read WebMCP registry: ${w}`)}let i=a.find(p=>p.name===s);if(!i)return vo(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return vo(`WebMCP tool not allowed by client allowlist: ${s}`);if(o!=null&&o.aborted)return vo("Aborted by cancel()");let d={toolName:s,args:n,description:i.description,reason:"gate"};if(!await this.requestConfirm(d))return vo("User declined the tool call.");if(o!=null&&o.aborted)return vo("Aborted by cancel()");let l=new AbortController,m=!1,u=setTimeout(()=>{m=!0,l.abort()},this.timeoutMs),g=()=>l.abort();o&&(o.aborted?l.abort():o.addEventListener("abort",g,{once:!0}));try{let p=await r.executeTool(i,_g(n),{signal:l.signal});return Fg(p)}catch(p){if(m)return vo(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return vo("Aborted by cancel()");let w=p instanceof Error?p.message:String(p);return vo(w)}finally{clearTimeout(u),o&&o.removeEventListener("abort",g)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){za.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,za.warn("document.modelContext is present but does not expose getTools()/executeTool() \u2014 WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var o;let n=(o=this.confirmHandler)!=null?o:Og;try{return await n(t)}catch(r){return za.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,r),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>Hg(t,o))}},Bg=e=>e.startsWith(al)?e.slice(al.length):e,qr=e=>e.startsWith(al),Hg=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Dg=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Fg=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:Vg(t)}]}},vo=e=>({isError:!0,content:[{type:"text",text:e}]}),Og=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Ng(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
1
|
+
var ku=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function $s(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];ku(s)&&ku(r)?n[o]=$s(s,r):n[o]=r}return n}var fo="min(440px, calc(100vw - 24px))",Fa="440px",Lt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:fo,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"follow",anchorTopOffset:16},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Eu(e,t){if(!(!e&&!t))return e?t?$s(e,t):e:t}function Mu(e){var t,n,o,r,s,a,i,d,l,f,u,g,m,C,v,E,L,I,R,H,P;return e?{...Lt,...e,theme:Eu(Lt.theme,e.theme),darkTheme:Eu(Lt.darkTheme,e.darkTheme),launcher:{...Lt.launcher,...e.launcher,dock:{...(t=Lt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(o=Lt.launcher)==null?void 0:o.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...Lt.copy,...e.copy},sendButton:{...Lt.sendButton,...e.sendButton},statusIndicator:{...Lt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Lt.voiceRecognition,...e.voiceRecognition},features:(()=>{var ie,X,re,be,he,j,se,Ie,ne,Z;let w=(ie=Lt.features)==null?void 0:ie.artifacts,x=(X=e.features)==null?void 0:X.artifacts,k=(re=Lt.features)==null?void 0:re.scrollToBottom,S=(be=e.features)==null?void 0:be.scrollToBottom,T=(he=Lt.features)==null?void 0:he.scrollBehavior,_=(j=e.features)==null?void 0:j.scrollBehavior,U=(se=Lt.features)==null?void 0:se.streamAnimation,G=(Ie=e.features)==null?void 0:Ie.streamAnimation,ge=(ne=Lt.features)==null?void 0:ne.askUserQuestion,ue=(Z=e.features)==null?void 0:Z.askUserQuestion,ce=w===void 0&&x===void 0?void 0:{...w,...x,layout:{...w==null?void 0:w.layout,...x==null?void 0:x.layout}},ke=k===void 0&&S===void 0?void 0:{...k,...S},ve=T===void 0&&_===void 0?void 0:{...T,..._},He=U===void 0&&G===void 0?void 0:{...U,...G},Se=ge===void 0&&ue===void 0?void 0:{...ge,...ue,styles:{...ge==null?void 0:ge.styles,...ue==null?void 0:ue.styles}};return{...Lt.features,...e.features,...ke!==void 0?{scrollToBottom:ke}:{},...ve!==void 0?{scrollBehavior:ve}:{},...ce!==void 0?{artifacts:ce}:{},...He!==void 0?{streamAnimation:He}:{},...Se!==void 0?{askUserQuestion:Se}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Lt.suggestionChips,suggestionChipsConfig:{...Lt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Lt.layout,...e.layout,header:{...(a=Lt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Lt.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(u=(f=Lt.layout)==null?void 0:f.messages)==null?void 0:u.avatar,...(m=(g=e.layout)==null?void 0:g.messages)==null?void 0:m.avatar},timestamp:{...(v=(C=Lt.layout)==null?void 0:C.messages)==null?void 0:v.timestamp,...(L=(E=e.layout)==null?void 0:E.messages)==null?void 0:L.timestamp}},slots:{...(I=Lt.layout)==null?void 0:I.slots,...(R=e.layout)==null?void 0:R.slots}},markdown:{...Lt.markdown,...e.markdown,options:{...(H=Lt.markdown)==null?void 0:H.options,...(P=e.markdown)==null?void 0:P.options}},messageActions:{...Lt.messageActions,...e.messageActions}}:Lt}var ng={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},og={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},rg={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:fo,maxWidth:Fa,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function ns(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?ns(e,o):o}function Lu(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let i=`${r}.${s}`;if(typeof a=="string"){let d=ns(e,a);d!==void 0&&(t[i]={path:i,value:d,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function sg(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function Iu(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=Iu(s,r):n[o]=r}return n}function ag(e,t){return t?Iu(e,t):e}function un(e,t={}){var r,s,a,i,d,l,f,u,g,m,C,v,E;let n={palette:ng,semantic:og,components:rg},o={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(f=e==null?void 0:e.semantic)==null?void 0:f.colors,interactive:{...n.semantic.colors.interactive,...(g=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:g.interactive},feedback:{...n.semantic.colors.feedback,...(C=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:C.feedback}},spacing:{...n.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...n.semantic.typography,...(E=e==null?void 0:e.semantic)==null?void 0:E.typography}},components:ag(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let L=sg(o);if(!L.valid)throw new Error(`Theme validation failed: ${L.errors.map(I=>I.message).join(", ")}`)}if(t.plugins)for(let L of t.plugins)o=L.transform(o);return o}function Ru(e){var v,E,L,I,R,H,P,w,x,k,S,T,_,U,G,ge,ue,ce,ke,ve,He,Se,ie,X,re,be,he,j,se,Ie,ne,Z,oe,at,it,Me,de,Xe,We,q,me,et,Et,ee,ze,Dn,Ht,sn,no,ko,D,pe,De,je,Ne,Ve,nt,Rt,jt,Xt,K,vt,rt,Ce,le,Ze,Jt,Kt,Ln,yn,ft,Mt,Je,zt,an,wn,Cn,bn,Eo,St,$n,Un,No,bo,xt,br,Mo,yr,Fn,Ur,Qo,_o,At,zn,qn,In,It,oo,ro,jn,Zo,Vo,er,Kn,Dt,Rn,so,tr,$o,nr,Lo,Gn,yo,ht,Qt,Zt,Yn,or;let t=Lu(e),n={};for(let[xe,ao]of Object.entries(t)){let io=xe.replace(/\./g,"-");n[`--persona-${io}`]=ao.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(E=n["--persona-semantic-colors-secondary"])!=null?E:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(L=n["--persona-semantic-colors-accent"])!=null?L:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(I=n["--persona-semantic-colors-surface"])!=null?I:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(R=n["--persona-semantic-colors-background"])!=null?R:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(H=n["--persona-semantic-colors-container"])!=null?H:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(P=n["--persona-semantic-colors-text"])!=null?P:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(w=n["--persona-semantic-colors-text-muted"])!=null?w:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(x=n["--persona-semantic-colors-text-inverse"])!=null?x:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(k=n["--persona-semantic-colors-border"])!=null?k:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(S=n["--persona-semantic-colors-divider"])!=null?S:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(T=n["--persona-components-voice-recording-indicator"])!=null?T:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(_=n["--persona-components-voice-recording-background"])!=null?_:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(U=n["--persona-components-voice-processing-icon"])!=null?U:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(G=n["--persona-components-voice-speaking-icon"])!=null?G:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(ge=n["--persona-components-approval-requested-background"])!=null?ge:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(ue=n["--persona-components-approval-requested-border"])!=null?ue:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(ce=n["--persona-components-approval-requested-text"])!=null?ce:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(ke=n["--persona-components-approval-requested-shadow"])!=null?ke:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-approval-approve-bg"]=(ve=n["--persona-components-approval-approve-background"])!=null?ve:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(He=n["--persona-components-approval-deny-background"])!=null?He:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Se=n["--persona-components-attachment-image-background"])!=null?Se:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(ie=n["--persona-components-attachment-image-border"])!=null?ie:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(X=n["--persona-semantic-typography-fontFamily"])!=null?X:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(re=n["--persona-semantic-typography-fontSize"])!=null?re:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(be=n["--persona-semantic-typography-fontWeight"])!=null?be:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(he=n["--persona-semantic-typography-lineHeight"])!=null?he:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(j=n["--persona-palette-radius-sm"])!=null?j:"0.125rem",n["--persona-radius-md"]=(se=n["--persona-palette-radius-md"])!=null?se:"0.375rem",n["--persona-radius-lg"]=(Ie=n["--persona-palette-radius-lg"])!=null?Ie:"0.5rem",n["--persona-radius-xl"]=(ne=n["--persona-palette-radius-xl"])!=null?ne:"0.75rem",n["--persona-radius-full"]=(Z=n["--persona-palette-radius-full"])!=null?Z:"9999px",n["--persona-launcher-radius"]=(at=(oe=n["--persona-components-launcher-borderRadius"])!=null?oe:n["--persona-palette-radius-full"])!=null?at:"9999px",n["--persona-launcher-bg"]=(it=n["--persona-components-launcher-background"])!=null?it:n["--persona-primary"],n["--persona-launcher-fg"]=(Me=n["--persona-components-launcher-foreground"])!=null?Me:n["--persona-text-inverse"],n["--persona-launcher-border"]=(de=n["--persona-components-launcher-border"])!=null?de:n["--persona-border"],n["--persona-button-primary-bg"]=(Xe=n["--persona-components-button-primary-background"])!=null?Xe:n["--persona-primary"],n["--persona-button-primary-fg"]=(We=n["--persona-components-button-primary-foreground"])!=null?We:n["--persona-text-inverse"],n["--persona-button-radius"]=(me=(q=n["--persona-components-button-primary-borderRadius"])!=null?q:n["--persona-palette-radius-full"])!=null?me:"9999px",n["--persona-panel-radius"]=(Et=(et=n["--persona-components-panel-borderRadius"])!=null?et:n["--persona-radius-xl"])!=null?Et:"0.75rem",n["--persona-panel-border"]=(ee=n["--persona-components-panel-border"])!=null?ee:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Dn=(ze=n["--persona-components-panel-shadow"])!=null?ze:n["--persona-palette-shadows-xl"])!=null?Dn:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(Ht=n["--persona-components-launcher-shadow"])!=null?Ht:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(no=(sn=n["--persona-components-input-borderRadius"])!=null?sn:n["--persona-radius-lg"])!=null?no:"0.5rem",n["--persona-message-user-radius"]=(D=(ko=n["--persona-components-message-user-borderRadius"])!=null?ko:n["--persona-radius-lg"])!=null?D:"0.5rem",n["--persona-message-assistant-radius"]=(De=(pe=n["--persona-components-message-assistant-borderRadius"])!=null?pe:n["--persona-radius-lg"])!=null?De:"0.5rem",n["--persona-header-bg"]=(je=n["--persona-components-header-background"])!=null?je:n["--persona-surface"],n["--persona-header-border"]=(Ne=n["--persona-components-header-border"])!=null?Ne:n["--persona-divider"],n["--persona-header-icon-bg"]=(Ve=n["--persona-components-header-iconBackground"])!=null?Ve:n["--persona-primary"],n["--persona-header-icon-fg"]=(nt=n["--persona-components-header-iconForeground"])!=null?nt:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(Rt=n["--persona-components-header-titleForeground"])!=null?Rt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(jt=n["--persona-components-header-subtitleForeground"])!=null?jt:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Xt=n["--persona-components-header-actionIconForeground"])!=null?Xt:n["--persona-muted"];let o=(K=e.components)==null?void 0:K.header;o!=null&&o.shadow&&(n["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom);let r=(vt=e.components)==null?void 0:vt.introCard;n["--persona-intro-card-bg"]=(rt=n["--persona-components-introCard-background"])!=null?rt:n["--persona-surface"],n["--persona-intro-card-radius"]=(Ce=n["--persona-components-introCard-borderRadius"])!=null?Ce:"1rem",n["--persona-intro-card-padding"]=(le=n["--persona-components-introCard-padding"])!=null?le:"1.5rem",n["--persona-intro-card-shadow"]=(Jt=(Ze=r==null?void 0:r.shadow)!=null?Ze:n["--persona-components-introCard-shadow"])!=null?Jt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Kt=n["--persona-components-input-background"])!=null?Kt:n["--persona-surface"],n["--persona-input-placeholder"]=(Ln=n["--persona-components-input-placeholder"])!=null?Ln:n["--persona-text-muted"],n["--persona-message-user-bg"]=(yn=n["--persona-components-message-user-background"])!=null?yn:n["--persona-accent"],n["--persona-message-user-text"]=(ft=n["--persona-components-message-user-text"])!=null?ft:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Mt=n["--persona-components-message-user-shadow"])!=null?Mt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Je=n["--persona-components-message-assistant-background"])!=null?Je:n["--persona-surface"],n["--persona-message-assistant-text"]=(zt=n["--persona-components-message-assistant-text"])!=null?zt:n["--persona-text"],n["--persona-message-assistant-border"]=(an=n["--persona-components-message-assistant-border"])!=null?an:n["--persona-border"],n["--persona-message-assistant-shadow"]=(wn=n["--persona-components-message-assistant-shadow"])!=null?wn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(bn=(Cn=n["--persona-components-scrollToBottom-background"])!=null?Cn:n["--persona-button-primary-bg"])!=null?bn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(St=(Eo=n["--persona-components-scrollToBottom-foreground"])!=null?Eo:n["--persona-button-primary-fg"])!=null?St:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=($n=n["--persona-components-scrollToBottom-border"])!=null?$n:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(Un=n["--persona-components-scrollToBottom-size"])!=null?Un:"40px",n["--persona-scroll-to-bottom-radius"]=(xt=(bo=(No=n["--persona-components-scrollToBottom-borderRadius"])!=null?No:n["--persona-button-radius"])!=null?bo:n["--persona-radius-full"])!=null?xt:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Mo=(br=n["--persona-components-scrollToBottom-shadow"])!=null?br:n["--persona-palette-shadows-sm"])!=null?Mo:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(yr=n["--persona-components-scrollToBottom-padding"])!=null?yr:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Fn=n["--persona-components-scrollToBottom-gap"])!=null?Fn:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Qo=(Ur=n["--persona-components-scrollToBottom-fontSize"])!=null?Ur:n["--persona-palette-typography-fontSize-sm"])!=null?Qo:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(_o=n["--persona-components-scrollToBottom-iconSize"])!=null?_o:"14px",n["--persona-tool-bubble-shadow"]=(At=n["--persona-components-toolBubble-shadow"])!=null?At:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(zn=n["--persona-components-reasoningBubble-shadow"])!=null?zn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(qn=n["--persona-components-composer-shadow"])!=null?qn:"none",n["--persona-md-inline-code-bg"]=(In=n["--persona-components-markdown-inlineCode-background"])!=null?In:n["--persona-container"],n["--persona-md-inline-code-color"]=(It=n["--persona-components-markdown-inlineCode-foreground"])!=null?It:n["--persona-text"],n["--persona-md-link-color"]=(ro=(oo=n["--persona-components-markdown-link-foreground"])!=null?oo:n["--persona-accent"])!=null?ro:"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let l=n["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(n["--persona-md-prose-font-family"]=l),n["--persona-md-code-block-bg"]=(jn=n["--persona-components-markdown-codeBlock-background"])!=null?jn:n["--persona-container"],n["--persona-md-code-block-border-color"]=(Zo=n["--persona-components-markdown-codeBlock-borderColor"])!=null?Zo:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Vo=n["--persona-components-markdown-codeBlock-textColor"])!=null?Vo:"inherit",n["--persona-md-table-header-bg"]=(er=n["--persona-components-markdown-table-headerBackground"])!=null?er:n["--persona-container"],n["--persona-md-table-border-color"]=(Kn=n["--persona-components-markdown-table-borderColor"])!=null?Kn:n["--persona-border"],n["--persona-md-hr-color"]=(Dt=n["--persona-components-markdown-hr-color"])!=null?Dt:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Rn=n["--persona-components-markdown-blockquote-borderColor"])!=null?Rn:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(so=n["--persona-components-markdown-blockquote-background"])!=null?so:"transparent",n["--persona-md-blockquote-text-color"]=(tr=n["--persona-components-markdown-blockquote-textColor"])!=null?tr:n["--persona-palette-colors-gray-500"],n["--cw-container"]=($o=n["--persona-components-collapsibleWidget-container"])!=null?$o:n["--persona-surface"],n["--cw-surface"]=(nr=n["--persona-components-collapsibleWidget-surface"])!=null?nr:n["--persona-surface"],n["--cw-border"]=(Lo=n["--persona-components-collapsibleWidget-border"])!=null?Lo:n["--persona-border"],n["--persona-message-border"]=(Gn=n["--persona-components-message-border"])!=null?Gn:n["--persona-border"];let f=e.components,u=f==null?void 0:f.iconButton;u&&(u.background&&(n["--persona-icon-btn-bg"]=u.background),u.border&&(n["--persona-icon-btn-border"]=u.border),u.color&&(n["--persona-icon-btn-color"]=u.color),u.padding&&(n["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(n["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(n["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(n["--persona-icon-btn-active-border"]=u.activeBorder));let g=f==null?void 0:f.labelButton;g&&(g.background&&(n["--persona-label-btn-bg"]=g.background),g.border&&(n["--persona-label-btn-border"]=g.border),g.color&&(n["--persona-label-btn-color"]=g.color),g.padding&&(n["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(n["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(n["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(n["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(n["--persona-label-btn-gap"]=g.gap));let m=f==null?void 0:f.toggleGroup;m&&(m.gap&&(n["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(n["--persona-toggle-group-radius"]=m.borderRadius));let C=f==null?void 0:f.artifact;if(C!=null&&C.toolbar){let xe=C.toolbar;xe.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=xe.iconHoverColor),xe.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=xe.iconHoverBackground),xe.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=xe.iconPadding),xe.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=xe.iconBorderRadius),xe.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=xe.iconBorder),xe.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=xe.toggleGroupGap),xe.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=xe.toggleBorderRadius),xe.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=xe.copyBackground),xe.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=xe.copyBorder),xe.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=xe.copyColor),xe.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=xe.copyBorderRadius),xe.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=xe.copyPadding),xe.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=xe.copyMenuBackground,n["--persona-dropdown-bg"]=(yo=n["--persona-dropdown-bg"])!=null?yo:xe.copyMenuBackground),xe.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=xe.copyMenuBorder,n["--persona-dropdown-border"]=(ht=n["--persona-dropdown-border"])!=null?ht:xe.copyMenuBorder),xe.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=xe.copyMenuShadow,n["--persona-dropdown-shadow"]=(Qt=n["--persona-dropdown-shadow"])!=null?Qt:xe.copyMenuShadow),xe.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=xe.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(Zt=n["--persona-dropdown-radius"])!=null?Zt:xe.copyMenuBorderRadius),xe.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=xe.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(Yn=n["--persona-dropdown-item-hover-bg"])!=null?Yn:xe.copyMenuItemHoverBackground),xe.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=xe.iconBackground),xe.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=xe.toolbarBorder)}if(C!=null&&C.tab){let xe=C.tab;xe.background&&(n["--persona-artifact-tab-bg"]=xe.background),xe.activeBackground&&(n["--persona-artifact-tab-active-bg"]=xe.activeBackground),xe.activeBorder&&(n["--persona-artifact-tab-active-border"]=xe.activeBorder),xe.borderRadius&&(n["--persona-artifact-tab-radius"]=xe.borderRadius),xe.textColor&&(n["--persona-artifact-tab-color"]=xe.textColor),xe.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=xe.hoverBackground),xe.listBackground&&(n["--persona-artifact-tab-list-bg"]=xe.listBackground),xe.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=xe.listBorderColor),xe.listPadding&&(n["--persona-artifact-tab-list-padding"]=xe.listPadding)}if(C!=null&&C.pane){let xe=C.pane;if(xe.toolbarBackground){let ao=(or=ns(e,xe.toolbarBackground))!=null?or:xe.toolbarBackground;n["--persona-artifact-toolbar-bg"]=ao}}return n}var ig={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},Pu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},il=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},lg=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":il()},cg=e=>lg(e),dg=e=>un(e),pg=e=>{var n;let t=un(void 0,{validate:!1});return un({...e,palette:{...t.palette,colors:{...ig.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Oa=e=>{let t=cg(e),n=Pu(e==null?void 0:e.theme),o=Pu(e==null?void 0:e.darkTheme);return t==="dark"?pg($s(n!=null?n:{},o!=null?o:{})):dg(n)},ug=e=>Ru(e),os=(e,t)=>{let n=Oa(t),o=ug(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s)},Wu=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(il())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(il());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};function ll(e,t){let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return o}function Ir(e,t,n){var i;let o=t.split(".");if(o.length===1)return{...e,[o[0]]:n};let[r,...s]=o,a=e;return{...a,[r]:Ir((i=a==null?void 0:a[r])!=null?i:{},s.join("."),n)}}var cl=class{constructor(t,n,o){this.listeners=[];this.history=[];this.historyIndex=-1;this.suppressHistory=!1;var s;let r=(s=o==null?void 0:o.mergeDefaults)!=null?s:!0;this.config=r?{...Lt,...n}:n!=null?n:Lt,this.theme=un(t,{validate:!1}),this.syncThemeIntoConfig(),this.pushHistorySnapshot(this.exportSnapshot(),!0)}get(t){var n;return t.startsWith("theme.")?ll(this.theme,t.replace("theme.","")):t.startsWith("darkTheme.")?ll((n=this.config.darkTheme)!=null?n:{},t.replace("darkTheme.","")):ll(this.config,t)}getTheme(){return this.theme}getConfig(){return this.config}set(t,n){var o;if(t.startsWith("theme.")){let r=t.replace("theme.","");this.theme=Ir(this.theme,r,n),this.syncThemeIntoConfig()}else if(t.startsWith("darkTheme.")){let r=t.replace("darkTheme.",""),s=(o=this.config.darkTheme)!=null?o:un();this.config={...this.config,darkTheme:Ir(s,r,n)}}else this.config=Ir(this.config,t,n);this.recordHistory(),this.notifyListeners()}setBatch(t){var s;let n=!1,o=!1,r=!1;for(let[a,i]of Object.entries(t))if(a.startsWith("theme.")){let d=a.replace("theme.","");this.theme=Ir(this.theme,d,i),n=!0}else if(a.startsWith("darkTheme.")){let d=a.replace("darkTheme.",""),l=(s=this.config.darkTheme)!=null?s:un();this.config={...this.config,darkTheme:Ir(l,d,i)},o=!0}else this.config=Ir(this.config,a,i),r=!0;n&&this.syncThemeIntoConfig(),(n||o||r)&&(this.recordHistory(),this.notifyListeners())}setTheme(t){this.theme=t,this.syncThemeIntoConfig(),this.recordHistory(),this.notifyListeners()}setFullConfig(t,n){this.config={...t},n&&(this.theme=n),this.syncThemeIntoConfig(),this.recordHistory(),this.notifyListeners()}importSnapshot(t){var r,s;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Snapshot must be a JSON object");let n=t;if("config"in n||"theme"in n||n.version===2){let a=(r=n.config)!=null?r:this.config,i=un((s=n.theme)!=null?s:this.theme,{validate:!1});this.setFullConfig(a,i);return}let o=un(n,{validate:!1});this.setTheme(o)}resetToDefaults(){this.config={...Lt},this.theme=un(),this.syncThemeIntoConfig(),this.history=[],this.historyIndex=-1,this.pushHistorySnapshot(this.exportSnapshot()),this.notifyListeners()}canUndo(){return this.historyIndex>0}canRedo(){return this.historyIndex>=0&&this.historyIndex<this.history.length-1}getHistoryLength(){return this.history.length}getHistoryIndex(){return this.historyIndex}undo(){this.canUndo()&&(this.historyIndex-=1,this.restoreSnapshot(this.history[this.historyIndex]))}redo(){this.canRedo()&&(this.historyIndex+=1,this.restoreSnapshot(this.history[this.historyIndex]))}exportSnapshot(){return{version:2,config:{...this.config,theme:void 0},theme:this.theme}}onChange(t){return this.listeners.push(t),()=>{let n=this.listeners.indexOf(t);n>=0&&this.listeners.splice(n,1)}}syncThemeIntoConfig(){this.config={...this.config,theme:this.theme}}notifyListeners(){for(let t of this.listeners)t(this.config,this.theme)}recordHistory(){this.pushHistorySnapshot(this.exportSnapshot())}pushHistorySnapshot(t,n=!1){if(this.suppressHistory)return;let o=JSON.stringify(t),r=this.historyIndex>=0&&this.history[this.historyIndex]?JSON.stringify(this.history[this.historyIndex]):null;if(n&&this.historyIndex>=0){this.history[this.historyIndex]=t;return}o!==r&&(this.history=this.history.slice(0,this.historyIndex+1),this.history.push(t),this.historyIndex=this.history.length-1)}restoreSnapshot(t){this.suppressHistory=!0,this.config=t.config,this.theme=un(t.theme,{validate:!1}),this.syncThemeIntoConfig(),this.suppressHistory=!1,this.notifyListeners()}};function dl(e){let t=e.trim();if(t==="9999px")return{value:100,unit:"px"};let n=t.match(/^([\d.]+)(px|rem)$/);if(!n){let o=parseFloat(t);return{value:isNaN(o)?0:o,unit:"px"}}return{value:parseFloat(n[1]),unit:n[2]}}function pl(e,t){return t==="rem"?`${e}rem`:`${e}px`}function mg(e,t){return t==="rem"?e*16:e}function fg(e,t){return t==="rem"?e/16:e}function Us(e){if(!e)return"#000000";let t=e.trim().toLowerCase();return t==="transparent"?"transparent":t.startsWith("rgba")||t.startsWith("rgb")?t:t.startsWith("#")?t.length===4?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:t:`#${t}`}function ul(e){return/^#[0-9A-Fa-f]{6}$/.test(e)}function ml(e){let t=e.trim().toLowerCase().match(/^rgba?\(([^)]+)\)$/);if(!t)return null;let n=t[1].split(",").map(d=>d.trim());if(n.length<3)return null;let o=d=>{let l=d.endsWith("%"),f=parseFloat(l?d.slice(0,-1):d);return Number.isFinite(f)?Math.max(0,Math.min(255,Math.round(l?f/100*255:f))):NaN},r=o(n[0]),s=o(n[1]),a=o(n[2]);if(!Number.isFinite(r)||!Number.isFinite(s)||!Number.isFinite(a))return null;let i=d=>d.toString(16).padStart(2,"0");return`#${i(r)}${i(s)}${i(a)}`}function Na(e,t){let n=s=>{var l;let a=Us(s),i=a.startsWith("rgb")?(l=ml(a))!=null?l:"#000000":a,d=[1,3,5].map(f=>{let u=parseInt(i.slice(f,f+2),16)/255;return u<=.03928?u/12.92:Math.pow((u+.055)/1.055,2.4)});return .2126*d[0]+.7152*d[1]+.0722*d[2]},o=n(e),r=n(t);return(Math.max(o,r)+.05)/(Math.min(o,r)+.05)}function Bu(e){var g;let t=Us(e),n=t.startsWith("rgb")?(g=ml(t))!=null?g:"#000000":t,o=parseInt(n.slice(1,3),16)/255,r=parseInt(n.slice(3,5),16)/255,s=parseInt(n.slice(5,7),16)/255,a=Math.max(o,r,s),i=Math.min(o,r,s),d=(a+i)/2;if(a===i)return{h:0,s:0,l:d};let l=a-i,f=d>.5?l/(2-a-i):l/(a+i),u;switch(a){case o:u=((r-s)/l+(r<s?6:0))/6;break;case r:u=((s-o)/l+2)/6;break;default:u=((o-r)/l+4)/6;break}return{h:u*360,s:f,l:d}}function Hu(e,t,n){let o=(e%360+360)%360,r=(1-Math.abs(2*n-1))*t,s=r*(1-Math.abs(o/60%2-1)),a=n-r/2,i,d,l;o<60?[i,d,l]=[r,s,0]:o<120?[i,d,l]=[s,r,0]:o<180?[i,d,l]=[0,r,s]:o<240?[i,d,l]=[0,s,r]:o<300?[i,d,l]=[s,0,r]:[i,d,l]=[r,0,s];let f=u=>{let g=Math.round((u+a)*255).toString(16);return g.length===1?"0"+g:g};return`#${f(i)}${f(d)}${f(l)}`}function fl(e){let{h:t,s:n,l:o}=Bu(e),r={50:.97,100:.94,200:.87,300:.77,400:.64,500:o,600:Math.max(.05,o-.1),700:Math.max(.05,o-.2),800:Math.max(.05,o-.28),900:Math.max(.05,o-.35),950:Math.max(.03,o-.42)},s={50:Math.min(1,n*.85),100:Math.min(1,n*.9),200:Math.min(1,n*.95),300:n,400:n,500:n,600:Math.min(1,n*1.05),700:Math.min(1,n*1.05),800:Math.min(1,n*1),900:Math.min(1,n*.95),950:Math.min(1,n*.9)},a={};for(let[i,d]of Object.entries(r)){let l=s[i];a[i]=Hu(t,l,d)}return a}var rs=["50","100","200","300","400","500","600","700","800","900","950"],gl=["primary","secondary","accent","gray","success","warning","error","info"];function gg(e,t){return`palette.colors.${e}.${t}`}function Du(e,t,n=0){if(n>5)return"#cbd5e1";let o=e(t);return typeof o!="string"?"#cbd5e1":o.startsWith("#")||o.startsWith("rgb")||o==="transparent"?o:o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components.")?Du(e,`theme.${o}`,n+1):"#cbd5e1"}function hg(e){if(!e.startsWith("palette.")&&!e.startsWith("semantic."))return e;let t=e.split(".");if(t[0]==="palette"&&t[1]==="colors"){let n=t[2],o=t[3];return`${n.charAt(0).toUpperCase()+n.slice(1)} ${o}`}return t[0]==="semantic"?t.slice(1).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):t[t.length-1]}var Do=[{id:"solid",label:"Solid"},{id:"soft",label:"Soft"}],_a=["primary","secondary","accent","gray"],bg={primary:"Primary",secondary:"Secondary",accent:"Accent",gray:"Neutral"},Va={roleId:"role-surfaces",helper:"Page and panel backgrounds",previewZone:"container",intensities:Do,targets:[{path:"semantic.colors.background",kind:"background"},{path:"semantic.colors.surface",kind:"background"},{path:"semantic.colors.container",kind:"background"}]},$a={roleId:"role-header",helper:"Widget header bar",previewZone:"header",intensities:Do,targets:[{path:"components.header.background",kind:"background"},{path:"components.header.border",kind:"border"},{path:"components.header.iconBackground",kind:"accent"},{path:"components.header.iconForeground",kind:"foreground"},{path:"components.header.titleForeground",kind:"accent"},{path:"components.header.subtitleForeground",kind:"foreground"},{path:"components.header.actionIconForeground",kind:"foreground"}]},Ua={roleId:"role-user-messages",helper:"User chat bubbles",previewZone:"user-message",intensities:Do,targets:[{path:"components.message.user.background",kind:"background"},{path:"components.message.user.text",kind:"foreground"}]},za={roleId:"role-assistant-messages",helper:"Assistant chat bubbles",previewZone:"assistant-message",intensities:Do,targets:[{path:"components.message.assistant.background",kind:"background"},{path:"components.message.assistant.text",kind:"foreground"}]},qa={roleId:"role-primary-actions",helper:"Send button and primary buttons",intensities:Do,targets:[{path:"components.button.primary.background",kind:"background"},{path:"components.button.primary.foreground",kind:"foreground"},{path:"semantic.colors.interactive.default",kind:"accent"},{path:"semantic.colors.interactive.hover",kind:"accent"}]},ja={roleId:"role-scroll-to-bottom",helper:"Scroll-to-bottom affordances in transcript and event stream",intensities:Do,targets:[{path:"components.scrollToBottom.background",kind:"background"},{path:"components.scrollToBottom.foreground",kind:"foreground"},{path:"components.scrollToBottom.border",kind:"border"}]},Ka={roleId:"role-input",helper:"Message input field",previewZone:"composer",intensities:Do,targets:[{path:"components.input.background",kind:"background"},{path:"components.input.placeholder",kind:"foreground"},{path:"components.input.focus.border",kind:"accent"},{path:"components.input.focus.ring",kind:"accent"}]},Ga={roleId:"role-links-focus",helper:"Links, focus rings, and interactive highlights",intensities:Do,targets:[{path:"semantic.colors.accent",kind:"accent"},{path:"semantic.colors.interactive.focus",kind:"accent"},{path:"semantic.colors.interactive.active",kind:"accent"},{path:"components.markdown.link.foreground",kind:"accent"}]},Ya={roleId:"role-borders",helper:"Borders, dividers, and separators",intensities:Do,targets:[{path:"semantic.colors.border",kind:"border"},{path:"semantic.colors.divider",kind:"border"}]},Rr=[Va,$a,Ua,za,qa,ja,Ka,Ga,Ya];function Xa(e,t,n){let o={},r=e==="neutral"?"gray":e;for(let s of n.targets){let a=yg(r,t,s,n.roleId);o[`theme.${s.path}`]=a,o[`darkTheme.${s.path}`]=a}if(n.roleId==="role-primary-actions"){let s=t==="solid"?`palette.colors.${r}.700`:`palette.colors.${r}.200`;o["theme.semantic.colors.interactive.hover"]=s,o["darkTheme.semantic.colors.interactive.hover"]=s}return o}function yg(e,t,n,o){let r=t==="solid";if(o==="role-header")return vg(e,r,n);if(o==="role-input")return xg(e,r,n);switch(n.kind){case"background":return r?`palette.colors.${e}.500`:`palette.colors.${e}.${e==="gray"?"50":"100"}`;case"foreground":return r?`palette.colors.${e==="gray"?"gray":e}.50`:`palette.colors.${e==="gray"?"gray":e}.900`;case"border":return r?`palette.colors.${e}.600`:`palette.colors.${e}.200`;case"accent":return r?`palette.colors.${e}.600`:`palette.colors.${e}.400`}}function vg(e,t,n){let o=n.path;return o.endsWith(".background")?t?`palette.colors.${e}.500`:`palette.colors.${e}.${e==="gray"?"50":"100"}`:o.endsWith(".border")?t?`palette.colors.${e}.600`:`palette.colors.${e}.200`:o.endsWith(".iconBackground")?t?`palette.colors.${e}.${e==="gray"?"700":"600"}`:`palette.colors.${e}.500`:o.endsWith(".iconForeground")?t?`palette.colors.${e}.50`:`palette.colors.${e}.50`:o.endsWith(".titleForeground")?t?`palette.colors.${e}.50`:`palette.colors.${e}.${e==="gray"?"900":"700"}`:o.endsWith(".subtitleForeground")?t?`palette.colors.${e}.200`:`palette.colors.${e}.500`:o.endsWith(".actionIconForeground")?t?`palette.colors.${e}.200`:`palette.colors.${e}.500`:`palette.colors.${e}.500`}function xg(e,t,n){let o=n.path;return o.endsWith(".background")?t?`palette.colors.${e}.${e==="gray"?"100":"50"}`:`palette.colors.${e}.50`:o.endsWith(".placeholder")?`palette.colors.${e}.400`:o.endsWith(".border")||o.endsWith(".ring")?t?`palette.colors.${e}.500`:`palette.colors.${e}.400`:`palette.colors.${e}.500`}var wg=/^palette\.colors\.(\w+)\.(\d+)$/;function hl(e,t){var i,d;let n=(i=t.targets.find(l=>l.kind==="background"))!=null?i:t.targets[0];if(!n)return null;let r=String((d=e(n.path))!=null?d:"").match(wg);if(!r)return null;let s=r[1],a=_a.includes(s)?s:null;if(!a)return null;for(let l of["solid","soft"]){let f=Xa(a,l,t);if(t.targets.every(g=>{var C;return String((C=e(g.path))!=null?C:"")===f[`theme.${g.path}`]}))return{family:a,intensity:l}}return null}var Cg={id:"theme-mode",title:"Runtime Theme",description:"Controls how the shipped widget picks light or dark mode.",collapsed:!1,fields:[{id:"theme-mode",label:"Runtime Theme",description:"Always Light, Always Dark, or follow the visitor system preference",type:"select",path:"colorScheme",defaultValue:"auto",options:[{value:"light",label:"Light"},{value:"dark",label:"Dark"},{value:"auto",label:"Follow System"}]}]},Sg={id:"brand-colors",title:"Brand Colors",description:"Pick your brand colors. A full shade scale is generated automatically for both light and dark themes.",collapsed:!1,fields:[{id:"brand-primary",label:"Primary",description:"Main brand color for buttons, links, and accents",type:"color",path:"theme.palette.colors.primary.500",defaultValue:"#171717"},{id:"brand-secondary",label:"Secondary",description:"Supporting brand color",type:"color",path:"theme.palette.colors.secondary.500",defaultValue:"#7c3aed"},{id:"brand-accent",label:"Accent",description:"Highlight and decorative color",type:"color",path:"theme.palette.colors.accent.500",defaultValue:"#06b6d4"}]},Ag={id:"chat-colors",title:"Chat Colors",description:"Customize the main colors of the chat interface.",collapsed:!0,fields:[{id:"chat-header-bg",label:"Header Background",type:"token-ref",path:"theme.components.header.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"chat-header-icon-bg",label:"Header Icon Background",type:"token-ref",path:"theme.components.header.iconBackground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-header-icon-fg",label:"Header Icon Color",type:"token-ref",path:"theme.components.header.iconForeground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"chat-header-title-fg",label:"Header Title Color",type:"token-ref",path:"theme.components.header.titleForeground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-header-subtitle-fg",label:"Header Subtitle Color",type:"token-ref",path:"theme.components.header.subtitleForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"chat-header-action-icons-fg",label:"Header Button Icons",type:"token-ref",path:"theme.components.header.actionIconForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"chat-msg-user-bg",label:"User Message Background",type:"token-ref",path:"theme.components.message.user.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-msg-user-text",label:"User Message Text",type:"token-ref",path:"theme.components.message.user.text",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"chat-msg-assistant-bg",label:"Assistant Message Background",type:"token-ref",path:"theme.components.message.assistant.background",defaultValue:"semantic.colors.container",tokenRef:{tokenType:"color"}},{id:"chat-msg-assistant-text",label:"Assistant Message Text",type:"token-ref",path:"theme.components.message.assistant.text",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},Tg={id:"typography",title:"Typography",collapsed:!0,fields:[{id:"typo-font-family",label:"Font Family",type:"select",path:"theme.semantic.typography.fontFamily",defaultValue:"palette.typography.fontFamily.sans",options:[{value:"palette.typography.fontFamily.sans",label:"Sans Serif"},{value:"palette.typography.fontFamily.serif",label:"Serif"},{value:"palette.typography.fontFamily.mono",label:"Monospace"}]},{id:"typo-font-size",label:"Base Font Size",type:"select",path:"theme.semantic.typography.fontSize",defaultValue:"palette.typography.fontSize.base",options:[{value:"palette.typography.fontSize.xs",label:"Extra Small (0.75rem)"},{value:"palette.typography.fontSize.sm",label:"Small (0.875rem)"},{value:"palette.typography.fontSize.base",label:"Base (1rem)"},{value:"palette.typography.fontSize.lg",label:"Large (1.125rem)"},{value:"palette.typography.fontSize.xl",label:"Extra Large (1.25rem)"}]},{id:"typo-font-weight",label:"Font Weight",type:"select",path:"theme.semantic.typography.fontWeight",defaultValue:"palette.typography.fontWeight.normal",options:[{value:"palette.typography.fontWeight.normal",label:"Normal (400)"},{value:"palette.typography.fontWeight.medium",label:"Medium (500)"},{value:"palette.typography.fontWeight.semibold",label:"Semibold (600)"},{value:"palette.typography.fontWeight.bold",label:"Bold (700)"}]},{id:"typo-line-height",label:"Line Height",type:"select",path:"theme.semantic.typography.lineHeight",defaultValue:"palette.typography.lineHeight.normal",options:[{value:"palette.typography.lineHeight.tight",label:"Tight (1.25)"},{value:"palette.typography.lineHeight.normal",label:"Normal (1.5)"},{value:"palette.typography.lineHeight.relaxed",label:"Relaxed (1.625)"}]}]},kg={id:"launcher-style",title:"Launcher",description:"Control launcher appearance.",collapsed:!0,fields:[{id:"style-launcher-size",label:"Launcher Size",type:"slider",path:"theme.components.launcher.size",defaultValue:"60px",slider:{min:32,max:80,step:2}},{id:"style-launcher-shape",label:"Launcher Shape",type:"select",path:"theme.components.launcher.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Rounded Square"},{value:"palette.radius.lg",label:"Rounded"},{value:"palette.radius.xl",label:"Very Rounded"},{value:"palette.radius.full",label:"Circle"}]},{id:"style-launcher-shadow",label:"Launcher Shadow",type:"select",path:"theme.components.launcher.shadow",defaultValue:"palette.shadows.lg",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},Eg={id:"shape",title:"Shape",description:"Control the corner roundness across the widget.",collapsed:!0,fields:[{id:"radius-sm",label:"Small",type:"slider",path:"theme.palette.radius.sm",defaultValue:"0.125rem",slider:{min:0,max:16,step:1}},{id:"radius-md",label:"Medium",type:"slider",path:"theme.palette.radius.md",defaultValue:"0.375rem",slider:{min:0,max:24,step:1}},{id:"radius-lg",label:"Large",type:"slider",path:"theme.palette.radius.lg",defaultValue:"0.5rem",slider:{min:0,max:32,step:1}},{id:"radius-xl",label:"Extra Large",type:"slider",path:"theme.palette.radius.xl",defaultValue:"0.75rem",slider:{min:0,max:48,step:1}},{id:"radius-full",label:"Full",type:"slider",path:"theme.palette.radius.full",defaultValue:"9999px",slider:{min:0,max:100,step:1,isRadiusFull:!0}}],presets:[{id:"radius-default",label:"Default",values:{"theme.palette.radius.sm":"0.125rem","theme.palette.radius.md":"0.375rem","theme.palette.radius.lg":"0.5rem","theme.palette.radius.xl":"0.75rem","theme.palette.radius.full":"9999px"}},{id:"radius-sharp",label:"Sharp",values:{"theme.palette.radius.sm":"1px","theme.palette.radius.md":"2px","theme.palette.radius.lg":"3px","theme.palette.radius.xl":"4px","theme.palette.radius.full":"4px"}},{id:"radius-rounded",label:"Rounded",values:{"theme.palette.radius.sm":"0.5rem","theme.palette.radius.md":"0.75rem","theme.palette.radius.lg":"1rem","theme.palette.radius.xl":"1.5rem","theme.palette.radius.full":"9999px"}}]},Mg={id:"shadows",title:"Shadows",collapsed:!0,fields:[{id:"shadow-sm",label:"Small",type:"text",path:"theme.palette.shadows.sm",defaultValue:"0 1px 2px 0 rgb(0 0 0 / 0.05)"},{id:"shadow-md",label:"Medium",type:"text",path:"theme.palette.shadows.md",defaultValue:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)"},{id:"shadow-lg",label:"Large",type:"text",path:"theme.palette.shadows.lg",defaultValue:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)"},{id:"shadow-xl",label:"Extra Large",type:"text",path:"theme.palette.shadows.xl",defaultValue:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)"}]},Lg={id:"widget-style",title:"Widget Surface",description:"Adjust the main panel and message bubble treatment.",collapsed:!0,fields:[{id:"style-panel-radius",label:"Panel Corner Radius",type:"select",path:"theme.components.panel.borderRadius",defaultValue:"palette.radius.xl",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"style-panel-shadow",label:"Panel Shadow",type:"select",path:"theme.components.panel.shadow",defaultValue:"palette.shadows.xl",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]},{id:"style-msg-user-radius",label:"User Message Radius",type:"select",path:"theme.components.message.user.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"style-msg-assistant-radius",label:"Assistant Message Radius",type:"select",path:"theme.components.message.assistant.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},as=[Sg,Ag,kg,Tg,Cg,Eg,Mg,Lg];function Ou(){return{id:"brand-palette",title:"Brand Palette",description:"Define your color palette. Edit the base color (500) to auto-generate the full scale.",collapsed:!1,fields:gl.map(t=>({id:`palette-${t}`,label:`${t.charAt(0).toUpperCase()+t.slice(1)}`,description:`${t} color palette (edit shade 500, auto-generate scale)`,type:"color-scale",path:`theme.palette.colors.${t}`,colorScale:{colorFamily:t}}))}}var Nu={id:"semantic-colors",title:"Semantic Colors",description:"Map intents to palette colors.",collapsed:!0,fields:[{id:"sem-primary",label:"Primary",description:"Main brand/action color",type:"token-ref",path:"theme.semantic.colors.primary",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sem-secondary",label:"Secondary",description:"Secondary actions",type:"token-ref",path:"theme.semantic.colors.secondary",defaultValue:"palette.colors.gray.500",tokenRef:{tokenType:"color"}},{id:"sem-accent",label:"Accent",description:"Accent/highlight color",type:"token-ref",path:"theme.semantic.colors.accent",defaultValue:"palette.colors.primary.600",tokenRef:{tokenType:"color"}},{id:"sem-surface",label:"Surface",description:"Primary surface background",type:"token-ref",path:"theme.semantic.colors.surface",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-background",label:"Background",description:"Page/widget background",type:"token-ref",path:"theme.semantic.colors.background",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-container",label:"Container",description:"Container/card background",type:"token-ref",path:"theme.semantic.colors.container",defaultValue:"palette.colors.gray.100",tokenRef:{tokenType:"color"}},{id:"sem-text",label:"Text",description:"Primary text color",type:"token-ref",path:"theme.semantic.colors.text",defaultValue:"palette.colors.gray.900",tokenRef:{tokenType:"color"}},{id:"sem-text-muted",label:"Text Muted",description:"Secondary/muted text",type:"token-ref",path:"theme.semantic.colors.textMuted",defaultValue:"palette.colors.gray.500",tokenRef:{tokenType:"color"}},{id:"sem-text-inverse",label:"Text Inverse",description:"Text on dark backgrounds",type:"token-ref",path:"theme.semantic.colors.textInverse",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-border",label:"Border",description:"Default border color",type:"token-ref",path:"theme.semantic.colors.border",defaultValue:"palette.colors.gray.200",tokenRef:{tokenType:"color"}},{id:"sem-divider",label:"Divider",description:"Divider/separator color",type:"token-ref",path:"theme.semantic.colors.divider",defaultValue:"palette.colors.gray.200",tokenRef:{tokenType:"color"}},{id:"sem-interactive-default",label:"Interactive Default",type:"token-ref",path:"theme.semantic.colors.interactive.default",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sem-interactive-hover",label:"Interactive Hover",type:"token-ref",path:"theme.semantic.colors.interactive.hover",defaultValue:"palette.colors.primary.600",tokenRef:{tokenType:"color"}},{id:"sem-interactive-focus",label:"Interactive Focus",type:"token-ref",path:"theme.semantic.colors.interactive.focus",defaultValue:"palette.colors.primary.700",tokenRef:{tokenType:"color"}},{id:"sem-interactive-active",label:"Interactive Active",type:"token-ref",path:"theme.semantic.colors.interactive.active",defaultValue:"palette.colors.primary.800",tokenRef:{tokenType:"color"}},{id:"sem-interactive-disabled",label:"Interactive Disabled",type:"token-ref",path:"theme.semantic.colors.interactive.disabled",defaultValue:"palette.colors.gray.300",tokenRef:{tokenType:"color"}},{id:"sem-feedback-success",label:"Success",type:"token-ref",path:"theme.semantic.colors.feedback.success",defaultValue:"palette.colors.success.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-warning",label:"Warning",type:"token-ref",path:"theme.semantic.colors.feedback.warning",defaultValue:"palette.colors.warning.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-error",label:"Error",type:"token-ref",path:"theme.semantic.colors.feedback.error",defaultValue:"palette.colors.error.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-info",label:"Info",type:"token-ref",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}}]},Ig=Ou(),Rg=Nu,Pg=[Ou(),Nu],Wg={id:"comp-panel",title:"Panel",collapsed:!1,fields:[{id:"panel-width",label:"Width",type:"text",path:"theme.components.panel.width",defaultValue:fo},{id:"panel-max-width",label:"Max Width",type:"text",path:"theme.components.panel.maxWidth",defaultValue:Fa},{id:"panel-height",label:"Height",type:"text",path:"theme.components.panel.height",defaultValue:"600px"},{id:"panel-max-height",label:"Max Height",type:"text",path:"theme.components.panel.maxHeight",defaultValue:"calc(100vh - 80px)"},{id:"panel-border-radius",label:"Border Radius",type:"select",path:"theme.components.panel.borderRadius",defaultValue:"palette.radius.xl",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"panel-shadow",label:"Shadow",type:"select",path:"theme.components.panel.shadow",defaultValue:"palette.shadows.xl",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},Bg={id:"comp-launcher",title:"Launcher",collapsed:!0,fields:[{id:"launcher-size",label:"Size",type:"slider",path:"theme.components.launcher.size",defaultValue:"60px",slider:{min:32,max:80,step:2}},{id:"launcher-icon-size",label:"Icon Size",type:"slider",path:"theme.components.launcher.iconSize",defaultValue:"28px",slider:{min:16,max:48,step:2}},{id:"launcher-border-radius",label:"Border Radius",type:"select",path:"theme.components.launcher.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"},{value:"palette.radius.full",label:"Full (Circle)"}]},{id:"launcher-shadow",label:"Shadow",type:"select",path:"theme.components.launcher.shadow",defaultValue:"palette.shadows.lg",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},Hg={id:"comp-message-shape",title:"Message Shape",collapsed:!0,fields:[{id:"msg-user-radius",label:"User Bubble Radius",type:"select",path:"theme.components.message.user.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"msg-assistant-radius",label:"Assistant Bubble Radius",type:"select",path:"theme.components.message.assistant.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},Dg={id:"comp-input-shape",title:"Input Shape",collapsed:!0,fields:[{id:"input-radius",label:"Border Radius",type:"select",path:"theme.components.input.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},Fg={id:"comp-button-shape",title:"Button Shape",collapsed:!0,fields:[{id:"btn-primary-radius",label:"Primary Radius",type:"select",path:"theme.components.button.primary.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.full",label:"Full"}]}]},Og={id:"comp-header-colors",title:"Header Colors",collapsed:!0,fields:[{id:"header-bg",label:"Background",type:"token-ref",path:"theme.components.header.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"header-icon-bg",label:"Icon background",type:"token-ref",path:"theme.components.header.iconBackground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"header-icon-fg",label:"Icon color",type:"token-ref",path:"theme.components.header.iconForeground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"header-title-fg",label:"Title color",type:"token-ref",path:"theme.components.header.titleForeground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"header-subtitle-fg",label:"Subtitle color",type:"token-ref",path:"theme.components.header.subtitleForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"header-action-icons-fg",label:"Clear / close icons",type:"token-ref",path:"theme.components.header.actionIconForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"header-border",label:"Border",type:"token-ref",path:"theme.components.header.border",defaultValue:"semantic.colors.border",tokenRef:{tokenType:"color"}}]},Ng={id:"comp-message-colors",title:"Message Colors",collapsed:!0,fields:[{id:"msg-user-bg",label:"User Bubble Background",type:"token-ref",path:"theme.components.message.user.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"msg-user-text",label:"User Bubble Text",type:"token-ref",path:"theme.components.message.user.text",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"msg-assistant-bg",label:"Assistant Bubble Background",type:"token-ref",path:"theme.components.message.assistant.background",defaultValue:"semantic.colors.container",tokenRef:{tokenType:"color"}},{id:"msg-assistant-text",label:"Assistant Bubble Text",type:"token-ref",path:"theme.components.message.assistant.text",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},_g={id:"comp-input-colors",title:"Input Colors",collapsed:!0,fields:[{id:"input-bg",label:"Background",type:"token-ref",path:"theme.components.input.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"input-placeholder",label:"Placeholder Color",type:"token-ref",path:"theme.components.input.placeholder",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"input-focus-border",label:"Focus Border",type:"token-ref",path:"theme.components.input.focus.border",defaultValue:"semantic.colors.interactive.focus",tokenRef:{tokenType:"color"}},{id:"input-focus-ring",label:"Focus Ring",type:"token-ref",path:"theme.components.input.focus.ring",defaultValue:"semantic.colors.interactive.focus",tokenRef:{tokenType:"color"}}]},Vg={id:"comp-button-colors",title:"Button Colors",collapsed:!0,fields:[{id:"btn-primary-bg",label:"Primary Background",type:"token-ref",path:"theme.components.button.primary.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"btn-primary-fg",label:"Primary Foreground",type:"token-ref",path:"theme.components.button.primary.foreground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"btn-secondary-bg",label:"Secondary Background",type:"token-ref",path:"theme.components.button.secondary.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"btn-secondary-fg",label:"Secondary Foreground",type:"token-ref",path:"theme.components.button.secondary.foreground",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}},{id:"btn-ghost-bg",label:"Ghost Background",type:"color",path:"theme.components.button.ghost.background",defaultValue:"transparent"},{id:"btn-ghost-fg",label:"Ghost Foreground",type:"token-ref",path:"theme.components.button.ghost.foreground",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},$g={id:"scroll-to-bottom-style",title:"Scroll To Bottom",description:"Style the floating jump-to-latest affordance.",collapsed:!0,fields:[{id:"scroll-bottom-bg",label:"Background",type:"token-ref",path:"theme.components.scrollToBottom.background",defaultValue:"components.button.primary.background",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-fg",label:"Foreground",type:"token-ref",path:"theme.components.scrollToBottom.foreground",defaultValue:"components.button.primary.foreground",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-border",label:"Border",type:"token-ref",path:"theme.components.scrollToBottom.border",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-size",label:"Size",type:"text",path:"theme.components.scrollToBottom.size",defaultValue:"40px"},{id:"scroll-bottom-radius",label:"Border Radius",type:"select",path:"theme.components.scrollToBottom.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"},{value:"palette.radius.full",label:"Full"}]},{id:"scroll-bottom-shadow",label:"Shadow",type:"select",path:"theme.components.scrollToBottom.shadow",defaultValue:"palette.shadows.sm",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]},{id:"scroll-bottom-padding",label:"Padding",type:"text",path:"theme.components.scrollToBottom.padding",defaultValue:"0.5rem 0.875rem"},{id:"scroll-bottom-gap",label:"Gap",type:"text",path:"theme.components.scrollToBottom.gap",defaultValue:"0.5rem"},{id:"scroll-bottom-font-size",label:"Font Size",type:"text",path:"theme.components.scrollToBottom.fontSize",defaultValue:"0.875rem"},{id:"scroll-bottom-icon-size",label:"Icon Size",type:"text",path:"theme.components.scrollToBottom.iconSize",defaultValue:"14px"}]},ss=[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}],bl="0 5px 15px rgba(15, 23, 42, 0.08)",Fu=[{value:bl,label:"Default"},...ss],Ug={id:"comp-shadows",title:"Component Shadows",description:"Box-shadow for chat bubbles and surfaces.",collapsed:!0,fields:[{id:"shadow-msg-user",label:"User Message",type:"select",path:"theme.components.message.user.shadow",defaultValue:"palette.shadows.sm",options:ss},{id:"shadow-msg-assistant",label:"Assistant Message",type:"select",path:"theme.components.message.assistant.shadow",defaultValue:"palette.shadows.sm",options:ss},{id:"shadow-tool-bubble",label:"Tool Call Bubble",type:"select",path:"theme.components.toolBubble.shadow",defaultValue:"palette.shadows.sm",options:ss},{id:"shadow-reasoning-bubble",label:"Reasoning Bubble",type:"select",path:"theme.components.reasoningBubble.shadow",defaultValue:"palette.shadows.sm",options:ss},{id:"shadow-approval",label:"Approval Bubble",type:"select",path:"theme.components.approval.requested.shadow",defaultValue:bl,options:Fu},{id:"shadow-intro-card",label:"Intro Card",type:"select",path:"theme.components.introCard.shadow",defaultValue:bl,options:Fu},{id:"shadow-composer",label:"Composer",type:"select",path:"theme.components.composer.shadow",defaultValue:"palette.shadows.none",options:ss}]},_u=[Wg,Bg,Hg,Dg,Fg,Ug],Vu=[Og,Ng,_g,Vg,$g],$u=[..._u,...Vu],yl=1024*1024,zg=["What can you help me with?","Tell me about your features","How does this work?"],zs={images:["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],"images-pdf":["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf"],"images-text-pdf":["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf","text/plain","text/markdown","text/csv","application/json"],all:["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"]};function qg(e){return Number(e)*yl}function jg(e){let t=Number(e);return Number.isFinite(t)?t>1024?String(Math.round(t/yl)):String(t):"10"}function Kg(e){var t;return(t=zs[String(e)])!=null?t:zs.images}function Gg(e){let t=Array.isArray(e)?e:zs.images,n=[...new Set(t)].sort();for(let[o,r]of Object.entries(zs)){let s=[...r].sort();if(n.length===s.length&&n.every((a,i)=>a===s[i]))return o}return n.some(o=>o.startsWith("application/vnd")||o==="application/msword")?"all":n.some(o=>o==="text/plain"||o==="text/markdown"||o==="text/csv")?"images-text-pdf":n.includes("application/pdf")?"images-pdf":"images"}var Yg={id:"copy",title:"Content & Copy",collapsed:!1,fields:[{id:"copy-show-welcome-card",label:"Show Welcome Card",type:"toggle",path:"copy.showWelcomeCard",defaultValue:!0},{id:"copy-welcome-title",label:"Welcome Title",type:"text",path:"copy.welcomeTitle",defaultValue:"Hello \u{1F44B}"},{id:"copy-welcome-subtitle",label:"Welcome Subtitle",type:"text",path:"copy.welcomeSubtitle",defaultValue:"Ask anything about your account or products."},{id:"copy-placeholder",label:"Input Placeholder",type:"text",path:"copy.inputPlaceholder",defaultValue:"Type your message\u2026"},{id:"copy-send-label",label:"Send Button Label",type:"text",path:"copy.sendButtonLabel",defaultValue:"Send"}]},Xg={id:"suggestions",title:"Suggestion Chips",description:"Configure chip content and styling.",collapsed:!0,fields:[{id:"suggestions-list",label:"Suggestions",description:"Add, edit, and remove chips directly.",type:"chip-list",path:"suggestionChips",defaultValue:zg}]},Jg={id:"general-layout",title:"Layout Basics",collapsed:!0,fields:[{id:"layout-show-header",label:"Show Header",type:"toggle",path:"layout.showHeader",defaultValue:!0},{id:"layout-show-footer",label:"Show Footer",type:"toggle",path:"layout.showFooter",defaultValue:!0},{id:"layout-content-max-width",label:"Content Max Width",description:"Max width for messages + composer",type:"text",path:"layout.contentMaxWidth",defaultValue:""}]},Qg={id:"header-layout",title:"Header",collapsed:!0,fields:[{id:"layout-header",label:"Header Layout",type:"select",path:"layout.header.layout",defaultValue:"default",options:[{value:"default",label:"Default"},{value:"minimal",label:"Minimal"}]},{id:"layout-show-icon",label:"Show Header Icon",type:"toggle",path:"layout.header.showIcon",defaultValue:!0},{id:"layout-show-title",label:"Show Header Title",type:"toggle",path:"layout.header.showTitle",defaultValue:!0},{id:"layout-show-subtitle",label:"Show Header Subtitle",type:"toggle",path:"layout.header.showSubtitle",defaultValue:!0},{id:"layout-show-close",label:"Show Close Button",type:"toggle",path:"layout.header.showCloseButton",defaultValue:!0},{id:"layout-show-clear",label:"Show Clear Chat",type:"toggle",path:"layout.header.showClearChat",defaultValue:!0}]},Zg={id:"messages-layout",title:"Messages",collapsed:!0,fields:[{id:"layout-messages",label:"Messages Layout",type:"select",path:"layout.messages.layout",defaultValue:"bubble",options:[{value:"bubble",label:"Bubble"},{value:"flat",label:"Flat"},{value:"minimal",label:"Minimal"}]},{id:"layout-group",label:"Group Consecutive",type:"toggle",path:"layout.messages.groupConsecutive",defaultValue:!1},{id:"layout-avatar-show",label:"Show Avatars",type:"toggle",path:"layout.messages.avatar.show",defaultValue:!1},{id:"layout-avatar-pos",label:"Avatar Position",type:"select",path:"layout.messages.avatar.position",defaultValue:"left",options:[{value:"left",label:"Left"},{value:"right",label:"Right"}]},{id:"layout-avatar-user",label:"User Avatar URL",type:"text",path:"layout.messages.avatar.userAvatar",defaultValue:""},{id:"layout-avatar-assistant",label:"Assistant Avatar URL",type:"text",path:"layout.messages.avatar.assistantAvatar",defaultValue:""},{id:"layout-timestamp-show",label:"Show Timestamps",type:"toggle",path:"layout.messages.timestamp.show",defaultValue:!1},{id:"layout-timestamp-pos",label:"Timestamp Position",type:"select",path:"layout.messages.timestamp.position",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"below",label:"Below"}]}]},eh={id:"message-actions",title:"Message Actions",collapsed:!0,fields:[{id:"msg-actions-enabled",label:"Enabled",type:"toggle",path:"messageActions.enabled",defaultValue:!0},{id:"msg-actions-copy",label:"Show Copy",type:"toggle",path:"messageActions.showCopy",defaultValue:!0},{id:"msg-actions-upvote",label:"Show Upvote",type:"toggle",path:"messageActions.showUpvote",defaultValue:!0},{id:"msg-actions-downvote",label:"Show Downvote",type:"toggle",path:"messageActions.showDownvote",defaultValue:!0},{id:"msg-actions-visibility",label:"Visibility",type:"select",path:"messageActions.visibility",defaultValue:"hover",options:[{value:"hover",label:"On Hover"},{value:"always",label:"Always Visible"}]},{id:"msg-actions-align",label:"Alignment",type:"select",path:"messageActions.align",defaultValue:"right",options:[{value:"left",label:"Left"},{value:"right",label:"Right"}]},{id:"msg-actions-layout",label:"Layout",type:"select",path:"messageActions.layout",defaultValue:"pill-inside",options:[{value:"pill-inside",label:"Pill"},{value:"row-inside",label:"Row"}]}]},th={id:"launcher-basics",title:"Launcher",collapsed:!0,fields:[{id:"launch-enabled",label:"Enabled",type:"toggle",path:"launcher.enabled",defaultValue:!0},{id:"launch-mount-mode",label:"Mount Mode",type:"select",path:"launcher.mountMode",defaultValue:"floating",options:[{value:"floating",label:"Floating"},{value:"docked",label:"Docked"}]},{id:"launch-position",label:"Position",type:"select",path:"launcher.position",defaultValue:"bottom-right",options:[{value:"bottom-right",label:"Bottom Right"},{value:"bottom-left",label:"Bottom Left"},{value:"top-right",label:"Top Right"},{value:"top-left",label:"Top Left"}]},{id:"launch-width",label:"Width",type:"text",path:"launcher.width",defaultValue:fo},{id:"launch-auto-expand",label:"Auto Expand",type:"toggle",path:"launcher.autoExpand",defaultValue:!1},{id:"launch-title",label:"Title",type:"text",path:"launcher.title",defaultValue:"Chat Assistant"},{id:"launch-subtitle",label:"Subtitle",type:"text",path:"launcher.subtitle",defaultValue:"Here to help you get answers fast"}]},nh={id:"launcher-advanced",title:"Launcher Advanced",collapsed:!0,fields:[{id:"launch-dock-side",label:"Dock Side",type:"select",path:"launcher.dock.side",defaultValue:"right",options:[{value:"right",label:"Right"},{value:"left",label:"Left"}]},{id:"launch-dock-width",label:"Dock Width",type:"text",path:"launcher.dock.width",defaultValue:"420px"},{id:"launch-dock-animate",label:"Dock Animate",type:"toggle",path:"launcher.dock.animate",defaultValue:!0},{id:"launch-dock-reveal",label:"Dock Reveal",type:"select",path:"launcher.dock.reveal",defaultValue:"resize",options:[{value:"resize",label:"Resize"},{value:"overlay",label:"Overlay"},{value:"push",label:"Push"},{value:"emerge",label:"Emerge"}]},{id:"launch-text-hidden",label:"Hide Text",type:"toggle",path:"launcher.textHidden",defaultValue:!1},{id:"launch-icon-text",label:"Agent Icon Text",type:"text",path:"launcher.agentIconText",defaultValue:"\u{1F4AC}"},{id:"launch-icon-name",label:"Agent Icon Name (Lucide)",type:"text",path:"launcher.agentIconName",defaultValue:"bot"},{id:"launch-icon-hidden",label:"Hide Agent Icon",type:"toggle",path:"launcher.agentIconHidden",defaultValue:!1},{id:"launch-icon-size",label:"Agent Icon Size",type:"slider",path:"launcher.agentIconSize",defaultValue:"40px",slider:{min:16,max:72,step:2}},{id:"launch-icon-url",label:"Icon Image URL",description:"Custom image URL (overrides emoji/lucide)",type:"text",path:"launcher.iconUrl",defaultValue:""},{id:"launch-header-icon-name",label:"Header Icon Name (Lucide)",type:"text",path:"launcher.headerIconName",defaultValue:"bot"},{id:"launch-header-icon-size",label:"Header Icon Size",type:"slider",path:"launcher.headerIconSize",defaultValue:"48px",slider:{min:24,max:80,step:2}},{id:"launch-header-icon-hidden",label:"Hide Header Icon",type:"toggle",path:"launcher.headerIconHidden",defaultValue:!1},{id:"launch-full-height",label:"Full Height",type:"toggle",path:"launcher.fullHeight",defaultValue:!1},{id:"launch-sidebar",label:"Sidebar Mode",type:"toggle",path:"launcher.sidebarMode",defaultValue:!1},{id:"launch-sidebar-width",label:"Sidebar Width",type:"text",path:"launcher.sidebarWidth",defaultValue:"420px"},{id:"launch-mobile-fullscreen",label:"Mobile Fullscreen",description:"Fullscreen on mobile devices",type:"toggle",path:"launcher.mobileFullscreen",defaultValue:!0},{id:"launch-mobile-breakpoint",label:"Mobile Breakpoint (px)",type:"text",path:"launcher.mobileBreakpoint",defaultValue:640,formatValue:e=>String(e!=null?e:640),parseValue:e=>Number(e)},{id:"launch-height-offset",label:"Height Offset (px)",type:"text",path:"launcher.heightOffset",defaultValue:0,formatValue:e=>String(e!=null?e:0),parseValue:e=>Number(e)},{id:"launch-collapsed-max-width",label:"Collapsed Max Width",description:"Max width of launcher pill when closed",type:"text",path:"launcher.collapsedMaxWidth",defaultValue:""},{id:"launch-cta-text",label:"CTA Icon Text",type:"text",path:"launcher.callToActionIconText",defaultValue:"\u2197"},{id:"launch-cta-name",label:"CTA Icon Name",type:"text",path:"launcher.callToActionIconName",defaultValue:""},{id:"launch-cta-hidden",label:"Hide CTA Icon",type:"toggle",path:"launcher.callToActionIconHidden",defaultValue:!1},{id:"launch-cta-size",label:"CTA Icon Size",type:"slider",path:"launcher.callToActionIconSize",defaultValue:"32px",slider:{min:16,max:64,step:2}},{id:"launch-cta-padding",label:"CTA Icon Padding",type:"slider",path:"launcher.callToActionIconPadding",defaultValue:"5px",slider:{min:0,max:24,step:1}},{id:"launch-cta-bg",label:"CTA Icon Background",type:"color",path:"launcher.callToActionIconBackgroundColor",defaultValue:""}]},oh={id:"send-button",title:"Send Button",collapsed:!0,fields:[{id:"send-use-icon",label:"Use Icon",type:"toggle",path:"sendButton.useIcon",defaultValue:!1},{id:"send-icon-text",label:"Icon Text",type:"text",path:"sendButton.iconText",defaultValue:"\u2191"},{id:"send-icon-name",label:"Icon Name (Lucide)",type:"text",path:"sendButton.iconName",defaultValue:""},{id:"send-size",label:"Size",type:"slider",path:"sendButton.size",defaultValue:"40px",slider:{min:24,max:64,step:2}},{id:"send-border-width",label:"Border Width",type:"slider",path:"sendButton.borderWidth",defaultValue:"0px",slider:{min:0,max:10,step:1}},{id:"send-padding-x",label:"Padding X",type:"slider",path:"sendButton.paddingX",defaultValue:"10px",slider:{min:0,max:32,step:1}},{id:"send-padding-y",label:"Padding Y",type:"slider",path:"sendButton.paddingY",defaultValue:"6px",slider:{min:0,max:32,step:1}},{id:"send-show-tooltip",label:"Show Tooltip",type:"toggle",path:"sendButton.showTooltip",defaultValue:!1},{id:"send-tooltip-text",label:"Tooltip Text",type:"text",path:"sendButton.tooltipText",defaultValue:"Send message"}]},rh={id:"close-button",title:"Close Button",collapsed:!0,fields:[{id:"close-size",label:"Size",type:"slider",path:"launcher.closeButtonSize",defaultValue:"32px",slider:{min:16,max:64,step:1}},{id:"close-placement",label:"Placement",type:"select",path:"launcher.closeButtonPlacement",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"top-right",label:"Top Right"}]},{id:"close-border-width",label:"Border Width",type:"slider",path:"launcher.closeButtonBorderWidth",defaultValue:"0px",slider:{min:0,max:8,step:1}},{id:"close-border-radius",label:"Border Radius",type:"slider",path:"launcher.closeButtonBorderRadius",defaultValue:"50%",slider:{min:0,max:100,step:1,isRadiusFull:!0}},{id:"close-icon-name",label:"Icon Name",type:"text",path:"launcher.closeButtonIconName",defaultValue:"x"},{id:"close-icon-text",label:"Icon Text",type:"text",path:"launcher.closeButtonIconText",defaultValue:"\xD7"},{id:"close-show-tooltip",label:"Show Tooltip",type:"toggle",path:"launcher.closeButtonShowTooltip",defaultValue:!0},{id:"close-tooltip-text",label:"Tooltip Text",type:"text",path:"launcher.closeButtonTooltipText",defaultValue:"Close chat"}]},sh={id:"clear-chat",title:"Clear Chat Button",collapsed:!0,fields:[{id:"clear-enabled",label:"Enabled",type:"toggle",path:"launcher.clearChat.enabled",defaultValue:!0},{id:"clear-placement",label:"Placement",type:"select",path:"launcher.clearChat.placement",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"top-right",label:"Top Right"}]},{id:"clear-icon-name",label:"Icon Name",type:"text",path:"launcher.clearChat.iconName",defaultValue:"refresh-cw"},{id:"clear-size",label:"Size",type:"slider",path:"launcher.clearChat.size",defaultValue:"32px",slider:{min:16,max:64,step:1}},{id:"clear-show-tooltip",label:"Show Tooltip",type:"toggle",path:"launcher.clearChat.showTooltip",defaultValue:!0},{id:"clear-tooltip-text",label:"Tooltip Text",type:"text",path:"launcher.clearChat.tooltipText",defaultValue:"Clear chat"}]},ah={id:"status-indicator",title:"Status Indicator",collapsed:!0,fields:[{id:"status-visible",label:"Visible",type:"toggle",path:"statusIndicator.visible",defaultValue:!0},{id:"status-align",label:"Alignment",type:"select",path:"statusIndicator.align",defaultValue:"right",options:[{value:"left",label:"Left"},{value:"center",label:"Center"},{value:"right",label:"Right"}]},{id:"status-idle-text",label:"Idle Text",type:"text",path:"statusIndicator.idleText",defaultValue:"Online"},{id:"status-connecting-text",label:"Connecting Text",type:"text",path:"statusIndicator.connectingText",defaultValue:"Connecting\u2026"},{id:"status-connected-text",label:"Connected Text",type:"text",path:"statusIndicator.connectedText",defaultValue:"Streaming\u2026"},{id:"status-error-text",label:"Error Text",type:"text",path:"statusIndicator.errorText",defaultValue:"Offline"}]},ih={id:"features",title:"Features",collapsed:!0,fields:[{id:"feat-voice",label:"Voice Recognition",description:"Enable voice input",type:"toggle",path:"voiceRecognition.enabled",defaultValue:!1},{id:"feat-auto-focus",label:"Auto Focus Input",description:"Focus input after panel opens",type:"toggle",path:"autoFocusInput",defaultValue:!1},{id:"feat-scroll-bottom-enabled",label:"Scroll To Bottom",description:"Show a jump-to-latest affordance when the user scrolls away from new content",type:"toggle",path:"features.scrollToBottom.enabled",defaultValue:!0},{id:"feat-scroll-bottom-icon",label:"Scroll To Bottom Icon",type:"text",path:"features.scrollToBottom.iconName",defaultValue:"arrow-down"},{id:"feat-scroll-bottom-label",label:"Scroll To Bottom Label",description:"Leave empty for icon-only mode",type:"text",path:"features.scrollToBottom.label",defaultValue:""}]},lh={id:"stream-animation",title:"Stream Animation",description:"Control how assistant text appears while streaming.",collapsed:!0,fields:[{id:"stream-anim-type",label:"Animation",description:"Reveal effect applied to each assistant reply as it streams.",type:"select",path:"features.streamAnimation.type",defaultValue:"none",options:[{value:"none",label:"None"},{value:"typewriter",label:"Typewriter"},{value:"word-fade",label:"Word fade"},{value:"letter-rise",label:"Letter rise"},{value:"glyph-cycle",label:"Glyph cycle"},{value:"wipe",label:"Wipe"},{value:"pop-bubble",label:"Pop bubble"}]},{id:"stream-anim-placeholder",label:"Pre-first-token Placeholder",description:"What to show before the first token arrives.",type:"select",path:"features.streamAnimation.placeholder",defaultValue:"none",options:[{value:"none",label:"Typing indicator (default)"},{value:"skeleton",label:"Skeleton shimmer"}]},{id:"stream-anim-buffer",label:"Content Buffering",description:"Trim in-progress units so only complete words/lines reveal.",type:"select",path:"features.streamAnimation.buffer",defaultValue:"none",options:[{value:"none",label:"None \u2014 stream every character"},{value:"word",label:"Word \u2014 hold until whitespace"},{value:"line",label:"Line \u2014 hold until newline"}]},{id:"stream-anim-speed",label:"Per-unit Duration (ms)",description:"Animation length for each character or word.",type:"select",path:"features.streamAnimation.speed",defaultValue:120,options:[{value:"40",label:"40ms \u2014 snappy"},{value:"80",label:"80ms"},{value:"120",label:"120ms (default)"},{value:"200",label:"200ms"},{value:"320",label:"320ms"},{value:"480",label:"480ms \u2014 slow"}],formatValue:e=>String(e!=null?e:120),parseValue:e=>Number(e)},{id:"stream-anim-duration",label:"Container Duration (ms)",description:"Length of container-level effects (pop-bubble, custom plugins).",type:"select",path:"features.streamAnimation.duration",defaultValue:1800,options:[{value:"600",label:"600ms"},{value:"1200",label:"1200ms"},{value:"1800",label:"1800ms (default)"},{value:"2400",label:"2400ms"},{value:"3600",label:"3600ms \u2014 slow"}],formatValue:e=>String(e!=null?e:1800),parseValue:e=>Number(e)}]},ch={id:"attachments-config",title:"Attachments",collapsed:!0,fields:[{id:"attach-enabled",label:"Enabled",type:"toggle",path:"attachments.enabled",defaultValue:!1},{id:"attach-max-files",label:"Max Files",type:"select",path:"attachments.maxFiles",defaultValue:4,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"4",label:"4"},{value:"6",label:"6"},{value:"8",label:"8"},{value:"10",label:"10"}],formatValue:e=>String(e!=null?e:4),parseValue:e=>Number(e)},{id:"attach-max-size",label:"Max File Size (MB)",type:"select",path:"attachments.maxFileSize",defaultValue:10*yl,options:[{value:"1",label:"1 MB"},{value:"5",label:"5 MB"},{value:"10",label:"10 MB"},{value:"25",label:"25 MB"},{value:"50",label:"50 MB"}],formatValue:jg,parseValue:qg},{id:"attach-types",label:"Allowed File Types",type:"select",path:"attachments.allowedTypes",defaultValue:zs.images,options:[{value:"images",label:"Images only"},{value:"images-pdf",label:"Images + PDF"},{value:"images-text-pdf",label:"Images + text + PDF"},{value:"all",label:"All supported types"}],formatValue:Gg,parseValue:Kg}]},dh={id:"artifacts-config",title:"Artifacts",collapsed:!0,fields:[{id:"art-enabled",label:"Enabled",description:"Show artifact sidebar for documents and components",type:"toggle",path:"features.artifacts.enabled",defaultValue:!1},{id:"art-appearance",label:"Pane Appearance",type:"select",path:"features.artifacts.layout.paneAppearance",defaultValue:"panel",options:[{value:"panel",label:"Panel (bordered)"},{value:"seamless",label:"Seamless"}]}]},ph={id:"artifacts-customization",title:"Artifact Customization",collapsed:!0,fields:[{id:"art-toolbar",label:"Toolbar Preset",type:"select",path:"features.artifacts.layout.toolbarPreset",defaultValue:"default",options:[{value:"default",label:"Default"},{value:"document",label:"Document"}]},{id:"art-pane-width",label:"Pane Width",description:"CSS width (e.g. 40%, 28rem)",type:"text",path:"features.artifacts.layout.paneWidth",defaultValue:"40%"},{id:"art-pane-max-width",label:"Pane Max Width",type:"text",path:"features.artifacts.layout.paneMaxWidth",defaultValue:"28rem"},{id:"art-split-gap",label:"Split Gap",type:"text",path:"features.artifacts.layout.splitGap",defaultValue:"0.5rem"},{id:"art-pane-bg",label:"Pane Background",type:"color",path:"features.artifacts.layout.paneBackground",defaultValue:""},{id:"art-unified",label:"Unified Split Chrome",description:"Wrap chat and artifact in a single container",type:"toggle",path:"features.artifacts.layout.unifiedSplitChrome",defaultValue:!1},{id:"art-resizable",label:"Resizable",description:"Allow dragging the pane divider",type:"toggle",path:"features.artifacts.layout.resizable",defaultValue:!1},{id:"art-expand-panel",label:"Expand Panel When Open",description:"Widen the launcher panel to fit artifacts",type:"toggle",path:"features.artifacts.layout.expandLauncherPanelWhenOpen",defaultValue:!0}]},uh={id:"api-integration",title:"API & Integration",description:"Runtime and integration options.",collapsed:!0,fields:[{id:"dev-api-url",label:"API URL",type:"text",path:"apiUrl",defaultValue:""},{id:"dev-flow",label:"Flow ID",type:"text",path:"flowId",defaultValue:""},{id:"dev-parser",label:"Stream Parser",type:"select",path:"parserType",defaultValue:"plain",options:[{value:"plain",label:"Plain Text"},{value:"json",label:"JSON"},{value:"regex-json",label:"Regex JSON"},{value:"xml",label:"XML"}]}]},mh={id:"debug-inspection",title:"Debug & Inspection",collapsed:!0,fields:[{id:"dev-reasoning",label:"Show Reasoning",description:"Display AI reasoning steps",type:"toggle",path:"features.showReasoning",defaultValue:!1},{id:"dev-tool-calls",label:"Show Tool Calls",description:"Display tool call details",type:"toggle",path:"features.showToolCalls",defaultValue:!1},{id:"dev-tool-collapsed-mode",label:"Tool Call Summary",description:"Choose what collapsed tool rows show by default",type:"select",path:"features.toolCallDisplay.collapsedMode",defaultValue:"tool-call",options:[{value:"tool-call",label:"Tool Call"},{value:"tool-name",label:"Tool Name"},{value:"tool-preview",label:"Tool Preview"}]},{id:"dev-tool-active-preview",label:"Tool Preview While Active",description:"Show a lightweight preview in collapsed active tool rows",type:"toggle",path:"features.toolCallDisplay.activePreview",defaultValue:!1},{id:"dev-tool-preview-lines",label:"Tool Preview Lines",type:"select",path:"features.toolCallDisplay.previewMaxLines",defaultValue:3,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"3",label:"3"},{value:"4",label:"4"},{value:"5",label:"5"}],formatValue:e=>String(e!=null?e:3),parseValue:e=>Number(e)},{id:"dev-tool-active-min-height",label:"Tool Active Min Height",description:"CSS min-height for collapsed active tool rows (e.g. 5rem)",type:"text",path:"features.toolCallDisplay.activeMinHeight",defaultValue:""},{id:"dev-tool-expandable",label:"Tool Calls Expandable",description:"Allow expanding tool call rows to see full details",type:"toggle",path:"features.toolCallDisplay.expandable",defaultValue:!0},{id:"dev-tool-grouped",label:"Group Sequential Tool Calls",description:"Render consecutive tool rows inside a grouped container",type:"toggle",path:"features.toolCallDisplay.grouped",defaultValue:!1},{id:"dev-reasoning-expandable",label:"Reasoning Expandable",description:"Allow expanding reasoning rows to see full details",type:"toggle",path:"features.reasoningDisplay.expandable",defaultValue:!0},{id:"dev-reasoning-active-preview",label:"Reasoning Preview While Active",description:"Show a lightweight preview in collapsed active reasoning rows",type:"toggle",path:"features.reasoningDisplay.activePreview",defaultValue:!1},{id:"dev-reasoning-preview-lines",label:"Reasoning Preview Lines",type:"select",path:"features.reasoningDisplay.previewMaxLines",defaultValue:3,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"3",label:"3"},{value:"4",label:"4"},{value:"5",label:"5"}],formatValue:e=>String(e!=null?e:3),parseValue:e=>Number(e)},{id:"dev-reasoning-active-min-height",label:"Reasoning Active Min Height",description:"CSS min-height for collapsed active reasoning rows (e.g. 5rem)",type:"text",path:"features.reasoningDisplay.activeMinHeight",defaultValue:""},{id:"dev-debug",label:"Debug Mode",description:"Show debug information",type:"toggle",path:"debug",defaultValue:!1}]},fh={id:"markdown",title:"Markdown Options",collapsed:!0,fields:[{id:"md-gfm",label:"GitHub Flavored Markdown",type:"toggle",path:"markdown.options.gfm",defaultValue:!0},{id:"md-breaks",label:"Line Breaks",type:"toggle",path:"markdown.options.breaks",defaultValue:!0},{id:"md-header-ids",label:"Header IDs",type:"toggle",path:"markdown.options.headerIds",defaultValue:!1},{id:"md-pedantic",label:"Pedantic Mode",type:"toggle",path:"markdown.options.pedantic",defaultValue:!1},{id:"md-silent",label:"Silent",type:"toggle",path:"markdown.options.silent",defaultValue:!1},{id:"md-disable-styles",label:"Disable Default Styles",type:"toggle",path:"markdown.disableDefaultStyles",defaultValue:!1}]},Ja=[{label:"Content",sections:[Yg,Xg]},{label:"Layout",sections:[Jg,Qg,Zg,eh]},{label:"Widget",sections:[th,nh,oh,rh,sh,ah]},{label:"Features",sections:[ih,lh,ch,dh,ph]},{label:"Developer",collapsedByDefault:!0,sections:[uh,mh,fh]}],Uu=Ja.flatMap(e=>e.sections),zu={id:"theme-mode-v2",title:"Theme",description:"Choose how the interface adapts across light and dark mode.",collapsed:!1,fields:[{id:"color-mode",label:"Color Mode",type:"select",path:"colorScheme",defaultValue:"auto",options:[{value:"auto",label:"Auto"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}]}]},qu={id:"brand-palette-v2",title:"Brand Palette",description:"Set your brand, accent, and neutral colors. These are used to generate the interface theme.",collapsed:!1,fields:[{id:"bp-primary",label:"Primary",description:"Main brand color",type:"color",path:"theme.palette.colors.primary.500",defaultValue:"#171717"},{id:"bp-secondary",label:"Secondary",description:"Supporting brand color",type:"color",path:"theme.palette.colors.secondary.500",defaultValue:"#8b5cf6"},{id:"bp-accent",label:"Accent",description:"Highlight and decorative color",type:"color",path:"theme.palette.colors.accent.500",defaultValue:"#06b6d4"},{id:"bp-neutral",label:"Neutral",description:"Backgrounds, text, and borders",type:"color",path:"theme.palette.colors.gray.500",defaultValue:"#6b7280"}]},ju={id:"status-palette",title:"Status Palette",description:"Colors for system feedback states.",collapsed:!0,fields:[{id:"sp-success",label:"Success",type:"color",path:"theme.palette.colors.success.500",defaultValue:"#22c55e"},{id:"sp-warning",label:"Warning",type:"color",path:"theme.palette.colors.warning.500",defaultValue:"#eab308"},{id:"sp-error",label:"Error",type:"color",path:"theme.palette.colors.error.500",defaultValue:"#ef4444"},{id:"sp-notice",label:"Notice",description:"Info and notice states",type:"color",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500"}]},Ku={id:"interface-roles",title:"Interface Roles",description:"Control where brand and neutral colors appear across the interface.",collapsed:!1,fields:[{id:"role-surfaces",label:"Background Surfaces",type:"role-assignment",path:"theme.semantic.colors.background",roleAssignment:Va},{id:"role-header",label:"Header",type:"role-assignment",path:"theme.components.header.background",roleAssignment:$a},{id:"role-user-messages",label:"User Messages",type:"role-assignment",path:"theme.components.message.user.background",roleAssignment:Ua},{id:"role-assistant-messages",label:"Assistant Messages",type:"role-assignment",path:"theme.components.message.assistant.background",roleAssignment:za},{id:"role-primary-actions",label:"Primary Actions",type:"role-assignment",path:"theme.components.button.primary.background",roleAssignment:qa},{id:"role-scroll-to-bottom",label:"Scroll To Bottom",type:"role-assignment",path:"theme.components.scrollToBottom.background",roleAssignment:ja},{id:"role-input",label:"Input Field",type:"role-assignment",path:"theme.components.input.background",roleAssignment:Ka},{id:"role-links-focus",label:"Links & Focus",type:"role-assignment",path:"theme.semantic.colors.accent",roleAssignment:Ga},{id:"role-borders",label:"Borders & Dividers",type:"role-assignment",path:"theme.semantic.colors.border",roleAssignment:Ya}]},Gu={id:"status-colors",title:"Status Colors",description:"Used for system states like success, warning, notice, and error.",collapsed:!0,fields:[{id:"sc-notice",label:"Notice",type:"token-ref",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sc-success",label:"Success",type:"token-ref",path:"theme.semantic.colors.feedback.success",defaultValue:"palette.colors.success.500",tokenRef:{tokenType:"color"}},{id:"sc-warning",label:"Warning",type:"token-ref",path:"theme.semantic.colors.feedback.warning",defaultValue:"palette.colors.warning.500",tokenRef:{tokenType:"color"}},{id:"sc-error",label:"Error",type:"token-ref",path:"theme.semantic.colors.feedback.error",defaultValue:"palette.colors.error.500",tokenRef:{tokenType:"color"}}]},Yu={id:"advanced-tokens",title:"Advanced Tokens",description:"Override individual semantic and component values when you need precise control.",collapsed:!0,fields:[]},gh=[zu,qu,ju,Ku,Gu,Yu],vl=[{id:"style",label:"Style",sections:as},{id:"design-system",label:"Design System",sections:$u},{id:"configure",label:"Configure",sections:Uu}];function Xu(e,t){return e.startsWith("theme.")?e.replace(/^theme\./,`${t}.`):e}function hh(e,t,n){return{...e,id:`${n}-${e.id}`,path:Xu(e.path,t)}}function bh(e,t){let n=e.find(o=>o.id===t);if(!n)throw new Error(`Section "${t}" not found in definitions`);return n}function yh(e,t,n,o=e.collapsed){var a;let r=n==="light"?"Light":"Dark",s=n==="light"?"Applies when the widget is in light mode.":"Applies when the widget is in dark mode.";return{...e,id:`${n}-${e.id}`,title:`${r} ${e.title}`,description:e.description?`${s} ${e.description}`:s,collapsed:o,fields:e.fields.map(i=>hh(i,t,n)),presets:(a=e.presets)==null?void 0:a.map(i=>({...i,id:`${n}-${i.id}`,values:Object.fromEntries(Object.entries(i.values).map(([d,l])=>[Xu(d,t),l]))}))}}var Ju=[{id:"default-light",name:"Default Light",description:"Clean monochrome light theme",theme:{components:{artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}}},preview:{primary:"#171717",surface:"#ffffff",accent:"#0f0f0f"},tags:["light"]},{id:"default-dark",name:"Default Dark",description:"Monochrome dark theme",theme:{palette:{colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},semantic:{colors:{primary:"palette.colors.primary.400",secondary:"palette.colors.gray.400",accent:"palette.colors.primary.500",surface:"palette.colors.gray.800",background:"palette.colors.gray.900",container:"palette.colors.gray.800",text:"palette.colors.gray.100",textMuted:"palette.colors.gray.400",textInverse:"palette.colors.gray.900",border:"palette.colors.gray.700",divider:"palette.colors.gray.700",interactive:{default:"palette.colors.primary.400",hover:"palette.colors.primary.300",focus:"palette.colors.primary.500",active:"palette.colors.primary.600",disabled:"palette.colors.gray.600"},feedback:{success:"palette.colors.success.400",warning:"palette.colors.warning.400",error:"palette.colors.error.400",info:"palette.colors.primary.400"}}}},preview:{primary:"#171717",surface:"#1f2937",accent:"#0f0f0f"},tags:["dark"]},{id:"high-contrast",name:"High Contrast",description:"Maximum contrast for accessibility",theme:{semantic:{colors:{primary:"palette.colors.primary.700",secondary:"palette.colors.gray.700",accent:"palette.colors.primary.800",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.200",text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.400",divider:"palette.colors.gray.400",interactive:{default:"palette.colors.primary.700",hover:"palette.colors.primary.800",focus:"palette.colors.primary.900",active:"palette.colors.primary.950",disabled:"palette.colors.gray.400"},feedback:{success:"palette.colors.success.700",warning:"palette.colors.warning.700",error:"palette.colors.error.700",info:"palette.colors.primary.700"}}}},preview:{primary:"#0a0a0a",surface:"#f9fafb",accent:"#050505"},tags:["light","high-contrast","accessibility"]}],qs=[...Ju];function xl(e){return qs.find(t=>t.id===e)}import{Marked as vh}from"marked";var xh=e=>{if(e)return e},wl=e=>{var r,s;let t=e==null?void 0:e.markedOptions,n=new vh({gfm:(r=t==null?void 0:t.gfm)!=null?r:!0,breaks:(s=t==null?void 0:t.breaks)!=null?s:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),o=xh(e==null?void 0:e.renderer);return o&&n.use({renderer:o}),a=>n.parse(a)},Qa=e=>e?wl({markedOptions:e.options,renderer:e.renderer}):wl(),Kw=wl();var js=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");import wh from"dompurify";var Ch={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},Sh=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ah=()=>{let e=wh(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(t,n)=>{if(n.attrName==="src"||n.attrName==="href"){let o=n.attrValue;o.toLowerCase().startsWith("data:")&&!Sh.test(o)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,Ch)},Za=e=>e===!1?null:typeof e=="function"?e:Ah();var Pr="webmcp:",Cl=new Map,Qu=e=>{var t;Cl.clear();for(let n of e){let o=(t=n.title)==null?void 0:t.trim();o&&Cl.set(n.name,o)}},Sl=e=>Cl.get(tm(e)),ei={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function em(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var o,r;return[n.name,(o=n.description)!=null?o:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(r=n.origin)!=null?r:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${Th(t.join(""))}`}function Zu(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function Th(e){let t=Zu(e,0).toString(36),n=Zu(e,2654435761).toString(36);return`${t}.${n}`}var ti=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return ei.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",r),[]}Qu(n);let o=typeof location!="undefined"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=Eh(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Ao("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let C=typeof document!="undefined"&&!!document.modelContext;return Ao(C?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=tm(t),a;try{a=await r.getTools()}catch(C){let v=C instanceof Error?C.message:String(C);return Ao(`Failed to read WebMCP registry: ${v}`)}Qu(a);let i=a.find(C=>C.name===s);if(!i)return Ao(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Ao(`WebMCP tool not allowed by client allowlist: ${s}`);if(o!=null&&o.aborted)return Ao("Aborted by cancel()");let d=Sl(s),l={toolName:s,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(l))return Ao("User declined the tool call.");if(o!=null&&o.aborted)return Ao("Aborted by cancel()");let f=new AbortController,u=!1,g=setTimeout(()=>{u=!0,f.abort()},this.timeoutMs),m=()=>f.abort();o&&(o.aborted?f.abort():o.addEventListener("abort",m,{once:!0}));try{let C=await r.executeTool(i,Rh(n),{signal:f.signal});return Mh(C)}catch(C){if(u)return Ao(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return Ao("Aborted by cancel()");let v=C instanceof Error?C.message:String(C);return Ao(v)}finally{clearTimeout(g),o&&o.removeEventListener("abort",m)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){ei.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,ei.warn("document.modelContext is present but does not expose getTools()/executeTool() \u2014 WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var o;let n=(o=this.confirmHandler)!=null?o:Lh;try{return await n(t)}catch(r){return ei.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,r),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>kh(t,o))}},tm=e=>e.startsWith(Pr)?e.slice(Pr.length):e,is=e=>e.startsWith(Pr),kh=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Eh=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Mh=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:Ph(t)}]}},Ao=e=>({isError:!0,content:[{type:"text",text:e}]}),Lh=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Ih(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
2
2
|
|
|
3
3
|
Arguments:
|
|
4
4
|
${t}`:"")+(e.description?`
|
|
5
5
|
|
|
6
|
-
${e.description}`:"");return window.confirm(n)},
|
|
7
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
6
|
+
${e.description}`:"");return window.confirm(n)},Ih=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},Rh=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Ph=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};import{parse as Wh,STR as Bh,OBJ as Hh}from"partial-json";var nm=e=>e.replace(/\\n/g,`
|
|
7
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ls=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Dh=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},om=e=>e.status==="complete"?Dh(e):e.status==="pending"?"Waiting":"",Fh=e=>{var r,s,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((a=(s=e.startedAt)!=null?s:e.completedAt)!=null?a:Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var rm=e=>e.status==="complete"?Fh(e):"Using tool...",ni=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Gs=e=>{var n,o,r;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((r=(o=e.startedAt)!=null?o:e.completedAt)!=null?r:Date.now()));return ni(t)},oi=e=>{var n,o,r;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((r=(o=e.startedAt)!=null?o:e.completedAt)!=null?r:Date.now()));return ni(t)},Al=(e,t,n)=>{var s;if(!t)return n;let o=((s=e.name)==null?void 0:s.trim())||"tool",r=Gs(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},ri=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Ks(o,n.slice(s,a.index),[]),a[1]!==void 0?Ks(o,a[1],["bold"]):a[2]!==void 0?Ks(o,a[2],["italic"]):a[3]!==void 0&&Ks(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Ks(o,n.slice(s),[]),o},Ks=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Oh=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
|
|
8
8
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=o.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
|
|
9
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Cr=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},ku=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Eu=()=>{var t;let e=Kg();return{processChunk:async n=>{let o=n.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},Mu=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=$g(n,Ug|zg);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Su(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Su(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var Lu=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Ya=class{constructor(t,n=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=n}push(t,n){var s,a,i;let o=(i=(s=n==null?void 0:n.seq)!=null?s:n==null?void 0:n.sequenceIndex)!=null?i:(a=n==null?void 0:n.agentContext)==null?void 0:a.seq;if(o==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,n);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),o===this.nextExpectedSeq){this.emitter(t,n),this.nextExpectedSeq=o+1,this.drainConsecutive();return}if(o<this.nextExpectedSeq){this.emitter(t,n);return}let r=this.buffer.get(o);r!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${o} (${r.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(r.payloadType,r.payload)),this.buffer.set(o,{payloadType:t,payload:n,seq:o}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((n,o)=>n[0]-o[0]);for(let[n,o]of t)this.buffer.delete(n),this.emitter(o.payloadType,o.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Gg="https://api.runtype.com/v1/dispatch",Xa="https://api.runtype.com";function Yg(e){var s,a;let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let i=(a=(s=t.slice(r+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var ll=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Xg(e){switch(e){case"json":return Mu;case"regex-json":return Eu;case"xml":return Lu;default:return ku}}var Iu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Qg(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=Iu(n);if(!Iu(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Cr(e);return Cr(t)!==null&&a===null?t:e}var Ws=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,o,r,s;this.apiUrl=(n=t.apiUrl)!=null?n:Gg,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:Xg(t.parserType),this.contextProviders=(r=t.contextProviders)!=null?r:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new qa(t.webmcp):null}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Xa}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let o=await this.sessionInitPromise;return this.clientSession=o,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,o),o}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let t=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},o=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){let i=await o.json().catch(()=>({error:"Session initialization failed"}));throw o.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):o.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let r=await o.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(r.sessionId),{sessionId:r.sessionId,expiresAt:new Date(r.expiresAt),flow:r.flow,config:{welcomeMessage:r.config.welcomeMessage,placeholder:r.config.placeholder,theme:r.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Xa}/v1/client/feedback`}async sendFeedback(t){var s,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var r,s,a,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(r=this.config).onSessionExpired)==null||s.call(r);let D=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:D}),D}let l=await this.buildPayload(t.messages),m=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([D])=>D!=="sessionId"&&D!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(ll).map(D=>{var W,v,x;return{id:D.id,role:D.role,content:(x=(v=(W=D.contentParts)!=null?W:D.llmContent)!=null?v:D.rawContent)!=null?x:D.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...m&&Object.keys(m).length>0&&{metadata:m},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},g=l.clientTools,p=!!(g&&g.length>0),w=p?Cu(g):void 0,S=this.clientToolsFingerprintSessionId===d.sessionId,M=p&&S&&this.lastSentClientToolsFingerprint===w,I=!1,L=null,H;for(let D=0;;D++){let v={...u,...p&&(I||!M)&&g?{clientTools:g}:{},...w?{clientToolsFingerprint:w}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",v),H=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v),signal:o.signal}),H.status===409&&D===0&&p){let x=await H.json().catch(()=>null);if((x==null?void 0:x.error)==="client_tools_resend_required"){I=!0,this.lastSentClientToolsFingerprint=null;continue}L=x!=null?x:{error:"Chat request failed"}}break}if(!H.ok){let D=L!=null?L:await H.json().catch(()=>({error:"Chat request failed"}));if(H.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let v=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:v}),v}if(H.status===429){let v=new Error(D.hint||"Message limit reached for this session.");throw n({type:"error",error:v}),v}let W=new Error(D.error||"Failed to send message");throw n({type:"error",error:W}),W}if(!H.body){let D=new Error("No response body received");throw n({type:"error",error:D}),D}this.lastSentClientToolsFingerprint=w!=null?w:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(H.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let r=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Xa}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,o){var l,m;let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Xa}/resume`,a;r&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(m=o==null?void 0:o.streamResponse)!=null?m:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var s;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(ll).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),o={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},r=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(r&&r.length>0&&(o.clientTools=r),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(o.context=a)}return o}async buildPayload(t){var s;let o={messages:t.slice().filter(ll).sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},r=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(r&&r.length>0&&(o.clientTools=r),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(o.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...o},config:this.config});if(a&&typeof a=="object"){let i=a;return o.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=o.clientTools),i}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return o}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=m=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...m!==void 0&&{partId:m}};return o.current=u,r(u),u},l=m=>o.current?o.current:d(m);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let m=l(i.partId);i.partId!==void 0&&!m.partId&&(m.partId=i.partId),m.content+=i.text,r(m)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o){var ln,Dn,Jn,qe;let r=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,m=_=>{let ke=_.reasoning?{..._.reasoning,chunks:[..._.reasoning.chunks]}:void 0,De=_.toolCall?{..._.toolCall,chunks:_.toolCall.chunks?[..._.toolCall.chunks]:void 0}:void 0,Fe=_.tools?_.tools.map($e=>({...$e,chunks:$e.chunks?[...$e.chunks]:void 0})):void 0;return{..._,reasoning:ke,toolCall:De,tools:Fe}},u=_=>{if(_.role!=="assistant"||_.variant)return!0;let ke=Array.isArray(_.contentParts)&&_.contentParts.length>0,De=typeof _.rawContent=="string"&&_.rawContent.trim()!=="";return typeof _.content=="string"&&_.content.trim()!==""||ke||De||!!_.stopReason},g=_=>{u(_)&&n({type:"message",message:m(_)})},p=null,w=null,S={current:null},M={current:null},I=!1,L=new Map,H=new Map,D=new Map,W=new Map,v={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},k=(_,ke,De="")=>`${_}::${ke}::${De}`,C=(_,ke)=>`${_}::${ke}::`,T=(_,ke,De,Fe)=>{let $e=k(_,ke,De),dt=D.get($e);if(dt)return dt;let ot=De?`-${De}`:"",At={id:`nested-${_}-${ke}${ot}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...De?{partId:De}:{},agentMetadata:{executionId:Fe,parentToolId:_,parentStepId:ke}};return D.set($e,At),g(At),At},F=_=>{if(_==null)return null;try{return String(_)}catch{return null}},$=_=>{var ke,De,Fe,$e,dt;return F((dt=($e=(Fe=(De=(ke=_.stepId)!=null?ke:_.step_id)!=null?De:_.step)!=null?Fe:_.parentId)!=null?$e:_.flowStepId)!=null?dt:_.flow_step_id)},j=_=>{var ke,De,Fe,$e,dt,ot,At;return F((At=(ot=(dt=($e=(Fe=(De=(ke=_.callId)!=null?ke:_.call_id)!=null?De:_.requestId)!=null?Fe:_.request_id)!=null?$e:_.toolCallId)!=null?dt:_.tool_call_id)!=null?ot:_.stepId)!=null?At:_.step_id)},me=o,se=!1,fe=()=>{if(p)return p;let _;return!se&&me?(_=me,se=!0):me&&M.current?_=`${me}_${M.current}`:_=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,p={id:_,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},g(p),p},ie=(_,ke)=>{v.lastId=ke,_&&v.byStep.set(_,ke)},be=(_,ke)=>{var dt;let De=(dt=_.reasoningId)!=null?dt:_.id,Fe=$(_);if(De){let ot=String(De);return ie(Fe,ot),ot}if(Fe){let ot=v.byStep.get(Fe);if(ot)return v.lastId=ot,ot}if(v.lastId&&!ke)return v.lastId;if(!ke)return null;let $e=`reason-${l()}`;return ie(Fe,$e),$e},Oe=_=>{let ke=L.get(_);if(ke)return ke;let De={id:`reason-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:_,status:"streaming",chunks:[]}};return L.set(_,De),g(De),De},ve=(_,ke)=>{x.lastId=ke,_&&x.byCall.set(_,ke)},Q=new Set,Le=new Map,Y=new Set,xe=new Map,Se=_=>{if(!_)return!1;let ke=_.replace(/_+/g,"_").replace(/^_|_$/g,"");return ke==="emit_artifact_markdown"||ke==="emit_artifact_component"},de=(_,ke)=>{var dt;let De=(dt=_.toolId)!=null?dt:_.id,Fe=j(_);if(De){let ot=String(De);return ve(Fe,ot),ot}if(Fe){let ot=x.byCall.get(Fe);if(ot)return x.lastId=ot,ot}if(x.lastId&&!ke)return x.lastId;if(!ke)return null;let $e=`tool-${l()}`;return ve(Fe,$e),$e},we=_=>{let ke=H.get(_);if(ke)return ke;let De={id:`tool-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:_,status:"pending"}};return H.set(_,De),g(De),De},ze=_=>{if(typeof _=="number"&&Number.isFinite(_))return _;if(typeof _=="string"){let ke=Number(_);if(!Number.isNaN(ke)&&Number.isFinite(ke))return ke;let De=Date.parse(_);if(!Number.isNaN(De))return De}return Date.now()},te=_=>{if(typeof _=="string")return _;if(_==null)return"";try{return JSON.stringify(_)}catch{return String(_)}},ne=new Map,re=new Map,nt=new Map,ye=new Map,le=null,Ue=(_,ke,De)=>{var At;let Fe=nt.get(_);Fe||(Fe=[],nt.set(_,Fe));let $e=0,dt=Fe.length;for(;$e<dt;){let Vt=$e+dt>>>1;Fe[Vt].seq<ke?$e=Vt+1:dt=Vt}((At=Fe[$e])==null?void 0:At.seq)===ke?Fe[$e]={seq:ke,text:De}:Fe.splice($e,0,{seq:ke,text:De});let ot="";for(let Vt=0;Vt<Fe.length;Vt++)ot+=Fe[Vt].text;return ot},He=(_,ke)=>{let De=te(ke),Fe=re.get(_.id),$e=Qg(Fe,De);_.rawContent=$e;let dt=ne.get(_.id),ot=Qe=>{var oe;let Ft=(oe=_.content)!=null?oe:"";Qe.trim()!==""&&(Ft.trim().length===0||Qe.startsWith(Ft)||Qe.trimStart().startsWith(Ft.trim()))&&(_.content=Qe)},At=()=>{var Qe;if(dt){let Ft=(Qe=dt.close)==null?void 0:Qe.call(dt);Ft instanceof Promise&&Ft.catch(()=>{})}ne.delete(_.id),re.delete(_.id),_.streaming=!1,g(_)};if(!dt){ot(De),At();return}let Vt=Cr($e);if(Vt!==null&&Vt.trim()!==""){ot(Vt),At();return}let q=Qe=>{var ge;let Ft=typeof Qe=="string"?Qe:(ge=Qe==null?void 0:Qe.text)!=null?ge:null;if(Ft!==null&&Ft.trim()!=="")return Ft;let oe=dt.getExtractedText();return oe!==null&&oe.trim()!==""?oe:De},_t;try{_t=dt.processChunk($e)}catch{ot(De),At();return}if(_t instanceof Promise){_t.then(Qe=>{ot(q(Qe)),At()}).catch(()=>{ot(De),At()});return}ot(q(_t)),At()},ce=[],G=!1,Ve,Et=()=>{G||(G=!0,queueMicrotask(()=>{G=!1,Ve()}))},pe=new Ya((_,ke)=>{ce.push({payloadType:_,payload:ke}),Et()}),ae=null,Ln=new Map,Nt=(ln=this.config.iterationDisplay)!=null?ln:"separate";for(Ve=()=>{var _,ke,De,Fe,$e,dt,ot,At,Vt,q,_t,Qe,Ft,oe,ge,xt,$t,Jt,yn,Tt,wt,gt,bt,zt,et,Fn,Zn,vn,On,ut,wo,Nn,ir,In,Rr,$o,Lo,yt,_n,Vn,xn,It,eo,to,$n,Uo,Io,zo,Un,Wt,wn,no,qo,Ro,jo,Co,zn,po,ft,Kt,Gt,qn,Ko,oo,uo,jn,E,Kn,mo,Po,So,as,fo,go,ho,Wo,lr,aa,is,ia,Pr,mt,ls,ro,Rn,la,ca,Wr,Bo,da,cr,cs,Ho,ds,Go,Yo,pa,ua,zi,dr,Xo,ma,ps,Qo,fa,us,Jo,ms,ga,Do,ha,Zo,Bt,Br,Hr,fs,Ao,ba,gs,hs,ya,Dr,Fr,pr,va,xa,bs,ys,vs,xs,Cn,Gn,Fo,rt,ws,ur,bo,wa;for(let er=0;er<ce.length;er++){let Ke=ce[er].payloadType,A=ce[er].payload;if(Ke==="reason_start"){let U=(_=be(A,!0))!=null?_:`reason-${l()}`,B=Oe(U);B.reasoning=(ke=B.reasoning)!=null?ke:{id:U,status:"streaming",chunks:[]},B.reasoning.startedAt=(Fe=B.reasoning.startedAt)!=null?Fe:ze((De=A.startedAt)!=null?De:A.timestamp),B.reasoning.completedAt=void 0,B.reasoning.durationMs=void 0,B.streaming=!0,B.reasoning.status="streaming",g(B)}else if(Ke==="reason_delta"||Ke==="reason_chunk"){let U=(dt=($e=be(A,!1))!=null?$e:be(A,!0))!=null?dt:`reason-${l()}`,B=Oe(U);B.reasoning=(ot=B.reasoning)!=null?ot:{id:U,status:"streaming",chunks:[]},B.reasoning.startedAt=(Vt=B.reasoning.startedAt)!=null?Vt:ze((At=A.startedAt)!=null?At:A.timestamp);let J=(Qe=(_t=(q=A.reasoningText)!=null?q:A.text)!=null?_t:A.delta)!=null?Qe:"";if(J&&A.hidden!==!0){let ee=typeof A.sequenceIndex=="number"?A.sequenceIndex:void 0;if(ee!==void 0){let K=Ue(U,ee,String(J));B.reasoning.chunks=[K]}else B.reasoning.chunks.push(String(J))}if(B.reasoning.status=A.done?"complete":"streaming",A.done){B.reasoning.completedAt=ze((Ft=A.completedAt)!=null?Ft:A.timestamp);let ee=(oe=B.reasoning.startedAt)!=null?oe:Date.now();B.reasoning.durationMs=Math.max(0,((ge=B.reasoning.completedAt)!=null?ge:Date.now())-ee)}B.streaming=B.reasoning.status!=="complete",g(B)}else if(Ke==="reason_complete"){let U=($t=(xt=be(A,!1))!=null?xt:be(A,!0))!=null?$t:`reason-${l()}`,B=L.get(U);if(B!=null&&B.reasoning){B.reasoning.status="complete",B.reasoning.completedAt=ze((Jt=A.completedAt)!=null?Jt:A.timestamp);let ee=(yn=B.reasoning.startedAt)!=null?yn:Date.now();B.reasoning.durationMs=Math.max(0,((Tt=B.reasoning.completedAt)!=null?Tt:Date.now())-ee),B.streaming=!1,g(B)}let J=$(A);J&&v.byStep.delete(J)}else if(Ke==="tool_start"){let U=(wt=de(A,!0))!=null?wt:`tool-${l()}`,B=(gt=A.toolName)!=null?gt:A.name;if(Se(B)){Q.add(U);continue}let J=we(U),ee=(bt=J.toolCall)!=null?bt:{id:U,status:"pending"};ee.name=B!=null?B:ee.name,ee.status="running",A.args!==void 0?ee.args=A.args:A.parameters!==void 0&&(ee.args=A.parameters),ee.startedAt=(et=ee.startedAt)!=null?et:ze((zt=A.startedAt)!=null?zt:A.timestamp),ee.completedAt=void 0,ee.durationMs=void 0,J.toolCall=ee,J.streaming=!0;let K=A.agentContext;(K||A.executionId)&&(J.agentMetadata={executionId:(Fn=K==null?void 0:K.executionId)!=null?Fn:A.executionId,iteration:(Zn=K==null?void 0:K.iteration)!=null?Zn:A.iteration}),g(J)}else if(Ke==="tool_chunk"||Ke==="tool_delta"){let U=(On=(vn=de(A,!1))!=null?vn:de(A,!0))!=null?On:`tool-${l()}`;if(Q.has(U))continue;let B=we(U),J=(ut=B.toolCall)!=null?ut:{id:U,status:"running"};J.startedAt=(Nn=J.startedAt)!=null?Nn:ze((wo=A.startedAt)!=null?wo:A.timestamp);let ee=(Rr=(In=(ir=A.text)!=null?ir:A.delta)!=null?In:A.message)!=null?Rr:"";ee&&(J.chunks=($o=J.chunks)!=null?$o:[],J.chunks.push(String(ee))),J.status="running",B.toolCall=J,B.streaming=!0;let K=A.agentContext;(K||A.executionId)&&(B.agentMetadata=(_n=B.agentMetadata)!=null?_n:{executionId:(Lo=K==null?void 0:K.executionId)!=null?Lo:A.executionId,iteration:(yt=K==null?void 0:K.iteration)!=null?yt:A.iteration}),g(B)}else if(Ke==="tool_complete"){let U=(xn=(Vn=de(A,!1))!=null?Vn:de(A,!0))!=null?xn:`tool-${l()}`;if(Q.has(U)){Q.delete(U);continue}let B=we(U),J=(It=B.toolCall)!=null?It:{id:U,status:"running"};J.status="complete",A.result!==void 0&&(J.result=A.result),typeof A.duration=="number"&&(J.duration=A.duration),J.completedAt=ze((eo=A.completedAt)!=null?eo:A.timestamp);let ee=(to=A.duration)!=null?to:A.executionTime;if(typeof ee=="number")J.durationMs=ee;else{let _e=($n=J.startedAt)!=null?$n:Date.now();J.durationMs=Math.max(0,((Uo=J.completedAt)!=null?Uo:Date.now())-_e)}B.toolCall=J,B.streaming=!1;let K=A.agentContext;(K||A.executionId)&&(B.agentMetadata=(Un=B.agentMetadata)!=null?Un:{executionId:(Io=K==null?void 0:K.executionId)!=null?Io:A.executionId,iteration:(zo=K==null?void 0:K.iteration)!=null?zo:A.iteration}),g(B);let We=j(A);We&&x.byCall.delete(We)}else if(Ke==="step_await"&&A.awaitReason==="local_tool_required"&&A.toolName){let U=typeof A.toolCallId=="string"&&A.toolCallId.length>0?A.toolCallId:void 0,B=(Wt=U!=null?U:A.toolId)!=null?Wt:`local-${l()}`,J=we(B),ee=A.toolName,K=qr(ee),We=(wn=J.toolCall)!=null?wn:{id:B,status:"pending"};We.name=ee,We.args=A.parameters,We.status=K?"running":"complete",We.chunks=(no=We.chunks)!=null?no:[],We.startedAt=(Ro=We.startedAt)!=null?Ro:ze((qo=A.startedAt)!=null?qo:A.timestamp),K?(We.completedAt=void 0,We.duration=void 0,We.durationMs=void 0):We.completedAt=(jo=We.completedAt)!=null?jo:We.startedAt,J.toolCall=We,J.streaming=!1,J.agentMetadata={...J.agentMetadata,executionId:(zn=A.executionId)!=null?zn:(Co=J.agentMetadata)==null?void 0:Co.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},g(J)}else if(Ke==="text_start"){if((po=A.toolContext)!=null&&po.toolId)continue;let U=A.partId;if(U!==void 0&&M.current!==null&&U!==M.current){let B=p;B&&(B.streaming=!1,g(B),le=B,p=null,I=!0)}U!==void 0&&(M.current=U)}else if(Ke==="text_end"){if((ft=A.toolContext)!=null&&ft.toolId)continue;let U=p;U&&(U.streaming=!1,g(U),le=U,p=null,I=!0)}else if(Ke==="step_chunk"||Ke==="step_delta"){let U=A.stepType,B=A.executionType;if(U==="tool"||B==="context")continue;let J=A.toolContext;if(J!=null&&J.toolId){let _e=String((Gt=(Kt=A.id)!=null?Kt:J.stepId)!=null?Gt:`step-${l()}`),Ze=A.partId!==void 0&&A.partId!==null?String(A.partId):"",Ie=`${J.toolId}::${_e}`,Ye=W.get(Ie);if(Ze!==""&&Ye!==void 0&&Ye!==""&&Ye!==Ze){let Ct=D.get(k(J.toolId,_e,Ye));Ct&&Ct.streaming!==!1&&(Ct.streaming=!1,g(Ct))}Ze!==""&&W.set(Ie,Ze);let Rt=T(J.toolId,_e,Ze,J.executionId),nn=(uo=(oo=(Ko=(qn=A.text)!=null?qn:A.delta)!=null?Ko:A.content)!=null?oo:A.chunk)!=null?uo:"";nn&&(Rt.content+=String(nn),Rt.streaming=!0,g(Rt)),A.isComplete&&(Rt.streaming=!1,g(Rt));continue}let ee=A.partId;if(ee!==void 0&&M.current!==null&&ee!==M.current){let _e=p;_e&&(_e.streaming=!1,g(_e),le=_e,p=null,I=!0)}ee!==void 0&&(M.current=ee);let K=ee!==void 0&&(jn=ye.get(ee))!=null?jn:fe();ee!==void 0&&(K.partId||(K.partId=ee),ye.set(ee,K));let We=(Po=(mo=(Kn=(E=A.text)!=null?E:A.delta)!=null?Kn:A.content)!=null?mo:A.chunk)!=null?Po:"";if(We){let _e=typeof A.seq=="number"?A.seq:void 0,Ze=ee!=null?ee:K.id,Ie=_e!==void 0?Ue(Ze,_e,String(We)):((So=re.get(K.id))!=null?So:"")+We;K.rawContent=Ie,ne.has(K.id)||ne.set(K.id,this.createStreamParser());let Ye=ne.get(K.id),Rt=Ie.trim().startsWith("{")||Ie.trim().startsWith("[");if(Rt&&re.set(K.id,Ie),Ye.__isPlainTextParser===!0){K.content=_e!==void 0?Ie:K.content+We,re.delete(K.id),ne.delete(K.id),K.rawContent=void 0,g(K);continue}let Ct=Ye.processChunk(Ie);if(Ct instanceof Promise)Ct.then(Mt=>{var un;let on=typeof Mt=="string"?Mt:(un=Mt==null?void 0:Mt.text)!=null?un:null;if(on!==null&&on.trim()!=="")K.content=on,g(K);else if(!Rt&&!Ie.trim().startsWith("<")){let Sn=p,Yt=Sn&&Sn.id===K.id?Sn:K;Yt.id===K.id&&(Yt.content=_e!==void 0?Ie:Yt.content+We,re.delete(Yt.id),ne.delete(Yt.id),Yt.rawContent=void 0,g(Yt))}}).catch(()=>{K.content=_e!==void 0?Ie:K.content+We,re.delete(K.id),ne.delete(K.id),K.rawContent=void 0,g(K)});else{let Mt=typeof Ct=="string"?Ct:(as=Ct==null?void 0:Ct.text)!=null?as:null;Mt!==null&&Mt.trim()!==""?(K.content=Mt,g(K)):!Rt&&!Ie.trim().startsWith("<")&&(K.content=_e!==void 0?Ie:K.content+We,re.delete(K.id),ne.delete(K.id),K.rawContent=void 0,g(K))}}if(A.isComplete){let _e=(go=(fo=A.result)==null?void 0:fo.response)!=null?go:K.content;if(_e){let Ze=re.get(K.id),Ie=Ze!=null?Ze:te(_e);K.rawContent=Ie;let Ye=ne.get(K.id),Rt=null,nn=!1;if(Ye&&(Rt=Ye.getExtractedText(),Rt===null&&(Rt=Cr(Ie)),Rt===null)){let Ct=Ye.processChunk(Ie);Ct instanceof Promise?(nn=!0,Ct.then(Mt=>{var un;let on=typeof Mt=="string"?Mt:(un=Mt==null?void 0:Mt.text)!=null?un:null;if(on!==null){let Sn=p;Sn&&Sn.id===K.id&&(Sn.content=on,Sn.streaming=!1,ne.delete(Sn.id),re.delete(Sn.id),g(Sn))}})):Rt=typeof Ct=="string"?Ct:(ho=Ct==null?void 0:Ct.text)!=null?ho:null}if(!nn){Rt!==null&&Rt.trim()!==""?K.content=Rt:re.has(K.id)||(K.content=te(_e));let Ct=ne.get(K.id);if(Ct){let Mt=(Wo=Ct.close)==null?void 0:Wo.call(Ct);Mt instanceof Promise&&Mt.catch(()=>{}),ne.delete(K.id)}re.delete(K.id),K.streaming=!1,g(K)}}}}else if(Ke==="step_complete"){let U=A.stepType,B=A.executionType;if(U==="tool"||B==="context")continue;let J=A.toolContext;if(J!=null&&J.toolId){let _e=String((aa=(lr=A.id)!=null?lr:J.stepId)!=null?aa:"");if(_e){let Ze=C(J.toolId,_e);for(let[Ie,Ye]of D)Ie.startsWith(Ze)&&Ye.streaming!==!1&&(Ye.streaming=!1,g(Ye));W.delete(`${J.toolId}::${_e}`)}continue}let ee=A.stopReason;if(I){if(p!==null){let Ie=p;ee&&(Ie.stopReason=ee),ne.delete(Ie.id),re.delete(Ie.id),Ie.streaming!==!1&&(Ie.streaming=!1,g(Ie))}let _e=(is=A.result)==null?void 0:is.response,Ze=le;Ze&&(ee&&(Ze.stopReason=ee),_e!=null?He(Ze,_e):(ne.delete(Ze.id),re.delete(Ze.id))),le=null;continue}let K=(ia=A.result)==null?void 0:ia.response,We=fe();if(ee&&(We.stopReason=ee),K!=null){let _e=ne.get(We.id),Ze=!1,Ie=!1;if(_e){let Ye=_e.getExtractedText(),Rt=re.get(We.id),nn=Rt!=null?Rt:te(K);if(We.rawContent=nn,Ye!==null&&Ye.trim()!=="")We.content=Ye,Ze=!0;else{let Ct=Cr(nn);if(Ct!==null)We.content=Ct,Ze=!0;else{let Mt=_e.processChunk(nn);if(Mt instanceof Promise)Ie=!0,Mt.then(on=>{var Sn;let un=typeof on=="string"?on:(Sn=on==null?void 0:on.text)!=null?Sn:null;if(un!==null&&un.trim()!==""){let Yt=p;Yt&&Yt.id===We.id&&(Yt.content=un,Yt.streaming=!1,ne.delete(Yt.id),re.delete(Yt.id),g(Yt))}else{let Yt=_e.getExtractedText(),so=p;so&&so.id===We.id&&(Yt!==null&&Yt.trim()!==""?so.content=Yt:re.has(so.id)||(so.content=te(K)),so.streaming=!1,ne.delete(so.id),re.delete(so.id),g(so))}});else{let on=typeof Mt=="string"?Mt:(Pr=Mt==null?void 0:Mt.text)!=null?Pr:null;if(on!==null&&on.trim()!=="")We.content=on,Ze=!0;else{let un=_e.getExtractedText();un!==null&&un.trim()!==""&&(We.content=un,Ze=!0)}}}}}if(!Ie){if(!We.rawContent){let Ye=re.get(We.id);We.rawContent=Ye!=null?Ye:te(K)}if(!Ze&&!re.has(We.id)&&(We.content=te(K)),_e){let Ye=(mt=_e.close)==null?void 0:mt.call(_e);Ye instanceof Promise&&Ye.catch(()=>{})}ne.delete(We.id),re.delete(We.id),We.streaming=!1,g(We)}}else ne.delete(We.id),re.delete(We.id),We.streaming=!1,g(We)}else if(Ke==="flow_complete"){let U=(ls=A.result)==null?void 0:ls.response;if(I){if(p!==null){let B=p;ne.delete(B.id),re.delete(B.id),B.streaming!==!1&&(B.streaming=!1,g(B))}}else if(U!=null){let B=fe(),J=re.get(B.id),ee=J!=null?J:te(U);B.rawContent=ee;let K=te(U),We=ne.get(B.id);if(We){let Ie=Cr(ee);if(Ie!==null)K=Ie;else{let Ye=We.processChunk(ee);Ye instanceof Promise&&Ye.then(nn=>{var Mt;let Ct=typeof nn=="string"?nn:(Mt=nn==null?void 0:nn.text)!=null?Mt:null;Ct!==null&&(B.content=Ct,B.streaming=!1,g(B))});let Rt=We.getExtractedText();Rt!==null&&(K=Rt)}}ne.delete(B.id),re.delete(B.id);let _e=K!==B.content,Ze=B.streaming!==!1;_e&&(B.content=K),B.streaming=!1,(_e||Ze)&&g(B)}else if(p!==null){let B=p;ne.delete(B.id),re.delete(B.id),B.streaming!==!1&&(B.streaming=!1,g(B))}n({type:"status",status:"idle"})}else if(Ke==="agent_start")ae={executionId:A.executionId,agentId:(ro=A.agentId)!=null?ro:"virtual",agentName:(Rn=A.agentName)!=null?Rn:"",status:"running",currentIteration:0,maxTurns:(la=A.maxTurns)!=null?la:1,startedAt:ze(A.startedAt)};else if(Ke==="agent_iteration_start"){if(ae&&(ae.currentIteration=A.iteration),Nt==="separate"&&A.iteration>1){let U=p;U&&(U.streaming=!1,g(U),Ln.set(A.iteration-1,U),p=null)}}else if(Ke==="agent_turn_start")w=null;else if(Ke==="agent_turn_delta"){if(A.contentType==="text"){let U=fe();U.content+=(ca=A.delta)!=null?ca:"",U.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId,agentName:ae==null?void 0:ae.agentName},w=U,g(U)}else if(A.contentType==="thinking"){let U=(Wr=A.turnId)!=null?Wr:`agent-think-${A.iteration}`,B=Oe(U);B.reasoning=(Bo=B.reasoning)!=null?Bo:{id:U,status:"streaming",chunks:[]},B.reasoning.chunks.push((da=A.delta)!=null?da:""),B.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId},g(B)}else if(A.contentType==="tool_input"){let U=(cr=A.toolCallId)!=null?cr:x.lastId;if(U){let B=H.get(U);B!=null&&B.toolCall&&(B.toolCall.chunks=(cs=B.toolCall.chunks)!=null?cs:[],B.toolCall.chunks.push((Ho=A.delta)!=null?Ho:""),g(B))}}}else if(Ke==="agent_turn_complete"){let U=A.turnId;if(U){let ee=L.get(U);if(ee!=null&&ee.reasoning){ee.reasoning.status="complete",ee.reasoning.completedAt=ze(A.completedAt);let K=(ds=ee.reasoning.startedAt)!=null?ds:Date.now();ee.reasoning.durationMs=Math.max(0,((Go=ee.reasoning.completedAt)!=null?Go:Date.now())-K),ee.streaming=!1,g(ee)}}let B=A.stopReason,J=p!=null?p:w;if(B&&J!==null){let ee=A.turnId;(!ee||((Yo=J.agentMetadata)==null?void 0:Yo.turnId)===ee)&&(J.stopReason=B,g(J))}}else if(Ke==="agent_tool_start"){p&&(p.streaming=!1,g(p),p=null);let U=(pa=A.toolCallId)!=null?pa:`agent-tool-${l()}`;ve(j(A),U);let B=we(U),J=(ua=B.toolCall)!=null?ua:{id:U,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};J.name=(dr=(zi=A.toolName)!=null?zi:A.name)!=null?dr:J.name,J.status="running",A.parameters!==void 0&&(J.args=A.parameters),J.startedAt=ze((Xo=A.startedAt)!=null?Xo:A.timestamp),B.toolCall=J,B.streaming=!0,B.agentMetadata={executionId:A.executionId,iteration:A.iteration},g(B)}else if(Ke==="agent_tool_delta"){let U=(ma=A.toolCallId)!=null?ma:x.lastId;if(U){let B=(ps=H.get(U))!=null?ps:we(U);B.toolCall&&(B.toolCall.chunks=(Qo=B.toolCall.chunks)!=null?Qo:[],B.toolCall.chunks.push((fa=A.delta)!=null?fa:""),B.toolCall.status="running",B.streaming=!0,g(B))}}else if(Ke==="agent_tool_complete"){let U=(us=A.toolCallId)!=null?us:x.lastId;if(U){let B=(Jo=H.get(U))!=null?Jo:we(U);if(B.toolCall){B.toolCall.status="complete",A.result!==void 0&&(B.toolCall.result=A.result),typeof A.executionTime=="number"&&(B.toolCall.durationMs=A.executionTime),B.toolCall.completedAt=ze((ms=A.completedAt)!=null?ms:A.timestamp),B.streaming=!1,g(B);let J=j(A);J&&x.byCall.delete(J)}}}else if(Ke==="agent_media"){let U=Array.isArray(A.media)?A.media:[],B=[];for(let J of U){if(!J||typeof J!="object")continue;let ee=J,K=typeof ee.type=="string"?ee.type:void 0,We=typeof ee.mediaType=="string"?ee.mediaType.toLowerCase():"",_e=null,Ze="";if(K==="media"){let Ie=typeof ee.data=="string"?ee.data:void 0;if(!Ie)continue;Ze=We.length>0?We:"application/octet-stream",_e=`data:${Ze};base64,${Ie}`}else if(K==="image-url"){let Ie=typeof ee.url=="string"?ee.url:void 0;if(!Ie)continue;Ze=We,_e=Ie}else if(K==="file-url"){let Ie=typeof ee.url=="string"?ee.url:void 0;if(!Ie)continue;Ze=We,_e=Ie}else continue;if(_e)if(K==="image-url"||Ze.startsWith("image/"))B.push({type:"image",image:_e,...Ze?{mimeType:Ze}:{}});else if(Ze.startsWith("audio/"))B.push({type:"audio",audio:_e,mimeType:Ze});else if(Ze.startsWith("video/"))B.push({type:"video",video:_e,mimeType:Ze});else{let Ie=Ze||"application/octet-stream";B.push({type:"file",data:_e,mimeType:Ie,filename:Yg(Ie)})}}if(B.length>0){let J=l(),ee=A.toolCallId,We={id:`agent-media-${typeof ee=="string"&&ee.length>0?`${ee}-${J}`:String(J)}`,role:"assistant",content:"",contentParts:B,createdAt:new Date().toISOString(),streaming:!1,sequence:J,agentMetadata:{executionId:A.executionId,iteration:A.iteration}};g(We);let _e=p;_e&&(_e.streaming=!1,g(_e)),p=null,S.current=null}}else if(Ke!=="agent_iteration_complete"){if(Ke==="agent_reflection"||Ke==="agent_reflect"){let U=`agent-reflection-${A.executionId}-${A.iteration}`,B={id:U,role:"assistant",content:(ga=A.reflection)!=null?ga:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:U,status:"complete",chunks:[(Do=A.reflection)!=null?Do:""]},agentMetadata:{executionId:A.executionId,iteration:A.iteration}};g(B)}else if(Ke==="agent_complete"){ae&&(ae.status=A.success?"complete":"error",ae.completedAt=ze(A.completedAt),ae.stopReason=A.stopReason);let U=p;U&&(U.streaming=!1,g(U)),n({type:"status",status:"idle"})}else if(Ke==="agent_error"){let U=typeof A.error=="string"?A.error:(Zo=(ha=A.error)==null?void 0:ha.message)!=null?Zo:"Agent execution error";A.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",U):n({type:"error",error:new Error(U)})}else if(Ke!=="agent_ping"){if(Ke==="agent_approval_start"){let U=(Bt=A.approvalId)!=null?Bt:`approval-${l()}`,B={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(Br=ae==null?void 0:ae.agentId)!=null?Br:"virtual",executionId:(fs=(Hr=A.executionId)!=null?Hr:ae==null?void 0:ae.executionId)!=null?fs:"",toolName:(Ao=A.toolName)!=null?Ao:"",toolType:A.toolType,description:(gs=A.description)!=null?gs:`Execute ${(ba=A.toolName)!=null?ba:"tool"}`,parameters:A.parameters}};g(B)}else if(Ke==="step_await"&&A.awaitReason==="approval_required"){let U=(hs=A.approvalId)!=null?hs:`approval-${l()}`,B={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(ya=ae==null?void 0:ae.agentId)!=null?ya:"virtual",executionId:(Fr=(Dr=A.executionId)!=null?Dr:ae==null?void 0:ae.executionId)!=null?Fr:"",toolName:(pr=A.toolName)!=null?pr:"",toolType:A.toolType,description:(xa=A.description)!=null?xa:`Execute ${(va=A.toolName)!=null?va:"tool"}`,parameters:A.parameters}};g(B)}else if(Ke==="agent_approval_complete"){let U=A.approvalId;if(U){let J={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:(bs=A.decision)!=null?bs:"approved",agentId:(ys=ae==null?void 0:ae.agentId)!=null?ys:"virtual",executionId:(xs=(vs=A.executionId)!=null?vs:ae==null?void 0:ae.executionId)!=null?xs:"",toolName:(Cn=A.toolName)!=null?Cn:"",description:(Gn=A.description)!=null?Gn:"",resolvedAt:Date.now()}};g(J)}}else if(Ke==="artifact_start"||Ke==="artifact_delta"||Ke==="artifact_update"||Ke==="artifact_complete"){if(Ke==="artifact_start"){let U=A.artifactType,B=String(A.id),J=typeof A.title=="string"?A.title:void 0;if(n({type:"artifact_start",id:B,artifactType:U,title:J,component:typeof A.component=="string"?A.component:void 0}),xe.set(B,{markdown:"",title:J}),!Y.has(B)){Y.add(B);let ee={id:`artifact-ref-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:B,title:J,artifactType:U,status:"streaming"}})};Le.set(B,ee),g(ee)}}else if(Ke==="artifact_delta"){let U=String(A.id),B=typeof A.delta=="string"?A.delta:String((Fo=A.delta)!=null?Fo:"");n({type:"artifact_delta",id:U,artDelta:B});let J=xe.get(U);J&&(J.markdown+=B)}else if(Ke==="artifact_update"){let U=A.props&&typeof A.props=="object"&&!Array.isArray(A.props)?A.props:{};n({type:"artifact_update",id:String(A.id),props:U,component:typeof A.component=="string"?A.component:void 0})}else if(Ke==="artifact_complete"){let U=String(A.id);n({type:"artifact_complete",id:U});let B=Le.get(U);if(B){B.streaming=!1;try{let J=JSON.parse((rt=B.rawContent)!=null?rt:"{}");if(J.props){J.props.status="complete";let ee=xe.get(U);ee!=null&&ee.markdown&&(J.props.markdown=ee.markdown)}B.rawContent=JSON.stringify(J)}catch{}xe.delete(U),g(B),Le.delete(U)}}}else if(Ke==="transcript_insert"){let U=A.message;if(!U||typeof U!="object")continue;let B=String((ws=U.id)!=null?ws:`msg-${l()}`),J=U.role,K={id:B,role:J==="user"?"user":J==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:l()};if(g(K),K.rawContent)try{let We=JSON.parse(K.rawContent),_e=(ur=We==null?void 0:We.props)==null?void 0:ur.artifactId;typeof _e=="string"&&Y.add(_e)}catch{}p=null,S.current=null,ne.delete(B),re.delete(B)}else if(Ke==="error"||Ke==="step_error"||Ke==="dispatch_error"||Ke==="flow_error"){let U=null;if(A.error instanceof Error)U=A.error;else if(Ke==="dispatch_error"){let B=(bo=A.message)!=null?bo:A.error;B!=null&&B!==""&&(U=new Error(String(B)))}else if(Ke==="step_error"||Ke==="flow_error"){let B=A.error;typeof B=="string"&&B!==""?U=new Error(B):B!=null&&typeof B=="object"&&"message"in B&&(U=new Error(String((wa=B.message)!=null?wa:B)))}else Ke==="error"&&A.error!=null&&A.error!==""&&(U=new Error(String(A.error)));if(U){n({type:"error",error:U});let B=p;B&&B.streaming&&(B.streaming=!1,g(B)),n({type:"status",status:"idle"})}}}}}ce.length=0};;){let{done:_,value:ke}=await r.read();if(_)break;a+=s.decode(ke,{stream:!0});let De=a.split(`
|
|
9
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Wr=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},sm=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},am=()=>{var t;let e=Oh();return{processChunk:async n=>{let o=n.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},im=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=Wh(n,Bh|Hh);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?nm(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=nm(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var lm=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var si=class{constructor(t,n=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=n}push(t,n){var s,a,i;let o=(i=(s=n==null?void 0:n.seq)!=null?s:n==null?void 0:n.sequenceIndex)!=null?i:(a=n==null?void 0:n.agentContext)==null?void 0:a.seq;if(o==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,n);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),o===this.nextExpectedSeq){this.emitter(t,n),this.nextExpectedSeq=o+1,this.drainConsecutive();return}if(o<this.nextExpectedSeq){this.emitter(t,n);return}let r=this.buffer.get(o);r!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${o} (${r.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(r.payloadType,r.payload)),this.buffer.set(o,{payloadType:t,payload:n,seq:o}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((n,o)=>n[0]-o[0]);for(let[n,o]of t)this.buffer.delete(n),this.emitter(o.payloadType,o.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Nh="https://api.runtype.com/v1/dispatch",ai="https://api.runtype.com";function _h(e){var s,a;let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let i=(a=(s=t.slice(r+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Tl=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Vh(e){switch(e){case"json":return im;case"regex-json":return am;case"xml":return lm;default:return sm}}var cm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function $h(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=cm(n);if(!cm(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Wr(e);return Wr(t)!==null&&a===null?t:e}var Ys=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,o,r,s;this.apiUrl=(n=t.apiUrl)!=null?n:Nh,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:Vh(t.parserType),this.contextProviders=(r=t.contextProviders)!=null?r:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new ti(t.webmcp):null}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ai}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let o=await this.sessionInitPromise;return this.clientSession=o,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,o),o}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let t=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},o=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){let i=await o.json().catch(()=>({error:"Session initialization failed"}));throw o.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):o.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let r=await o.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(r.sessionId),{sessionId:r.sessionId,expiresAt:new Date(r.expiresAt),flow:r.flow,config:{welcomeMessage:r.config.welcomeMessage,placeholder:r.config.placeholder,theme:r.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ai}/v1/client/feedback`}async sendFeedback(t){var s,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var r,s,a,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(r=this.config).onSessionExpired)==null||s.call(r);let H=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:H}),H}let l=await this.buildPayload(t.messages),f=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([H])=>H!=="sessionId"&&H!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(Tl).map(H=>{var P,w,x;return{id:H.id,role:H.role,content:(x=(w=(P=H.contentParts)!=null?P:H.llmContent)!=null?w:H.rawContent)!=null?x:H.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...f&&Object.keys(f).length>0&&{metadata:f},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},g=l.clientTools,m=!!(g&&g.length>0),C=m?em(g):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,E=m&&v&&this.lastSentClientToolsFingerprint===C,L=!1,I=null,R;for(let H=0;;H++){let w={...u,...m&&(L||!E)&&g?{clientTools:g}:{},...C?{clientToolsFingerprint:C}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",w),R=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w),signal:o.signal}),R.status===409&&H===0&&m){let x=await R.json().catch(()=>null);if((x==null?void 0:x.error)==="client_tools_resend_required"){L=!0,this.lastSentClientToolsFingerprint=null;continue}I=x!=null?x:{error:"Chat request failed"}}break}if(!R.ok){let H=I!=null?I:await R.json().catch(()=>({error:"Chat request failed"}));if(R.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let w=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:w}),w}if(R.status===429){let w=new Error(H.hint||"Message limit reached for this session.");throw n({type:"error",error:w}),w}let P=new Error(H.error||"Failed to send message");throw n({type:"error",error:P}),P}if(!R.body){let H=new Error("No response body received");throw n({type:"error",error:H}),H}this.lastSentClientToolsFingerprint=C!=null?C:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(R.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let r=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ai}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,o){var l,f;let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||ai}/resume`,a;r&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(f=o==null?void 0:o.streamResponse)!=null?f:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var s;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(Tl).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),o={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},r=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(r&&r.length>0&&(o.clientTools=r),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(o.context=a)}return o}async buildPayload(t){var s;let o={messages:t.slice().filter(Tl).sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},r=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(r&&r.length>0&&(o.clientTools=r),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(o.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...o},config:this.config});if(a&&typeof a=="object"){let i=a;return o.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=o.clientTools),i}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return o}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=f=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...f!==void 0&&{partId:f}};return o.current=u,r(u),u},l=f=>o.current?o.current:d(f);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let f=l(i.partId);i.partId!==void 0&&!f.partId&&(f.partId=i.partId),f.content+=i.text,r(f)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o){var Ht,sn,no,ko;let r=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,f=D=>{let pe=D.reasoning?{...D.reasoning,chunks:[...D.reasoning.chunks]}:void 0,De=D.toolCall?{...D.toolCall,chunks:D.toolCall.chunks?[...D.toolCall.chunks]:void 0}:void 0,je=D.tools?D.tools.map(Ne=>({...Ne,chunks:Ne.chunks?[...Ne.chunks]:void 0})):void 0;return{...D,reasoning:pe,toolCall:De,tools:je}},u=D=>{if(D.role!=="assistant"||D.variant)return!0;let pe=Array.isArray(D.contentParts)&&D.contentParts.length>0,De=typeof D.rawContent=="string"&&D.rawContent.trim()!=="";return typeof D.content=="string"&&D.content.trim()!==""||pe||De||!!D.stopReason},g=D=>{u(D)&&n({type:"message",message:f(D)})},m=null,C=null,v={current:null},E={current:null},L=!1,I=new Map,R=new Map,H=new Map,P=new Map,w={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},k=(D,pe,De="")=>`${D}::${pe}::${De}`,S=(D,pe)=>`${D}::${pe}::`,T=(D,pe,De,je)=>{let Ne=k(D,pe,De),Ve=H.get(Ne);if(Ve)return Ve;let nt=De?`-${De}`:"",Rt={id:`nested-${D}-${pe}${nt}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...De?{partId:De}:{},agentMetadata:{executionId:je,parentToolId:D,parentStepId:pe}};return H.set(Ne,Rt),g(Rt),Rt},_=D=>{if(D==null)return null;try{return String(D)}catch{return null}},U=D=>{var pe,De,je,Ne,Ve;return _((Ve=(Ne=(je=(De=(pe=D.stepId)!=null?pe:D.step_id)!=null?De:D.step)!=null?je:D.parentId)!=null?Ne:D.flowStepId)!=null?Ve:D.flow_step_id)},G=D=>{var pe,De,je,Ne,Ve,nt,Rt;return _((Rt=(nt=(Ve=(Ne=(je=(De=(pe=D.callId)!=null?pe:D.call_id)!=null?De:D.requestId)!=null?je:D.request_id)!=null?Ne:D.toolCallId)!=null?Ve:D.tool_call_id)!=null?nt:D.stepId)!=null?Rt:D.step_id)},ge=o,ue=!1,ce=()=>{if(m)return m;let D;return!ue&&ge?(D=ge,ue=!0):ge&&E.current?D=`${ge}_${E.current}`:D=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:D,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},g(m),m},ke=(D,pe)=>{w.lastId=pe,D&&w.byStep.set(D,pe)},ve=(D,pe)=>{var Ve;let De=(Ve=D.reasoningId)!=null?Ve:D.id,je=U(D);if(De){let nt=String(De);return ke(je,nt),nt}if(je){let nt=w.byStep.get(je);if(nt)return w.lastId=nt,nt}if(w.lastId&&!pe)return w.lastId;if(!pe)return null;let Ne=`reason-${l()}`;return ke(je,Ne),Ne},He=D=>{let pe=I.get(D);if(pe)return pe;let De={id:`reason-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:D,status:"streaming",chunks:[]}};return I.set(D,De),g(De),De},Se=(D,pe)=>{x.lastId=pe,D&&x.byCall.set(D,pe)},ie=new Set,X=new Map,re=new Set,be=new Map,he=D=>{if(!D)return!1;let pe=D.replace(/_+/g,"_").replace(/^_|_$/g,"");return pe==="emit_artifact_markdown"||pe==="emit_artifact_component"},j=(D,pe)=>{var Ve;let De=(Ve=D.toolId)!=null?Ve:D.id,je=G(D);if(De){let nt=String(De);return Se(je,nt),nt}if(je){let nt=x.byCall.get(je);if(nt)return x.lastId=nt,nt}if(x.lastId&&!pe)return x.lastId;if(!pe)return null;let Ne=`tool-${l()}`;return Se(je,Ne),Ne},se=D=>{let pe=R.get(D);if(pe)return pe;let De={id:`tool-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:D,status:"pending"}};return R.set(D,De),g(De),De},Ie=D=>{if(typeof D=="number"&&Number.isFinite(D))return D;if(typeof D=="string"){let pe=Number(D);if(!Number.isNaN(pe)&&Number.isFinite(pe))return pe;let De=Date.parse(D);if(!Number.isNaN(De))return De}return Date.now()},ne=D=>{if(typeof D=="string")return D;if(D==null)return"";try{return JSON.stringify(D)}catch{return String(D)}},Z=new Map,oe=new Map,at=new Map,it=new Map,Me=null,de=(D,pe,De)=>{var Rt;let je=at.get(D);je||(je=[],at.set(D,je));let Ne=0,Ve=je.length;for(;Ne<Ve;){let jt=Ne+Ve>>>1;je[jt].seq<pe?Ne=jt+1:Ve=jt}((Rt=je[Ne])==null?void 0:Rt.seq)===pe?je[Ne]={seq:pe,text:De}:je.splice(Ne,0,{seq:pe,text:De});let nt="";for(let jt=0;jt<je.length;jt++)nt+=je[jt].text;return nt},Xe=(D,pe)=>{let De=ne(pe),je=oe.get(D.id),Ne=$h(je,De);D.rawContent=Ne;let Ve=Z.get(D.id),nt=vt=>{var Ce;let rt=(Ce=D.content)!=null?Ce:"";vt.trim()!==""&&(rt.trim().length===0||vt.startsWith(rt)||vt.trimStart().startsWith(rt.trim()))&&(D.content=vt)},Rt=()=>{var vt;if(Ve){let rt=(vt=Ve.close)==null?void 0:vt.call(Ve);rt instanceof Promise&&rt.catch(()=>{})}Z.delete(D.id),oe.delete(D.id),D.streaming=!1,g(D)};if(!Ve){nt(De),Rt();return}let jt=Wr(Ne);if(jt!==null&&jt.trim()!==""){nt(jt),Rt();return}let Xt=vt=>{var le;let rt=typeof vt=="string"?vt:(le=vt==null?void 0:vt.text)!=null?le:null;if(rt!==null&&rt.trim()!=="")return rt;let Ce=Ve.getExtractedText();return Ce!==null&&Ce.trim()!==""?Ce:De},K;try{K=Ve.processChunk(Ne)}catch{nt(De),Rt();return}if(K instanceof Promise){K.then(vt=>{nt(Xt(vt)),Rt()}).catch(()=>{nt(De),Rt()});return}nt(Xt(K)),Rt()},We=[],q=!1,me,et=()=>{q||(q=!0,queueMicrotask(()=>{q=!1,me()}))},Et=new si((D,pe)=>{We.push({payloadType:D,payload:pe}),et()}),ee=null,ze=new Map,Dn=(Ht=this.config.iterationDisplay)!=null?Ht:"separate";for(me=()=>{var D,pe,De,je,Ne,Ve,nt,Rt,jt,Xt,K,vt,rt,Ce,le,Ze,Jt,Kt,Ln,yn,ft,Mt,Je,zt,an,wn,Cn,bn,Eo,St,$n,Un,No,bo,xt,br,Mo,yr,Fn,Ur,Qo,_o,At,zn,qn,In,It,oo,ro,jn,Zo,Vo,er,Kn,Dt,Rn,so,tr,$o,nr,Lo,Gn,yo,ht,Qt,Zt,Yn,or,xe,ao,io,V,Io,Uo,zo,Ro,vo,Cs,Xn,Jn,xo,wo,vr,qo,Sn,Po,zr,xr,qr,xa,jr,wa,Kr,yt,Ss,lo,On,Ca,Sa,Gr,jo,As,rr,Ts,ks,Es,Ms,Nn,Yr,Wo,Bo,Ls,Aa,Is,Rs,wr,Ta,ka,Ea,Ma,nl,Cr,sr,La,Ps,ar,Ia,Ws,ir,Bs,Ra,Ko,Pa,lr,Ft,Xr,Jr,Hs;for(let co=0;co<We.length;co++){let Ke=We[co].payloadType,A=We[co].payload;if(Ke==="reason_start"){let $=(D=ve(A,!0))!=null?D:`reason-${l()}`,W=He($);W.reasoning=(pe=W.reasoning)!=null?pe:{id:$,status:"streaming",chunks:[]},W.reasoning.startedAt=(je=W.reasoning.startedAt)!=null?je:Ie((De=A.startedAt)!=null?De:A.timestamp),W.reasoning.completedAt=void 0,W.reasoning.durationMs=void 0,W.streaming=!0,W.reasoning.status="streaming",g(W)}else if(Ke==="reason_delta"||Ke==="reason_chunk"){let $=(Ve=(Ne=ve(A,!1))!=null?Ne:ve(A,!0))!=null?Ve:`reason-${l()}`,W=He($);W.reasoning=(nt=W.reasoning)!=null?nt:{id:$,status:"streaming",chunks:[]},W.reasoning.startedAt=(jt=W.reasoning.startedAt)!=null?jt:Ie((Rt=A.startedAt)!=null?Rt:A.timestamp);let Q=(vt=(K=(Xt=A.reasoningText)!=null?Xt:A.text)!=null?K:A.delta)!=null?vt:"";if(Q&&A.hidden!==!0){let ae=typeof A.sequenceIndex=="number"?A.sequenceIndex:void 0;if(ae!==void 0){let Y=de($,ae,String(Q));W.reasoning.chunks=[Y]}else W.reasoning.chunks.push(String(Q))}if(W.reasoning.status=A.done?"complete":"streaming",A.done){W.reasoning.completedAt=Ie((rt=A.completedAt)!=null?rt:A.timestamp);let ae=(Ce=W.reasoning.startedAt)!=null?Ce:Date.now();W.reasoning.durationMs=Math.max(0,((le=W.reasoning.completedAt)!=null?le:Date.now())-ae)}W.streaming=W.reasoning.status!=="complete",g(W)}else if(Ke==="reason_complete"){let $=(Jt=(Ze=ve(A,!1))!=null?Ze:ve(A,!0))!=null?Jt:`reason-${l()}`,W=I.get($);if(W!=null&&W.reasoning){W.reasoning.status="complete",W.reasoning.completedAt=Ie((Kt=A.completedAt)!=null?Kt:A.timestamp);let ae=(Ln=W.reasoning.startedAt)!=null?Ln:Date.now();W.reasoning.durationMs=Math.max(0,((yn=W.reasoning.completedAt)!=null?yn:Date.now())-ae),W.streaming=!1,g(W)}let Q=U(A);Q&&w.byStep.delete(Q)}else if(Ke==="tool_start"){let $=(ft=j(A,!0))!=null?ft:`tool-${l()}`,W=(Mt=A.toolName)!=null?Mt:A.name;if(he(W)){ie.add($);continue}let Q=se($),ae=(Je=Q.toolCall)!=null?Je:{id:$,status:"pending"};ae.name=W!=null?W:ae.name,ae.status="running",A.args!==void 0?ae.args=A.args:A.parameters!==void 0&&(ae.args=A.parameters),ae.startedAt=(an=ae.startedAt)!=null?an:Ie((zt=A.startedAt)!=null?zt:A.timestamp),ae.completedAt=void 0,ae.durationMs=void 0,Q.toolCall=ae,Q.streaming=!0;let Y=A.agentContext;(Y||A.executionId)&&(Q.agentMetadata={executionId:(wn=Y==null?void 0:Y.executionId)!=null?wn:A.executionId,iteration:(Cn=Y==null?void 0:Y.iteration)!=null?Cn:A.iteration}),g(Q)}else if(Ke==="tool_chunk"||Ke==="tool_delta"){let $=(Eo=(bn=j(A,!1))!=null?bn:j(A,!0))!=null?Eo:`tool-${l()}`;if(ie.has($))continue;let W=se($),Q=(St=W.toolCall)!=null?St:{id:$,status:"running"};Q.startedAt=(Un=Q.startedAt)!=null?Un:Ie(($n=A.startedAt)!=null?$n:A.timestamp);let ae=(xt=(bo=(No=A.text)!=null?No:A.delta)!=null?bo:A.message)!=null?xt:"";ae&&(Q.chunks=(br=Q.chunks)!=null?br:[],Q.chunks.push(String(ae))),Q.status="running",W.toolCall=Q,W.streaming=!0;let Y=A.agentContext;(Y||A.executionId)&&(W.agentMetadata=(Fn=W.agentMetadata)!=null?Fn:{executionId:(Mo=Y==null?void 0:Y.executionId)!=null?Mo:A.executionId,iteration:(yr=Y==null?void 0:Y.iteration)!=null?yr:A.iteration}),g(W)}else if(Ke==="tool_complete"){let $=(Qo=(Ur=j(A,!1))!=null?Ur:j(A,!0))!=null?Qo:`tool-${l()}`;if(ie.has($)){ie.delete($);continue}let W=se($),Q=(_o=W.toolCall)!=null?_o:{id:$,status:"running"};Q.status="complete",A.result!==void 0&&(Q.result=A.result),typeof A.duration=="number"&&(Q.duration=A.duration),Q.completedAt=Ie((At=A.completedAt)!=null?At:A.timestamp);let ae=(zn=A.duration)!=null?zn:A.executionTime;if(typeof ae=="number")Q.durationMs=ae;else{let Oe=(qn=Q.startedAt)!=null?qn:Date.now();Q.durationMs=Math.max(0,((In=Q.completedAt)!=null?In:Date.now())-Oe)}W.toolCall=Q,W.streaming=!1;let Y=A.agentContext;(Y||A.executionId)&&(W.agentMetadata=(ro=W.agentMetadata)!=null?ro:{executionId:(It=Y==null?void 0:Y.executionId)!=null?It:A.executionId,iteration:(oo=Y==null?void 0:Y.iteration)!=null?oo:A.iteration}),g(W);let Re=G(A);Re&&x.byCall.delete(Re)}else if(Ke==="step_await"&&A.awaitReason==="local_tool_required"&&A.toolName){let $=typeof A.toolCallId=="string"&&A.toolCallId.length>0?A.toolCallId:void 0,W=(jn=$!=null?$:A.toolId)!=null?jn:`local-${l()}`,Q=se(W),ae=A.toolName,Y=is(ae),Re=(Zo=Q.toolCall)!=null?Zo:{id:W,status:"pending"};Re.name=ae,Re.args=A.parameters,Re.status=Y?"running":"complete",Re.chunks=(Vo=Re.chunks)!=null?Vo:[],Re.startedAt=(Kn=Re.startedAt)!=null?Kn:Ie((er=A.startedAt)!=null?er:A.timestamp),Y?(Re.completedAt=void 0,Re.duration=void 0,Re.durationMs=void 0):Re.completedAt=(Dt=Re.completedAt)!=null?Dt:Re.startedAt,Q.toolCall=Re,Q.streaming=!1,Q.agentMetadata={...Q.agentMetadata,executionId:(so=A.executionId)!=null?so:(Rn=Q.agentMetadata)==null?void 0:Rn.executionId,awaitingLocalTool:!0,...$?{webMcpToolCallId:$}:{}},g(Q)}else if(Ke==="text_start"){if((tr=A.toolContext)!=null&&tr.toolId)continue;let $=A.partId;if($!==void 0&&E.current!==null&&$!==E.current){let W=m;W&&(W.streaming=!1,g(W),Me=W,m=null,L=!0)}$!==void 0&&(E.current=$)}else if(Ke==="text_end"){if(($o=A.toolContext)!=null&&$o.toolId)continue;let $=m;$&&($.streaming=!1,g($),Me=$,m=null,L=!0)}else if(Ke==="step_chunk"||Ke==="step_delta"){let $=A.stepType,W=A.executionType;if($==="tool"||W==="context")continue;let Q=A.toolContext;if(Q!=null&&Q.toolId){let Oe=String((Lo=(nr=A.id)!=null?nr:Q.stepId)!=null?Lo:`step-${l()}`),st=A.partId!==void 0&&A.partId!==null?String(A.partId):"",Qe=`${Q.toolId}::${Oe}`,Bt=P.get(Qe);if(st!==""&&Bt!==void 0&&Bt!==""&&Bt!==st){let lt=H.get(k(Q.toolId,Oe,Bt));lt&<.streaming!==!1&&(lt.streaming=!1,g(lt))}st!==""&&P.set(Qe,st);let Vt=T(Q.toolId,Oe,st,Q.executionId),Nt=(Qt=(ht=(yo=(Gn=A.text)!=null?Gn:A.delta)!=null?yo:A.content)!=null?ht:A.chunk)!=null?Qt:"";Nt&&(Vt.content+=String(Nt),Vt.streaming=!0,g(Vt)),A.isComplete&&(Vt.streaming=!1,g(Vt));continue}let ae=A.partId;if(ae!==void 0&&E.current!==null&&ae!==E.current){let Oe=m;Oe&&(Oe.streaming=!1,g(Oe),Me=Oe,m=null,L=!0)}ae!==void 0&&(E.current=ae);let Y=ae!==void 0&&(Zt=it.get(ae))!=null?Zt:ce();ae!==void 0&&(Y.partId||(Y.partId=ae),it.set(ae,Y));let Re=(ao=(xe=(or=(Yn=A.text)!=null?Yn:A.delta)!=null?or:A.content)!=null?xe:A.chunk)!=null?ao:"";if(Re){let Oe=typeof A.seq=="number"?A.seq:void 0,st=ae!=null?ae:Y.id,Qe=Oe!==void 0?de(st,Oe,String(Re)):((io=oe.get(Y.id))!=null?io:"")+Re;Y.rawContent=Qe,Z.has(Y.id)||Z.set(Y.id,this.createStreamParser());let Bt=Z.get(Y.id),Vt=Qe.trim().startsWith("{")||Qe.trim().startsWith("[");if(Vt&&oe.set(Y.id,Qe),Bt.__isPlainTextParser===!0){Y.content=Oe!==void 0?Qe:Y.content+Re,oe.delete(Y.id),Z.delete(Y.id),Y.rawContent=void 0,g(Y);continue}let lt=Bt.processChunk(Qe);if(lt instanceof Promise)lt.then(Tt=>{var An;let $e=typeof Tt=="string"?Tt:(An=Tt==null?void 0:Tt.text)!=null?An:null;if($e!==null&&$e.trim()!=="")Y.content=$e,g(Y);else if(!Vt&&!Qe.trim().startsWith("<")){let mn=m,$t=mn&&mn.id===Y.id?mn:Y;$t.id===Y.id&&($t.content=Oe!==void 0?Qe:$t.content+Re,oe.delete($t.id),Z.delete($t.id),$t.rawContent=void 0,g($t))}}).catch(()=>{Y.content=Oe!==void 0?Qe:Y.content+Re,oe.delete(Y.id),Z.delete(Y.id),Y.rawContent=void 0,g(Y)});else{let Tt=typeof lt=="string"?lt:(V=lt==null?void 0:lt.text)!=null?V:null;Tt!==null&&Tt.trim()!==""?(Y.content=Tt,g(Y)):!Vt&&!Qe.trim().startsWith("<")&&(Y.content=Oe!==void 0?Qe:Y.content+Re,oe.delete(Y.id),Z.delete(Y.id),Y.rawContent=void 0,g(Y))}}if(A.isComplete){let Oe=(Uo=(Io=A.result)==null?void 0:Io.response)!=null?Uo:Y.content;if(Oe){let st=oe.get(Y.id),Qe=st!=null?st:ne(Oe);Y.rawContent=Qe;let Bt=Z.get(Y.id),Vt=null,Nt=!1;if(Bt&&(Vt=Bt.getExtractedText(),Vt===null&&(Vt=Wr(Qe)),Vt===null)){let lt=Bt.processChunk(Qe);lt instanceof Promise?(Nt=!0,lt.then(Tt=>{var An;let $e=typeof Tt=="string"?Tt:(An=Tt==null?void 0:Tt.text)!=null?An:null;if($e!==null){let mn=m;mn&&mn.id===Y.id&&(mn.content=$e,mn.streaming=!1,Z.delete(mn.id),oe.delete(mn.id),g(mn))}})):Vt=typeof lt=="string"?lt:(zo=lt==null?void 0:lt.text)!=null?zo:null}if(!Nt){Vt!==null&&Vt.trim()!==""?Y.content=Vt:oe.has(Y.id)||(Y.content=ne(Oe));let lt=Z.get(Y.id);if(lt){let Tt=(Ro=lt.close)==null?void 0:Ro.call(lt);Tt instanceof Promise&&Tt.catch(()=>{}),Z.delete(Y.id)}oe.delete(Y.id),Y.streaming=!1,g(Y)}}}}else if(Ke==="step_complete"){let $=A.stepType,W=A.executionType;if($==="tool"||W==="context")continue;let Q=A.toolContext;if(Q!=null&&Q.toolId){let Oe=String((Cs=(vo=A.id)!=null?vo:Q.stepId)!=null?Cs:"");if(Oe){let st=S(Q.toolId,Oe);for(let[Qe,Bt]of H)Qe.startsWith(st)&&Bt.streaming!==!1&&(Bt.streaming=!1,g(Bt));P.delete(`${Q.toolId}::${Oe}`)}continue}let ae=A.stopReason;if(L){if(m!==null){let Qe=m;ae&&(Qe.stopReason=ae),Z.delete(Qe.id),oe.delete(Qe.id),Qe.streaming!==!1&&(Qe.streaming=!1,g(Qe))}let Oe=(Xn=A.result)==null?void 0:Xn.response,st=Me;st&&(ae&&(st.stopReason=ae),Oe!=null?Xe(st,Oe):(Z.delete(st.id),oe.delete(st.id))),Me=null;continue}let Y=(Jn=A.result)==null?void 0:Jn.response,Re=ce();if(ae&&(Re.stopReason=ae),Y!=null){let Oe=Z.get(Re.id),st=!1,Qe=!1;if(Oe){let Bt=Oe.getExtractedText(),Vt=oe.get(Re.id),Nt=Vt!=null?Vt:ne(Y);if(Re.rawContent=Nt,Bt!==null&&Bt.trim()!=="")Re.content=Bt,st=!0;else{let lt=Wr(Nt);if(lt!==null)Re.content=lt,st=!0;else{let Tt=Oe.processChunk(Nt);if(Tt instanceof Promise)Qe=!0,Tt.then($e=>{var mn;let An=typeof $e=="string"?$e:(mn=$e==null?void 0:$e.text)!=null?mn:null;if(An!==null&&An.trim()!==""){let $t=m;$t&&$t.id===Re.id&&($t.content=An,$t.streaming=!1,Z.delete($t.id),oe.delete($t.id),g($t))}else{let $t=Oe.getExtractedText(),Co=m;Co&&Co.id===Re.id&&($t!==null&&$t.trim()!==""?Co.content=$t:oe.has(Co.id)||(Co.content=ne(Y)),Co.streaming=!1,Z.delete(Co.id),oe.delete(Co.id),g(Co))}});else{let $e=typeof Tt=="string"?Tt:(xo=Tt==null?void 0:Tt.text)!=null?xo:null;if($e!==null&&$e.trim()!=="")Re.content=$e,st=!0;else{let An=Oe.getExtractedText();An!==null&&An.trim()!==""&&(Re.content=An,st=!0)}}}}}if(!Qe){if(!Re.rawContent){let Bt=oe.get(Re.id);Re.rawContent=Bt!=null?Bt:ne(Y)}if(!st&&!oe.has(Re.id)&&(Re.content=ne(Y)),Oe){let Bt=(wo=Oe.close)==null?void 0:wo.call(Oe);Bt instanceof Promise&&Bt.catch(()=>{})}Z.delete(Re.id),oe.delete(Re.id),Re.streaming=!1,g(Re)}}else Z.delete(Re.id),oe.delete(Re.id),Re.streaming=!1,g(Re)}else if(Ke==="flow_complete"){let $=(vr=A.result)==null?void 0:vr.response;if(L){if(m!==null){let W=m;Z.delete(W.id),oe.delete(W.id),W.streaming!==!1&&(W.streaming=!1,g(W))}}else if($!=null){let W=ce(),Q=oe.get(W.id),ae=Q!=null?Q:ne($);W.rawContent=ae;let Y=ne($),Re=Z.get(W.id);if(Re){let Qe=Wr(ae);if(Qe!==null)Y=Qe;else{let Bt=Re.processChunk(ae);Bt instanceof Promise&&Bt.then(Nt=>{var Tt;let lt=typeof Nt=="string"?Nt:(Tt=Nt==null?void 0:Nt.text)!=null?Tt:null;lt!==null&&(W.content=lt,W.streaming=!1,g(W))});let Vt=Re.getExtractedText();Vt!==null&&(Y=Vt)}}Z.delete(W.id),oe.delete(W.id);let Oe=Y!==W.content,st=W.streaming!==!1;Oe&&(W.content=Y),W.streaming=!1,(Oe||st)&&g(W)}else if(m!==null){let W=m;Z.delete(W.id),oe.delete(W.id),W.streaming!==!1&&(W.streaming=!1,g(W))}n({type:"status",status:"idle"})}else if(Ke==="agent_start")ee={executionId:A.executionId,agentId:(qo=A.agentId)!=null?qo:"virtual",agentName:(Sn=A.agentName)!=null?Sn:"",status:"running",currentIteration:0,maxTurns:(Po=A.maxTurns)!=null?Po:1,startedAt:Ie(A.startedAt)};else if(Ke==="agent_iteration_start"){if(ee&&(ee.currentIteration=A.iteration),Dn==="separate"&&A.iteration>1){let $=m;$&&($.streaming=!1,g($),ze.set(A.iteration-1,$),m=null)}}else if(Ke==="agent_turn_start")C=null;else if(Ke==="agent_turn_delta"){if(A.contentType==="text"){let $=ce();$.content+=(zr=A.delta)!=null?zr:"",$.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId,agentName:ee==null?void 0:ee.agentName},C=$,g($)}else if(A.contentType==="thinking"){let $=(xr=A.turnId)!=null?xr:`agent-think-${A.iteration}`,W=He($);W.reasoning=(qr=W.reasoning)!=null?qr:{id:$,status:"streaming",chunks:[]},W.reasoning.chunks.push((xa=A.delta)!=null?xa:""),W.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId},g(W)}else if(A.contentType==="tool_input"){let $=(jr=A.toolCallId)!=null?jr:x.lastId;if($){let W=R.get($);W!=null&&W.toolCall&&(W.toolCall.chunks=(wa=W.toolCall.chunks)!=null?wa:[],W.toolCall.chunks.push((Kr=A.delta)!=null?Kr:""),g(W))}}}else if(Ke==="agent_turn_complete"){let $=A.turnId;if($){let ae=I.get($);if(ae!=null&&ae.reasoning){ae.reasoning.status="complete",ae.reasoning.completedAt=Ie(A.completedAt);let Y=(yt=ae.reasoning.startedAt)!=null?yt:Date.now();ae.reasoning.durationMs=Math.max(0,((Ss=ae.reasoning.completedAt)!=null?Ss:Date.now())-Y),ae.streaming=!1,g(ae)}}let W=A.stopReason,Q=m!=null?m:C;if(W&&Q!==null){let ae=A.turnId;(!ae||((lo=Q.agentMetadata)==null?void 0:lo.turnId)===ae)&&(Q.stopReason=W,g(Q))}}else if(Ke==="agent_tool_start"){m&&(m.streaming=!1,g(m),m=null);let $=(On=A.toolCallId)!=null?On:`agent-tool-${l()}`;Se(G(A),$);let W=se($),Q=(Ca=W.toolCall)!=null?Ca:{id:$,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};Q.name=(Gr=(Sa=A.toolName)!=null?Sa:A.name)!=null?Gr:Q.name,Q.status="running",A.parameters!==void 0&&(Q.args=A.parameters),Q.startedAt=Ie((jo=A.startedAt)!=null?jo:A.timestamp),W.toolCall=Q,W.streaming=!0,W.agentMetadata={executionId:A.executionId,iteration:A.iteration},g(W)}else if(Ke==="agent_tool_delta"){let $=(As=A.toolCallId)!=null?As:x.lastId;if($){let W=(rr=R.get($))!=null?rr:se($);W.toolCall&&(W.toolCall.chunks=(Ts=W.toolCall.chunks)!=null?Ts:[],W.toolCall.chunks.push((ks=A.delta)!=null?ks:""),W.toolCall.status="running",W.streaming=!0,g(W))}}else if(Ke==="agent_tool_complete"){let $=(Es=A.toolCallId)!=null?Es:x.lastId;if($){let W=(Ms=R.get($))!=null?Ms:se($);if(W.toolCall){W.toolCall.status="complete",A.result!==void 0&&(W.toolCall.result=A.result),typeof A.executionTime=="number"&&(W.toolCall.durationMs=A.executionTime),W.toolCall.completedAt=Ie((Nn=A.completedAt)!=null?Nn:A.timestamp),W.streaming=!1,g(W);let Q=G(A);Q&&x.byCall.delete(Q)}}}else if(Ke==="agent_media"){let $=Array.isArray(A.media)?A.media:[],W=[];for(let Q of $){if(!Q||typeof Q!="object")continue;let ae=Q,Y=typeof ae.type=="string"?ae.type:void 0,Re=typeof ae.mediaType=="string"?ae.mediaType.toLowerCase():"",Oe=null,st="";if(Y==="media"){let Qe=typeof ae.data=="string"?ae.data:void 0;if(!Qe)continue;st=Re.length>0?Re:"application/octet-stream",Oe=`data:${st};base64,${Qe}`}else if(Y==="image-url"){let Qe=typeof ae.url=="string"?ae.url:void 0;if(!Qe)continue;st=Re,Oe=Qe}else if(Y==="file-url"){let Qe=typeof ae.url=="string"?ae.url:void 0;if(!Qe)continue;st=Re,Oe=Qe}else continue;if(Oe)if(Y==="image-url"||st.startsWith("image/"))W.push({type:"image",image:Oe,...st?{mimeType:st}:{}});else if(st.startsWith("audio/"))W.push({type:"audio",audio:Oe,mimeType:st});else if(st.startsWith("video/"))W.push({type:"video",video:Oe,mimeType:st});else{let Qe=st||"application/octet-stream";W.push({type:"file",data:Oe,mimeType:Qe,filename:_h(Qe)})}}if(W.length>0){let Q=l(),ae=A.toolCallId,Re={id:`agent-media-${typeof ae=="string"&&ae.length>0?`${ae}-${Q}`:String(Q)}`,role:"assistant",content:"",contentParts:W,createdAt:new Date().toISOString(),streaming:!1,sequence:Q,agentMetadata:{executionId:A.executionId,iteration:A.iteration}};g(Re);let Oe=m;Oe&&(Oe.streaming=!1,g(Oe)),m=null,v.current=null}}else if(Ke!=="agent_iteration_complete"){if(Ke==="agent_reflection"||Ke==="agent_reflect"){let $=`agent-reflection-${A.executionId}-${A.iteration}`,W={id:$,role:"assistant",content:(Yr=A.reflection)!=null?Yr:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:$,status:"complete",chunks:[(Wo=A.reflection)!=null?Wo:""]},agentMetadata:{executionId:A.executionId,iteration:A.iteration}};g(W)}else if(Ke==="agent_complete"){ee&&(ee.status=A.success?"complete":"error",ee.completedAt=Ie(A.completedAt),ee.stopReason=A.stopReason);let $=m;$&&($.streaming=!1,g($)),n({type:"status",status:"idle"})}else if(Ke==="agent_error"){let $=typeof A.error=="string"?A.error:(Ls=(Bo=A.error)==null?void 0:Bo.message)!=null?Ls:"Agent execution error";A.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",$):n({type:"error",error:new Error($)})}else if(Ke!=="agent_ping"){if(Ke==="agent_approval_start"){let $=(Aa=A.approvalId)!=null?Aa:`approval-${l()}`,W={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:"pending",agentId:(Is=ee==null?void 0:ee.agentId)!=null?Is:"virtual",executionId:(wr=(Rs=A.executionId)!=null?Rs:ee==null?void 0:ee.executionId)!=null?wr:"",toolName:(Ta=A.toolName)!=null?Ta:"",toolType:A.toolType,description:(Ea=A.description)!=null?Ea:`Execute ${(ka=A.toolName)!=null?ka:"tool"}`,...typeof A.reason=="string"&&A.reason?{reason:A.reason}:{},parameters:A.parameters}};g(W)}else if(Ke==="step_await"&&A.awaitReason==="approval_required"){let $=(Ma=A.approvalId)!=null?Ma:`approval-${l()}`,W={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:"pending",agentId:(nl=ee==null?void 0:ee.agentId)!=null?nl:"virtual",executionId:(sr=(Cr=A.executionId)!=null?Cr:ee==null?void 0:ee.executionId)!=null?sr:"",toolName:(La=A.toolName)!=null?La:"",toolType:A.toolType,description:(ar=A.description)!=null?ar:`Execute ${(Ps=A.toolName)!=null?Ps:"tool"}`,...typeof A.reason=="string"&&A.reason?{reason:A.reason}:{},parameters:A.parameters}};g(W)}else if(Ke==="agent_approval_complete"){let $=A.approvalId;if($){let Q={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:(Ia=A.decision)!=null?Ia:"approved",agentId:(Ws=ee==null?void 0:ee.agentId)!=null?Ws:"virtual",executionId:(Bs=(ir=A.executionId)!=null?ir:ee==null?void 0:ee.executionId)!=null?Bs:"",toolName:(Ra=A.toolName)!=null?Ra:"",description:(Ko=A.description)!=null?Ko:"",resolvedAt:Date.now()}};g(Q)}}else if(Ke==="artifact_start"||Ke==="artifact_delta"||Ke==="artifact_update"||Ke==="artifact_complete"){if(Ke==="artifact_start"){let $=A.artifactType,W=String(A.id),Q=typeof A.title=="string"?A.title:void 0;if(n({type:"artifact_start",id:W,artifactType:$,title:Q,component:typeof A.component=="string"?A.component:void 0}),be.set(W,{markdown:"",title:Q}),!re.has(W)){re.add(W);let ae={id:`artifact-ref-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:W,title:Q,artifactType:$,status:"streaming"}})};X.set(W,ae),g(ae)}}else if(Ke==="artifact_delta"){let $=String(A.id),W=typeof A.delta=="string"?A.delta:String((Pa=A.delta)!=null?Pa:"");n({type:"artifact_delta",id:$,artDelta:W});let Q=be.get($);Q&&(Q.markdown+=W)}else if(Ke==="artifact_update"){let $=A.props&&typeof A.props=="object"&&!Array.isArray(A.props)?A.props:{};n({type:"artifact_update",id:String(A.id),props:$,component:typeof A.component=="string"?A.component:void 0})}else if(Ke==="artifact_complete"){let $=String(A.id);n({type:"artifact_complete",id:$});let W=X.get($);if(W){W.streaming=!1;try{let Q=JSON.parse((lr=W.rawContent)!=null?lr:"{}");if(Q.props){Q.props.status="complete";let ae=be.get($);ae!=null&&ae.markdown&&(Q.props.markdown=ae.markdown)}W.rawContent=JSON.stringify(Q)}catch{}be.delete($),g(W),X.delete($)}}}else if(Ke==="transcript_insert"){let $=A.message;if(!$||typeof $!="object")continue;let W=String((Ft=$.id)!=null?Ft:`msg-${l()}`),Q=$.role,Y={id:W,role:Q==="user"?"user":Q==="system"?"system":"assistant",content:typeof $.content=="string"?$.content:"",rawContent:typeof $.rawContent=="string"?$.rawContent:void 0,createdAt:typeof $.createdAt=="string"?$.createdAt:new Date().toISOString(),streaming:$.streaming===!0,...typeof $.variant=="string"?{variant:$.variant}:{},sequence:l()};if(g(Y),Y.rawContent)try{let Re=JSON.parse(Y.rawContent),Oe=(Xr=Re==null?void 0:Re.props)==null?void 0:Xr.artifactId;typeof Oe=="string"&&re.add(Oe)}catch{}m=null,v.current=null,Z.delete(W),oe.delete(W)}else if(Ke==="error"||Ke==="step_error"||Ke==="dispatch_error"||Ke==="flow_error"){let $=null;if(A.error instanceof Error)$=A.error;else if(Ke==="dispatch_error"){let W=(Jr=A.message)!=null?Jr:A.error;W!=null&&W!==""&&($=new Error(String(W)))}else if(Ke==="step_error"||Ke==="flow_error"){let W=A.error;typeof W=="string"&&W!==""?$=new Error(W):W!=null&&typeof W=="object"&&"message"in W&&($=new Error(String((Hs=W.message)!=null?Hs:W)))}else Ke==="error"&&A.error!=null&&A.error!==""&&($=new Error(String(A.error)));if($){n({type:"error",error:$});let W=m;W&&W.streaming&&(W.streaming=!1,g(W)),n({type:"status",status:"idle"})}}}}}We.length=0};;){let{done:D,value:pe}=await r.read();if(D)break;a+=s.decode(pe,{stream:!0});let De=a.split(`
|
|
10
10
|
|
|
11
|
-
`);a=(
|
|
12
|
-
`),dt="message",ot="";for(let q of $e)q.startsWith("event:")?dt=q.replace("event:","").trim():q.startsWith("data:")&&(ot+=q.replace("data:","").trim());if(!ot)continue;let At;try{At=JSON.parse(ot)}catch(q){n({type:"error",error:q instanceof Error?q:new Error("Failed to parse chat stream payload")});continue}let Vt=dt!=="message"?dt:(Jn=At.type)!=null?Jn:"message";if((qe=this.onSSEEvent)==null||qe.call(this,Vt,At),this.parseSSEEvent){S.current=p;let q=await this.handleCustomSSEEvent(At,n,S,g,l,M);if(S.current&&S.current!==p&&(p=S.current),q)continue}pe.push(Vt,At),Ve()}}pe.flushPending(),Ve(),pe.destroy()}};function Qa(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Bs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ja="[Image]";function cl(e){return{type:"text",text:e}}var Ru=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Jg=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],_o=[...Ru,...Jg];function Zg(e){return Ru.includes(e)||e.startsWith("image/")}function Za(e){return Zg(e.type)}async function Pu(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Za(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function Wu(e,t=_o,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function eh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Bu(e,t){let n=eh(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var ei=class{constructor(t=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=t}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let d=new Uint8Array(this.remainder.length+t.length);d.set(this.remainder),d.set(t,this.remainder.length),n=d,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.ensureContext(),r=this.pcmToFloat32(n),s=o.createBuffer(1,r.length,this.sampleRate);s.getChannelData(0).set(r);let a=o.createBufferSource();a.buffer=s,a.connect(o.destination);let i=o.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=s.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=r.getInt16(s*2,!0);o[s]=a/32768}return o}};var ti=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,o,r,s){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(n),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let m=0;m<a.length;m++)i+=a[m]*a[m];let d=Math.sqrt(i/a.length);(o==="silence"?d<r.threshold:d>=r.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=r.duration&&(this.fired=!0,s()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Hs=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new ti;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,n,o;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let r=this.w;if(!r||!r.location)throw new Error("Window object or location not available");let s=r.location.protocol==="https:"?"wss:":"ws:",a=(t=this.config)==null?void 0:t.host,i=(n=this.config)==null?void 0:n.agentId,d=(o=this.config)==null?void 0:o.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let m=`${s}//${a}/ws/agents/${i}/voice?token=...`,u=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((g,p)=>{if(!this.ws)return p(new Error("WebSocket not created"));let w=!1,S=I=>{w||(w=!0,clearTimeout(M),p(new Error(I)))},M=setTimeout(()=>S("WebSocket connection timed out."+u),1e4);this.ws.addEventListener("open",()=>{w||(w=!0,clearTimeout(M),g())},{once:!0}),this.ws.addEventListener("error",()=>{S("WebSocket connection failed to "+m+"."+u)},{once:!0}),this.ws.addEventListener("close",I=>{if(!I.wasClean&&!w){let L=I.code!==1006?` (code ${I.code})`:"";S("WebSocket connection failed"+L+"."+u)}},{once:!0})}),this.sendHeartbeat()}catch(r){throw this.ws=null,this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(n=>n(new Error("WebSocket error"))),this.statusCallbacks.forEach(n=>n("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let n=JSON.parse(t.data);this.handleWebSocketMessage(n)}catch{this.errorCallbacks.forEach(o=>o(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var n,o;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(r=>r({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),(n=t.response.audio)!=null&&n.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(r=>r("speaking")),this.playAudio(t.response.audio).catch(r=>this.errorCallbacks.forEach(s=>s(r instanceof Error?r:new Error(String(r)))))):(o=t.response.audio)!=null&&o.base64;break;case"audio_end":if(t.requestId&&t.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(r=>r("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(r=>r(new Error(t.error))),this.statusCallbacks.forEach(r=>r("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new ei(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,n,o,r;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(r=(o=this.config)==null?void 0:o.silenceThreshold)!=null?r:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(g=>g("processing")),this.processingStartCallbacks.forEach(g=>g());let m=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",u=new Blob(this.audioChunks,{type:m});await this.sendAudio(u),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var s,a;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let n=this.audioContext,o=(a=(s=this.config)==null?void 0:s.silenceThreshold)!=null?a:.01;this.vad.start(n,this.mediaStream,"speech",{threshold:o,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(n=>n(t instanceof Error?t:new Error(String(t))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(t){var n;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(o=>o(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(o=>o("error"));return}try{let o=await this.blobToBase64(t),r=this.getFormatFromMimeType(t.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:o,format:r,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:s}))}catch(o){this.errorCallbacks.forEach(r=>r(o)),this.statusCallbacks.forEach(r=>r("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,o)=>{let r=new FileReader;r.onload=()=>{let a=r.result.split(",")[1];n(a)},r.onerror=o,r.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let n=atob(t.base64),o=new Uint8Array(n.length);for(let l=0;l<n.length;l++)o[l]=n.charCodeAt(l);let r=t.format||"mp3",s=r==="mp3"?"audio/mpeg":`audio/${r}`,a=new Blob([o],{type:s}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Sr=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let o=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!o)throw new Error("Browser speech recognition not supported");this.recognition=new o,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=r=>{var i;let s=Array.from(r.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=r.results[r.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=r=>{this.errorCallbacks.forEach(s=>s(new Error(r.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(r=>r("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(r=>r("idle"))},this.recognition.start()}catch(o){throw this.errorCallbacks.forEach(r=>r(o)),this.statusCallbacks.forEach(r=>r("error")),o}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Ds(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Hs(e.runtype);case"browser":if(!Sr.isSupported())throw new Error("Browser speech recognition not supported");return new Sr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Hu(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Ds({type:"runtype",runtype:e.runtype});if(Sr.isSupported())return Ds({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function dl(e){try{return Hu(e),!0}catch{return!1}}function Du(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let o="Sorry \u2014 I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
|
|
11
|
+
`);a=(sn=De.pop())!=null?sn:"";for(let je of De){let Ne=je.split(`
|
|
12
|
+
`),Ve="message",nt="";for(let Xt of Ne)Xt.startsWith("event:")?Ve=Xt.replace("event:","").trim():Xt.startsWith("data:")&&(nt+=Xt.replace("data:","").trim());if(!nt)continue;let Rt;try{Rt=JSON.parse(nt)}catch(Xt){n({type:"error",error:Xt instanceof Error?Xt:new Error("Failed to parse chat stream payload")});continue}let jt=Ve!=="message"?Ve:(no=Rt.type)!=null?no:"message";if((ko=this.onSSEEvent)==null||ko.call(this,jt,Rt),this.parseSSEEvent){v.current=m;let Xt=await this.handleCustomSSEEvent(Rt,n,v,g,l,E);if(v.current&&v.current!==m&&(m=v.current),Xt)continue}Et.push(jt,Rt),me()}}Et.flushPending(),me(),Et.destroy()}};function ii(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Xs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var li="[Image]";function kl(e){return{type:"text",text:e}}var dm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Uh=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Yo=[...dm,...Uh];function zh(e){return dm.includes(e)||e.startsWith("image/")}function ci(e){return zh(e.type)}async function pm(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;ci(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function um(e,t=Yo,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function qh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function mm(e,t){let n=qh(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var di=class{constructor(t=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=t}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let d=new Uint8Array(this.remainder.length+t.length);d.set(this.remainder),d.set(t,this.remainder.length),n=d,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.ensureContext(),r=this.pcmToFloat32(n),s=o.createBuffer(1,r.length,this.sampleRate);s.getChannelData(0).set(r);let a=o.createBufferSource();a.buffer=s,a.connect(o.destination);let i=o.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=s.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=r.getInt16(s*2,!0);o[s]=a/32768}return o}};var pi=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,o,r,s){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(n),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let f=0;f<a.length;f++)i+=a[f]*a[f];let d=Math.sqrt(i/a.length);(o==="silence"?d<r.threshold:d>=r.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=r.duration&&(this.fired=!0,s()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Js=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new pi;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,n,o;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let r=this.w;if(!r||!r.location)throw new Error("Window object or location not available");let s=r.location.protocol==="https:"?"wss:":"ws:",a=(t=this.config)==null?void 0:t.host,i=(n=this.config)==null?void 0:n.agentId,d=(o=this.config)==null?void 0:o.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let f=`${s}//${a}/ws/agents/${i}/voice?token=...`,u=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((g,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let C=!1,v=L=>{C||(C=!0,clearTimeout(E),m(new Error(L)))},E=setTimeout(()=>v("WebSocket connection timed out."+u),1e4);this.ws.addEventListener("open",()=>{C||(C=!0,clearTimeout(E),g())},{once:!0}),this.ws.addEventListener("error",()=>{v("WebSocket connection failed to "+f+"."+u)},{once:!0}),this.ws.addEventListener("close",L=>{if(!L.wasClean&&!C){let I=L.code!==1006?` (code ${L.code})`:"";v("WebSocket connection failed"+I+"."+u)}},{once:!0})}),this.sendHeartbeat()}catch(r){throw this.ws=null,this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(n=>n(new Error("WebSocket error"))),this.statusCallbacks.forEach(n=>n("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let n=JSON.parse(t.data);this.handleWebSocketMessage(n)}catch{this.errorCallbacks.forEach(o=>o(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var n,o;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(r=>r({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),(n=t.response.audio)!=null&&n.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(r=>r("speaking")),this.playAudio(t.response.audio).catch(r=>this.errorCallbacks.forEach(s=>s(r instanceof Error?r:new Error(String(r)))))):(o=t.response.audio)!=null&&o.base64;break;case"audio_end":if(t.requestId&&t.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(r=>r("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(r=>r(new Error(t.error))),this.statusCallbacks.forEach(r=>r("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new di(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,n,o,r;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(r=(o=this.config)==null?void 0:o.silenceThreshold)!=null?r:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(g=>g("processing")),this.processingStartCallbacks.forEach(g=>g());let f=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",u=new Blob(this.audioChunks,{type:f});await this.sendAudio(u),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var s,a;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let n=this.audioContext,o=(a=(s=this.config)==null?void 0:s.silenceThreshold)!=null?a:.01;this.vad.start(n,this.mediaStream,"speech",{threshold:o,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(n=>n(t instanceof Error?t:new Error(String(t))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(t){var n;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(o=>o(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(o=>o("error"));return}try{let o=await this.blobToBase64(t),r=this.getFormatFromMimeType(t.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:o,format:r,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:s}))}catch(o){this.errorCallbacks.forEach(r=>r(o)),this.statusCallbacks.forEach(r=>r("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,o)=>{let r=new FileReader;r.onload=()=>{let a=r.result.split(",")[1];n(a)},r.onerror=o,r.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let n=atob(t.base64),o=new Uint8Array(n.length);for(let l=0;l<n.length;l++)o[l]=n.charCodeAt(l);let r=t.format||"mp3",s=r==="mp3"?"audio/mpeg":`audio/${r}`,a=new Blob([o],{type:s}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Br=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let o=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!o)throw new Error("Browser speech recognition not supported");this.recognition=new o,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=r=>{var i;let s=Array.from(r.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=r.results[r.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=r=>{this.errorCallbacks.forEach(s=>s(new Error(r.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(r=>r("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(r=>r("idle"))},this.recognition.start()}catch(o){throw this.errorCallbacks.forEach(r=>r(o)),this.statusCallbacks.forEach(r=>r("error")),o}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Qs(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Js(e.runtype);case"browser":if(!Br.isSupported())throw new Error("Browser speech recognition not supported");return new Br(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function fm(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Qs({type:"runtype",runtype:e.runtype});if(Br.isSupported())return Qs({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function El(e){try{return fm(e),!0}catch{return!1}}function gm(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let o="Sorry \u2014 I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
|
|
13
13
|
|
|
14
|
-
_Details: ${n.message}_`:o}var Fs=e=>({isError:!0,content:[{type:"text",text:e}]}),Fu=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,ni=class e{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=t=>{var n,o,r,s,a,i,d,l;if(t.type==="message"){this.upsertMessage(t.message);let m=t.message.toolCall;((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&(m!=null&&m.name)&&qr(m.name)&&this.enqueueWebMcpAwait(t.message),(o=t.message.agentMetadata)!=null&&o.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(r=t.message.agentMetadata.agentName)!=null?r:"",status:"running",currentIteration:(s=t.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let m=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":m||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var o,r;this.messages=[...(o=t.initialMessages)!=null?o:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Ws(t),this.wireDefaultWebMcpConfirm();for(let s of(r=t.initialArtifacts)!=null?r:[])this.artifacts.set(s.id,{...s,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return dl((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,o;return(o=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?o:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(t){var n,o,r;try{let s=t||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=Ds(s);let a=(n=this.config.voiceRecognition)!=null?n:{},i=(o=a.processingText)!=null?o:"\u{1F3A4} Processing voice...",d=(r=a.processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let m=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=m.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var m,u,g,p,w,S;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((m=l.transcript)!=null&&m.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(u=l.transcript)!=null&&u.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((g=l.text)!=null&&g.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=l.text)!=null&&p.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let M=(S=this.pendingVoiceAssistantMessageId)!=null?S:(w=[...this.messages].reverse().find(I=>I.role==="assistant"))==null?void 0:w.id;M&&this.ttsSpokenMessageIds.add(M)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var m,u;this.voiceStatus=l,this.voiceActive=l==="listening",(u=(m=this.callbacks).onVoiceStatusChanged)==null||u.call(m,l)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,o,r,s,a,i,d,l,m;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((o=t.runtype)==null?void 0:o.agentId)||"",clientToken:((r=t.runtype)==null?void 0:r.clientToken)||"",host:(s=t.runtype)==null?void 0:s.host,voiceId:(a=t.runtype)==null?void 0:a.voiceId,pauseDuration:(i=t.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=t.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=t.browser)==null?void 0:l.language)||"en-US",continuous:(m=t.browser)==null?void 0:m.continuous}};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let o=await this.client.initSession();return this.setClientSession(o),o}catch(o){return(n=(t=this.callbacks).onError)==null||n.call(t,o instanceof Error?o:new Error(String(o))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let n=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new Ws(this.config),this.wireDefaultWebMcpConfirm(),n&&this.client.setSSEEventCallback(n)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:m,rawContent:u}=t,p={id:a!=null?a:n==="user"?Qa():n==="assistant"?Bs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...m!==void 0&&{voiceProcessing:m},...u!==void 0&&{rawContent:u}};return this.upsertMessage(p),p}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:m,streaming:u=!1,voiceProcessing:g,rawContent:p}=o,S={id:d!=null?d:r==="user"?Qa():r==="assistant"?Bs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:m!=null?m:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...p!==void 0&&{rawContent:p}};n.push(S)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:i,sequence:d}=t,l={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(l),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var l,m,u,g,p;let o=t.trim();if(!o&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let r=Qa(),s=Bs(),a={id:r,role:"user",content:o||Ja,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(w){let S=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));if(!S){let M=Du(w,this.config.errorMessage);if(M){let I={id:s,role:"assistant",createdAt:new Date().toISOString(),content:M,sequence:this.nextSequence()};this.appendMessage(I)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,S||(w instanceof Error?(u=(m=this.callbacks).onError)==null||u.call(m,w):(p=(g=this.callbacks).onError)==null||p.call(g,new Error(String(w))))}}async continueConversation(){var r,s,a,i,d;if(this.streaming)return;(r=this.abortController)==null||r.abort();let t=Bs();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(l){let m=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!m){let u=Du(l,this.config.errorMessage);if(u){let g={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,m||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var r,s,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(r=this.abortController)==null||r.abort();let o=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var r,s,a;try{if(((s=(r=this.config.webmcp)==null?void 0:r.autoApprove)==null?void 0:s.call(r,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(o,i)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r!=null&&r.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n){var d,l,m,u;let o=`approval-${t.id}`,r={...t,status:n,resolvedAt:Date.now()},s={id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:r};this.upsertMessage(s),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let g;if(i?g=await i({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n):g=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),g){let p=null;if(g instanceof Response){if(!g.ok){let w=await g.json().catch(()=>null);throw new Error((l=w==null?void 0:w.error)!=null?l:`Approval request failed: ${g.status}`)}p=g.body}else g instanceof ReadableStream&&(p=g);p?await this.connectStream(p,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(g){let p=g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"));this.setStreaming(!1),this.abortController=null,p||(u=(m=this.callbacks).onError)==null||u.call(m,g instanceof Error?g:new Error(String(g)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var m,u,g,p,w,S,M,I,L,H,D,W;let o=this.messages.find(v=>v.id===t.id);if(((m=o==null?void 0:o.agentMetadata)==null?void 0:m.askUserQuestionAnswered)===!0)return;let r=(u=t.agentMetadata)==null?void 0:u.executionId,s=(g=t.toolCall)==null?void 0:g.name;if(!r||!s){(w=(p=this.callbacks).onError)==null||w.call(p,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let v=(S=t.toolCall)==null?void 0:S.args,x=Array.isArray(v==null?void 0:v.questions)?v.questions:[];if(x.length===1){let k=typeof((M=x[0])==null?void 0:M.question)=="string"?x[0].question:"";k&&(a={[k]:n})}}this.markAskUserQuestionResolved(t,a),(I=this.abortController)==null||I.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(L=t.toolCall)==null?void 0:L.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let v=typeof n=="string"?n:Object.entries(n).map(([x,k])=>`${x}: ${Array.isArray(k)?k.join(", "):k}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:v,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let v=a!=null?a:{};l.forEach((x,k)=>{let C=typeof(x==null?void 0:x.question)=="string"?x.question:"";if(!C)return;let T=v[C],F=Array.isArray(T)?T.join(", "):typeof T=="string"?T:"";this.appendMessage({id:`ask-user-q-${i}-${k}`,role:"assistant",content:C,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${k}`,role:"user",content:F||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let v=await this.client.resumeFlow(r,{[s]:n});if(!v.ok){let x=await v.json().catch(()=>null);throw new Error((H=x==null?void 0:x.error)!=null?H:`Resume failed: ${v.status}`)}v.body?await this.connectStream(v.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,x||(W=(D=this.callbacks).onError)==null||W.call(D,v instanceof Error?v:new Error(String(v)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,o=(a=t.toolCall)==null?void 0:a.id;if(!n||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){var r,s;let n=this.messages.find(a=>a.id===t.id),o=[(r=n==null?void 0:n.toolCall)==null?void 0:r.startedAt,(s=t.toolCall)==null?void 0:s.startedAt];for(let a of o)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now()){this.messages.some(s=>s.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,l,m;let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async u=>{var D,W,v,x,k,C,T;let g=(D=u.toolCall)==null?void 0:D.name,p=(W=u.toolCall)==null?void 0:W.id;if(!g||!p)return null;let w=`${t}:${p}`;if(this.webMcpInflightKeys.has(w)||this.webMcpResolvedKeys.has(w))return null;this.webMcpInflightKeys.add(w),o.push(w);let S=this.markWebMcpToolRunning(u),M=new AbortController;this.webMcpResolveControllers.add(M),r.push(M);let I=(x=(v=u.agentMetadata)==null?void 0:v.webMcpToolCallId)!=null?x:g,L=this.client.executeWebMcpToolCall(g,(k=u.toolCall)==null?void 0:k.args,M.signal),H;if(!L)H={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{H=await L}catch(F){let $=F instanceof Error&&(F.name==="AbortError"||F.message.includes("aborted")||F.message.includes("abort"));return $||(T=(C=this.callbacks).onError)==null||T.call(C,F instanceof Error?F:new Error(String(F))),this.markWebMcpToolComplete(u,Fs($?"Aborted by cancel()":Fu(F)),S),this.webMcpInflightKeys.delete(w),null}return M.signal.aborted?(this.markWebMcpToolComplete(u,Fs("Aborted by cancel()"),S),this.webMcpInflightKeys.delete(w),null):{dedupeKey:w,resumeKey:I,output:H,toolMessage:u,startedAt:S,completedAt:Date.now()}})),i=[];try{if(i=a.filter(p=>p!==null),i.length===0)return;let u={};for(let p of i)u[p.resumeKey]=p.output;let g=await this.client.resumeFlow(t,u,{signal:s.signal});if(!g.ok){let p=await g.json().catch(()=>null);throw new Error((d=p==null?void 0:p.error)!=null?d:`Resume failed: ${g.status}`)}for(let p of i)this.webMcpResolvedKeys.add(p.dedupeKey),this.markWebMcpToolComplete(p.toolMessage,p.output,p.startedAt,p.completedAt);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(u){if(!(u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))))(m=(l=this.callbacks).onError)==null||m.call(l,u instanceof Error?u:new Error(String(u)));else for(let p of i)this.markWebMcpToolComplete(p.toolMessage,Fs("Aborted by cancel()"),p.startedAt)}finally{for(let u of o)this.webMcpInflightKeys.delete(u);for(let u of r)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var p,w,S,M,I,L,H,D,W,v,x,k;let n=(p=t.agentMetadata)==null?void 0:p.executionId,o=(w=t.toolCall)==null?void 0:w.name,r=(S=t.toolCall)==null?void 0:S.id;if(!n){(I=(M=this.callbacks).onError)==null||I.call(M,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!o)return;if(!r){let C=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(C)||this.webMcpResolvedKeys.has(C))return;this.webMcpInflightKeys.add(C);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(C)}catch(T){(H=(L=this.callbacks).onError)==null||H.call(L,T instanceof Error?T:new Error(String(T)))}finally{this.webMcpInflightKeys.delete(C)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let l=(D=t.toolCall)==null?void 0:D.args,m=this.client.executeWebMcpToolCall(o,l,d),u="execute",g=a;try{let C;if(m?C=await m:C={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),d.aborted){this.markWebMcpToolComplete(t,Fs("Aborted by cancel()"),a);return}let T=(v=(W=t.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?v:o;u="resume",await this.resumeWithToolOutput(n,T,C,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,C,a,g)},signal:d})}catch(C){let T=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));(u==="execute"||T||d.aborted)&&this.markWebMcpToolComplete(t,Fs(T||d.aborted?"Aborted by cancel()":Fu(C)),a),T||(k=(x=this.callbacks).onError)==null||k.call(x,C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){var a,i;let s=await this.client.resumeFlow(t,{[n]:o},{signal:r==null?void 0:r.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=r==null?void 0:r.onHttpOk)==null||i.call(r),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var r;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let o={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(r=t.props)!=null?r:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),o}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,o;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let r=this.artifacts.get(t.id);(r==null?void 0:r.artifactType)==="markdown"&&(r.markdown=((o=r.markdown)!=null?o:"")+t.artDelta);break}case"artifact_update":{let r=this.artifacts.get(t.id);(r==null?void 0:r.artifactType)==="component"&&(r.props={...r.props,...t.props},t.component&&(r.component=t.component));break}case"artifact_complete":{let r=this.artifacts.get(t.id);r&&(r.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>{var r;return{...o,streaming:!1,sequence:(r=o.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=o.content;r.trim()&&this.speak(r,t)}speak(t,n){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t),s=o.getVoices();if(n.voice){let a=s.find(i=>i.name===n.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=n.pickVoice?n.pickVoice(s):e.pickBestVoice(s));n.rate!==void 0&&(r.rate=n.rate),n.pitch!==void 0&&(r.pitch=n.pitch),setTimeout(()=>o.speak(r),50)}static pickBestVoice(t){var o;let n=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of n){let s=t.find(a=>a.name===r);if(s)return s}return(o=t.find(r=>r.lang.startsWith("en")))!=null?o:t[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{var m,u,g,p,w,S,M,I,L,H;if(s!==o)return r;let a={...r,...n};((m=r.agentMetadata)==null?void 0:m.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(u=n.toolCall)==null?void 0:u.name,d=(g=n.agentMetadata)==null?void 0:g.executionId,l=(p=n.toolCall)==null?void 0:p.id;if(i&&qr(i)&&d&&l&&((w=n.agentMetadata)==null?void 0:w.awaitingLocalTool)===!0){let D=`${d}:${l}`,W=this.webMcpInflightKeys.has(D),v=this.webMcpResolvedKeys.has(D),x=(S=r.toolCall)==null?void 0:S.name,k=((M=r.agentMetadata)==null?void 0:M.executionId)===d&&((I=r.toolCall)==null?void 0:I.id)===l&&x!==void 0&&qr(x)&&((L=r.toolCall)==null?void 0:L.status)==="complete";(W||v||k)&&(a.agentMetadata={...(H=a.agentMetadata)!=null?H:{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{var d,l;let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=(d=n.sequence)!=null?d:0,i=(l=o.sequence)!=null?l:0;return a!==i?a-i:n.id.localeCompare(o.id)})}};var b=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Eo=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o};import{Activity as th,ArrowDown as nh,ArrowUp as oh,ArrowUpRight as rh,Bot as sh,ChevronDown as ah,ChevronUp as ih,ChevronRight as lh,ChevronLeft as ch,Check as dh,Clipboard as ph,ClipboardCopy as uh,Copy as mh,File as fh,FileCode as gh,FileSpreadsheet as hh,FileText as bh,ImagePlus as yh,Loader as vh,LoaderCircle as xh,Mic as wh,Paperclip as Ch,RefreshCw as Sh,Search as Ah,Send as Th,ShieldAlert as kh,ShieldCheck as Eh,ShieldX as Mh,Square as Lh,ThumbsDown as Ih,ThumbsUp as Rh,Upload as Ph,Volume2 as Wh,X as Bh,User as Hh,Mail as Dh,Phone as Fh,Calendar as Oh,Clock as Nh,Building as _h,MapPin as Vh,Lock as $h,Key as Uh,CreditCard as zh,AtSign as qh,Hash as jh,Globe as Kh,Link as Gh,CircleCheck as Yh,CircleX as Xh,TriangleAlert as Qh,Info as Jh,Ban as Zh,Shield as eb,ArrowLeft as tb,ArrowRight as nb,ExternalLink as ob,Ellipsis as rb,EllipsisVertical as sb,Menu as ab,House as ib,Plus as lb,Minus as cb,Pencil as db,Trash as pb,Trash2 as ub,Save as mb,Download as fb,Share as gb,Funnel as hb,Settings as bb,RotateCw as yb,Maximize as vb,Minimize as xb,ShoppingCart as wb,ShoppingBag as Cb,Package as Sb,Truck as Ab,Tag as Tb,Gift as kb,Receipt as Eb,Wallet as Mb,Store as Lb,DollarSign as Ib,Percent as Rb,Play as Pb,Pause as Wb,VolumeX as Bb,Camera as Hb,Image as Db,Film as Fb,Headphones as Ob,MessageCircle as Nb,MessageSquare as _b,Bell as Vb,Heart as $b,Star as Ub,Eye as zb,EyeOff as qb,Bookmark as jb,CalendarDays as Kb,History as Gb,Timer as Yb,Folder as Xb,FolderOpen as Qb,Files as Jb,Sparkles as Zb,Zap as ey,Sun as ty,Moon as ny,Flag as oy,Monitor as ry,Smartphone as sy}from"lucide";var ay={activity:th,"arrow-down":nh,"arrow-up":oh,"arrow-up-right":rh,bot:sh,"chevron-down":ah,"chevron-up":ih,"chevron-right":lh,"chevron-left":ch,check:dh,clipboard:ph,"clipboard-copy":uh,copy:mh,file:fh,"file-code":gh,"file-spreadsheet":hh,"file-text":bh,"image-plus":yh,loader:vh,"loader-circle":xh,mic:wh,paperclip:Ch,"refresh-cw":Sh,search:Ah,send:Th,"shield-alert":kh,"shield-check":Eh,"shield-x":Mh,square:Lh,"thumbs-down":Ih,"thumbs-up":Rh,upload:Ph,"volume-2":Wh,x:Bh,user:Hh,mail:Dh,phone:Fh,calendar:Oh,clock:Nh,building:_h,"map-pin":Vh,lock:$h,key:Uh,"credit-card":zh,"at-sign":qh,hash:jh,globe:Kh,link:Gh,"circle-check":Yh,"circle-x":Xh,"triangle-alert":Qh,info:Jh,ban:Zh,shield:eb,"arrow-left":tb,"arrow-right":nb,"external-link":ob,ellipsis:rb,"ellipsis-vertical":sb,menu:ab,house:ib,plus:lb,minus:cb,pencil:db,trash:pb,"trash-2":ub,save:mb,download:fb,share:gb,funnel:hb,settings:bb,"rotate-cw":yb,maximize:vb,minimize:xb,"shopping-cart":wb,"shopping-bag":Cb,package:Sb,truck:Ab,tag:Tb,gift:kb,receipt:Eb,wallet:Mb,store:Lb,"dollar-sign":Ib,percent:Rb,play:Pb,pause:Wb,"volume-x":Bb,camera:Hb,image:Db,film:Fb,headphones:Ob,"message-circle":Nb,"message-square":_b,bell:Vb,heart:$b,star:Ub,eye:zb,"eye-off":qb,bookmark:jb,"calendar-days":Kb,history:Gb,timer:Yb,folder:Xb,"folder-open":Qb,files:Jb,sparkles:Zb,zap:ey,sun:ty,moon:ny,flag:oy,monitor:ry,smartphone:sy},Te=(e,t=24,n="currentColor",o=2)=>{let r=ay[e];return r?iy(r,t,n,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function iy(e,t,n,o){if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,m])=>{l!=="stroke"&&d.setAttribute(l,String(m))}),r.appendChild(d)}),r}var oi={allowedTypes:_o,maxFileSize:10*1024*1024,maxFiles:4};function ly(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function cy(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var Os=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,o,r;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:oi.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:oi.maxFileSize,maxFiles:(r=t.maxFiles)!=null?r:oi.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:oi.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,o,r,s,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(o=(n=this.config).onFileRejected)==null||o.call(n,l,"count");continue}let m=Wu(l,this.config.allowedTypes,this.config.maxFileSize);if(!m.valid){let u=(r=m.error)!=null&&r.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,u);continue}try{let u=await Pu(l),g=Za(l)?URL.createObjectURL(l):null,p={id:ly(),file:l,previewUrl:g,contentPart:u};this.attachments.push(p),this.renderPreview(p)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let o of this.attachments)o.previewUrl&&URL.revokeObjectURL(o.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Za(t.file),o=b("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let a=b("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=b("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=cy(t.file.type),d=Te(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=b("span");l.textContent=Bu(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),o.appendChild(a)}let r=b("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=Te("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};import{Idiomorph as dy}from"idiomorph";var ri=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;dy.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){var a,i;if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=r.textContent)!=null?a:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var si={index:-1,draft:""};function Ou(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:o}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...si}}}function Nu(e,t){var n,o,r,s,a,i,d,l,m,u,g,p,w,S,M,I,L,H,D,W,v,x,k,C,T,F,$,j,me,se,fe,ie,be,Oe,ve,Q,Le,Y;return[e.id,e.role,(o=(n=e.content)==null?void 0:n.length)!=null?o:0,(s=(r=e.content)==null?void 0:r.slice(-32))!=null?s:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(m=(l=e.llmContent)==null?void 0:l.length)!=null?m:0,(g=(u=e.approval)==null?void 0:u.status)!=null?g:"",(w=(p=e.toolCall)==null?void 0:p.status)!=null?w:"",(M=(S=e.toolCall)==null?void 0:S.name)!=null?M:"",(H=(L=(I=e.toolCall)==null?void 0:I.chunks)==null?void 0:L.length)!=null?H:0,(x=(v=(W=(D=e.toolCall)==null?void 0:D.chunks)==null?void 0:W[e.toolCall.chunks.length-1])==null?void 0:v.slice(-32))!=null?x:"",typeof((k=e.toolCall)==null?void 0:k.args)=="string"?e.toolCall.args.length:(C=e.toolCall)!=null&&C.args?JSON.stringify(e.toolCall.args).length:0,($=(F=(T=e.reasoning)==null?void 0:T.chunks)==null?void 0:F.length)!=null?$:0,(fe=(se=(me=(j=e.reasoning)==null?void 0:j.chunks)==null?void 0:me[e.reasoning.chunks.length-1])==null?void 0:se.length)!=null?fe:0,(ve=(Oe=(be=(ie=e.reasoning)==null?void 0:ie.chunks)==null?void 0:be[e.reasoning.chunks.length-1])==null?void 0:Oe.slice(-32))!=null?ve:"",(Le=(Q=e.contentParts)==null?void 0:Q.length)!=null?Le:0,(Y=e.stopReason)!=null?Y:"",t].join("\0")}function _u(){return new Map}function Vu(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function $u(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Uu(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function ai(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Ns(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function _s(e,t){return Ns(e)-e.scrollTop<=t}function ii(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,m=n-o;return a||Math.abs(m)<s?{action:"none",delta:m,nextLastScrollTop:n}:!t&&r&&(!l||m>0)?{action:"resume",delta:m,nextLastScrollTop:n}:t&&i&&m<0?{action:"pause",delta:m,nextLastScrollTop:n}:t&&d&&!r?{action:"pause",delta:m,nextLastScrollTop:n}:{action:"none",delta:m,nextLastScrollTop:n}}function li(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}var gn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},hn=1e5,or=hn+1;var Vs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},py=["pre","code","a","script","style"],ci=e=>{var t,n,o,r,s;return{type:(t=e==null?void 0:e.type)!=null?t:Vs.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:Vs.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:Vs.speed,duration:(r=e==null?void 0:e.duration)!=null?r:Vs.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:Vs.buffer}},uy=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],qu=new Map;for(let e of uy)qu.set(e.name,e);var $s=(e,t)=>{var n,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(o=qu.get(e))!=null?o:null},di=(e,t,n,o,r)=>{if(!r)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
|
|
15
|
-
`);return s<0?"":e.slice(0,s)}return e},
|
|
14
|
+
_Details: ${n.message}_`:o}var Zs=e=>({isError:!0,content:[{type:"text",text:e}]}),hm=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,ui=class e{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=t=>{var n,o,r,s,a,i,d,l;if(t.type==="message"){this.upsertMessage(t.message);let f=t.message.toolCall;((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&(f!=null&&f.name)&&is(f.name)&&this.enqueueWebMcpAwait(t.message),(o=t.message.agentMetadata)!=null&&o.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(r=t.message.agentMetadata.agentName)!=null?r:"",status:"running",currentIteration:(s=t.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let f=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":f||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var o,r;this.messages=[...(o=t.initialMessages)!=null?o:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Ys(t),this.wireDefaultWebMcpConfirm();for(let s of(r=t.initialArtifacts)!=null?r:[])this.artifacts.set(s.id,{...s,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return El((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,o;return(o=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?o:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(t){var n,o,r;try{let s=t||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=Qs(s);let a=(n=this.config.voiceRecognition)!=null?n:{},i=(o=a.processingText)!=null?o:"\u{1F3A4} Processing voice...",d=(r=a.processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let f=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=f.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var f,u,g,m,C,v;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((f=l.transcript)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(u=l.transcript)!=null&&u.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((g=l.text)!=null&&g.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=l.text)!=null&&m.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let E=(v=this.pendingVoiceAssistantMessageId)!=null?v:(C=[...this.messages].reverse().find(L=>L.role==="assistant"))==null?void 0:C.id;E&&this.ttsSpokenMessageIds.add(E)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var f,u;this.voiceStatus=l,this.voiceActive=l==="listening",(u=(f=this.callbacks).onVoiceStatusChanged)==null||u.call(f,l)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,o,r,s,a,i,d,l,f;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((o=t.runtype)==null?void 0:o.agentId)||"",clientToken:((r=t.runtype)==null?void 0:r.clientToken)||"",host:(s=t.runtype)==null?void 0:s.host,voiceId:(a=t.runtype)==null?void 0:a.voiceId,pauseDuration:(i=t.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=t.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=t.browser)==null?void 0:l.language)||"en-US",continuous:(f=t.browser)==null?void 0:f.continuous}};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let o=await this.client.initSession();return this.setClientSession(o),o}catch(o){return(n=(t=this.callbacks).onError)==null||n.call(t,o instanceof Error?o:new Error(String(o))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let n=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new Ys(this.config),this.wireDefaultWebMcpConfirm(),n&&this.client.setSSEEventCallback(n)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:f,rawContent:u}=t,m={id:a!=null?a:n==="user"?ii():n==="assistant"?Xs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...f!==void 0&&{voiceProcessing:f},...u!==void 0&&{rawContent:u}};return this.upsertMessage(m),m}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:f,streaming:u=!1,voiceProcessing:g,rawContent:m}=o,v={id:d!=null?d:r==="user"?ii():r==="assistant"?Xs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:f!=null?f:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...m!==void 0&&{rawContent:m}};n.push(v)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:i,sequence:d}=t,l={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(l),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var l,f,u,g,m;let o=t.trim();if(!o&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let r=ii(),s=Xs(),a={id:r,role:"user",content:o||li,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(C){let v=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!v){let E=gm(C,this.config.errorMessage);if(E){let L={id:s,role:"assistant",createdAt:new Date().toISOString(),content:E,sequence:this.nextSequence()};this.appendMessage(L)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(C instanceof Error?(u=(f=this.callbacks).onError)==null||u.call(f,C):(m=(g=this.callbacks).onError)==null||m.call(g,new Error(String(C))))}}async continueConversation(){var r,s,a,i,d;if(this.streaming)return;(r=this.abortController)==null||r.abort();let t=Xs();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(l){let f=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!f){let u=gm(l,this.config.errorMessage);if(u){let g={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,f||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var r,s,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(r=this.abortController)==null||r.abort();let o=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var r,s,a;try{if(((s=(r=this.config.webmcp)==null?void 0:r.autoApprove)==null?void 0:s.call(r,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(o,i)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r!=null&&r.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){var f,u,g,m,C;let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(v=>v.id===r),i={id:r,role:"assistant",content:"",createdAt:(f=a==null?void 0:a.createdAt)!=null?f:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(u=this.abortController)==null||u.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,l=d&&typeof d=="object"?d.onDecision:void 0;try{let v;if(l?v=await l({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):v=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),v){let E=null;if(v instanceof Response){if(!v.ok){let L=await v.json().catch(()=>null);throw new Error((g=L==null?void 0:L.error)!=null?g:`Approval request failed: ${v.status}`)}E=v.body}else v instanceof ReadableStream&&(E=v);E?await this.connectStream(E,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(v){let E=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,E||(C=(m=this.callbacks).onError)==null||C.call(m,v instanceof Error?v:new Error(String(v)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var f,u,g,m,C,v,E,L,I,R,H,P;let o=this.messages.find(w=>w.id===t.id);if(((f=o==null?void 0:o.agentMetadata)==null?void 0:f.askUserQuestionAnswered)===!0)return;let r=(u=t.agentMetadata)==null?void 0:u.executionId,s=(g=t.toolCall)==null?void 0:g.name;if(!r||!s){(C=(m=this.callbacks).onError)==null||C.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let w=(v=t.toolCall)==null?void 0:v.args,x=Array.isArray(w==null?void 0:w.questions)?w.questions:[];if(x.length===1){let k=typeof((E=x[0])==null?void 0:E.question)=="string"?x[0].question:"";k&&(a={[k]:n})}}this.markAskUserQuestionResolved(t,a),(L=this.abortController)==null||L.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(I=t.toolCall)==null?void 0:I.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let w=typeof n=="string"?n:Object.entries(n).map(([x,k])=>`${x}: ${Array.isArray(k)?k.join(", "):k}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:w,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let w=a!=null?a:{};l.forEach((x,k)=>{let S=typeof(x==null?void 0:x.question)=="string"?x.question:"";if(!S)return;let T=w[S],_=Array.isArray(T)?T.join(", "):typeof T=="string"?T:"";this.appendMessage({id:`ask-user-q-${i}-${k}`,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${k}`,role:"user",content:_||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let w=await this.client.resumeFlow(r,{[s]:n});if(!w.ok){let x=await w.json().catch(()=>null);throw new Error((R=x==null?void 0:x.error)!=null?R:`Resume failed: ${w.status}`)}w.body?await this.connectStream(w.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(w){let x=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));this.setStreaming(!1),this.abortController=null,x||(P=(H=this.callbacks).onError)==null||P.call(H,w instanceof Error?w:new Error(String(w)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,o=(a=t.toolCall)==null?void 0:a.id;if(!n||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){var r,s;let n=this.messages.find(a=>a.id===t.id),o=[(r=n==null?void 0:n.toolCall)==null?void 0:r.startedAt,(s=t.toolCall)==null?void 0:s.startedAt];for(let a of o)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now()){this.messages.some(s=>s.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,l,f;let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async u=>{var H,P,w,x,k,S,T;let g=(H=u.toolCall)==null?void 0:H.name,m=(P=u.toolCall)==null?void 0:P.id;if(!g||!m)return null;let C=`${t}:${m}`;if(this.webMcpInflightKeys.has(C)||this.webMcpResolvedKeys.has(C))return null;this.webMcpInflightKeys.add(C),o.push(C);let v=this.markWebMcpToolRunning(u),E=new AbortController;this.webMcpResolveControllers.add(E),r.push(E);let L=(x=(w=u.agentMetadata)==null?void 0:w.webMcpToolCallId)!=null?x:g,I=this.client.executeWebMcpToolCall(g,(k=u.toolCall)==null?void 0:k.args,E.signal),R;if(!I)R={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{R=await I}catch(_){let U=_ instanceof Error&&(_.name==="AbortError"||_.message.includes("aborted")||_.message.includes("abort"));return U||(T=(S=this.callbacks).onError)==null||T.call(S,_ instanceof Error?_:new Error(String(_))),this.markWebMcpToolComplete(u,Zs(U?"Aborted by cancel()":hm(_)),v),this.webMcpInflightKeys.delete(C),null}return E.signal.aborted?(this.markWebMcpToolComplete(u,Zs("Aborted by cancel()"),v),this.webMcpInflightKeys.delete(C),null):{dedupeKey:C,resumeKey:L,output:R,toolMessage:u,startedAt:v,completedAt:Date.now()}})),i=[];try{if(i=a.filter(m=>m!==null),i.length===0)return;let u={};for(let m of i)u[m.resumeKey]=m.output;let g=await this.client.resumeFlow(t,u,{signal:s.signal});if(!g.ok){let m=await g.json().catch(()=>null);throw new Error((d=m==null?void 0:m.error)!=null?d:`Resume failed: ${g.status}`)}for(let m of i)this.webMcpResolvedKeys.add(m.dedupeKey),this.markWebMcpToolComplete(m.toolMessage,m.output,m.startedAt,m.completedAt);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(u){if(!(u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))))(f=(l=this.callbacks).onError)==null||f.call(l,u instanceof Error?u:new Error(String(u)));else for(let m of i)this.markWebMcpToolComplete(m.toolMessage,Zs("Aborted by cancel()"),m.startedAt)}finally{for(let u of o)this.webMcpInflightKeys.delete(u);for(let u of r)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var m,C,v,E,L,I,R,H,P,w,x,k;let n=(m=t.agentMetadata)==null?void 0:m.executionId,o=(C=t.toolCall)==null?void 0:C.name,r=(v=t.toolCall)==null?void 0:v.id;if(!n){(L=(E=this.callbacks).onError)==null||L.call(E,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!o)return;if(!r){let S=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(S)||this.webMcpResolvedKeys.has(S))return;this.webMcpInflightKeys.add(S);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(S)}catch(T){(R=(I=this.callbacks).onError)==null||R.call(I,T instanceof Error?T:new Error(String(T)))}finally{this.webMcpInflightKeys.delete(S)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let l=(H=t.toolCall)==null?void 0:H.args,f=this.client.executeWebMcpToolCall(o,l,d),u="execute",g=a;try{let S;if(f?S=await f:S={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),d.aborted){this.markWebMcpToolComplete(t,Zs("Aborted by cancel()"),a);return}let T=(w=(P=t.agentMetadata)==null?void 0:P.webMcpToolCallId)!=null?w:o;u="resume",await this.resumeWithToolOutput(n,T,S,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,S,a,g)},signal:d})}catch(S){let T=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));(u==="execute"||T||d.aborted)&&this.markWebMcpToolComplete(t,Zs(T||d.aborted?"Aborted by cancel()":hm(S)),a),T||(k=(x=this.callbacks).onError)==null||k.call(x,S instanceof Error?S:new Error(String(S)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){var a,i;let s=await this.client.resumeFlow(t,{[n]:o},{signal:r==null?void 0:r.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=r==null?void 0:r.onHttpOk)==null||i.call(r),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var r;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let o={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(r=t.props)!=null?r:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),o}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,o;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let r=this.artifacts.get(t.id);(r==null?void 0:r.artifactType)==="markdown"&&(r.markdown=((o=r.markdown)!=null?o:"")+t.artDelta);break}case"artifact_update":{let r=this.artifacts.get(t.id);(r==null?void 0:r.artifactType)==="component"&&(r.props={...r.props,...t.props},t.component&&(r.component=t.component));break}case"artifact_complete":{let r=this.artifacts.get(t.id);r&&(r.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>{var r;return{...o,streaming:!1,sequence:(r=o.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=o.content;r.trim()&&this.speak(r,t)}speak(t,n){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t),s=o.getVoices();if(n.voice){let a=s.find(i=>i.name===n.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=n.pickVoice?n.pickVoice(s):e.pickBestVoice(s));n.rate!==void 0&&(r.rate=n.rate),n.pitch!==void 0&&(r.pitch=n.pitch),setTimeout(()=>o.speak(r),50)}static pickBestVoice(t){var o;let n=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of n){let s=t.find(a=>a.name===r);if(s)return s}return(o=t.find(r=>r.lang.startsWith("en")))!=null?o:t[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{var f,u,g,m,C,v,E,L,I,R,H,P,w;if(s!==o)return r;let a={...r,...n};if(((f=r.agentMetadata)==null?void 0:f.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let x=r.approval,k=n.approval;a.approval={...x,...k,executionId:k.executionId||x.executionId,toolName:k.toolName||x.toolName,description:k.description||x.description,toolType:(u=k.toolType)!=null?u:x.toolType,reason:(g=k.reason)!=null?g:x.reason,parameters:(m=k.parameters)!=null?m:x.parameters}}let i=(C=n.toolCall)==null?void 0:C.name,d=(v=n.agentMetadata)==null?void 0:v.executionId,l=(E=n.toolCall)==null?void 0:E.id;if(i&&is(i)&&d&&l&&((L=n.agentMetadata)==null?void 0:L.awaitingLocalTool)===!0){let x=`${d}:${l}`,k=this.webMcpInflightKeys.has(x),S=this.webMcpResolvedKeys.has(x),T=(I=r.toolCall)==null?void 0:I.name,_=((R=r.agentMetadata)==null?void 0:R.executionId)===d&&((H=r.toolCall)==null?void 0:H.id)===l&&T!==void 0&&is(T)&&((P=r.toolCall)==null?void 0:P.status)==="complete";(k||S||_)&&(a.agentMetadata={...(w=a.agentMetadata)!=null?w:{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{var d,l;let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=(d=n.sequence)!=null?d:0,i=(l=o.sequence)!=null?l:0;return a!==i?a-i:n.id.localeCompare(o.id)})}};var b=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Fo=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o};import{Activity as jh,ArrowDown as Kh,ArrowUp as Gh,ArrowUpRight as Yh,Bot as Xh,ChevronDown as Jh,ChevronUp as Qh,ChevronRight as Zh,ChevronLeft as eb,Check as tb,Clipboard as nb,ClipboardCopy as ob,Copy as rb,File as sb,FileCode as ab,FileSpreadsheet as ib,FileText as lb,ImagePlus as cb,Loader as db,LoaderCircle as pb,Mic as ub,Paperclip as mb,RefreshCw as fb,Search as gb,Send as hb,ShieldAlert as bb,ShieldCheck as yb,ShieldX as vb,Square as xb,ThumbsDown as wb,ThumbsUp as Cb,Upload as Sb,Volume2 as Ab,X as Tb,User as kb,Mail as Eb,Phone as Mb,Calendar as Lb,Clock as Ib,Building as Rb,MapPin as Pb,Lock as Wb,Key as Bb,CreditCard as Hb,AtSign as Db,Hash as Fb,Globe as Ob,Link as Nb,CircleCheck as _b,CircleX as Vb,TriangleAlert as $b,Info as Ub,Ban as zb,Shield as qb,ArrowLeft as jb,ArrowRight as Kb,ExternalLink as Gb,Ellipsis as Yb,EllipsisVertical as Xb,Menu as Jb,House as Qb,Plus as Zb,Minus as ey,Pencil as ty,Trash as ny,Trash2 as oy,Save as ry,Download as sy,Share as ay,Funnel as iy,Settings as ly,RotateCw as cy,Maximize as dy,Minimize as py,ShoppingCart as uy,ShoppingBag as my,Package as fy,Truck as gy,Tag as hy,Gift as by,Receipt as yy,Wallet as vy,Store as xy,DollarSign as wy,Percent as Cy,Play as Sy,Pause as Ay,VolumeX as Ty,Camera as ky,Image as Ey,Film as My,Headphones as Ly,MessageCircle as Iy,MessageSquare as Ry,Bell as Py,Heart as Wy,Star as By,Eye as Hy,EyeOff as Dy,Bookmark as Fy,CalendarDays as Oy,History as Ny,Timer as _y,Folder as Vy,FolderOpen as $y,Files as Uy,Sparkles as zy,Zap as qy,Sun as jy,Moon as Ky,Flag as Gy,Monitor as Yy,Smartphone as Xy}from"lucide";var Jy={activity:jh,"arrow-down":Kh,"arrow-up":Gh,"arrow-up-right":Yh,bot:Xh,"chevron-down":Jh,"chevron-up":Qh,"chevron-right":Zh,"chevron-left":eb,check:tb,clipboard:nb,"clipboard-copy":ob,copy:rb,file:sb,"file-code":ab,"file-spreadsheet":ib,"file-text":lb,"image-plus":cb,loader:db,"loader-circle":pb,mic:ub,paperclip:mb,"refresh-cw":fb,search:gb,send:hb,"shield-alert":bb,"shield-check":yb,"shield-x":vb,square:xb,"thumbs-down":wb,"thumbs-up":Cb,upload:Sb,"volume-2":Ab,x:Tb,user:kb,mail:Eb,phone:Mb,calendar:Lb,clock:Ib,building:Rb,"map-pin":Pb,lock:Wb,key:Bb,"credit-card":Hb,"at-sign":Db,hash:Fb,globe:Ob,link:Nb,"circle-check":_b,"circle-x":Vb,"triangle-alert":$b,info:Ub,ban:zb,shield:qb,"arrow-left":jb,"arrow-right":Kb,"external-link":Gb,ellipsis:Yb,"ellipsis-vertical":Xb,menu:Jb,house:Qb,plus:Zb,minus:ey,pencil:ty,trash:ny,"trash-2":oy,save:ry,download:sy,share:ay,funnel:iy,settings:ly,"rotate-cw":cy,maximize:dy,minimize:py,"shopping-cart":uy,"shopping-bag":my,package:fy,truck:gy,tag:hy,gift:by,receipt:yy,wallet:vy,store:xy,"dollar-sign":wy,percent:Cy,play:Sy,pause:Ay,"volume-x":Ty,camera:ky,image:Ey,film:My,headphones:Ly,"message-circle":Iy,"message-square":Ry,bell:Py,heart:Wy,star:By,eye:Hy,"eye-off":Dy,bookmark:Fy,"calendar-days":Oy,history:Ny,timer:_y,folder:Vy,"folder-open":$y,files:Uy,sparkles:zy,zap:qy,sun:jy,moon:Ky,flag:Gy,monitor:Yy,smartphone:Xy},Ee=(e,t=24,n="currentColor",o=2)=>{let r=Jy[e];return r?Qy(r,t,n,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Qy(e,t,n,o){if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,f])=>{l!=="stroke"&&d.setAttribute(l,String(f))}),r.appendChild(d)}),r}var mi={allowedTypes:Yo,maxFileSize:10*1024*1024,maxFiles:4};function Zy(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function ev(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var ea=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,o,r;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:mi.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:mi.maxFileSize,maxFiles:(r=t.maxFiles)!=null?r:mi.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:mi.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,o,r,s,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(o=(n=this.config).onFileRejected)==null||o.call(n,l,"count");continue}let f=um(l,this.config.allowedTypes,this.config.maxFileSize);if(!f.valid){let u=(r=f.error)!=null&&r.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,u);continue}try{let u=await pm(l),g=ci(l)?URL.createObjectURL(l):null,m={id:Zy(),file:l,previewUrl:g,contentPart:u};this.attachments.push(m),this.renderPreview(m)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let o of this.attachments)o.previewUrl&&URL.revokeObjectURL(o.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=ci(t.file),o=b("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let a=b("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=b("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=ev(t.file.type),d=Ee(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=b("span");l.textContent=mm(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),o.appendChild(a)}let r=b("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=Ee("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};import{Idiomorph as tv}from"idiomorph";var fi=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;tv.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){var a,i;if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=r.textContent)!=null?a:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var gi={index:-1,draft:""};function bm(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:o}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...gi}}}function ym(e,t){var n,o,r,s,a,i,d,l,f,u,g,m,C,v,E,L,I,R,H,P,w,x,k,S,T,_,U,G,ge,ue,ce,ke,ve,He,Se,ie,X,re;return[e.id,e.role,(o=(n=e.content)==null?void 0:n.length)!=null?o:0,(s=(r=e.content)==null?void 0:r.slice(-32))!=null?s:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(f=(l=e.llmContent)==null?void 0:l.length)!=null?f:0,(g=(u=e.approval)==null?void 0:u.status)!=null?g:"",(C=(m=e.toolCall)==null?void 0:m.status)!=null?C:"",(E=(v=e.toolCall)==null?void 0:v.name)!=null?E:"",(R=(I=(L=e.toolCall)==null?void 0:L.chunks)==null?void 0:I.length)!=null?R:0,(x=(w=(P=(H=e.toolCall)==null?void 0:H.chunks)==null?void 0:P[e.toolCall.chunks.length-1])==null?void 0:w.slice(-32))!=null?x:"",typeof((k=e.toolCall)==null?void 0:k.args)=="string"?e.toolCall.args.length:(S=e.toolCall)!=null&&S.args?JSON.stringify(e.toolCall.args).length:0,(U=(_=(T=e.reasoning)==null?void 0:T.chunks)==null?void 0:_.length)!=null?U:0,(ce=(ue=(ge=(G=e.reasoning)==null?void 0:G.chunks)==null?void 0:ge[e.reasoning.chunks.length-1])==null?void 0:ue.length)!=null?ce:0,(Se=(He=(ve=(ke=e.reasoning)==null?void 0:ke.chunks)==null?void 0:ve[e.reasoning.chunks.length-1])==null?void 0:He.slice(-32))!=null?Se:"",(X=(ie=e.contentParts)==null?void 0:ie.length)!=null?X:0,(re=e.stopReason)!=null?re:"",t].join("\0")}function vm(){return new Map}function xm(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function wm(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Cm(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function hi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Xo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Hr(e,t){return Xo(e)-e.scrollTop<=t}function bi(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,f=n-o;return a||Math.abs(f)<s?{action:"none",delta:f,nextLastScrollTop:n}:!t&&r&&(!l||f>0)?{action:"resume",delta:f,nextLastScrollTop:n}:t&&i&&f<0?{action:"pause",delta:f,nextLastScrollTop:n}:t&&d&&!r?{action:"pause",delta:f,nextLastScrollTop:n}:{action:"none",delta:f,nextLastScrollTop:n}}function yi(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function Sm(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Am(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function Tm(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var kn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},En=1e5,mr=En+1;var ta={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},nv=["pre","code","a","script","style"],vi=e=>{var t,n,o,r,s;return{type:(t=e==null?void 0:e.type)!=null?t:ta.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:ta.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:ta.speed,duration:(r=e==null?void 0:e.duration)!=null?r:ta.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:ta.buffer}},ov=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],Em=new Map;for(let e of ov)Em.set(e.name,e);var na=(e,t)=>{var n,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(o=Em.get(e))!=null?o:null},xi=(e,t,n,o,r)=>{if(!r)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
|
|
15
|
+
`);return s<0?"":e.slice(0,s)}return e},rv=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},sv=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},Ml=/\s/,av=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},iv=(e,t,n)=>{var d;let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=o.createDocumentFragment(),i=0;for(;i<s.length;)if(Ml.test(s[i])){let l=i;for(;l<s.length&&Ml.test(s[l]);)l+=1;a.appendChild(o.createTextNode(s.slice(i,l))),i=l}else{let l=o.createElement("span");l.className="persona-stream-word-group";let f=i;for(;f<s.length&&!Ml.test(s[f]);)l.appendChild(rv(o,s[f],t,n.value)),n.value+=1,f+=1;a.appendChild(l),i=f}r.replaceChild(a,e)},lv=(e,t,n)=>{var d;let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=o.createDocumentFragment(),i=s.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(o.createTextNode(l)):(a.appendChild(sv(o,l,t,n.value)),n.value+=1));r.replaceChild(a,e)},oa=(e,t,n,o)=>{var u,g;if(!e||typeof document=="undefined")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set(((u=o==null?void 0:o.skipTags)!=null?u:nv).map(m=>m.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)av(d,s)||i.push(d),d=a.nextNode();let l={value:(g=o==null?void 0:o.startIndex)!=null?g:0},f=t==="char"?iv:lv;for(let m of i)f(m,n,l);return r.innerHTML},wi=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},ra=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},km=new WeakMap,cv=(e,t)=>{var s;if(!e.styles)return;let n=km.get(t);if(n||(n=new Set,km.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},Ll=new WeakMap,dv=(e,t)=>{if(!e.onAttach)return;let n=Ll.get(t);if(n||(n=new Map,Ll.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},Mm=e=>{let t=Ll.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Il=(e,t)=>{cv(e,t),dv(e,t)};function Rl(e,t=En){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var sa=0,fr=null;function Pl(e=document){var n;if(sa++,sa===1){let o=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;fr={originalOverflow:o.style.overflow,originalPosition:o.style.position,originalTop:o.style.top,originalWidth:o.style.width,scrollY:s},o.style.overflow="hidden",o.style.position="fixed",o.style.top=`-${s}px`,o.style.width="100%"}let t=!1;return()=>{var o;if(!t&&(t=!0,sa=Math.max(0,sa-1),sa===0&&fr)){let r=e.body,s=(o=e.defaultView)!=null?o:window;r.style.overflow=fr.originalOverflow,r.style.position=fr.originalPosition,r.style.top=fr.originalTop,r.style.width=fr.originalWidth,s.scrollTo(0,fr.scrollY),fr=null}}}var Ci={side:"right",width:"420px",animate:!0,reveal:"resize"},xn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},aa=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},Oo=e=>{var n,o,r,s,a;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(o=t==null?void 0:t.side)!=null?o:Ci.side,width:(r=t==null?void 0:t.width)!=null?r:Ci.width,animate:(s=t==null?void 0:t.animate)!=null?s:Ci.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:Ci.reveal}};var To={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var ia=(e,t)=>{let n=b("button");n.type="button",n.innerHTML=`
|
|
16
16
|
<span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
17
17
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
18
18
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -20,14 +20,14 @@ _Details: ${n.message}_`:o}var Fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
20
20
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
21
21
|
</span>
|
|
22
22
|
<span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
23
|
-
`,n.addEventListener("click",t);let o=s=>{var H,D,W,v,x,k,C,T,F,$,j,me,se,fe;let a=(H=s.launcher)!=null?H:{},i=pn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let ie=(D=a.title)!=null?D:"Chat Assistant";d.textContent=ie,d.setAttribute("title",ie)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let ie=(W=a.subtitle)!=null?W:"Get answers fast";l.textContent=ie,l.setAttribute("title",ie)}let m=n.querySelector(".persona-flex-col");m&&(a.textHidden||i?m.style.display="none":m.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let ie=(v=a.agentIconSize)!=null?v:"40px";if(u.style.height=ie,u.style.width=ie,u.innerHTML="",a.agentIconName){let be=parseFloat(ie)||24,Oe=Te(a.agentIconName,be*.6,"var(--persona-text-inverse, #ffffff)",2);Oe?(u.appendChild(Oe),u.style.display=""):(u.textContent=(x=a.agentIconText)!=null?x:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(k=a.agentIconText)!=null?k:"\u{1F4AC}",u.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let ie=(C=a.agentIconSize)!=null?C:"40px";g.style.height=ie,g.style.width=ie,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let p=n.querySelector("[data-role='launcher-call-to-action-icon']");if(p){let ie=(T=a.callToActionIconSize)!=null?T:"32px";p.style.height=ie,p.style.width=ie,a.callToActionIconBackgroundColor?(p.style.backgroundColor=a.callToActionIconBackgroundColor,p.classList.remove("persona-bg-persona-primary")):(p.style.backgroundColor="",p.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(p.style.color=a.callToActionIconColor,p.classList.remove("persona-text-persona-call-to-action")):(p.style.color="",p.classList.add("persona-text-persona-call-to-action"));let be=0;if(a.callToActionIconPadding?(p.style.boxSizing="border-box",p.style.padding=a.callToActionIconPadding,be=(parseFloat(a.callToActionIconPadding)||0)*2):(p.style.boxSizing="",p.style.padding=""),a.callToActionIconHidden)p.style.display="none";else if(p.style.display=i?"none":"",p.innerHTML="",a.callToActionIconName){let Oe=parseFloat(ie)||24,ve=Math.max(Oe-be,8),Q=Te(a.callToActionIconName,ve,"currentColor",2);Q?p.appendChild(Q):p.textContent=(F=a.callToActionIconText)!=null?F:"\u2197"}else p.textContent=($=a.callToActionIconText)!=null?$:"\u2197"}let w=a.position&&xo[a.position]?xo[a.position]:xo["bottom-right"],S="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",M="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?M:`${S} ${w}`,i||(n.style.zIndex=String((j=a.zIndex)!=null?j:hn));let I="1px solid var(--persona-border, #e5e7eb)",L="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(me=a.border)!=null?me:I,n.style.boxShadow=(se=a.shadow)!=null?se:L,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(fe=a.collapsedMaxWidth)!=null?fe:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}};var xy="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",mi=(e,t={})=>{var S,M,I,L,H,D;let{showClose:n=!0,wrapperClassName:o=xy,buttonSize:r,iconSize:s="28px"}=t,a=(S=e==null?void 0:e.launcher)!=null?S:{},i=(M=r!=null?r:a.closeButtonSize)!=null?M:"32px",d=b("div",o),l=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let m=(I=a.closeButtonTooltipText)!=null?I:"Close chat",u=(L=a.closeButtonShowTooltip)!=null?L:!0;l.setAttribute("aria-label",m),l.style.display=n?"":"none";let g=(H=a.closeButtonIconName)!=null?H:"x",p=(D=a.closeButtonIconText)!=null?D:"\xD7";l.style.color=a.closeButtonColor||Mn.actionIconColor;let w=Te(g,s,"currentColor",1);if(w?(w.style.display="block",l.appendChild(w)):l.textContent=p,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let W=a.closeButtonBorderWidth||"0px",v=a.closeButtonBorderColor||"transparent";l.style.border=`${W} solid ${v}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),u&&m){let W=null,v=()=>{if(W)return;let k=l.ownerDocument,C=k.body;if(!C)return;W=Eo(k,"div","persona-clear-chat-tooltip"),W.textContent=m;let T=Eo(k,"div");T.className="persona-clear-chat-tooltip-arrow",W.appendChild(T);let F=l.getBoundingClientRect();W.style.position="fixed",W.style.zIndex=String(or),W.style.left=`${F.left+F.width/2}px`,W.style.top=`${F.top-8}px`,W.style.transform="translate(-50%, -100%)",C.appendChild(W)},x=()=>{W&&W.parentNode&&(W.parentNode.removeChild(W),W=null)};d.addEventListener("mouseenter",v),d.addEventListener("mouseleave",x),l.addEventListener("focus",v),l.addEventListener("blur",x),d._cleanupTooltip=()=>{x(),d.removeEventListener("mouseenter",v),d.removeEventListener("mouseleave",x),l.removeEventListener("focus",v),l.removeEventListener("blur",x)}}return{button:l,wrapper:d}},wy="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",fi=(e,t={})=>{var W,v,x,k,C,T,F,$,j,me,se,fe,ie;let{wrapperClassName:n=wy,buttonSize:o,iconSize:r="20px"}=t,a=(v=((W=e==null?void 0:e.launcher)!=null?W:{}).clearChat)!=null?v:{},i=(x=o!=null?o:a.size)!=null?x:"32px",d=(k=a.iconName)!=null?k:"refresh-cw",l=(C=a.iconColor)!=null?C:"",m=(T=a.backgroundColor)!=null?T:"",u=(F=a.borderWidth)!=null?F:"",g=($=a.borderColor)!=null?$:"",p=(j=a.borderRadius)!=null?j:"",w=(me=a.paddingX)!=null?me:"",S=(se=a.paddingY)!=null?se:"",M=(fe=a.tooltipText)!=null?fe:"Clear chat",I=(ie=a.showTooltip)!=null?ie:!0,L=b("div",n),H=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");H.style.height=i,H.style.width=i,H.type="button",H.setAttribute("aria-label",M),H.style.color=l||Mn.actionIconColor;let D=Te(d,r,"currentColor",1);if(D&&(D.style.display="block",H.appendChild(D)),m&&(H.style.backgroundColor=m,H.classList.remove("hover:persona-bg-gray-100")),u||g){let be=u||"0px",Oe=g||"transparent";H.style.border=`${be} solid ${Oe}`,H.classList.remove("persona-border-none")}if(p&&(H.style.borderRadius=p,H.classList.remove("persona-rounded-full")),w&&(H.style.paddingLeft=w,H.style.paddingRight=w),S&&(H.style.paddingTop=S,H.style.paddingBottom=S),L.appendChild(H),I&&M){let be=null,Oe=()=>{if(be)return;let Q=H.ownerDocument,Le=Q.body;if(!Le)return;be=Eo(Q,"div","persona-clear-chat-tooltip"),be.textContent=M;let Y=Eo(Q,"div");Y.className="persona-clear-chat-tooltip-arrow",be.appendChild(Y);let xe=H.getBoundingClientRect();be.style.position="fixed",be.style.zIndex=String(or),be.style.left=`${xe.left+xe.width/2}px`,be.style.top=`${xe.top-8}px`,be.style.transform="translate(-50%, -100%)",Le.appendChild(be)},ve=()=>{be&&be.parentNode&&(be.parentNode.removeChild(be),be=null)};L.addEventListener("mouseenter",Oe),L.addEventListener("mouseleave",ve),H.addEventListener("focus",Oe),H.addEventListener("blur",ve),L._cleanupTooltip=()=>{ve(),L.removeEventListener("mouseenter",Oe),L.removeEventListener("mouseleave",ve),H.removeEventListener("focus",Oe),H.removeEventListener("blur",ve)}}return{button:H,wrapper:L}};var Mn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Ar=e=>{var W,v,x,k,C,T,F,$,j,me,se,fe,ie,be,Oe,ve;let{config:t,showClose:n=!0}=e,o=b("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");o.setAttribute("data-persona-theme-zone","header"),o.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",o.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",o.style.boxShadow="var(--persona-header-shadow, none)",o.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let r=(W=t==null?void 0:t.launcher)!=null?W:{},s=(v=r.headerIconSize)!=null?v:"48px",a=(x=r.closeButtonPlacement)!=null?x:"inline",i=(k=r.headerIconHidden)!=null?k:!1,d=r.headerIconName,l=b("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let Q=parseFloat(s)||24,Le=Te(d,Q*.6,"currentColor",1);Le?l.replaceChildren(Le):l.textContent=(T=(C=t==null?void 0:t.launcher)==null?void 0:C.agentIconText)!=null?T:"\u{1F4AC}"}else if((F=t==null?void 0:t.launcher)!=null&&F.iconUrl){let Q=b("img");Q.src=t.launcher.iconUrl,Q.alt="",Q.className="persona-rounded-xl persona-object-cover",Q.style.height=s,Q.style.width=s,l.replaceChildren(Q)}else l.textContent=(j=($=t==null?void 0:t.launcher)==null?void 0:$.agentIconText)!=null?j:"\u{1F4AC}";let m=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=b("span","persona-text-base persona-font-semibold");u.style.color=Mn.titleColor,u.textContent=(se=(me=t==null?void 0:t.launcher)==null?void 0:me.title)!=null?se:"Chat Assistant";let g=b("span","persona-text-xs");g.style.color=Mn.subtitleColor,g.textContent=(ie=(fe=t==null?void 0:t.launcher)==null?void 0:fe.subtitle)!=null?ie:"Here to help you get answers fast",m.append(u,g),i?o.append(m):o.append(l,m);let p=(be=r.clearChat)!=null?be:{},w=(Oe=p.enabled)!=null?Oe:!0,S=(ve=p.placement)!=null?ve:"inline",M=null,I=null;if(w){let Le=fi(t,{wrapperClassName:S==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=Le.button,I=Le.wrapper,S==="top-right"&&(I.style.right="48px"),S==="inline"&&o.appendChild(I)}let L=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":w&&S==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:H,wrapper:D}=mi(t,{showClose:n,wrapperClassName:L});return a!=="top-right"&&o.appendChild(D),{header:o,iconHolder:l,headerTitle:u,headerSubtitle:g,closeButton:H,closeButtonWrapper:D,clearChatButton:M,clearChatButtonWrapper:I}},Gs=(e,t,n)=>{var a,i,d,l;let o=(a=n==null?void 0:n.launcher)!=null?a:{},r=(i=o.closeButtonPlacement)!=null?i:"inline",s=(l=(d=o.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Kr(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=e,a=b("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(or)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let p of t){if(p.dividerBefore){let M=document.createElement("hr");a.appendChild(M)}let w=document.createElement("button");if(w.type="button",w.setAttribute("role","menuitem"),w.setAttribute("data-dropdown-item-id",p.id),p.destructive&&w.setAttribute("data-destructive",""),p.icon){let M=Te(p.icon,16,"currentColor",1.5);M&&w.appendChild(M)}let S=document.createElement("span");S.textContent=p.label,w.appendChild(S),w.addEventListener("click",M=>{M.stopPropagation(),m(),n(p.id)}),a.appendChild(w)}let i=null;function d(){if(!s)return;let p=o.getBoundingClientRect();a.style.top=`${p.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-p.right}px`,a.style.left="auto"):(a.style.left=`${p.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let p=w=>{!a.contains(w.target)&&!o.contains(w.target)&&m()};document.addEventListener("click",p,!0),i=()=>document.removeEventListener("click",p,!0)})}function m(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?l():m()}function g(){m(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:m,toggle:u,destroy:g}}function bn(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:i}=e,d=b("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=Te(t,o!=null?o:16,"currentColor",r!=null?r:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[m,u]of Object.entries(i))d.setAttribute(m,u);return d}function hl(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";o!=="default"&&(l+=" persona-label-btn--"+o),l+=" persona-label-btn--"+r,a&&(l+=" "+a);let m=b("button",l);if(m.type="button",m.setAttribute("aria-label",n),t){let g=Te(t,s!=null?s:14,"currentColor",2);g&&m.appendChild(g)}let u=b("span");if(u.textContent=n,m.appendChild(u),i&&m.addEventListener("click",i),d)for(let[g,p]of Object.entries(d))m.setAttribute(g,p);return m}function Ku(e){var p,w;let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:i,hover:d}=e,l=b("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let m=b("span","persona-combo-btn-label");m.textContent=t,l.appendChild(m);let u=Te(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",l.appendChild(u)),d&&(l.style.borderRadius=(p=d.borderRadius)!=null?p:"10px",l.style.padding=(w=d.padding)!=null?w:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var S,M;l.style.backgroundColor=(S=d.background)!=null?S:"",l.style.borderColor=(M=d.border)!=null?M:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let g=Kr({items:o,onSelect:S=>{l.setAttribute("aria-expanded","false"),r(S)},anchor:l,position:s,portal:a});return a||l.appendChild(g.element),l.addEventListener("click",S=>{S.stopPropagation();let M=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",M?"false":"true"),g.toggle()}),l.addEventListener("keydown",S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),l.click())}),{element:l,setLabel:S=>{m.textContent=S,l.setAttribute("aria-label",S)},open:()=>{l.setAttribute("aria-expanded","true"),g.show()},close:()=>{l.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let S=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",S?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),l.remove()}}}var Cy=e=>{var o;let t=Ar({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(o=e.layoutHeaderConfig)==null?void 0:o.onTitleClick;if(n){let r=t.headerTitle.parentElement;r&&(r.style.cursor="pointer",r.setAttribute("role","button"),r.setAttribute("tabindex","0"),r.addEventListener("click",()=>n()),r.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function Sy(e,t,n){var o,r,s;if(t!=null&&t.length)for(let a of t){let i=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(r=(o=a.ariaLabel)!=null?o:a.label)!=null?r:a.id),a.icon){let d=Te(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=b("div","persona-relative");d.appendChild(i);let l=Kr({items:a.menuItems,onSelect:m=>n==null?void 0:n(m),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",m=>{m.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var Ay=e=>{var L,H,D,W,v,x,k,C,T;let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=(L=t==null?void 0:t.launcher)!=null?L:{},i=b("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=r==null?void 0:r.titleMenu,l,m;if(d)l=Ku({label:(H=a.title)!=null?H:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Mn.titleColor,m=(D=l.querySelector(".persona-combo-btn-label"))!=null?D:l;else{if(l=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),m=b("span","persona-text-base persona-font-semibold persona-truncate"),m.style.color=Mn.titleColor,m.textContent=(W=a.title)!=null?W:"Chat Assistant",l.appendChild(m),Sy(l,r==null?void 0:r.trailingActions,(v=r==null?void 0:r.onAction)!=null?v:s),r!=null&&r.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let $=r.onTitleClick;l.addEventListener("click",j=>{j.target.closest("button")||$()}),l.addEventListener("keydown",j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),$())})}let F=r==null?void 0:r.titleRowHover;F&&(l.style.borderRadius=(x=F.borderRadius)!=null?x:"10px",l.style.padding=(k=F.padding)!=null?k:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var $,j;l.style.backgroundColor=($=F.background)!=null?$:"",l.style.borderColor=(j=F.border)!=null?j:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let u=(C=a.closeButtonSize)!=null?C:"32px",g=b("div",""),p=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");p.style.height=u,p.style.width=u,p.type="button",p.setAttribute("aria-label","Close chat"),p.style.display=n?"":"none",p.style.color=a.closeButtonColor||Mn.actionIconColor;let w=(T=a.closeButtonIconName)!=null?T:"x",S=Te(w,"28px","currentColor",1);S?p.appendChild(S):p.textContent="\xD7",o&&p.addEventListener("click",o),g.appendChild(p),i.appendChild(g);let M=b("div");M.style.display="none";let I=b("span");return I.style.display="none",{header:i,iconHolder:M,headerTitle:m,headerSubtitle:I,closeButton:p,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},Gu={default:Cy,minimal:Ay},Ty=e=>{var t;return(t=Gu[e])!=null?t:Gu.default},gi=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),m=b("div");m.style.display="none";let u=b("span"),g=b("span"),p=b("button");p.style.display="none";let w=b("div");return w.style.display="none",{header:l,iconHolder:m,headerTitle:u,headerSubtitle:g,closeButton:p,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}}let o=(a=t==null?void 0:t.layout)!=null?a:"default",s=Ty(o)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var hi=e=>{var a,i;let t=b("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;t.style.maxHeight=`${n*o}px`,t.style.overflowY="auto";let r=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*o},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,r());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},bi=e=>{var W,v,x,k,C,T,F,$,j,me,se,fe;let t=(W=e==null?void 0:e.sendButton)!=null?W:{},n=(v=t.useIcon)!=null?v:!1,o=(x=t.iconText)!=null?x:"\u2191",r=t.iconName,s=(k=t.stopIconName)!=null?k:"square",a=(C=t.tooltipText)!=null?C:"Send message",i=(T=t.stopTooltipText)!=null?T:"Stop generating",d=($=(F=e==null?void 0:e.copy)==null?void 0:F.sendButtonLabel)!=null?$:"Send",l=(me=(j=e==null?void 0:e.copy)==null?void 0:j.stopButtonLabel)!=null?me:"Stop",m=(se=t.showTooltip)!=null?se:!1,u=(fe=t.size)!=null?fe:"40px",g=t.backgroundColor,p=t.textColor,w=b("div","persona-send-button-wrapper"),S=b("button",n?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");S.type="submit",S.setAttribute("data-persona-composer-submit","");let M=null,I=null;if(n){S.style.width=u,S.style.height=u,S.style.minWidth=u,S.style.minHeight=u,S.style.fontSize="18px",S.style.lineHeight="1",S.innerHTML="",p?S.style.color=p:S.style.color="var(--persona-button-primary-fg, #ffffff)";let ie=parseFloat(u)||24,be=(p==null?void 0:p.trim())||"currentColor";r?(M=Te(r,ie,be,2),M?S.appendChild(M):S.textContent=o):S.textContent=o,I=Te(s,ie,be,2),g?S.style.backgroundColor=g:S.classList.add("persona-bg-persona-primary")}else S.textContent=d,p?S.style.color=p:S.classList.add("persona-text-white");t.borderWidth&&(S.style.borderWidth=t.borderWidth,S.style.borderStyle="solid"),t.borderColor&&(S.style.borderColor=t.borderColor),t.paddingX?(S.style.paddingLeft=t.paddingX,S.style.paddingRight=t.paddingX):(S.style.paddingLeft="",S.style.paddingRight=""),t.paddingY?(S.style.paddingTop=t.paddingY,S.style.paddingBottom=t.paddingY):(S.style.paddingTop="",S.style.paddingBottom="");let L=null;m&&a&&(L=b("div","persona-send-button-tooltip"),L.textContent=a,w.appendChild(L)),S.setAttribute("aria-label",a),w.appendChild(S);let H="send";return{button:S,wrapper:w,setMode:ie=>{if(ie===H)return;H=ie;let be=ie==="stop"?i:a;if(S.setAttribute("aria-label",be),L&&(L.textContent=be),n){if(M&&I){let Oe=ie==="stop"?I:M;S.replaceChildren(Oe)}}else S.textContent=ie==="stop"?l:d}}},yi=e=>{var L,H,D,W,v,x,k,C,T,F,$,j;let t=(L=e==null?void 0:e.voiceRecognition)!=null?L:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),r=((H=t.provider)==null?void 0:H.type)==="runtype";if(!(o||r))return null;let a=(W=(D=e==null?void 0:e.sendButton)==null?void 0:D.size)!=null?W:"40px",i=b("div","persona-send-button-wrapper"),d=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(v=t.iconName)!=null?v:"mic",m=(x=t.iconSize)!=null?x:a,u=parseFloat(m)||24,g=(C=t.backgroundColor)!=null?C:(k=e==null?void 0:e.sendButton)==null?void 0:k.backgroundColor,p=(F=t.iconColor)!=null?F:(T=e==null?void 0:e.sendButton)==null?void 0:T.textColor;d.style.width=m,d.style.height=m,d.style.minWidth=m,d.style.minHeight=m,d.style.fontSize="18px",d.style.lineHeight="1",p?d.style.color=p:d.style.color="var(--persona-text, #111827)";let S=Te(l,u,p||"currentColor",1.5);S?d.appendChild(S):d.textContent="\u{1F3A4}",g&&(d.style.backgroundColor=g),t.borderWidth&&(d.style.borderWidth=t.borderWidth,d.style.borderStyle="solid"),t.borderColor&&(d.style.borderColor=t.borderColor),t.paddingX&&(d.style.paddingLeft=t.paddingX,d.style.paddingRight=t.paddingX),t.paddingY&&(d.style.paddingTop=t.paddingY,d.style.paddingBottom=t.paddingY),i.appendChild(d);let M=($=t.tooltipText)!=null?$:"Start voice recognition";if(((j=t.showTooltip)!=null?j:!1)&&M){let me=b("div","persona-send-button-tooltip");me.textContent=M,i.appendChild(me)}return{button:d,wrapper:i}},vi=e=>{var w,S,M,I,L,H,D,W;let t=(w=e==null?void 0:e.attachments)!=null?w:{};if(t.enabled!==!0)return null;let n=(M=(S=e==null?void 0:e.sendButton)==null?void 0:S.size)!=null?M:"40px",o=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.style.display="none";let r=b("input");r.type="file",r.accept=((I=t.allowedTypes)!=null?I:_o).join(","),r.multiple=((L=t.maxFiles)!=null?L:4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=b("div","persona-send-button-wrapper"),a=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(H=t.buttonTooltipText)!=null?H:"Attach file");let i=(D=t.buttonIconName)!=null?D:"paperclip",d=n,l=parseFloat(d)||40,m=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let u=Te(i,m,"currentColor",1.5);u?a.appendChild(u):a.textContent="\u{1F4CE}",a.addEventListener("click",v=>{v.preventDefault(),r.click()}),s.appendChild(a);let g=(W=t.buttonTooltipText)!=null?W:"Attach file",p=b("div","persona-send-button-tooltip");return p.textContent=g,s.appendChild(p),{button:a,wrapper:s,input:r,previewsContainer:o}},xi=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=b("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=(i=t.visible)!=null?i:!0;o.style.display=r?"":"none";let s=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let l=b("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=s,l.style.color="inherit",l.style.textDecoration="none",o.appendChild(l)}else o.textContent=s;return o},wi=()=>b("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var Ci=e=>{var w,S,M,I,L,H;let{config:t}=e,n=b("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");n.setAttribute("data-persona-theme-zone","composer");let o=wi(),r=b("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");r.setAttribute("data-persona-composer-form",""),r.style.outline="none";let{textarea:s,attachAutoResize:a}=hi(t);a();let i=bi(t),d=yi(t),l=vi(t),m=xi(t);l&&(l.previewsContainer.style.gap="8px",r.append(l.previewsContainer,l.input)),r.append(s);let u=b("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),g=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),p=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&g.append(l.wrapper),d&&p.append(d.wrapper),p.append(i.wrapper),u.append(g,p),r.append(u),r.addEventListener("click",D=>{D.target!==i.button&&D.target!==i.wrapper&&D.target!==(d==null?void 0:d.button)&&D.target!==(d==null?void 0:d.wrapper)&&D.target!==(l==null?void 0:l.button)&&D.target!==(l==null?void 0:l.wrapper)&&s.focus()}),n.append(o,r,m),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(w=d==null?void 0:d.button)!=null?w:null,micButtonWrapper:(S=d==null?void 0:d.wrapper)!=null?S:null,statusText:m,attachmentButton:(M=l==null?void 0:l.button)!=null?M:null,attachmentButtonWrapper:(I=l==null?void 0:l.wrapper)!=null?I:null,attachmentInput:(L=l==null?void 0:l.input)!=null?L:null,attachmentPreviewsContainer:(H=l==null?void 0:l.previewsContainer)!=null?H:null,actionsRow:u,leftActions:g,rightActions:p,setSendButtonMode:i.setMode}};var Yu=()=>{let e=b("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let t=b("span","persona-pill-peek__icon"),n=Te("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=b("span","persona-pill-peek__text"),r=b("span","persona-pill-peek__caret"),s=Te("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},Xu=e=>{var w,S,M,I,L,H;let{config:t}=e,n=b("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let o=wi();o.style.display="none";let r=xi(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=hi(t);s.style.maxHeight="100px",a();let i=bi(t),d=yi(t),l=vi(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let m=b("form","persona-widget-composer persona-pill-composer");m.setAttribute("data-persona-composer-form",""),m.style.outline="none";let u=b("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&u.append(l.wrapper);let g=b("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),m.addEventListener("click",D=>{D.target!==i.button&&D.target!==i.wrapper&&D.target!==(d==null?void 0:d.button)&&D.target!==(d==null?void 0:d.wrapper)&&D.target!==(l==null?void 0:l.button)&&D.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&m.append(l.input),m.append(u,s,g),l&&n.append(l.previewsContainer),n.append(m,o,r);let p=m;return{footer:n,suggestions:o,composerForm:m,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(w=d==null?void 0:d.button)!=null?w:null,micButtonWrapper:(S=d==null?void 0:d.wrapper)!=null?S:null,statusText:r,attachmentButton:(M=l==null?void 0:l.button)!=null?M:null,attachmentButtonWrapper:(I=l==null?void 0:l.wrapper)!=null?I:null,attachmentInput:(L=l==null?void 0:l.input)!=null?L:null,attachmentPreviewsContainer:(H=l==null?void 0:l.previewsContainer)!=null?H:null,actionsRow:p,leftActions:u,rightActions:g,setSendButtonMode:i.setMode}};var Qu=e=>{var m,u,g,p,w,S,M,I,L,H,D,W,v,x,k,C,T;let t=(u=(m=e==null?void 0:e.launcher)==null?void 0:m.enabled)!=null?u:!0,n=pn(e);if(js(e)){let F=(p=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?p:{},$=b("div","persona-widget-wrapper persona-fixed persona-transition");$.setAttribute("data-persona-composer-bar",""),$.dataset.state="collapsed",$.dataset.expandedSize=(w=F.expandedSize)!=null?w:"anchored",$.style.zIndex=String((M=(S=e==null?void 0:e.launcher)==null?void 0:S.zIndex)!=null?M:hn);let j=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");j.style.width="100%",$.appendChild(j);let me=b("div","persona-widget-pill-root");return me.setAttribute("data-persona-composer-bar",""),me.dataset.state="collapsed",me.dataset.expandedSize=(I=F.expandedSize)!=null?I:"anchored",me.style.zIndex=String((H=(L=e==null?void 0:e.launcher)==null?void 0:L.zIndex)!=null?H:hn),{wrapper:$,panel:j,pillRoot:me}}if(n){let F=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),$=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return F.appendChild($),{wrapper:F,panel:$}}if(!t){let F=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),$=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),j=(W=(D=e==null?void 0:e.launcher)==null?void 0:D.width)!=null?W:"100%";return F.style.width=j,$.style.width="100%",F.appendChild($),{wrapper:F,panel:$}}let r=(v=e==null?void 0:e.launcher)!=null?v:{},s=r.position&&xo[r.position]?xo[r.position]:xo["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((k=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?k:hn);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(T=(C=e==null?void 0:e.launcher)==null?void 0:C.width)!=null?T:e==null?void 0:e.launcherWidth,l=d!=null?d:io;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},ky=(e,t)=>{var D,W,v,x,k,C,T,F,$;let n=b("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=mi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=(v=(W=(D=e==null?void 0:e.launcher)==null?void 0:D.clearChat)==null?void 0:W.enabled)!=null?v:!0,a=null,i=null;if(s){let j=fi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=j.button,i=j.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=b("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=b("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let m=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");m.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",m.setAttribute("data-persona-intro-card","");let u=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");u.textContent=(k=(x=e==null?void 0:e.copy)==null?void 0:x.welcomeTitle)!=null?k:"Hello \u{1F44B}";let g=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");g.textContent=(T=(C=e==null?void 0:e.copy)==null?void 0:C.welcomeSubtitle)!=null?T:"Ask anything about your account or products.",m.append(u,g);let p=b("div","persona-flex persona-flex-col persona-gap-3"),w=(F=e==null?void 0:e.layout)==null?void 0:F.contentMaxWidth;w&&(p.style.maxWidth=w,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),(($=e==null?void 0:e.copy)==null?void 0:$.showWelcomeCard)!==!1||(m.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(m,p);let M=b("div","persona-composer-overlay persona-pointer-events-none");M.setAttribute("data-persona-composer-overlay",""),M.style.position="absolute",M.style.left="0",M.style.right="0",M.style.bottom="0",M.style.zIndex="20";let I=Xu({config:e}),{root:L,textNode:H}=Yu();return n.append(d,r,l,M),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:p,composerOverlay:M,suggestions:I.suggestions,textarea:I.textarea,sendButton:I.sendButton,sendButtonWrapper:I.sendButtonWrapper,micButton:I.micButton,micButtonWrapper:I.micButtonWrapper,composerForm:I.composerForm,statusText:I.statusText,introTitle:u,introSubtitle:g,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:d,footer:I.footer,attachmentButton:I.attachmentButton,attachmentButtonWrapper:I.attachmentButtonWrapper,attachmentInput:I.attachmentInput,attachmentPreviewsContainer:I.attachmentPreviewsContainer,actionsRow:I.actionsRow,leftActions:I.leftActions,rightActions:I.rightActions,setSendButtonMode:I.setSendButtonMode,peekBanner:L,peekTextNode:H}},Ju=(e,t=!0)=>{var M,I,L,H,D,W,v,x,k;if(js(e))return ky(e,t);let n=b("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");n.setAttribute("data-persona-theme-zone","container");let o=(M=e==null?void 0:e.layout)==null?void 0:M.header,r=((I=e==null?void 0:e.layout)==null?void 0:I.showHeader)!==!1,s=o?gi(e,o,{showClose:t}):Ar({config:e,showClose:t}),a=b("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=pn(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(H=(L=e==null?void 0:e.copy)==null?void 0:L.welcomeTitle)!=null?H:"Hello \u{1F44B}";let l=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(W=(D=e==null?void 0:e.copy)==null?void 0:D.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",i.append(d,l);let m=b("div","persona-flex persona-flex-col persona-gap-3"),u=(v=e==null?void 0:e.layout)==null?void 0:v.contentMaxWidth;u&&(m.style.maxWidth=u,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((x=e==null?void 0:e.copy)==null?void 0:x.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,m);let p=Ci({config:e}),w=((k=e==null?void 0:e.layout)==null?void 0:k.showFooter)!==!1;r?Gs(n,s,e):(s.header.style.display="none",Gs(n,s,e)),n.append(a);let S=b("div","persona-composer-overlay persona-pointer-events-none");return S.setAttribute("data-persona-composer-overlay",""),S.style.position="absolute",S.style.left="0",S.style.right="0",S.style.bottom="0",S.style.zIndex="20",w||(p.footer.style.display="none"),n.append(p.footer),n.append(S),{container:n,body:a,messagesWrapper:m,composerOverlay:S,suggestions:p.suggestions,textarea:p.textarea,sendButton:p.sendButton,sendButtonWrapper:p.sendButtonWrapper,micButton:p.micButton,micButtonWrapper:p.micButtonWrapper,composerForm:p.composerForm,statusText:p.statusText,introTitle:d,introSubtitle:l,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:p.footer,attachmentButton:p.attachmentButton,attachmentButtonWrapper:p.attachmentButtonWrapper,attachmentInput:p.attachmentInput,attachmentPreviewsContainer:p.attachmentPreviewsContainer,actionsRow:p.actionsRow,leftActions:p.leftActions,rightActions:p.rightActions,setSendButtonMode:p.setSendButtonMode}};var Ey=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},My=(e,t)=>{if(!e)return null;let n=Ey(e);if(n===null)return null;let o=t==null?void 0:t[e],r=o!==void 0?o:n;return r||null},Ly=(e,t)=>{let n=b("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},Iy=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},bl=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},yl=320,em=320,Ry=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Py=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Wy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),By=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Hy=(e,t,n)=>{if(e.length===0)return null;try{let o=b("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n==null||n())};return e.forEach((i,d)=>{var u;let l=b("img");l.alt=((u=i.alt)==null?void 0:u.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${yl}px`,l.style.maxHeight=`${em}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let m=!1;r+=1,l.addEventListener("error",()=>{m||(m=!0,r=Math.max(0,r-1),l.remove(),r===0&&a())}),l.addEventListener("load",()=>{m=!0}),Iy(i.image)?(l.src=i.image,o.appendChild(l)):(m=!0,r=Math.max(0,r-1),l.remove())}),r===0?(a(),null):o}catch{return n==null||n(),null}},Dy=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!bl(o.audio))return;let r=b("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${yl}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Fy=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!bl(o.video))return;let r=b("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${yl}px`,r.style.maxHeight=`${em}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Oy=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!bl(o.data))return;let r=b("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Ys=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},Ny=(e,t,n)=>{let o={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Ys};if(t){let r=t(o);if(r!==null)return r}return Ys()},_y=(e,t)=>{let n=b("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=b("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Zu=(e,t)=>{let n=b("div","persona-text-xs persona-text-persona-muted"),o=new Date(e.createdAt);return t.format?n.textContent=t.format(o):n.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},Vy=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},$y=(e,t,n)=>{var p,w,S,M,I,L;let o=(p=t.showCopy)!=null?p:!0,r=(w=t.showUpvote)!=null?w:!0,s=(S=t.showDownvote)!=null?S:!0;if(!o&&!r&&!s){let H=b("div");return H.style.display="none",H.id=`actions-${e.id}`,H.setAttribute("data-actions-for",e.id),H}let a=(M=t.visibility)!=null?M:"hover",i=(I=t.align)!=null?I:"right",d=(L=t.layout)!=null?L:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],m={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],u=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${m} ${a==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${e.id}`,u.setAttribute("data-actions-for",e.id);let g=(H,D,W)=>{let v=bn({icon:H,label:D,size:14,className:"persona-message-action-btn"});return v.setAttribute("data-action",W),v};return o&&u.appendChild(g("copy","Copy message","copy")),r&&u.appendChild(g("thumbs-up","Upvote","upvote")),s&&u.appendChild(g("thumbs-down","Downvote","downvote")),u},vl=(e,t,n,o,r,s)=>{var Q,Le,Y,xe,Se,de,we,ze,te,ne,re,nt,ye,le,Ue,He,ce;let a=n!=null?n:{},i=(Q=a.layout)!=null?Q:"bubble",d=a.avatar,l=a.timestamp,m=(Le=d==null?void 0:d.show)!=null?Le:!1,u=(Y=l==null?void 0:l.show)!=null?Y:!1,g=(xe=d==null?void 0:d.position)!=null?xe:"left",p=(Se=l==null?void 0:l.position)!=null?Se:"below",w=Vy(e.role,i),S=b("div",w.join(" "));S.id=`bubble-${e.id}`,S.setAttribute("data-message-id",e.id),S.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(S.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",S.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(S.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",S.style.color="var(--persona-message-assistant-text, var(--persona-text))");let M=Ry(e),I=(we=(de=e.content)==null?void 0:de.trim())!=null?we:"",H=M.length>0&&I===Ja,D=ci((te=(ze=s==null?void 0:s.widgetConfig)==null?void 0:ze.features)==null?void 0:te.streamAnimation),W=(nt=(re=(ne=s==null?void 0:s.widgetConfig)==null?void 0:ne.features)==null?void 0:re.streamAnimation)==null?void 0:nt.plugins,v=e.role==="assistant"&&D.type!=="none"?$s(D.type,W):null,x=e.role==="assistant"&&((ye=v==null?void 0:v.isAnimating)==null?void 0:ye.call(v,e))===!0,k=e.role==="assistant"&&v!==null&&(!!e.streaming||x);k&&(v!=null&&v.bubbleClass)&&S.classList.add(v.bubbleClass);let C=document.createElement("div");C.classList.add("persona-message-content"),k&&v&&(v.containerClass&&C.classList.add(v.containerClass),C.style.setProperty("--persona-stream-step",`${D.speed}ms`),C.style.setProperty("--persona-stream-duration",`${D.duration}ms`));let T=k?di((le=e.content)!=null?le:"",D.buffer,v,e,!!e.streaming):(Ue=e.content)!=null?Ue:"",F=t({text:T,message:e,streaming:!!e.streaming,raw:e.rawContent}),$=F;k&&(v==null?void 0:v.wrap)==="char"?$=Us(F,"char",e.id,{skipTags:v.skipTags}):k&&(v==null?void 0:v.wrap)==="word"&&($=Us(F,"word",e.id,{skipTags:v.skipTags}));let j=null;if(H?(j=document.createElement("div"),j.innerHTML=$,j.style.display="none",C.appendChild(j)):C.innerHTML=$,k&&(v!=null&&v.useCaret)&&!H&&I){let G=pi(),Ve=C.querySelectorAll(".persona-stream-char, .persona-stream-word"),Et=Ve[Ve.length-1];if(Et!=null&&Et.parentNode)Et.parentNode.insertBefore(G,Et.nextSibling);else{let pe=C.lastElementChild;pe?pe.appendChild(G):C.appendChild(G)}}if(u&&p==="inline"&&e.createdAt){let G=Zu(e,l);G.classList.add("persona-ml-2","persona-inline"),C.appendChild(G)}if(M.length>0){let G=Hy(M,!H&&!!I,()=>{H&&j&&(j.style.display="")});G?S.appendChild(G):H&&j&&(j.style.display="")}let me=Py(e);if(me.length>0){let G=Dy(me);G&&S.appendChild(G)}let se=Wy(e);if(se.length>0){let G=Fy(se);G&&S.appendChild(G)}let fe=By(e);if(fe.length>0){let G=Oy(fe);G&&S.appendChild(G)}if(S.appendChild(C),u&&p==="below"&&e.createdAt){let G=Zu(e,l);G.classList.add("persona-mt-1"),S.appendChild(G)}let ie=e.role==="assistant"?My(e.stopReason,(ce=(He=s==null?void 0:s.widgetConfig)==null?void 0:He.copy)==null?void 0:ce.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let G=!!(T&&T.trim()),Ve=D.placeholder==="skeleton",Et=Ve&&D.buffer==="line"&&G;if(G)Et&&S.appendChild(zs());else if(Ve)S.appendChild(zs());else{let pe=Ny("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);pe&&S.appendChild(pe)}}if(ie&&e.stopReason&&!e.streaming&&(I||(C.style.display="none"),S.appendChild(Ly(e.stopReason,ie))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let G=$y(e,o,r);S.appendChild(G)}if(!m||e.role==="system")return S;let Oe=b("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ve=_y(d,e.role);return g==="right"||g==="left"&&e.role==="user"?Oe.append(S,ve):Oe.append(ve,S),S.classList.remove("persona-max-w-[85%]"),S.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Oe};var Gr=new Set,Uy=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),zy=(e,t)=>{var o,r;let n=(r=(o=e.reasoning)==null?void 0:o.chunks.join("").trim())!=null?r:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
|
|
24
|
-
`):""},
|
|
25
|
-
`);let r=
|
|
26
|
-
`):""},Ky=(e,t)=>{var m,u,g,p,w;let n=e.toolCall,o=(m=t==null?void 0:t.features)==null?void 0:m.toolCallDisplay,r=(u=o==null?void 0:o.collapsedMode)!=null?u:"tool-call",s=jy(e,(g=o==null?void 0:o.previewMaxLines)!=null?g:3),a=n?Tu(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(p=t==null?void 0:t.toolCall)!=null?p:{},l=a;return r==="tool-name"?l=((w=n.name)==null?void 0:w.trim())||a:r==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=il(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=il(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},nm=(e,t,n)=>{var m;let o=Yr.has(e),r=(m=n==null?void 0:n.toolCall)!=null?m:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let u=r.toggleTextColor||r.headerTextColor||"currentColor",g=Te(o?"chevron-up":"chevron-down",16,u,2);g?l.appendChild(g):l.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},wl=(e,t)=>{var $,j,me,se,fe,ie,be,Oe,ve;let n=e.toolCall,o=($=t==null?void 0:t.toolCall)!=null?$:{},r=b("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),!n)return r;let s=(me=(j=t==null?void 0:t.features)==null?void 0:j.toolCallDisplay)!=null?me:{},a=s.expandable!==!1,i=a&&Yr.has(e.id),{summary:d,previewText:l,isActive:m}=Ky(e,t),u=b("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");u.type="button",a&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let g=b("div","persona-flex persona-flex-col persona-text-left"),p=b("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(p.style.color=o.headerTextColor);let w=String((se=n.startedAt)!=null?se:Date.now()),S=()=>{let Q=b("span","");return Q.setAttribute("data-tool-elapsed",w),Q.textContent=Ps(n),Q},M=(ie=o.renderCollapsedSummary)==null?void 0:ie.call(o,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(fe=s.collapsedMode)!=null?fe:"tool-call",isActive:m,config:t!=null?t:{},elapsed:Ps(n),createElapsedElement:S});typeof M=="string"&&M.trim()?(p.textContent=M,g.appendChild(p)):M instanceof HTMLElement?g.appendChild(M):(p.textContent=d,g.appendChild(p));let I=(be=s.loadingAnimation)!=null?be:"none",L=o.activeTextTemplate,H=o.completeTextTemplate,D=m?L:H,W=M instanceof HTMLElement,v=(Q,Le,Y)=>{let xe=Y;for(let Se of Le){let de=b("span","persona-tool-char");de.style.setProperty("--char-index",String(xe)),de.textContent=Se===" "?"\xA0":Se,Q.appendChild(de),xe++}return xe},x=(Q,Le)=>{var de;p.textContent="";let Y=((de=n.name)==null?void 0:de.trim())||"tool",xe=Ga(Q,Y),Se=0;for(let we of xe){let ze=we.styles.length>0?(()=>{let te=b("span",we.styles.map(ne=>`persona-tool-text-${ne}`).join(" "));return p.appendChild(te),te})():p;if(we.isDuration&&m)ze.appendChild(S());else{let te=we.isDuration?Ps(n):we.text;Le?Se=v(ze,te,Se):ze.appendChild(document.createTextNode(te))}}};if(!W)if(m&&I!=="none"){let Q=(Oe=o.loadingAnimationDuration)!=null?Oe:2e3;if(p.setAttribute("data-preserve-animation","true"),I==="pulse")p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${Q}ms`),D&&x(D,!1);else if(p.classList.add(`persona-tool-loading-${I}`),p.style.setProperty("--persona-tool-anim-duration",`${Q}ms`),I==="shimmer-color"&&(o.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),D)x(D,!0);else{let Le=p.textContent||d;p.textContent="",v(p,Le,0)}}else D&&x(D,!1);let k=null;if(a){k=b("div","persona-flex persona-items-center");let Q=o.toggleTextColor||o.headerTextColor||"currentColor",Le=Te(i?"chevron-up":"chevron-down",16,Q,2);Le?k.appendChild(Le):k.textContent=i?"Hide":"Show";let Y=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Y.append(k),u.append(g,Y)}else u.append(g);let C=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(C.setAttribute("data-persona-collapsed-preview","tool"),C.style.display="none",C.style.whiteSpace="pre-wrap",!i&&m&&s.activePreview&&l){let Q=(ve=o.renderCollapsedPreview)==null?void 0:ve.call(o,{message:e,toolCall:n,defaultPreview:l,isActive:m,config:t!=null?t:{}});qy(C,Q)||(C.textContent=l),C.style.display=""}if(!i&&m&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(u,C),r;let T=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(T.style.display=i?"":"none",o.contentBackgroundColor&&(T.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(T.style.color=o.contentTextColor),o.contentPaddingX&&(T.style.paddingLeft=o.contentPaddingX,T.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(T.style.paddingTop=o.contentPaddingY,T.style.paddingBottom=o.contentPaddingY),n.name){let Q=b("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?Q.style.color=o.contentTextColor:o.headerTextColor&&(Q.style.color=o.headerTextColor),Q.textContent=n.name,T.appendChild(Q)}if(n.args!==void 0){let Q=b("div","persona-space-y-1"),Le=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Le.style.color=o.labelTextColor),Le.textContent="Arguments";let Y=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(Y.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(Y.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(Y.style.color=o.codeBlockTextColor),Y.textContent=jr(n.args),Q.append(Le,Y),T.appendChild(Q)}if(n.chunks&&n.chunks.length){let Q=b("div","persona-space-y-1"),Le=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Le.style.color=o.labelTextColor),Le.textContent="Activity";let Y=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(Y.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(Y.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(Y.style.color=o.codeBlockTextColor),Y.textContent=n.chunks.join(""),Q.append(Le,Y),T.appendChild(Q)}if(n.status==="complete"&&n.result!==void 0){let Q=b("div","persona-space-y-1"),Le=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Le.style.color=o.labelTextColor),Le.textContent="Result";let Y=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(Y.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(Y.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(Y.style.color=o.codeBlockTextColor),Y.textContent=jr(n.result),Q.append(Le,Y),T.appendChild(Q)}if(n.status==="complete"&&typeof n.duration=="number"){let Q=b("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(Q.style.color=o.contentTextColor),Q.textContent=`Duration: ${n.duration}ms`,T.appendChild(Q)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),k){k.innerHTML="";let Q=o.toggleTextColor||o.headerTextColor||"currentColor",Le=Te(i?"chevron-up":"chevron-down",16,Q,2);Le?k.appendChild(Le):k.textContent=i?"Hide":"Show"}T.style.display=i?"":"none",C.style.display=i?"none":C.textContent||C.childNodes.length?"":"none"})(),r.append(u,C,T),r};import{parse as Gy,ARR as Yy,OBJ as Xy,STR as Qy}from"partial-json";var Jy="ask_user_question",Cl=8,Xr="data-persona-ask-sheet-for",Zy="Other",ev="Other\u2026",rm="Type your own answer here",sm="Send",tv="Next",nv="Back",ov="Submit all",rv="Skip",sv=3,Sl="data-ask-current-index",Al="data-ask-question-count",am="data-ask-answers",Tl="data-ask-grouped",im="data-ask-layout",av=e=>e.layout==="pills"?"pills":"rows",iv=e=>e.getAttribute(im)==="pills"?"pills":"rows",om=!1,lm=e=>e.replace(/["\\]/g,"\\$&"),Tr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Jy,kl=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},Qr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=Gy(r,Qy|Xy|Yy);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Xs=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>Cl&&!om&&(om=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Cl}.`)),t.slice(0,Cl)},lv=e=>{var t;return(t=Xs(e)[0])!=null?t:null},cv=(e,t)=>{var n;return(n=Xs(e)[t])!=null?n:null},dv=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},cm=(e,t,n)=>{if(e!=="rows")return null;let o=b("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=b("span","persona-ask-row-check");o.appendChild(r)}else{let r=b("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},pv=(e,t,n,o)=>{let s=b("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=b("span","persona-ask-row-content"),i=b("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=b("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}s.appendChild(a);let d=cm(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},uv=e=>{let n=b("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},mv=(e,t,n,o)=>{var m,u,g;let s=b("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(p=>p&&typeof p.label=="string"&&p.label.length>0);if(d.length===0&&!n){for(let p=0;p<sv;p++)s.appendChild(uv(o));return s}if(d.forEach((p,w)=>{s.appendChild(pv(p,w,o,a))}),(e==null?void 0:e.allowFreeText)!==!1){let p=o==="rows"?Zy:ev;if(o==="rows"){let w=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");w.setAttribute("data-ask-user-action","focus-free-text"),w.setAttribute("data-option-index",String(d.length)),w.setAttribute("data-ask-other-row","true");let S=b("span","persona-ask-row-content"),M=document.createElement("input");M.type="text",M.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",M.placeholder=(m=t.freeTextPlaceholder)!=null?m:rm,M.setAttribute("data-ask-free-text-input","true"),M.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:p),S.appendChild(M),w.appendChild(S);let I=cm(o,a,d.length);I&&w.appendChild(I),s.appendChild(w)}else{let w=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");w.type="button",w.setAttribute("data-ask-user-action","open-free-text"),w.textContent=(g=t.freeTextLabel)!=null?g:p,s.appendChild(w)}}return s},dm=(e,t)=>{var s,a;let o=b("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=(s=e.freeTextPlaceholder)!=null?s:rm,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let i=b("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:sm,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},fv=e=>{var o;let t=b("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=b("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(o=e.submitLabel)!=null?o:sm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},gv=(e,t,n)=>{var l,m,u,g;let o=b("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=b("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=(l=n.backLabel)!=null?l:nv,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(m=n.skipLabel)!=null?m:rv,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=b("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(u=n.submitAllLabel)!=null?u:ov:(g=n.nextLabel)!=null?g:tv,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},kr=e=>{let t=e.getAttribute(am);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},pm=(e,t)=>{e.setAttribute(am,JSON.stringify(t))},lo=e=>{var n;let t=Number((n=e.getAttribute(Sl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},hv=(e,t)=>{e.setAttribute(Sl,String(Math.max(0,Math.floor(t))))},Jr=e=>{var n;let t=Number((n=e.getAttribute(Al))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},sr=e=>e.getAttribute(Tl)==="true",bv=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(o[a]=d)}}),o},yv=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Si=(e,t)=>{let{payload:n}=Qr(t),o=Xs(n),r=kr(e),s={},a=new Set;return o.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(r,d)&&(s[l]=r[d]))}),s},um=e=>{let t=kr(e),n=lo(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(d=>r.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var u;let l=(u=d.getAttribute("data-option-label"))!=null?u:"",m=r.has(l);d.setAttribute("aria-pressed",m?"true":"false"),d.classList.toggle("persona-ask-pill-selected",m)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!a.has(o)){i.value=o;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},mm=e=>{if(!sr(e))return;let t=kr(e),n=lo(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},El=(e,t,n)=>{let o=kl(n),r=iv(e),{payload:s,complete:a}=Qr(t),i=sr(e),d=lo(e),l=Jr(e),m=i?cv(s,d):lv(s),u=!!(m!=null&&m.multiSelect),g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${l}`:"");let p=e.querySelector('[data-ask-stepper="true"]');p&&p.remove();let w=e.querySelector('[data-ask-question="true"]');if(w){let L=typeof(m==null?void 0:m.question)=="string"?m.question:"";w.textContent=L,w.classList.toggle("persona-ask-question-skeleton",!L&&!a)}let S=e.querySelector('[data-ask-pill-list="true"]');if(S){let L=mv(m,o,a,r);S.replaceWith(L)}if(r!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(dm(o,r))}let M=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!M?e.appendChild(fv(o)):(!u||i)&&M&&M.remove(),e.setAttribute("data-multi-select",u?"true":"false");let I=e.querySelector('[data-ask-nav-row="true"]');if(i){let L=gv(d,l,o);I?I.replaceWith(L):e.appendChild(L)}else I&&I.remove();um(e),mm(e)},vv=(e,t,n)=>{let o=kl(t),r=av(o),s=e.toolCall.id,a=Xs(n),i=Math.max(1,a.length),d=i>1,l=bv(e,a),m=d?yv(e,i):0,u=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Xr,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(Al,String(i)),u.setAttribute(Sl,String(m)),u.setAttribute(Tl,d?"true":"false"),u.setAttribute(im,r),pm(u,l),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),dv(u,o);let g=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),p=b("div","persona-ask-sheet-question persona-flex-1");p.setAttribute("data-ask-question","true"),p.textContent="",g.appendChild(p);let w=b("span","persona-ask-sheet-step-inline");w.setAttribute("data-ask-step-inline","true"),w.textContent="",g.appendChild(w),u.appendChild(g);let M=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),u.appendChild(M),r!=="rows"&&u.appendChild(dm(o,r)),El(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},xv=(e,t,n)=>{let{payload:o}=Qr(t),r=Math.max(1,Xs(o).length);r>Jr(e)&&(e.setAttribute(Al,String(r)),r>1&&!sr(e)&&e.setAttribute(Tl,"true")),El(e,t,n)};var Ai=(e,t,n)=>{if(!n||!Tr(e)||kl(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Xr}]`).forEach(l=>{l.getAttribute(Xr)!==r&&l.remove()});let a=n.querySelector(`[${Xr}="${lm(r)}"]`);if(a){xv(a,e,t);return}let{payload:i}=Qr(e),d=vv(e,t,i);n.appendChild(d)},Zr=(e,t)=>{if(!e)return;let n=t?`[${Xr}="${lm(t)}"]`:`[${Xr}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},Ml=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),ar=(e,t)=>{let n=kr(e),o=lo(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,pm(e,n),um(e),mm(e)},Ti=(e,t,n,o)=>{let r=Jr(e),s=Math.max(0,Math.min(r-1,o));hv(e,s),El(e,t,n)};var Ll=(e,t)=>{var S,M,I,L,H,D,W,v,x,k,C,T;let n=e.approval,o=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,r=(n==null?void 0:n.status)==="pending",s=b("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(S=o==null?void 0:o.backgroundColor)!=null?S:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(M=o==null?void 0:o.borderColor)!=null?M:"var(--persona-approval-border, #fef08a)",!n)return s;let a=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=b("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",l=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(I=o==null?void 0:o.titleColor)!=null?I:"currentColor",m=Te(d,20,l,2);m&&i.appendChild(m);let u=b("div","persona-flex-1 persona-min-w-0"),g=b("div","persona-flex persona-items-center persona-gap-2"),p=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o!=null&&o.titleColor&&(p.style.color=o.titleColor),p.textContent=(L=o==null?void 0:o.title)!=null?L:"Approval Required",g.appendChild(p),!r){let F=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");F.setAttribute("data-approval-status",n.status),n.status==="approved"?(F.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",F.style.color="var(--persona-palette-colors-success-700, #15803d)",F.textContent="Approved"):n.status==="denied"?(F.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",F.style.color="var(--persona-palette-colors-error-700, #b91c1c)",F.textContent="Denied"):n.status==="timeout"&&(F.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",F.style.color="var(--persona-palette-colors-warning-700, #b45309)",F.textContent="Timeout"),g.appendChild(F)}u.appendChild(g);let w=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(o!=null&&o.descriptionColor&&(w.style.color=o.descriptionColor),w.textContent=n.description,u.appendChild(w),n.parameters){let F=b("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o!=null&&o.parameterBackgroundColor&&(F.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(F.style.color=o.parameterTextColor),F.style.fontSize="0.75rem",F.style.lineHeight="1rem",F.textContent=jr(n.parameters),u.appendChild(F)}if(r){let F=b("div","persona-flex persona-gap-2 persona-mt-2");F.setAttribute("data-approval-buttons","true");let $=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");$.type="button",$.style.backgroundColor=(H=o==null?void 0:o.approveButtonColor)!=null?H:"var(--persona-approval-approve-bg, #22c55e)",$.style.color=(D=o==null?void 0:o.approveButtonTextColor)!=null?D:"#ffffff",$.setAttribute("data-approval-action","approve");let j=Te("shield-check",14,(W=o==null?void 0:o.approveButtonTextColor)!=null?W:"#ffffff",2);j&&(j.style.marginRight="4px",$.appendChild(j));let me=document.createTextNode((v=o==null?void 0:o.approveLabel)!=null?v:"Approve");$.appendChild(me);let se=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");se.type="button",se.style.backgroundColor=(x=o==null?void 0:o.denyButtonColor)!=null?x:"transparent",se.style.color=(k=o==null?void 0:o.denyButtonTextColor)!=null?k:"var(--persona-feedback-error, #dc2626)",se.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,se.setAttribute("data-approval-action","deny");let fe=Te("shield-x",14,(C=o==null?void 0:o.denyButtonTextColor)!=null?C:"var(--persona-feedback-error, #dc2626)",2);fe&&(fe.style.marginRight="4px",se.appendChild(fe));let ie=document.createTextNode((T=o==null?void 0:o.denyLabel)!=null?T:"Deny");se.appendChild(ie),F.append($,se),u.appendChild(F)}return a.append(i,u),s.appendChild(a),s};var fm=e=>{let t=[];return{buttons:t,render:(o,r,s,a,i)=>{if(e.innerHTML="",t.length=0,!o||!o.length||(a!=null?a:r?r.getMessages():[]).some(p=>p.role==="user"))return;let m=document.createDocumentFragment(),u=r?r.isStreaming():!1,g=p=>{switch(p){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};o.forEach(p=>{let w=b("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");w.type="button",w.textContent=p,w.disabled=u,i!=null&&i.fontFamily&&(w.style.fontFamily=g(i.fontFamily)),i!=null&&i.fontWeight&&(w.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(w.style.paddingLeft=i.paddingX,w.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(w.style.paddingTop=i.paddingY,w.style.paddingBottom=i.paddingY),w.addEventListener("click",()=>{!r||r.isStreaming()||(s.value="",r.sendMessage(p))}),m.appendChild(w),t.push(w)}),e.appendChild(m)}}};var Qs=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Js=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}};var wv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Cv=new Set(["step_start","execution_start"]),Sv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Av=new Set(["step_complete","agent_turn_complete"]),Tv=new Set(["flow_complete","agent_complete"]),gm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),bm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Er=(e,t)=>{let n=e[t];return bm(n)?n:void 0};function Il(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function ki(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function kv(e,t){return typeof t.type=="string"?t.type:e}function Ev(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function Mv(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function hm(e){var o,r,s,a,i;let t=Er(e,"result"),n=[Er(e,"tokens"),Er(e,"totalTokens"),t?Er(t,"tokens"):void 0,Er(e,"usage"),t?Er(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(r=(o=Qn(d.output))!=null?o:Qn(d.outputTokens))!=null?r:Qn(d.completionTokens);if(l!==void 0)return l}return(i=(s=Qn(e.outputTokens))!=null?s:Qn(e.completionTokens))!=null?i:t?(a=Qn(t.outputTokens))!=null?a:Qn(t.completionTokens):void 0}function Lv(e){var n,o,r,s,a;let t=Er(e,"result");return(a=(r=(o=(n=Qn(e.executionTime))!=null?n:Qn(e.executionTimeMs))!=null?o:Qn(e.execution_time))!=null?r:Qn(e.duration))!=null?a:t?(s=Qn(t.executionTime))!=null?s:Qn(t.executionTimeMs):void 0}function Iv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Zs=class{constructor(t=Iv){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:ki(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var s;if(!bm(n)){gm.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=kv(t,n),r=this.now();if(wv.has(o)){this.startRun(r);return}if(Cv.has(o)){this.run||this.startRun(r);return}if(Sv.has(o)){if(!Mv(o,n))return;let a=Ev(n);if(!a)return;this.run||this.startRun(r);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=r),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Il(i.visibleCharCount),l=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:ki(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Av.has(o)){if(!this.run)return;let a=this.run,i=hm(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Il(a.visibleCharCount),m=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:ki(l,m),outputTokens:l,durationMs:m,source:d?"usage":"estimate"};return}if(Tv.has(o)){if(!this.run)return;let a=this.run,i=hm(n),d=i!=null?i:a.exactOutputTokens+Il(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",m=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:ki(d,m),outputTokens:d,durationMs:m,source:l},this.run=null;return}if(gm.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;if(r!==void 0&&r>=250)return r;let s=Lv(n);return s!=null?s:o-t.startedAt}};function es(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Rv={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},Pv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Wv=["flowName","stepName","reasoningText","text","name","tool","toolName"],Bv=100;function Hv(e,t){let n={...Rv,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Pv}function Dv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Fv(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function Ov(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Nv(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let o=document.createElement("textarea");o.value=e,o.style.position="fixed",o.style.opacity="0",document.body.appendChild(o),o.select(),document.execCommand("copy"),document.body.removeChild(o),n()})}function _v(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function Vv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function $v(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function Uv(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(i)return i}return a();function a(){let i=b("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=b("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=o,i.appendChild(d),i}}function Rl(e,t,n,o,r,s,a,i){var g;let d=r.has(e.id),l=b("div","persona-border-b persona-border-persona-divider persona-text-xs");es(l,(g=o.classNames)==null?void 0:g.eventRow);let m=a.find(p=>p.renderEventStreamRow);if(m!=null&&m.renderEventStreamRow&&i){let p=m.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(p)return l.appendChild(p),l}return l.appendChild(u()),l;function u(){var $,j;let p=b("div",""),w=b("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");w.setAttribute("data-event-id",e.id);let S=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),M=Te(d?"chevron-down":"chevron-right","14px","currentColor",2);M&&S.appendChild(M);let I=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=($=o.timestampFormat)!=null?$:"relative";I.textContent=L==="relative"?Dv(e.timestamp,n):Fv(e.timestamp);let H=null;o.showSequenceNumbers!==!1&&(H=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),H.textContent=String(t+1));let D=Hv(e.type,o.badgeColors),W=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");W.style.backgroundColor=D.bg,W.style.color=D.text,W.style.borderColor=D.text+"50",W.textContent=e.type;let v=(j=o.descriptionFields)!=null?j:Wv,x=Ov(e.payload,v),k=null;x&&(k=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),k.textContent=x);let C=b("div","persona-flex-1 persona-min-w-0"),T=b("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),F=Te("clipboard","12px","currentColor",1.5);return F&&T.appendChild(F),T.addEventListener("click",async me=>{me.stopPropagation(),await Nv(_v(e)),T.innerHTML="";let se=Te("check","12px","currentColor",1.5);se&&T.appendChild(se),setTimeout(()=>{T.innerHTML="";let fe=Te("clipboard","12px","currentColor",1.5);fe&&T.appendChild(fe)},1500)}),w.appendChild(S),w.appendChild(I),H&&w.appendChild(H),w.appendChild(W),k&&w.appendChild(k),w.appendChild(C),w.appendChild(T),p.appendChild(w),d&&p.appendChild(Uv(e,a,i)),p}}function ym(e){var w,S,M,I,L;let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,i=(w=r==null?void 0:r.features)==null?void 0:w.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(S=i==null?void 0:i.iconName)!=null?S:"arrow-down",m=(M=i==null?void 0:i.label)!=null?M:"",u=(L=(I=r==null?void 0:r.features)==null?void 0:I.eventStream)!=null?L:{},g=s.find(H=>H.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&r){let H=g.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>p().element,onClose:o});if(H)return{element:H,update:()=>{},destroy:()=>{}}}return p();function p(){let H=u.classNames,D=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");es(D,H==null?void 0:H.panel);let W=[],v="",x="",k=null,C=[],T={},F=0,$=ai(),j=0,me=0,se=!1,fe=null,ie=!1,be=0,Oe=new Set,ve=new Map,Q="",Le="",Y=null,xe,Se,de,we,ze,te=null,ne=null,re=null;function nt(){let oe=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ge=b("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");es(ge,H==null?void 0:H.headerBar);let xt=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(xt.textContent="Events",xe=b("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),xe.textContent="0",a){ne=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ne.style.cursor="help";let Fn=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Fn.textContent="Throughput",te=b("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),te.textContent="-- tok/s",re=b("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),re.style.display="none",re.style.pointerEvents="none";let Zn=ne,vn=re,On=()=>{if(!vn.textContent)return;let wo=Zn.getBoundingClientRect(),Nn=oe.getBoundingClientRect();vn.style.left=`${wo.left-Nn.left}px`,vn.style.top=`${wo.bottom-Nn.top+4}px`,vn.style.display="block"},ut=()=>{vn.style.display="none"};ne.addEventListener("mouseenter",On),ne.addEventListener("mouseleave",ut),ne.appendChild(Fn),ne.appendChild(te)}let $t=b("div","persona-flex-1");Se=b("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Jt=b("option","");Jt.value="",Jt.textContent="All events",Se.appendChild(Jt),de=b("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),de.type="button",de.title="Copy All";let Tt=Te("clipboard-copy","12px","currentColor",1.5);Tt&&de.appendChild(Tt);let wt=b("span","persona-text-xs");wt.textContent="Copy All",de.appendChild(wt),ge.appendChild(xt),ge.appendChild(xe),ne&&ge.appendChild(ne),ge.appendChild($t),ge.appendChild(Se),ge.appendChild(de);let gt=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");es(gt,H==null?void 0:H.searchBar);let bt=Te("search","14px","var(--persona-muted, #9ca3af)",1.5),zt=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");bt&&zt.appendChild(bt),we=b("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),es(we,H==null?void 0:H.searchInput),we.type="text",we.placeholder="Search event payloads...",ze=b("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),ze.type="button",ze.style.display="none";let et=Te("x","12px","currentColor",2);return et&&ze.appendChild(et),gt.appendChild(zt),gt.appendChild(we),gt.appendChild(ze),oe.appendChild(ge),oe.appendChild(gt),re&&oe.appendChild(re),oe}let ye,le=s.find(oe=>oe.renderEventStreamToolbar);if(le!=null&&le.renderEventStreamToolbar&&r){let oe=le.renderEventStreamToolbar({config:r,defaultRenderer:()=>nt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:ge=>{v=ge,Dn(),_()},onSearchChange:ge=>{x=ge,Dn(),_()}});ye=oe!=null?oe:nt()}else ye=nt();let Ue=b("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Ue.style.display="none";function He(){if(!a||!te||!ne)return;let oe=a();te.textContent=Vv(oe);let ge=$v(oe);re&&(re.textContent=ge,ge||(re.style.display="none")),ge?ne.setAttribute("aria-label",ge):ne.removeAttribute("aria-label")}let ce=b("div","persona-flex-1 persona-min-h-0 persona-relative"),G=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");G.style.height="100%";let Ve=b("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");es(Ve,H==null?void 0:H.scrollIndicator),Ve.style.display="none",Ve.setAttribute("data-persona-scroll-to-bottom-has-label",m?"true":"false");let Et=Te(l,"14px","currentColor",2);Et&&Ve.appendChild(Et);let pe=b("span","");pe.textContent=m,Ve.appendChild(pe);let ae=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ae.style.display="none",ce.appendChild(G),ce.appendChild(ae),ce.appendChild(Ve),D.setAttribute("tabindex","0"),D.appendChild(ye),D.appendChild(Ue),D.appendChild(ce);function Ln(){let oe=t.getAll(),ge={};for(let wt of oe)ge[wt.type]=(ge[wt.type]||0)+1;let xt=Object.keys(ge).sort(),$t=xt.length!==C.length||!xt.every((wt,gt)=>wt===C[gt]),Jt=!$t&&xt.some(wt=>ge[wt]!==T[wt]),yn=oe.length!==Object.values(T).reduce((wt,gt)=>wt+gt,0);if(!$t&&!Jt&&!yn||(C=xt,T=ge,!Se))return;let Tt=Se.value;if(Se.options[0].textContent="All events",$t){for(;Se.options.length>1;)Se.remove(1);for(let wt of xt){let gt=b("option","");gt.value=wt,gt.textContent=`${wt} (${ge[wt]||0})`,Se.appendChild(gt)}Tt&&xt.includes(Tt)?Se.value=Tt:Tt&&(Se.value="",v="")}else for(let wt=1;wt<Se.options.length;wt++){let gt=Se.options[wt];gt.textContent=`${gt.value} (${ge[gt.value]||0})`}}function Nt(){let oe=t.getAll();if(v&&(oe=oe.filter(ge=>ge.type===v)),x){let ge=x.toLowerCase();oe=oe.filter(xt=>xt.type.toLowerCase().includes(ge)||xt.payload.toLowerCase().includes(ge))}return oe}function ln(){return v!==""||x!==""}function Dn(){F=0,j=0,$.resume(),Ve.style.display="none"}function Jn(oe){Oe.has(oe)?Oe.delete(oe):Oe.add(oe),Y=oe;let ge=G.scrollTop,xt=$.isFollowing();ie=!0,$.pause(),_(),G.scrollTop=ge,xt&&$.resume(),ie=!1}function qe(){return _s(G,50)}function _(){me=Date.now(),se=!1,He(),Ln();let oe=t.getEvictedCount();oe>0?(Ue.textContent=`${oe.toLocaleString()} older events truncated`,Ue.style.display=""):Ue.style.display="none",W=Nt();let ge=W.length,xt=t.getSize()>0;xe&&(xe.textContent=String(t.getSize())),ge===0&&xt&&ln()?(ae.textContent=x?`No events matching '${x}'`:"No events matching filter",ae.style.display="",G.style.display="none"):(ae.style.display="none",G.style.display=""),de&&(de.title=ln()?`Copy Filtered (${ge})`:"Copy All"),d&&!$.isFollowing()&&ge>F&&(j+=ge-F,pe.textContent=m?`${m}${j>0?` (${j})`:""}`:"",Ve.style.display=""),F=ge;let $t=t.getAll(),Jt=$t.length>0?$t[0].timestamp:0,yn=new Set(W.map(gt=>gt.id));for(let gt of Oe)yn.has(gt)||Oe.delete(gt);let Tt=v!==Q||x!==Le,wt=ve.size===0&&W.length>0;if(Tt||wt||W.length===0){G.innerHTML="",ve.clear();let gt=document.createDocumentFragment();for(let bt=0;bt<W.length;bt++){let zt=Rl(W[bt],bt,Jt,u,Oe,Jn,s,r);ve.set(W[bt].id,zt),gt.appendChild(zt)}G.appendChild(gt),Q=v,Le=x,Y=null}else{if(Y!==null){let bt=ve.get(Y);if(bt&&bt.parentNode===G){let zt=W.findIndex(et=>et.id===Y);if(zt>=0){let et=Rl(W[zt],zt,Jt,u,Oe,Jn,s,r);G.insertBefore(et,bt),bt.remove(),ve.set(Y,et)}}Y=null}let gt=new Set(W.map(bt=>bt.id));for(let[bt,zt]of ve)gt.has(bt)||(zt.remove(),ve.delete(bt));for(let bt=0;bt<W.length;bt++){let zt=W[bt];if(!ve.has(zt.id)){let et=Rl(zt,bt,Jt,u,Oe,Jn,s,r);ve.set(zt.id,et),G.appendChild(et)}}}$.isFollowing()&&(G.scrollTop=G.scrollHeight)}function ke(){if(Date.now()-me>=Bv){fe!==null&&(cancelAnimationFrame(fe),fe=null),_();return}se||(se=!0,fe=requestAnimationFrame(()=>{fe=null,_()}))}let De=(oe,ge)=>{if(!de)return;de.innerHTML="";let xt=Te(oe,"12px","currentColor",1.5);xt&&de.appendChild(xt);let $t=b("span","persona-text-xs");$t.textContent="Copy All",de.appendChild($t),setTimeout(()=>{de.innerHTML="";let Jt=Te("clipboard-copy","12px","currentColor",1.5);Jt&&de.appendChild(Jt);let yn=b("span","persona-text-xs");yn.textContent="Copy All",de.appendChild(yn),de.disabled=!1},ge)},Fe=async()=>{if(de){de.disabled=!0;try{let oe;ln()?oe=W:n?(oe=await n(),oe.length===0&&(oe=t.getAll())):oe=t.getAll();let ge=oe.map(xt=>{try{return JSON.parse(xt.payload)}catch{return xt.payload}});await navigator.clipboard.writeText(JSON.stringify(ge,null,2)),De("check",1500)}catch{De("x",1500)}}},$e=()=>{Se&&(v=Se.value,Dn(),_())},dt=()=>{!we||!ze||(ze.style.display=we.value?"":"none",k&&clearTimeout(k),k=setTimeout(()=>{x=we.value,Dn(),_()},150))},ot=()=>{!we||!ze||(we.value="",x="",ze.style.display="none",k&&clearTimeout(k),Dn(),_())},At=()=>{if(ie)return;let oe=G.scrollTop,{action:ge,nextLastScrollTop:xt}=ii({following:$.isFollowing(),currentScrollTop:oe,lastScrollTop:be,nearBottom:qe(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});be=xt,ge==="resume"?($.resume(),j=0,Ve.style.display="none"):ge==="pause"&&($.pause(),d&&(pe.textContent=m,Ve.style.display=""))},Vt=oe=>{let ge=li({following:$.isFollowing(),deltaY:oe.deltaY,nearBottom:qe(),resumeWhenNearBottom:!0});ge==="pause"?($.pause(),d&&(pe.textContent=m,Ve.style.display="")):ge==="resume"&&($.resume(),j=0,Ve.style.display="none")},q=()=>{d&&(G.scrollTop=G.scrollHeight,$.resume(),j=0,Ve.style.display="none")},_t=oe=>{let ge=oe.target;if(!ge||ge.closest("button"))return;let xt=ge.closest("[data-event-id]");if(!xt)return;let $t=xt.getAttribute("data-event-id");$t&&Jn($t)},Qe=oe=>{if((oe.metaKey||oe.ctrlKey)&&oe.key==="f"){oe.preventDefault(),we==null||we.focus(),we==null||we.select();return}oe.key==="Escape"&&(we&&document.activeElement===we?(ot(),we.blur(),D.focus()):o&&o())};de&&de.addEventListener("click",Fe),Se&&Se.addEventListener("change",$e),we&&we.addEventListener("input",dt),ze&&ze.addEventListener("click",ot),G.addEventListener("scroll",At),G.addEventListener("wheel",Vt,{passive:!0}),G.addEventListener("click",_t),Ve.addEventListener("click",q),D.addEventListener("keydown",Qe);function Ft(){k&&clearTimeout(k),fe!==null&&(cancelAnimationFrame(fe),fe=null),se=!1,ve.clear(),de&&de.removeEventListener("click",Fe),Se&&Se.removeEventListener("change",$e),we&&we.removeEventListener("input",dt),ze&&ze.removeEventListener("click",ot),G.removeEventListener("scroll",At),G.removeEventListener("wheel",Vt),G.removeEventListener("click",_t),Ve.removeEventListener("click",q),D.removeEventListener("keydown",Qe)}return{element:D,update:ke,destroy:Ft}}}function vm(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",o=typeof e.artifactId=="string"?e.artifactId:"",r=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),o&&i.setAttribute("data-open-artifact",o);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let m=document.createElement("div");m.className="persona-truncate persona-text-sm persona-font-medium",m.style.color="var(--persona-text, #1f2937)",m.textContent=n;let u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.style.color="var(--persona-muted, #9ca3af)",r==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(g);let p=document.createElement("span");p.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(p)}else u.textContent=a;if(l.append(m,u),i.append(d,l),r==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${n}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",o),i.append(g)}return i}var xm=(e,t)=>{var o,r,s;let n=(s=(r=(o=t==null?void 0:t.config)==null?void 0:o.features)==null?void 0:r.artifacts)==null?void 0:s.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",m=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>vm(e,t)});if(m)return m}return vm(e,t)};var Pl=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},Mr=new Pl;Mr.register("PersonaArtifactCard",xm);function zv(e){var r;let t=b("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=b("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify((r=e.props)!=null?r:{},null,2),t.appendChild(n),t.appendChild(o),t}function wm(e,t){var Se,de,we,ze;let n=(de=(Se=e.features)==null?void 0:Se.artifacts)==null?void 0:de.layout,r=((we=n==null?void 0:n.toolbarPreset)!=null?we:"default")==="document",s=(ze=n==null?void 0:n.panePadding)==null?void 0:ze.trim(),a=e.markdown?$a(e.markdown):null,i=Ua(e.sanitize),d=te=>{let ne=a?a(te):Is(te);return i?i(ne):ne},l=typeof document!="undefined"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,m=()=>{l==null||l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),F==null||F.hide()};l&&l.addEventListener("click",()=>{var te;m(),(te=t.onDismiss)==null||te.call(t)});let u=b("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");u.setAttribute("data-persona-theme-zone","artifact-pane"),r&&u.classList.add("persona-artifact-pane-document");let g=b("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&g.classList.add("persona-artifact-toolbar-document");let p=b("span","persona-text-xs persona-font-medium persona-truncate");p.textContent="Artifacts";let w=b("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");w.type="button",w.textContent="Close",w.setAttribute("aria-label","Close artifacts panel"),w.addEventListener("click",()=>{var te;m(),(te=t.onDismiss)==null||te.call(t)});let S="rendered",M=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),I=r?bn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):bn({icon:"eye",label:"Rendered view"}),L=r?bn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):bn({icon:"code-2",label:"Source"}),H=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),D=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,W=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,v=n==null?void 0:n.documentToolbarCopyMenuItems,x=!!(W&&v&&v.length>0),k=null,C,T=null,F=null;if(r&&(D||W)&&!x){if(C=D?hl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):bn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W){let te=Te("chevron-down",14,"currentColor",2);te&&C.appendChild(te)}}else r&&x?(k=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),C=D?hl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):bn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),T=bn({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),k.append(C,T)):r?C=bn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):C=bn({icon:"copy",label:"Copy"});let $=r?bn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):bn({icon:"refresh-cw",label:"Refresh"}),j=r?bn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):bn({icon:"x",label:"Close"}),me=()=>{var ye,le,Ue;let te=(ye=ve.find(He=>He.id===Q))!=null?ye:ve[ve.length-1],ne=(le=te==null?void 0:te.id)!=null?le:null,re=(te==null?void 0:te.artifactType)==="markdown"&&(Ue=te.markdown)!=null?Ue:"",nt=te?JSON.stringify({component:te.component,props:te.props},null,2):"";return{markdown:re,jsonPayload:nt,id:ne}},se=async()=>{var ye;let{markdown:te,jsonPayload:ne}=me(),re=(ye=ve.find(le=>le.id===Q))!=null?ye:ve[ve.length-1],nt=(re==null?void 0:re.artifactType)==="markdown"?te:re?ne:"";try{await navigator.clipboard.writeText(nt)}catch{}};if(C.addEventListener("click",async()=>{let te=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(te&&x){let{markdown:ne,jsonPayload:re,id:nt}=me();try{await te({actionId:"primary",artifactId:nt,markdown:ne,jsonPayload:re})}catch{}return}await se()}),T&&(v!=null&&v.length)){let te=()=>{var re;return(re=u.closest("[data-persona-root]"))!=null?re:document.body},ne=()=>{F=Kr({items:v.map(re=>({id:re.id,label:re.label})),onSelect:async re=>{let{markdown:nt,jsonPayload:ye,id:le}=me(),Ue=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Ue?await Ue({actionId:re,artifactId:le,markdown:nt,jsonPayload:ye}):re==="markdown"||re==="md"?await navigator.clipboard.writeText(nt):re==="json"||re==="source"?await navigator.clipboard.writeText(ye):await navigator.clipboard.writeText(nt||ye)}catch{}},anchor:k!=null?k:T,position:"bottom-right",portal:te()})};u.isConnected?ne():requestAnimationFrame(ne),T.addEventListener("click",re=>{re.stopPropagation(),F==null||F.toggle()})}$.addEventListener("click",async()=>{var te;try{await((te=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:te.call(n))}catch{}Y()}),j.addEventListener("click",()=>{var te;m(),(te=t.onDismiss)==null||te.call(t)});let fe=()=>{r&&(I.setAttribute("aria-pressed",S==="rendered"?"true":"false"),L.setAttribute("aria-pressed",S==="source"?"true":"false"))};I.addEventListener("click",()=>{S="rendered",fe(),Y()}),L.addEventListener("click",()=>{S="source",fe(),Y()});let ie=b("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");r?(g.replaceChildren(),M.append(I,L),k?H.append(k,$,j):H.append(C,$,j),g.append(M,ie,H),fe()):(g.appendChild(p),g.appendChild(w)),s&&(g.style.paddingLeft=s,g.style.paddingRight=s);let be=b("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Oe=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(be.style.paddingLeft=s,be.style.paddingRight=s,Oe.style.padding=s),u.appendChild(g),u.appendChild(be),u.appendChild(Oe);let ve=[],Q=null,Le=!1,Y=()=>{var nt,ye,le,Ue;let te=r&&ve.length<=1;be.classList.toggle("persona-hidden",te),be.replaceChildren();for(let He of ve){let ce=b("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");ce.type="button",ce.textContent=He.title||He.id.slice(0,8),He.id===Q&&ce.classList.add("persona-bg-persona-container","persona-border-persona-border"),ce.addEventListener("click",()=>t.onSelect(He.id)),be.appendChild(ce)}Oe.replaceChildren();let ne=Q&&ve.find(He=>He.id===Q)||ve[ve.length-1];if(!ne)return;if(r){let He=ne.artifactType==="markdown"?"MD":(nt=ne.component)!=null?nt:"Component",G=(ne.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ie.textContent=`${G} \xB7 ${He}`}else p.textContent="Artifacts";if(ne.artifactType==="markdown"){if(r&&S==="source"){let ce=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ce.textContent=(ye=ne.markdown)!=null?ye:"",Oe.appendChild(ce);return}let He=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");He.innerHTML=d((le=ne.markdown)!=null?le:""),Oe.appendChild(He);return}let re=ne.component?Mr.get(ne.component):void 0;if(re){let ce={message:{id:ne.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let G=re((Ue=ne.props)!=null?Ue:{},ce);if(G){Oe.appendChild(G);return}}catch{}}Oe.appendChild(zv(ne))},xe=()=>{var ne;let te=ve.length>0;if(u.classList.toggle("persona-hidden",!te),l){let re=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,ye=((ne=re==null?void 0:re.classList.contains("persona-artifact-narrow-host"))!=null?ne:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;te&&ye&&Le?(l.classList.remove("persona-hidden"),u.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:l,update(te){var ne,re,nt;ve=te.artifacts,Q=(nt=(re=te.selectedId)!=null?re:(ne=te.artifacts[te.artifacts.length-1])==null?void 0:ne.id)!=null?nt:null,ve.length>0&&(Le=!0),Y(),xe()},setMobileOpen(te){Le=te,!te&&l?(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):xe()}}}function co(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function Cm(e,t){var s,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!co(t))return;let n=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,o=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),r=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function qv(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function Ei(e,t){var d,l,m,u,g,p,w,S,M,I;if(!co(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),qv(e),Cm(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(m=n==null?void 0:n.splitGap)!=null?m:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(u=n==null?void 0:n.paneWidth)!=null?u:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(g=n==null?void 0:n.paneMaxWidth)!=null?g:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=(p=n==null?void 0:n.paneBackground)==null?void 0:p.trim();o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let r=(w=n==null?void 0:n.panePadding)==null?void 0:w.trim();r?e.style.setProperty("--persona-artifact-pane-padding",r):e.style.removeProperty("--persona-artifact-pane-padding");let s=(S=n==null?void 0:n.documentToolbarIconColor)==null?void 0:S.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(M=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:M.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(I=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:I.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Cm(e,t)}var Sm=["panel","seamless"];function Mi(e,t){var i,d,l,m,u,g;for(let p of Sm)e.classList.remove(`persona-artifact-appearance-${p}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!co(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,o=(l=n==null?void 0:n.paneAppearance)!=null?l:"panel",r=Sm.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${r}`);let s=(m=n==null?void 0:n.paneBorderRadius)==null?void 0:m.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(u=n==null?void 0:n.paneShadow)==null?void 0:u.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let p=((g=n.unifiedSplitOuterRadius)==null?void 0:g.trim())||s;p&&e.style.setProperty("--persona-artifact-unified-outer-radius",p)}}function Am(e,t){var n,o,r;return!t||!co(e)?!1:((r=(o=(n=e.features)==null?void 0:n.artifacts)==null?void 0:o.layout)==null?void 0:r.expandLauncherPanelWhenOpen)!==!1}function jv(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function Kv(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function Gv(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Yv(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Tm(e,t){var a;let o=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function km(e,t,n,o,r,s){let a=jv(r,200),i=Yv(t,n,o,200);i=Math.max(a,i);let d=Kv(s);return d!==null&&(i=Math.min(i,d)),Gv(e,a,i)}var Em={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Wl=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var w,S,M;if(s.dataset.enhanced==="true")return;let a=(w=s.dataset.tvForm)!=null?w:"init";s.dataset.enhanced="true";let i=(S=Em[a])!=null?S:Em.init;s.classList.add("persona-form-card","persona-space-y-4");let d=b("div","persona-space-y-1"),l=b("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let I=b("p","persona-text-sm persona-text-persona-muted");I.textContent=i.description,d.appendChild(I)}let m=document.createElement("form");m.className="persona-form-grid persona-space-y-3",i.fields.forEach(I=>{var v,x;let L=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");L.htmlFor=`${t.id}-${a}-${I.name}`;let H=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");H.textContent=I.label,L.appendChild(H);let D=(v=I.type)!=null?v:"text",W;D==="textarea"?(W=document.createElement("textarea"),W.rows=3):(W=document.createElement("input"),W.type=D),W.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",W.id=`${t.id}-${a}-${I.name}`,W.name=I.name,W.placeholder=(x=I.placeholder)!=null?x:"",I.required&&(W.required=!0),L.appendChild(W),m.appendChild(L)});let u=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),p=b("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");p.type="submit",p.textContent=(M=i.submitLabel)!=null?M:"Submit",u.appendChild(g),u.appendChild(p),m.appendChild(u),s.replaceChildren(d,m),m.addEventListener("submit",async I=>{var W,v;I.preventDefault();let L=(W=n.formEndpoint)!=null?W:"/form",H=new FormData(m),D={};H.forEach((x,k)=>{D[k]=x}),D.type=a,p.disabled=!0,g.textContent="Submitting\u2026";try{let x=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D)});if(!x.ok)throw new Error(`Form submission failed (${x.status})`);let k=await x.json();g.textContent=(v=k.message)!=null?v:"Thanks! We'll be in touch soon.",k.success&&k.nextPrompt&&await o.sendMessage(String(k.nextPrompt))}catch(x){g.textContent=x instanceof Error?x.message:"Something went wrong. Please try again."}finally{p.disabled=!1}})})};var Bl=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var o;let n=this.plugins.get(t);n&&((o=n.onUnregister)==null||o.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var o,r;return((o=n.priority)!=null?o:0)-((r=t.priority)!=null?r:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},Hl=new Bl;var Mm=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{var a;(a=e.get(r))==null||a.delete(s)};return{on:t,off:n,emit:(r,s)=>{var a;(a=e.get(r))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Xv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Qv=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},Fl=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Xv(e),n=Qv(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},Dl=e=>typeof e=="string"?e:e==null?"":String(e),ea={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Dl(e.payload.text)},messageAndClick:(e,t)=>{var r;if(e.type!=="message_and_click")return;let n=e.payload,o=Dl(n.element);if(o&&((r=t.document)!=null&&r.querySelector)){let s=t.document.querySelector(o);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Dl(n.text)}}},Lm=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ol=e=>{let t=new Set(Lm(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Lm(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,m)=>l||(m==null?void 0:m({text:a,message:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),o();let d={action:i,message:s.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let m=()=>{e.emit("action:resubmit",d)},u=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:m});if(!u)continue;if(u.handled){let g=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:g,resubmit:u.resubmit}}}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",m)}return{text:"",persist:!0}},syncFromMetadata:n}};var Jv=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Zv=e=>e.map(t=>({...t,streaming:!1})),ex=e=>e.map(t=>({...t,status:"complete"})),Im=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Jv(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?Zv(n.messages):void 0,artifacts:n.artifacts?ex(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};import{parse as G0,STR as Y0,OBJ as X0}from"partial-json";function Rm(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Mr.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:i=>{r&&r(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Pm(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function Wm(e){let t=Pm(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Bm(e){let t=Pm(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var tx=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Hm(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=tx}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-csat",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Customer satisfaction feedback");let u=null,g=document.createElement("div");g.className="persona-feedback-content";let p=document.createElement("div");p.className="persona-feedback-header";let w=document.createElement("h3");w.className="persona-feedback-title",w.textContent=o,p.appendChild(w);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=r,p.appendChild(S),g.appendChild(p);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let I=[];for(let v=1;v<=5;v++){let x=document.createElement("button");x.type="button",x.className="persona-feedback-rating-btn persona-feedback-star-btn",x.setAttribute("role","radio"),x.setAttribute("aria-checked","false"),x.setAttribute("aria-label",`${v} star${v>1?"s":""}: ${l[v-1]}`),x.title=l[v-1],x.dataset.rating=String(v),x.innerHTML=`
|
|
23
|
+
`,n.addEventListener("click",t);let o=s=>{var R,H,P,w,x,k,S,T,_,U,G,ge,ue;let a=(R=s.launcher)!=null?R:{},i=xn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let ce=(H=a.title)!=null?H:"Chat Assistant";d.textContent=ce,d.setAttribute("title",ce)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let ce=(P=a.subtitle)!=null?P:"Get answers fast";l.textContent=ce,l.setAttribute("title",ce)}let f=n.querySelector(".persona-flex-col");f&&(a.textHidden||i?f.style.display="none":f.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let ce=(w=a.agentIconSize)!=null?w:"40px";if(u.style.height=ce,u.style.width=ce,u.innerHTML="",a.agentIconName){let ke=parseFloat(ce)||24,ve=Ee(a.agentIconName,ke*.6,"var(--persona-text-inverse, #ffffff)",2);ve?(u.appendChild(ve),u.style.display=""):(u.textContent=(x=a.agentIconText)!=null?x:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(k=a.agentIconText)!=null?k:"\u{1F4AC}",u.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let ce=(S=a.agentIconSize)!=null?S:"40px";g.style.height=ce,g.style.width=ce,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let m=n.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let ce=(T=a.callToActionIconSize)!=null?T:"32px";m.style.height=ce,m.style.width=ce,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let ke=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,ke=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let ve=parseFloat(ce)||24,He=Math.max(ve-ke,8),Se=Ee(a.callToActionIconName,He,"currentColor",2);Se?m.appendChild(Se):m.textContent=(_=a.callToActionIconText)!=null?_:"\u2197"}else m.textContent=(U=a.callToActionIconText)!=null?U:"\u2197"}let C=a.position&&To[a.position]?To[a.position]:To["bottom-right"],v="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?E:`${v} ${C}`,i||(n.style.zIndex=String((G=a.zIndex)!=null?G:En));let L="1px solid var(--persona-border, #e5e7eb)",I="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(ge=a.border)!=null?ge:L,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:I,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(ue=a.collapsedMaxWidth)!=null?ue:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}};var pv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Si=(e,t={})=>{var v,E,L,I,R,H;let{showClose:n=!0,wrapperClassName:o=pv,buttonSize:r,iconSize:s="28px"}=t,a=(v=e==null?void 0:e.launcher)!=null?v:{},i=(E=r!=null?r:a.closeButtonSize)!=null?E:"32px",d=b("div",o),l=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let f=(L=a.closeButtonTooltipText)!=null?L:"Close chat",u=(I=a.closeButtonShowTooltip)!=null?I:!0;l.setAttribute("aria-label",f),l.style.display=n?"":"none";let g=(R=a.closeButtonIconName)!=null?R:"x",m=(H=a.closeButtonIconText)!=null?H:"\xD7";l.style.color=a.closeButtonColor||Hn.actionIconColor;let C=Ee(g,s,"currentColor",1);if(C?(C.style.display="block",l.appendChild(C)):l.textContent=m,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let P=a.closeButtonBorderWidth||"0px",w=a.closeButtonBorderColor||"transparent";l.style.border=`${P} solid ${w}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),u&&f){let P=null,w=()=>{if(P)return;let k=l.ownerDocument,S=k.body;if(!S)return;P=Fo(k,"div","persona-clear-chat-tooltip"),P.textContent=f;let T=Fo(k,"div");T.className="persona-clear-chat-tooltip-arrow",P.appendChild(T);let _=l.getBoundingClientRect();P.style.position="fixed",P.style.zIndex=String(mr),P.style.left=`${_.left+_.width/2}px`,P.style.top=`${_.top-8}px`,P.style.transform="translate(-50%, -100%)",S.appendChild(P)},x=()=>{P&&P.parentNode&&(P.parentNode.removeChild(P),P=null)};d.addEventListener("mouseenter",w),d.addEventListener("mouseleave",x),l.addEventListener("focus",w),l.addEventListener("blur",x),d._cleanupTooltip=()=>{x(),d.removeEventListener("mouseenter",w),d.removeEventListener("mouseleave",x),l.removeEventListener("focus",w),l.removeEventListener("blur",x)}}return{button:l,wrapper:d}},uv="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ai=(e,t={})=>{var P,w,x,k,S,T,_,U,G,ge,ue,ce,ke;let{wrapperClassName:n=uv,buttonSize:o,iconSize:r="20px"}=t,a=(w=((P=e==null?void 0:e.launcher)!=null?P:{}).clearChat)!=null?w:{},i=(x=o!=null?o:a.size)!=null?x:"32px",d=(k=a.iconName)!=null?k:"refresh-cw",l=(S=a.iconColor)!=null?S:"",f=(T=a.backgroundColor)!=null?T:"",u=(_=a.borderWidth)!=null?_:"",g=(U=a.borderColor)!=null?U:"",m=(G=a.borderRadius)!=null?G:"",C=(ge=a.paddingX)!=null?ge:"",v=(ue=a.paddingY)!=null?ue:"",E=(ce=a.tooltipText)!=null?ce:"Clear chat",L=(ke=a.showTooltip)!=null?ke:!0,I=b("div",n),R=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");R.style.height=i,R.style.width=i,R.type="button",R.setAttribute("aria-label",E),R.style.color=l||Hn.actionIconColor;let H=Ee(d,r,"currentColor",1);if(H&&(H.style.display="block",R.appendChild(H)),f&&(R.style.backgroundColor=f,R.classList.remove("hover:persona-bg-gray-100")),u||g){let ve=u||"0px",He=g||"transparent";R.style.border=`${ve} solid ${He}`,R.classList.remove("persona-border-none")}if(m&&(R.style.borderRadius=m,R.classList.remove("persona-rounded-full")),C&&(R.style.paddingLeft=C,R.style.paddingRight=C),v&&(R.style.paddingTop=v,R.style.paddingBottom=v),I.appendChild(R),L&&E){let ve=null,He=()=>{if(ve)return;let ie=R.ownerDocument,X=ie.body;if(!X)return;ve=Fo(ie,"div","persona-clear-chat-tooltip"),ve.textContent=E;let re=Fo(ie,"div");re.className="persona-clear-chat-tooltip-arrow",ve.appendChild(re);let be=R.getBoundingClientRect();ve.style.position="fixed",ve.style.zIndex=String(mr),ve.style.left=`${be.left+be.width/2}px`,ve.style.top=`${be.top-8}px`,ve.style.transform="translate(-50%, -100%)",X.appendChild(ve)},Se=()=>{ve&&ve.parentNode&&(ve.parentNode.removeChild(ve),ve=null)};I.addEventListener("mouseenter",He),I.addEventListener("mouseleave",Se),R.addEventListener("focus",He),R.addEventListener("blur",Se),I._cleanupTooltip=()=>{Se(),I.removeEventListener("mouseenter",He),I.removeEventListener("mouseleave",Se),R.removeEventListener("focus",He),R.removeEventListener("blur",Se)}}return{button:R,wrapper:I}};var Hn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Dr=e=>{var P,w,x,k,S,T,_,U,G,ge,ue,ce,ke,ve,He,Se;let{config:t,showClose:n=!0}=e,o=b("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");o.setAttribute("data-persona-theme-zone","header"),o.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",o.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",o.style.boxShadow="var(--persona-header-shadow, none)",o.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let r=(P=t==null?void 0:t.launcher)!=null?P:{},s=(w=r.headerIconSize)!=null?w:"48px",a=(x=r.closeButtonPlacement)!=null?x:"inline",i=(k=r.headerIconHidden)!=null?k:!1,d=r.headerIconName,l=b("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let ie=parseFloat(s)||24,X=Ee(d,ie*.6,"currentColor",1);X?l.replaceChildren(X):l.textContent=(T=(S=t==null?void 0:t.launcher)==null?void 0:S.agentIconText)!=null?T:"\u{1F4AC}"}else if((_=t==null?void 0:t.launcher)!=null&&_.iconUrl){let ie=b("img");ie.src=t.launcher.iconUrl,ie.alt="",ie.className="persona-rounded-xl persona-object-cover",ie.style.height=s,ie.style.width=s,l.replaceChildren(ie)}else l.textContent=(G=(U=t==null?void 0:t.launcher)==null?void 0:U.agentIconText)!=null?G:"\u{1F4AC}";let f=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=b("span","persona-text-base persona-font-semibold");u.style.color=Hn.titleColor,u.textContent=(ue=(ge=t==null?void 0:t.launcher)==null?void 0:ge.title)!=null?ue:"Chat Assistant";let g=b("span","persona-text-xs");g.style.color=Hn.subtitleColor,g.textContent=(ke=(ce=t==null?void 0:t.launcher)==null?void 0:ce.subtitle)!=null?ke:"Here to help you get answers fast",f.append(u,g),i?o.append(f):o.append(l,f);let m=(ve=r.clearChat)!=null?ve:{},C=(He=m.enabled)!=null?He:!0,v=(Se=m.placement)!=null?Se:"inline",E=null,L=null;if(C){let X=Ai(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=X.button,L=X.wrapper,v==="top-right"&&(L.style.right="48px"),v==="inline"&&o.appendChild(L)}let I=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":C&&v==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:R,wrapper:H}=Si(t,{showClose:n,wrapperClassName:I});return a!=="top-right"&&o.appendChild(H),{header:o,iconHolder:l,headerTitle:u,headerSubtitle:g,closeButton:R,closeButtonWrapper:H,clearChatButton:E,clearChatButtonWrapper:L}},la=(e,t,n)=>{var a,i,d,l;let o=(a=n==null?void 0:n.launcher)!=null?a:{},r=(i=o.closeButtonPlacement)!=null?i:"inline",s=(l=(d=o.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function cs(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=e,a=b("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(mr)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of t){if(m.dividerBefore){let E=document.createElement("hr");a.appendChild(E)}let C=document.createElement("button");if(C.type="button",C.setAttribute("role","menuitem"),C.setAttribute("data-dropdown-item-id",m.id),m.destructive&&C.setAttribute("data-destructive",""),m.icon){let E=Ee(m.icon,16,"currentColor",1.5);E&&C.appendChild(E)}let v=document.createElement("span");v.textContent=m.label,C.appendChild(v),C.addEventListener("click",E=>{E.stopPropagation(),f(),n(m.id)}),a.appendChild(C)}let i=null;function d(){if(!s)return;let m=o.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=C=>{!a.contains(C.target)&&!o.contains(C.target)&&f()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function f(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?l():f()}function g(){f(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:f,toggle:u,destroy:g}}function Mn(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:i}=e,d=b("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=Ee(t,o!=null?o:16,"currentColor",r!=null?r:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[f,u]of Object.entries(i))d.setAttribute(f,u);return d}function Wl(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";o!=="default"&&(l+=" persona-label-btn--"+o),l+=" persona-label-btn--"+r,a&&(l+=" "+a);let f=b("button",l);if(f.type="button",f.setAttribute("aria-label",n),t){let g=Ee(t,s!=null?s:14,"currentColor",2);g&&f.appendChild(g)}let u=b("span");if(u.textContent=n,f.appendChild(u),i&&f.addEventListener("click",i),d)for(let[g,m]of Object.entries(d))f.setAttribute(g,m);return f}function Lm(e){var m,C;let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:i,hover:d}=e,l=b("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let f=b("span","persona-combo-btn-label");f.textContent=t,l.appendChild(f);let u=Ee(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",l.appendChild(u)),d&&(l.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",l.style.padding=(C=d.padding)!=null?C:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var v,E;l.style.backgroundColor=(v=d.background)!=null?v:"",l.style.borderColor=(E=d.border)!=null?E:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let g=cs({items:o,onSelect:v=>{l.setAttribute("aria-expanded","false"),r(v)},anchor:l,position:s,portal:a});return a||l.appendChild(g.element),l.addEventListener("click",v=>{v.stopPropagation();let E=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",E?"false":"true"),g.toggle()}),l.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),l.click())}),{element:l,setLabel:v=>{f.textContent=v,l.setAttribute("aria-label",v)},open:()=>{l.setAttribute("aria-expanded","true"),g.show()},close:()=>{l.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let v=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",v?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),l.remove()}}}var mv=e=>{var o;let t=Dr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(o=e.layoutHeaderConfig)==null?void 0:o.onTitleClick;if(n){let r=t.headerTitle.parentElement;r&&(r.style.cursor="pointer",r.setAttribute("role","button"),r.setAttribute("tabindex","0"),r.addEventListener("click",()=>n()),r.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function fv(e,t,n){var o,r,s;if(t!=null&&t.length)for(let a of t){let i=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(r=(o=a.ariaLabel)!=null?o:a.label)!=null?r:a.id),a.icon){let d=Ee(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=b("div","persona-relative");d.appendChild(i);let l=cs({items:a.menuItems,onSelect:f=>n==null?void 0:n(f),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",f=>{f.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var gv=e=>{var I,R,H,P,w,x,k,S,T;let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=(I=t==null?void 0:t.launcher)!=null?I:{},i=b("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=r==null?void 0:r.titleMenu,l,f;if(d)l=Lm({label:(R=a.title)!=null?R:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Hn.titleColor,f=(H=l.querySelector(".persona-combo-btn-label"))!=null?H:l;else{if(l=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),f=b("span","persona-text-base persona-font-semibold persona-truncate"),f.style.color=Hn.titleColor,f.textContent=(P=a.title)!=null?P:"Chat Assistant",l.appendChild(f),fv(l,r==null?void 0:r.trailingActions,(w=r==null?void 0:r.onAction)!=null?w:s),r!=null&&r.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let U=r.onTitleClick;l.addEventListener("click",G=>{G.target.closest("button")||U()}),l.addEventListener("keydown",G=>{(G.key==="Enter"||G.key===" ")&&(G.preventDefault(),U())})}let _=r==null?void 0:r.titleRowHover;_&&(l.style.borderRadius=(x=_.borderRadius)!=null?x:"10px",l.style.padding=(k=_.padding)!=null?k:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var U,G;l.style.backgroundColor=(U=_.background)!=null?U:"",l.style.borderColor=(G=_.border)!=null?G:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let u=(S=a.closeButtonSize)!=null?S:"32px",g=b("div",""),m=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=u,m.style.width=u,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=n?"":"none",m.style.color=a.closeButtonColor||Hn.actionIconColor;let C=(T=a.closeButtonIconName)!=null?T:"x",v=Ee(C,"28px","currentColor",1);v?m.appendChild(v):m.textContent="\xD7",o&&m.addEventListener("click",o),g.appendChild(m),i.appendChild(g);let E=b("div");E.style.display="none";let L=b("span");return L.style.display="none",{header:i,iconHolder:E,headerTitle:f,headerSubtitle:L,closeButton:m,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},Im={default:mv,minimal:gv},hv=e=>{var t;return(t=Im[e])!=null?t:Im.default},Ti=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),f=b("div");f.style.display="none";let u=b("span"),g=b("span"),m=b("button");m.style.display="none";let C=b("div");return C.style.display="none",{header:l,iconHolder:f,headerTitle:u,headerSubtitle:g,closeButton:m,closeButtonWrapper:C,clearChatButton:null,clearChatButtonWrapper:null}}let o=(a=t==null?void 0:t.layout)!=null?a:"default",s=hv(o)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var ki=e=>{var a,i;let t=b("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;t.style.maxHeight=`${n*o}px`,t.style.overflowY="auto";let r=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*o},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,r());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},Ei=e=>{var P,w,x,k,S,T,_,U,G,ge,ue,ce;let t=(P=e==null?void 0:e.sendButton)!=null?P:{},n=(w=t.useIcon)!=null?w:!1,o=(x=t.iconText)!=null?x:"\u2191",r=t.iconName,s=(k=t.stopIconName)!=null?k:"square",a=(S=t.tooltipText)!=null?S:"Send message",i=(T=t.stopTooltipText)!=null?T:"Stop generating",d=(U=(_=e==null?void 0:e.copy)==null?void 0:_.sendButtonLabel)!=null?U:"Send",l=(ge=(G=e==null?void 0:e.copy)==null?void 0:G.stopButtonLabel)!=null?ge:"Stop",f=(ue=t.showTooltip)!=null?ue:!1,u=(ce=t.size)!=null?ce:"40px",g=t.backgroundColor,m=t.textColor,C=b("div","persona-send-button-wrapper"),v=b("button",n?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");v.type="submit",v.setAttribute("data-persona-composer-submit","");let E=null,L=null;if(n){v.style.width=u,v.style.height=u,v.style.minWidth=u,v.style.minHeight=u,v.style.fontSize="18px",v.style.lineHeight="1",v.innerHTML="",m?v.style.color=m:v.style.color="var(--persona-button-primary-fg, #ffffff)";let ke=parseFloat(u)||24,ve=(m==null?void 0:m.trim())||"currentColor";r?(E=Ee(r,ke,ve,2),E?v.appendChild(E):v.textContent=o):v.textContent=o,L=Ee(s,ke,ve,2),g?v.style.backgroundColor=g:v.classList.add("persona-bg-persona-primary")}else v.textContent=d,m?v.style.color=m:v.classList.add("persona-text-white");t.borderWidth&&(v.style.borderWidth=t.borderWidth,v.style.borderStyle="solid"),t.borderColor&&(v.style.borderColor=t.borderColor),t.paddingX?(v.style.paddingLeft=t.paddingX,v.style.paddingRight=t.paddingX):(v.style.paddingLeft="",v.style.paddingRight=""),t.paddingY?(v.style.paddingTop=t.paddingY,v.style.paddingBottom=t.paddingY):(v.style.paddingTop="",v.style.paddingBottom="");let I=null;f&&a&&(I=b("div","persona-send-button-tooltip"),I.textContent=a,C.appendChild(I)),v.setAttribute("aria-label",a),C.appendChild(v);let R="send";return{button:v,wrapper:C,setMode:ke=>{if(ke===R)return;R=ke;let ve=ke==="stop"?i:a;if(v.setAttribute("aria-label",ve),I&&(I.textContent=ve),n){if(E&&L){let He=ke==="stop"?L:E;v.replaceChildren(He)}}else v.textContent=ke==="stop"?l:d}}},Mi=e=>{var I,R,H,P,w,x,k,S,T,_,U,G;let t=(I=e==null?void 0:e.voiceRecognition)!=null?I:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),r=((R=t.provider)==null?void 0:R.type)==="runtype";if(!(o||r))return null;let a=(P=(H=e==null?void 0:e.sendButton)==null?void 0:H.size)!=null?P:"40px",i=b("div","persona-send-button-wrapper"),d=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(w=t.iconName)!=null?w:"mic",f=(x=t.iconSize)!=null?x:a,u=parseFloat(f)||24,g=(S=t.backgroundColor)!=null?S:(k=e==null?void 0:e.sendButton)==null?void 0:k.backgroundColor,m=(_=t.iconColor)!=null?_:(T=e==null?void 0:e.sendButton)==null?void 0:T.textColor;d.style.width=f,d.style.height=f,d.style.minWidth=f,d.style.minHeight=f,d.style.fontSize="18px",d.style.lineHeight="1",m?d.style.color=m:d.style.color="var(--persona-text, #111827)";let v=Ee(l,u,m||"currentColor",1.5);v?d.appendChild(v):d.textContent="\u{1F3A4}",g&&(d.style.backgroundColor=g),t.borderWidth&&(d.style.borderWidth=t.borderWidth,d.style.borderStyle="solid"),t.borderColor&&(d.style.borderColor=t.borderColor),t.paddingX&&(d.style.paddingLeft=t.paddingX,d.style.paddingRight=t.paddingX),t.paddingY&&(d.style.paddingTop=t.paddingY,d.style.paddingBottom=t.paddingY),i.appendChild(d);let E=(U=t.tooltipText)!=null?U:"Start voice recognition";if(((G=t.showTooltip)!=null?G:!1)&&E){let ge=b("div","persona-send-button-tooltip");ge.textContent=E,i.appendChild(ge)}return{button:d,wrapper:i}},Li=e=>{var C,v,E,L,I,R,H,P;let t=(C=e==null?void 0:e.attachments)!=null?C:{};if(t.enabled!==!0)return null;let n=(E=(v=e==null?void 0:e.sendButton)==null?void 0:v.size)!=null?E:"40px",o=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.style.display="none";let r=b("input");r.type="file",r.accept=((L=t.allowedTypes)!=null?L:Yo).join(","),r.multiple=((I=t.maxFiles)!=null?I:4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=b("div","persona-send-button-wrapper"),a=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(R=t.buttonTooltipText)!=null?R:"Attach file");let i=(H=t.buttonIconName)!=null?H:"paperclip",d=n,l=parseFloat(d)||40,f=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let u=Ee(i,f,"currentColor",1.5);u?a.appendChild(u):a.textContent="\u{1F4CE}",a.addEventListener("click",w=>{w.preventDefault(),r.click()}),s.appendChild(a);let g=(P=t.buttonTooltipText)!=null?P:"Attach file",m=b("div","persona-send-button-tooltip");return m.textContent=g,s.appendChild(m),{button:a,wrapper:s,input:r,previewsContainer:o}},Ii=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=b("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=(i=t.visible)!=null?i:!0;o.style.display=r?"":"none";let s=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let l=b("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=s,l.style.color="inherit",l.style.textDecoration="none",o.appendChild(l)}else o.textContent=s;return o},Ri=()=>b("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var Pi=e=>{var C,v,E,L,I,R;let{config:t}=e,n=b("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");n.setAttribute("data-persona-theme-zone","composer");let o=Ri(),r=b("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");r.setAttribute("data-persona-composer-form",""),r.style.outline="none";let{textarea:s,attachAutoResize:a}=ki(t);a();let i=Ei(t),d=Mi(t),l=Li(t),f=Ii(t);l&&(l.previewsContainer.style.gap="8px",r.append(l.previewsContainer,l.input)),r.append(s);let u=b("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),g=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&g.append(l.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),u.append(g,m),r.append(u),r.addEventListener("click",H=>{H.target!==i.button&&H.target!==i.wrapper&&H.target!==(d==null?void 0:d.button)&&H.target!==(d==null?void 0:d.wrapper)&&H.target!==(l==null?void 0:l.button)&&H.target!==(l==null?void 0:l.wrapper)&&s.focus()}),n.append(o,r,f),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(C=d==null?void 0:d.button)!=null?C:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:f,attachmentButton:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(L=l==null?void 0:l.wrapper)!=null?L:null,attachmentInput:(I=l==null?void 0:l.input)!=null?I:null,attachmentPreviewsContainer:(R=l==null?void 0:l.previewsContainer)!=null?R:null,actionsRow:u,leftActions:g,rightActions:m,setSendButtonMode:i.setMode}};var Rm=()=>{let e=b("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let t=b("span","persona-pill-peek__icon"),n=Ee("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=b("span","persona-pill-peek__text"),r=b("span","persona-pill-peek__caret"),s=Ee("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},Pm=e=>{var C,v,E,L,I,R;let{config:t}=e,n=b("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let o=Ri();o.style.display="none";let r=Ii(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=ki(t);s.style.maxHeight="100px",a();let i=Ei(t),d=Mi(t),l=Li(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let f=b("form","persona-widget-composer persona-pill-composer");f.setAttribute("data-persona-composer-form",""),f.style.outline="none";let u=b("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&u.append(l.wrapper);let g=b("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),f.addEventListener("click",H=>{H.target!==i.button&&H.target!==i.wrapper&&H.target!==(d==null?void 0:d.button)&&H.target!==(d==null?void 0:d.wrapper)&&H.target!==(l==null?void 0:l.button)&&H.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&f.append(l.input),f.append(u,s,g),l&&n.append(l.previewsContainer),n.append(f,o,r);let m=f;return{footer:n,suggestions:o,composerForm:f,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(C=d==null?void 0:d.button)!=null?C:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:r,attachmentButton:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(L=l==null?void 0:l.wrapper)!=null?L:null,attachmentInput:(I=l==null?void 0:l.input)!=null?I:null,attachmentPreviewsContainer:(R=l==null?void 0:l.previewsContainer)!=null?R:null,actionsRow:m,leftActions:u,rightActions:g,setSendButtonMode:i.setMode}};var Wm=e=>{var f,u,g,m,C,v,E,L,I,R,H,P,w,x,k,S,T;let t=(u=(f=e==null?void 0:e.launcher)==null?void 0:f.enabled)!=null?u:!0,n=xn(e);if(aa(e)){let _=(m=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?m:{},U=b("div","persona-widget-wrapper persona-fixed persona-transition");U.setAttribute("data-persona-composer-bar",""),U.dataset.state="collapsed",U.dataset.expandedSize=(C=_.expandedSize)!=null?C:"anchored",U.style.zIndex=String((E=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?E:En);let G=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");G.style.width="100%",U.appendChild(G);let ge=b("div","persona-widget-pill-root");return ge.setAttribute("data-persona-composer-bar",""),ge.dataset.state="collapsed",ge.dataset.expandedSize=(L=_.expandedSize)!=null?L:"anchored",ge.style.zIndex=String((R=(I=e==null?void 0:e.launcher)==null?void 0:I.zIndex)!=null?R:En),{wrapper:U,panel:G,pillRoot:ge}}if(n){let _=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),U=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return _.appendChild(U),{wrapper:_,panel:U}}if(!t){let _=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),U=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),G=(P=(H=e==null?void 0:e.launcher)==null?void 0:H.width)!=null?P:"100%";return _.style.width=G,U.style.width="100%",_.appendChild(U),{wrapper:_,panel:U}}let r=(w=e==null?void 0:e.launcher)!=null?w:{},s=r.position&&To[r.position]?To[r.position]:To["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((k=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?k:En);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(T=(S=e==null?void 0:e.launcher)==null?void 0:S.width)!=null?T:e==null?void 0:e.launcherWidth,l=d!=null?d:fo;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},bv=(e,t)=>{var H,P,w,x,k,S,T,_,U;let n=b("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=Si(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=(w=(P=(H=e==null?void 0:e.launcher)==null?void 0:H.clearChat)==null?void 0:P.enabled)!=null?w:!0,a=null,i=null;if(s){let G=Ai(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=G.button,i=G.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=b("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=b("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages"),l.style.setProperty("scrollbar-gutter","stable");let f=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");f.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",f.setAttribute("data-persona-intro-card","");let u=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");u.textContent=(k=(x=e==null?void 0:e.copy)==null?void 0:x.welcomeTitle)!=null?k:"Hello \u{1F44B}";let g=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");g.textContent=(T=(S=e==null?void 0:e.copy)==null?void 0:S.welcomeSubtitle)!=null?T:"Ask anything about your account or products.",f.append(u,g);let m=b("div","persona-flex persona-flex-col persona-gap-3"),C=(_=e==null?void 0:e.layout)==null?void 0:_.contentMaxWidth;C&&(m.style.maxWidth=C,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((U=e==null?void 0:e.copy)==null?void 0:U.showWelcomeCard)!==!1||(f.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(f,m);let E=b("div","persona-composer-overlay persona-pointer-events-none");E.setAttribute("data-persona-composer-overlay",""),E.style.position="absolute",E.style.left="0",E.style.right="0",E.style.bottom="0",E.style.zIndex="20";let L=Pm({config:e}),{root:I,textNode:R}=Rm();return n.append(d,r,l,E),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:m,composerOverlay:E,suggestions:L.suggestions,textarea:L.textarea,sendButton:L.sendButton,sendButtonWrapper:L.sendButtonWrapper,micButton:L.micButton,micButtonWrapper:L.micButtonWrapper,composerForm:L.composerForm,statusText:L.statusText,introTitle:u,introSubtitle:g,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:d,footer:L.footer,attachmentButton:L.attachmentButton,attachmentButtonWrapper:L.attachmentButtonWrapper,attachmentInput:L.attachmentInput,attachmentPreviewsContainer:L.attachmentPreviewsContainer,actionsRow:L.actionsRow,leftActions:L.leftActions,rightActions:L.rightActions,setSendButtonMode:L.setSendButtonMode,peekBanner:I,peekTextNode:R}},Bm=(e,t=!0)=>{var E,L,I,R,H,P,w,x,k;if(aa(e))return bv(e,t);let n=b("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");n.setAttribute("data-persona-theme-zone","container");let o=(E=e==null?void 0:e.layout)==null?void 0:E.header,r=((L=e==null?void 0:e.layout)==null?void 0:L.showHeader)!==!1,s=o?Ti(e,o,{showClose:t}):Dr({config:e,showClose:t}),a=b("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages"),a.style.setProperty("scrollbar-gutter","stable");let i=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=xn(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(R=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeTitle)!=null?R:"Hello \u{1F44B}";let l=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(P=(H=e==null?void 0:e.copy)==null?void 0:H.welcomeSubtitle)!=null?P:"Ask anything about your account or products.",i.append(d,l);let f=b("div","persona-flex persona-flex-col persona-gap-3"),u=(w=e==null?void 0:e.layout)==null?void 0:w.contentMaxWidth;u&&(f.style.maxWidth=u,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((x=e==null?void 0:e.copy)==null?void 0:x.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,f);let m=Pi({config:e}),C=((k=e==null?void 0:e.layout)==null?void 0:k.showFooter)!==!1;r?la(n,s,e):(s.header.style.display="none",la(n,s,e)),n.append(a);let v=b("div","persona-composer-overlay persona-pointer-events-none");return v.setAttribute("data-persona-composer-overlay",""),v.style.position="absolute",v.style.left="0",v.style.right="0",v.style.bottom="0",v.style.zIndex="20",C||(m.footer.style.display="none"),n.append(m.footer),n.append(v),{container:n,body:a,messagesWrapper:f,composerOverlay:v,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:d,introSubtitle:l,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var yv=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},vv=(e,t)=>{if(!e)return null;let n=yv(e);if(n===null)return null;let o=t==null?void 0:t[e],r=o!==void 0?o:n;return r||null},xv=(e,t)=>{let n=b("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},wv=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Bl=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Hl=320,Dm=320,Cv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Sv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Av=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Tv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),kv=(e,t,n)=>{if(e.length===0)return null;try{let o=b("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n==null||n())};return e.forEach((i,d)=>{var u;let l=b("img");l.alt=((u=i.alt)==null?void 0:u.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${Hl}px`,l.style.maxHeight=`${Dm}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let f=!1;r+=1,l.addEventListener("error",()=>{f||(f=!0,r=Math.max(0,r-1),l.remove(),r===0&&a())}),l.addEventListener("load",()=>{f=!0}),wv(i.image)?(l.src=i.image,o.appendChild(l)):(f=!0,r=Math.max(0,r-1),l.remove())}),r===0?(a(),null):o}catch{return n==null||n(),null}},Ev=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!Bl(o.audio))return;let r=b("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Hl}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Mv=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!Bl(o.video))return;let r=b("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Hl}px`,r.style.maxHeight=`${Dm}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Lv=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!Bl(o.data))return;let r=b("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ca=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},Iv=(e,t,n)=>{let o={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:ca};if(t){let r=t(o);if(r!==null)return r}return ca()},Rv=(e,t)=>{let n=b("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=b("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Hm=(e,t)=>{let n=b("div","persona-text-xs persona-text-persona-muted"),o=new Date(e.createdAt);return t.format?n.textContent=t.format(o):n.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},Pv=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},Wv=(e,t,n)=>{var m,C,v,E,L,I;let o=(m=t.showCopy)!=null?m:!0,r=(C=t.showUpvote)!=null?C:!0,s=(v=t.showDownvote)!=null?v:!0;if(!o&&!r&&!s){let R=b("div");return R.style.display="none",R.id=`actions-${e.id}`,R.setAttribute("data-actions-for",e.id),R}let a=(E=t.visibility)!=null?E:"hover",i=(L=t.align)!=null?L:"right",d=(I=t.layout)!=null?I:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],f={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],u=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${f} ${a==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${e.id}`,u.setAttribute("data-actions-for",e.id);let g=(R,H,P)=>{let w=Mn({icon:R,label:H,size:14,className:"persona-message-action-btn"});return w.setAttribute("data-action",P),w};return o&&u.appendChild(g("copy","Copy message","copy")),r&&u.appendChild(g("thumbs-up","Upvote","upvote")),s&&u.appendChild(g("thumbs-down","Downvote","downvote")),u},Dl=(e,t,n,o,r,s)=>{var ie,X,re,be,he,j,se,Ie,ne,Z,oe,at,it,Me,de,Xe,We;let a=n!=null?n:{},i=(ie=a.layout)!=null?ie:"bubble",d=a.avatar,l=a.timestamp,f=(X=d==null?void 0:d.show)!=null?X:!1,u=(re=l==null?void 0:l.show)!=null?re:!1,g=(be=d==null?void 0:d.position)!=null?be:"left",m=(he=l==null?void 0:l.position)!=null?he:"below",C=Pv(e.role,i),v=b("div",C.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=Cv(e),L=(se=(j=e.content)==null?void 0:j.trim())!=null?se:"",R=E.length>0&&L===li,H=vi((ne=(Ie=s==null?void 0:s.widgetConfig)==null?void 0:Ie.features)==null?void 0:ne.streamAnimation),P=(at=(oe=(Z=s==null?void 0:s.widgetConfig)==null?void 0:Z.features)==null?void 0:oe.streamAnimation)==null?void 0:at.plugins,w=e.role==="assistant"&&H.type!=="none"?na(H.type,P):null,x=e.role==="assistant"&&((it=w==null?void 0:w.isAnimating)==null?void 0:it.call(w,e))===!0,k=e.role==="assistant"&&w!==null&&(!!e.streaming||x);k&&(w!=null&&w.bubbleClass)&&v.classList.add(w.bubbleClass);let S=document.createElement("div");S.classList.add("persona-message-content"),k&&w&&(w.containerClass&&S.classList.add(w.containerClass),S.style.setProperty("--persona-stream-step",`${H.speed}ms`),S.style.setProperty("--persona-stream-duration",`${H.duration}ms`));let T=k?xi((Me=e.content)!=null?Me:"",H.buffer,w,e,!!e.streaming):(de=e.content)!=null?de:"",_=t({text:T,message:e,streaming:!!e.streaming,raw:e.rawContent}),U=_;k&&(w==null?void 0:w.wrap)==="char"?U=oa(_,"char",e.id,{skipTags:w.skipTags}):k&&(w==null?void 0:w.wrap)==="word"&&(U=oa(_,"word",e.id,{skipTags:w.skipTags}));let G=null;if(R?(G=document.createElement("div"),G.innerHTML=U,G.style.display="none",S.appendChild(G)):S.innerHTML=U,k&&(w!=null&&w.useCaret)&&!R&&L){let q=wi(),me=S.querySelectorAll(".persona-stream-char, .persona-stream-word"),et=me[me.length-1];if(et!=null&&et.parentNode)et.parentNode.insertBefore(q,et.nextSibling);else{let Et=S.lastElementChild;Et?Et.appendChild(q):S.appendChild(q)}}if(u&&m==="inline"&&e.createdAt){let q=Hm(e,l);q.classList.add("persona-ml-2","persona-inline"),S.appendChild(q)}if(E.length>0){let q=kv(E,!R&&!!L,()=>{R&&G&&(G.style.display="")});q?v.appendChild(q):R&&G&&(G.style.display="")}let ge=Sv(e);if(ge.length>0){let q=Ev(ge);q&&v.appendChild(q)}let ue=Av(e);if(ue.length>0){let q=Mv(ue);q&&v.appendChild(q)}let ce=Tv(e);if(ce.length>0){let q=Lv(ce);q&&v.appendChild(q)}if(v.appendChild(S),u&&m==="below"&&e.createdAt){let q=Hm(e,l);q.classList.add("persona-mt-1"),v.appendChild(q)}let ke=e.role==="assistant"?vv(e.stopReason,(We=(Xe=s==null?void 0:s.widgetConfig)==null?void 0:Xe.copy)==null?void 0:We.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let q=!!(T&&T.trim()),me=H.placeholder==="skeleton",et=me&&H.buffer==="line"&&q;if(q)et&&v.appendChild(ra());else if(me)v.appendChild(ra());else{let Et=Iv("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Et&&v.appendChild(Et)}}if(ke&&e.stopReason&&!e.streaming&&(L||(S.style.display="none"),v.appendChild(xv(e.stopReason,ke))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let q=Wv(e,o,r);v.appendChild(q)}if(!f||e.role==="system")return v;let He=b("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Se=Rv(d,e.role);return g==="right"||g==="left"&&e.role==="user"?He.append(v,Se):He.append(Se,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),He};var ds=new Set,Bv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Hv=(e,t)=>{var o,r;let n=(r=(o=e.reasoning)==null?void 0:o.chunks.join("").trim())!=null?r:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
|
|
24
|
+
`):""},Fm=(e,t)=>{let n=ds.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let a=o.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=Ee(n?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},Fl=(e,t)=>{var ue,ce,ke,ve,He,Se,ie,X,re,be,he;let n=e.reasoning,o=b("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let r=(ce=(ue=t==null?void 0:t.features)==null?void 0:ue.reasoningDisplay)!=null?ce:{},s=r.expandable!==!1,a=s&&ds.has(e.id),i=n.status!=="complete",d=Hv(e,(ke=r.previewMaxLines)!=null?ke:3),l=b("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",s&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let f=b("div","persona-flex persona-flex-col persona-text-left"),u=b("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",m=(ve=t==null?void 0:t.reasoning)!=null?ve:{},C=String((He=n.startedAt)!=null?He:Date.now()),v=()=>{let j=b("span","");return j.setAttribute("data-tool-elapsed",C),j.textContent=oi(n),j},E=(Se=m.renderCollapsedSummary)==null?void 0:Se.call(m,{message:e,reasoning:n,defaultSummary:g,previewText:d,isActive:i,config:t!=null?t:{},elapsed:oi(n),createElapsedElement:v});typeof E=="string"&&E.trim()?(u.textContent=E,f.appendChild(u)):E instanceof HTMLElement?f.appendChild(E):(u.textContent=g,f.appendChild(u));let L=b("span","persona-text-xs persona-text-persona-primary");L.textContent=om(n),f.appendChild(L);let I=(ie=r.loadingAnimation)!=null?ie:"none",R=m.activeTextTemplate,H=m.completeTextTemplate,P=i?R:H,w=E instanceof HTMLElement,x=(j,se,Ie)=>{let ne=Ie;for(let Z of se){let oe=b("span","persona-tool-char");oe.style.setProperty("--char-index",String(ne)),oe.textContent=Z===" "?"\xA0":Z,j.appendChild(oe),ne++}return ne},k=(j,se)=>{u.textContent="";let Ie=ri(j,""),ne=0;for(let Z of Ie){let oe=Z.styles.length>0?(()=>{let at=b("span",Z.styles.map(it=>`persona-tool-text-${it}`).join(" "));return u.appendChild(at),at})():u;if(Z.isDuration&&i)oe.appendChild(v());else{let at=Z.isDuration?oi(n):Z.text;se?ne=x(oe,at,ne):oe.appendChild(document.createTextNode(at))}}};if(!w&&P)if(L.style.display="none",u.style.display="",i&&I!=="none"){let j=(X=m.loadingAnimationDuration)!=null?X:2e3;u.setAttribute("data-preserve-animation","true"),I==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${j}ms`),k(P,!1)):(u.classList.add(`persona-tool-loading-${I}`),u.style.setProperty("--persona-tool-anim-duration",`${j}ms`),I==="shimmer-color"&&(m.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),k(P,!0))}else k(P,!1);else if(!w&&i&&I!=="none"){u.style.display="";let j=(re=m.loadingAnimationDuration)!=null?re:2e3;if(u.setAttribute("data-preserve-animation","true"),I==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${j}ms`);else{u.classList.add(`persona-tool-loading-${I}`),u.style.setProperty("--persona-tool-anim-duration",`${j}ms`),I==="shimmer-color"&&(m.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let se=u.textContent||g;u.textContent="",x(u,se,0)}n.status==="complete"&&(u.style.display="none")}else w||(n.status==="complete"?u.style.display="none":u.style.display="");let S=null;if(s){S=b("div","persona-flex persona-items-center");let se=Ee(a?"chevron-up":"chevron-down",16,"currentColor",2);se?S.appendChild(se):S.textContent=a?"Hide":"Show";let Ie=b("div","persona-flex persona-items-center persona-ml-auto");Ie.append(S),l.append(f,Ie)}else l.append(f);let T=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(T.setAttribute("data-persona-collapsed-preview","reasoning"),T.style.display="none",T.style.whiteSpace="pre-wrap",!a&&i&&r.activePreview&&d){let j=(he=(be=t==null?void 0:t.reasoning)==null?void 0:be.renderCollapsedPreview)==null?void 0:he.call(be,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});Bv(T,j)||(T.textContent=d),T.style.display=""}if(!a&&i&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(l,T),o;let _=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");_.style.display=a?"":"none";let U=n.chunks.join(""),G=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return G.textContent=U||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),_.appendChild(G),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),S){S.innerHTML="";let se=Ee(a?"chevron-up":"chevron-down",16,"currentColor",2);se?S.appendChild(se):S.textContent=a?"Hide":"Show"}_.style.display=a?"":"none",T.style.display=a?"none":T.textContent||T.childNodes.length?"":"none"})(),o.append(l,T,_),o};var ps=new Set,Dv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Fv=(e,t)=>{var s;let n=e.toolCall;if(!n)return"";let o=((s=n.chunks)!=null?s:[]).join("").trim();if(o)return o.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
|
|
25
|
+
`);let r=ls(n.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
|
|
26
|
+
`):""},Ov=(e,t)=>{var f,u,g,m,C;let n=e.toolCall,o=(f=t==null?void 0:t.features)==null?void 0:f.toolCallDisplay,r=(u=o==null?void 0:o.collapsedMode)!=null?u:"tool-call",s=Fv(e,(g=o==null?void 0:o.previewMaxLines)!=null?g:3),a=n?rm(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(m=t==null?void 0:t.toolCall)!=null?m:{},l=a;return r==="tool-name"?l=((C=n.name)==null?void 0:C.trim())||a:r==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=Al(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Al(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},Om=(e,t,n)=>{var f;let o=ps.has(e),r=(f=n==null?void 0:n.toolCall)!=null?f:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let u=r.toggleTextColor||r.headerTextColor||"currentColor",g=Ee(o?"chevron-up":"chevron-down",16,u,2);g?l.appendChild(g):l.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},Ol=(e,t)=>{var U,G,ge,ue,ce,ke,ve,He,Se;let n=e.toolCall,o=(U=t==null?void 0:t.toolCall)!=null?U:{},r=b("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=(ge=(G=t==null?void 0:t.features)==null?void 0:G.toolCallDisplay)!=null?ge:{},a=s.expandable!==!1,i=a&&ps.has(e.id),{summary:d,previewText:l,isActive:f}=Ov(e,t),u=b("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");u.type="button",a&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let g=b("div","persona-flex persona-flex-col persona-text-left"),m=b("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(m.style.color=o.headerTextColor);let C=String((ue=n.startedAt)!=null?ue:Date.now()),v=()=>{let ie=b("span","");return ie.setAttribute("data-tool-elapsed",C),ie.textContent=Gs(n),ie},E=(ke=o.renderCollapsedSummary)==null?void 0:ke.call(o,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(ce=s.collapsedMode)!=null?ce:"tool-call",isActive:f,config:t!=null?t:{},elapsed:Gs(n),createElapsedElement:v});typeof E=="string"&&E.trim()?(m.textContent=E,g.appendChild(m)):E instanceof HTMLElement?g.appendChild(E):(m.textContent=d,g.appendChild(m));let L=(ve=s.loadingAnimation)!=null?ve:"none",I=o.activeTextTemplate,R=o.completeTextTemplate,H=f?I:R,P=E instanceof HTMLElement,w=(ie,X,re)=>{let be=re;for(let he of X){let j=b("span","persona-tool-char");j.style.setProperty("--char-index",String(be)),j.textContent=he===" "?"\xA0":he,ie.appendChild(j),be++}return be},x=(ie,X)=>{var j;m.textContent="";let re=((j=n.name)==null?void 0:j.trim())||"tool",be=ri(ie,re),he=0;for(let se of be){let Ie=se.styles.length>0?(()=>{let ne=b("span",se.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return m.appendChild(ne),ne})():m;if(se.isDuration&&f)Ie.appendChild(v());else{let ne=se.isDuration?Gs(n):se.text;X?he=w(Ie,ne,he):Ie.appendChild(document.createTextNode(ne))}}};if(!P)if(f&&L!=="none"){let ie=(He=o.loadingAnimationDuration)!=null?He:2e3;if(m.setAttribute("data-preserve-animation","true"),L==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),H&&x(H,!1);else if(m.classList.add(`persona-tool-loading-${L}`),m.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),L==="shimmer-color"&&(o.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),H)x(H,!0);else{let X=m.textContent||d;m.textContent="",w(m,X,0)}}else H&&x(H,!1);let k=null;if(a){k=b("div","persona-flex persona-items-center");let ie=o.toggleTextColor||o.headerTextColor||"currentColor",X=Ee(i?"chevron-up":"chevron-down",16,ie,2);X?k.appendChild(X):k.textContent=i?"Hide":"Show";let re=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");re.append(k),u.append(g,re)}else u.append(g);let S=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(S.setAttribute("data-persona-collapsed-preview","tool"),S.style.display="none",S.style.whiteSpace="pre-wrap",!i&&f&&s.activePreview&&l){let ie=(Se=o.renderCollapsedPreview)==null?void 0:Se.call(o,{message:e,toolCall:n,defaultPreview:l,isActive:f,config:t!=null?t:{}});Dv(S,ie)||(S.textContent=l),S.style.display=""}if(!i&&f&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(u,S),r;let T=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(T.style.display=i?"":"none",o.contentBackgroundColor&&(T.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(T.style.color=o.contentTextColor),o.contentPaddingX&&(T.style.paddingLeft=o.contentPaddingX,T.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(T.style.paddingTop=o.contentPaddingY,T.style.paddingBottom=o.contentPaddingY),n.name){let ie=b("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?ie.style.color=o.contentTextColor:o.headerTextColor&&(ie.style.color=o.headerTextColor),ie.textContent=n.name,T.appendChild(ie)}if(n.args!==void 0){let ie=b("div","persona-space-y-1"),X=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(X.style.color=o.labelTextColor),X.textContent="Arguments";let re=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(re.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(re.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(re.style.color=o.codeBlockTextColor),re.textContent=ls(n.args),ie.append(X,re),T.appendChild(ie)}if(n.chunks&&n.chunks.length){let ie=b("div","persona-space-y-1"),X=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(X.style.color=o.labelTextColor),X.textContent="Activity";let re=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(re.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(re.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(re.style.color=o.codeBlockTextColor),re.textContent=n.chunks.join(""),ie.append(X,re),T.appendChild(ie)}if(n.status==="complete"&&n.result!==void 0){let ie=b("div","persona-space-y-1"),X=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(X.style.color=o.labelTextColor),X.textContent="Result";let re=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(re.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(re.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(re.style.color=o.codeBlockTextColor),re.textContent=ls(n.result),ie.append(X,re),T.appendChild(ie)}if(n.status==="complete"&&typeof n.duration=="number"){let ie=b("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(ie.style.color=o.contentTextColor),ie.textContent=`Duration: ${n.duration}ms`,T.appendChild(ie)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),k){k.innerHTML="";let ie=o.toggleTextColor||o.headerTextColor||"currentColor",X=Ee(i?"chevron-up":"chevron-down",16,ie,2);X?k.appendChild(X):k.textContent=i?"Hide":"Show"}T.style.display=i?"":"none",S.style.display=i?"none":S.textContent||S.childNodes.length?"":"none"})(),r.append(u,S,T),r};import{parse as Nv,ARR as _v,OBJ as Vv,STR as $v}from"partial-json";var Uv="ask_user_question",Nl=8,us="data-persona-ask-sheet-for",zv="Other",qv="Other\u2026",_m="Type your own answer here",Vm="Send",jv="Next",Kv="Back",Gv="Submit all",Yv="Skip",Xv=3,_l="data-ask-current-index",Vl="data-ask-question-count",$m="data-ask-answers",$l="data-ask-grouped",Um="data-ask-layout",Jv=e=>e.layout==="pills"?"pills":"rows",Qv=e=>e.getAttribute(Um)==="pills"?"pills":"rows",Nm=!1,zm=e=>e.replace(/["\\]/g,"\\$&"),Fr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Uv,Ul=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},ms=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=Nv(r,$v|Vv|_v);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},da=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>Nl&&!Nm&&(Nm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Nl}.`)),t.slice(0,Nl)},Zv=e=>{var t;return(t=da(e)[0])!=null?t:null},ex=(e,t)=>{var n;return(n=da(e)[t])!=null?n:null},tx=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},qm=(e,t,n)=>{if(e!=="rows")return null;let o=b("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=b("span","persona-ask-row-check");o.appendChild(r)}else{let r=b("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},nx=(e,t,n,o)=>{let s=b("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=b("span","persona-ask-row-content"),i=b("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=b("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}s.appendChild(a);let d=qm(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},ox=e=>{let n=b("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},rx=(e,t,n,o)=>{var f,u,g;let s=b("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!n){for(let m=0;m<Xv;m++)s.appendChild(ox(o));return s}if(d.forEach((m,C)=>{s.appendChild(nx(m,C,o,a))}),(e==null?void 0:e.allowFreeText)!==!1){let m=o==="rows"?zv:qv;if(o==="rows"){let C=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");C.setAttribute("data-ask-user-action","focus-free-text"),C.setAttribute("data-option-index",String(d.length)),C.setAttribute("data-ask-other-row","true");let v=b("span","persona-ask-row-content"),E=document.createElement("input");E.type="text",E.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",E.placeholder=(f=t.freeTextPlaceholder)!=null?f:_m,E.setAttribute("data-ask-free-text-input","true"),E.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:m),v.appendChild(E),C.appendChild(v);let L=qm(o,a,d.length);L&&C.appendChild(L),s.appendChild(C)}else{let C=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");C.type="button",C.setAttribute("data-ask-user-action","open-free-text"),C.textContent=(g=t.freeTextLabel)!=null?g:m,s.appendChild(C)}}return s},jm=(e,t)=>{var s,a;let o=b("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=(s=e.freeTextPlaceholder)!=null?s:_m,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let i=b("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:Vm,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},sx=e=>{var o;let t=b("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=b("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(o=e.submitLabel)!=null?o:Vm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},ax=(e,t,n)=>{var l,f,u,g;let o=b("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=b("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=(l=n.backLabel)!=null?l:Kv,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(f=n.skipLabel)!=null?f:Yv,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=b("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(u=n.submitAllLabel)!=null?u:Gv:(g=n.nextLabel)!=null?g:jv,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},Or=e=>{let t=e.getAttribute($m);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Km=(e,t)=>{e.setAttribute($m,JSON.stringify(t))},go=e=>{var n;let t=Number((n=e.getAttribute(_l))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},ix=(e,t)=>{e.setAttribute(_l,String(Math.max(0,Math.floor(t))))},fs=e=>{var n;let t=Number((n=e.getAttribute(Vl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},gr=e=>e.getAttribute($l)==="true",lx=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(o[a]=d)}}),o},cx=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Wi=(e,t)=>{let{payload:n}=ms(t),o=da(n),r=Or(e),s={},a=new Set;return o.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(r,d)&&(s[l]=r[d]))}),s},Gm=e=>{let t=Or(e),n=go(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(d=>r.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var u;let l=(u=d.getAttribute("data-option-label"))!=null?u:"",f=r.has(l);d.setAttribute("aria-pressed",f?"true":"false"),d.classList.toggle("persona-ask-pill-selected",f)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!a.has(o)){i.value=o;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Ym=e=>{if(!gr(e))return;let t=Or(e),n=go(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},zl=(e,t,n)=>{let o=Ul(n),r=Qv(e),{payload:s,complete:a}=ms(t),i=gr(e),d=go(e),l=fs(e),f=i?ex(s,d):Zv(s),u=!!(f!=null&&f.multiSelect),g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${l}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let C=e.querySelector('[data-ask-question="true"]');if(C){let I=typeof(f==null?void 0:f.question)=="string"?f.question:"";C.textContent=I,C.classList.toggle("persona-ask-question-skeleton",!I&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let I=rx(f,o,a,r);v.replaceWith(I)}if(r!=="rows"){let I=e.querySelector('[data-ask-free-text-row="true"]');I&&I.replaceWith(jm(o,r))}let E=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!E?e.appendChild(sx(o)):(!u||i)&&E&&E.remove(),e.setAttribute("data-multi-select",u?"true":"false");let L=e.querySelector('[data-ask-nav-row="true"]');if(i){let I=ax(d,l,o);L?L.replaceWith(I):e.appendChild(I)}else L&&L.remove();Gm(e),Ym(e)},dx=(e,t,n)=>{let o=Ul(t),r=Jv(o),s=e.toolCall.id,a=da(n),i=Math.max(1,a.length),d=i>1,l=lx(e,a),f=d?cx(e,i):0,u=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(us,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(Vl,String(i)),u.setAttribute(_l,String(f)),u.setAttribute($l,d?"true":"false"),u.setAttribute(Um,r),Km(u,l),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),tx(u,o);let g=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=b("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",g.appendChild(m);let C=b("span","persona-ask-sheet-step-inline");C.setAttribute("data-ask-step-inline","true"),C.textContent="",g.appendChild(C),u.appendChild(g);let E=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),u.appendChild(E),r!=="rows"&&u.appendChild(jm(o,r)),zl(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},px=(e,t,n)=>{let{payload:o}=ms(t),r=Math.max(1,da(o).length);r>fs(e)&&(e.setAttribute(Vl,String(r)),r>1&&!gr(e)&&e.setAttribute($l,"true")),zl(e,t,n)};var Bi=(e,t,n)=>{if(!n||!Fr(e)||Ul(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${us}]`).forEach(l=>{l.getAttribute(us)!==r&&l.remove()});let a=n.querySelector(`[${us}="${zm(r)}"]`);if(a){px(a,e,t);return}let{payload:i}=ms(e),d=dx(e,t,i);n.appendChild(d)},gs=(e,t)=>{if(!e)return;let n=t?`[${us}="${zm(t)}"]`:`[${us}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},ql=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),hr=(e,t)=>{let n=Or(e),o=go(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Km(e,n),Gm(e),Ym(e)},Hi=(e,t,n,o)=>{let r=fs(e),s=Math.max(0,Math.min(r-1,o));ix(e,s),zl(e,t,n)};var Di=new Map,ux=e=>{let n=(e.startsWith(Pr)?e.slice(Pr.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Xm=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Jm=(e,t)=>{var o,r,s;let n=(r=(o=Xm(t))==null?void 0:o.detailsDisplay)!=null?r:"collapsed";return(s=Di.get(e))!=null?s:n==="expanded"},Qm=(e,t,n)=>{var a,i;let o=Xm(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?(a=o==null?void 0:o.hideDetailsLabel)!=null?a:"Hide details":(i=o==null?void 0:o.showDetailsLabel)!=null?i:"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=Ee(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},Zm=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=Jm(e,n);Qm(o,s,n),r.style.display=s?"":"none"};var Fi=(e,t)=>{var x,k,S,T,_,U,G,ge,ue,ce,ke,ve,He,Se,ie;let n=e.approval,o=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,r=(n==null?void 0:n.status)==="pending",s=b("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(x=o==null?void 0:o.backgroundColor)!=null?x:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(k=o==null?void 0:o.borderColor)!=null?k:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(o==null?void 0:o.shadow)!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=b("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",l=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(S=o==null?void 0:o.titleColor)!=null?S:"currentColor",f=Ee(d,20,l,2);f&&i.appendChild(f);let u=b("div","persona-flex-1 persona-min-w-0"),g=b("div","persona-flex persona-items-center persona-gap-2"),m=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o!=null&&o.titleColor&&(m.style.color=o.titleColor),m.textContent=(T=o==null?void 0:o.title)!=null?T:"Approval Required",g.appendChild(m),!r){let X=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");X.setAttribute("data-approval-status",n.status),n.status==="approved"?(X.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",X.style.color="var(--persona-palette-colors-success-700, #15803d)",X.textContent="Approved"):n.status==="denied"?(X.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",X.style.color="var(--persona-palette-colors-error-700, #b91c1c)",X.textContent="Denied"):n.status==="timeout"&&(X.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",X.style.color="var(--persona-palette-colors-warning-700, #b45309)",X.textContent="Timeout"),g.appendChild(X)}u.appendChild(g);let v=n.toolType==="webmcp"||n.toolName.startsWith(Pr)?Sl(n.toolName):void 0,E=(_=o==null?void 0:o.formatDescription)==null?void 0:_.call(o,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...v?{displayTitle:v}:{},...n.reason?{reason:n.reason}:{}}),L=!n.toolName,I=E||(L?n.description:`The assistant wants to use \u201C${v!=null?v:ux(n.toolName)}\u201D.`),R=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(R.setAttribute("data-approval-summary","true"),o!=null&&o.descriptionColor&&(R.style.color=o.descriptionColor),R.textContent=I,u.appendChild(R),n.reason){let X=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");X.setAttribute("data-approval-reason","true"),o!=null&&o.reasonColor?X.style.color=o.reasonColor:o!=null&&o.descriptionColor&&(X.style.color=o.descriptionColor);let re=b("span","persona-font-medium");re.textContent=`${(U=o==null?void 0:o.reasonLabel)!=null?U:"Agent's stated reason:"} `,X.appendChild(re),X.appendChild(document.createTextNode(n.reason)),u.appendChild(X)}let H=(G=o==null?void 0:o.detailsDisplay)!=null?G:"collapsed",P=!!n.description&&!L,w=P||!!n.parameters;if(H!=="hidden"&&w){let X=Jm(e.id,t),re=b("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");re.type="button",re.setAttribute("data-expand-header","true"),re.setAttribute("data-bubble-type","approval"),o!=null&&o.descriptionColor&&(re.style.color=o.descriptionColor);let be=b("span");be.setAttribute("data-approval-details-label","true");let he=b("span","persona-inline-flex persona-items-center");he.setAttribute("data-approval-details-chevron","true"),re.append(be,he),Qm(re,X,t),u.appendChild(re);let j=b("div");if(j.setAttribute("data-approval-details","true"),j.style.display=X?"":"none",P){let se=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o!=null&&o.descriptionColor&&(se.style.color=o.descriptionColor),se.textContent=n.description,j.appendChild(se)}if(n.parameters){let se=b("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o!=null&&o.parameterBackgroundColor&&(se.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(se.style.color=o.parameterTextColor),se.style.fontSize="0.75rem",se.style.lineHeight="1rem",se.textContent=ls(n.parameters),j.appendChild(se)}u.appendChild(j)}if(r){let X=b("div","persona-flex persona-gap-2 persona-mt-2");X.setAttribute("data-approval-buttons","true");let re=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");re.type="button",re.style.backgroundColor=(ge=o==null?void 0:o.approveButtonColor)!=null?ge:"var(--persona-approval-approve-bg, #22c55e)",re.style.color=(ue=o==null?void 0:o.approveButtonTextColor)!=null?ue:"#ffffff",re.setAttribute("data-approval-action","approve");let be=Ee("shield-check",14,(ce=o==null?void 0:o.approveButtonTextColor)!=null?ce:"#ffffff",2);be&&(be.style.marginRight="4px",re.appendChild(be));let he=document.createTextNode((ke=o==null?void 0:o.approveLabel)!=null?ke:"Approve");re.appendChild(he);let j=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");j.type="button",j.style.backgroundColor=(ve=o==null?void 0:o.denyButtonColor)!=null?ve:"transparent",j.style.color=(He=o==null?void 0:o.denyButtonTextColor)!=null?He:"var(--persona-feedback-error, #dc2626)",j.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,j.setAttribute("data-approval-action","deny");let se=Ee("shield-x",14,(Se=o==null?void 0:o.denyButtonTextColor)!=null?Se:"var(--persona-feedback-error, #dc2626)",2);se&&(se.style.marginRight="4px",j.appendChild(se));let Ie=document.createTextNode((ie=o==null?void 0:o.denyLabel)!=null?ie:"Deny");j.appendChild(Ie),X.append(re,j),u.appendChild(X)}return a.append(i,u),s.appendChild(a),s};var ef=e=>{let t=[];return{buttons:t,render:(o,r,s,a,i)=>{if(e.innerHTML="",t.length=0,!o||!o.length||(a!=null?a:r?r.getMessages():[]).some(m=>m.role==="user"))return;let f=document.createDocumentFragment(),u=r?r.isStreaming():!1,g=m=>{switch(m){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};o.forEach(m=>{let C=b("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");C.type="button",C.textContent=m,C.disabled=u,i!=null&&i.fontFamily&&(C.style.fontFamily=g(i.fontFamily)),i!=null&&i.fontWeight&&(C.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(C.style.paddingLeft=i.paddingX,C.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(C.style.paddingTop=i.paddingY,C.style.paddingBottom=i.paddingY),C.addEventListener("click",()=>{!r||r.isStreaming()||(s.value="",r.sendMessage(m))}),f.appendChild(C),t.push(C)}),e.appendChild(f)}}};var pa=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var ua=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}};var mx=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),fx=new Set(["step_start","execution_start"]),gx=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),hx=new Set(["step_complete","agent_turn_complete"]),bx=new Set(["flow_complete","agent_complete"]),tf=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),of=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),to=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Nr=(e,t)=>{let n=e[t];return of(n)?n:void 0};function jl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Oi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function yx(e,t){return typeof t.type=="string"?t.type:e}function vx(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function xx(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function nf(e){var o,r,s,a,i;let t=Nr(e,"result"),n=[Nr(e,"tokens"),Nr(e,"totalTokens"),t?Nr(t,"tokens"):void 0,Nr(e,"usage"),t?Nr(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(r=(o=to(d.output))!=null?o:to(d.outputTokens))!=null?r:to(d.completionTokens);if(l!==void 0)return l}return(i=(s=to(e.outputTokens))!=null?s:to(e.completionTokens))!=null?i:t?(a=to(t.outputTokens))!=null?a:to(t.completionTokens):void 0}function wx(e){var n,o,r,s,a;let t=Nr(e,"result");return(a=(r=(o=(n=to(e.executionTime))!=null?n:to(e.executionTimeMs))!=null?o:to(e.execution_time))!=null?r:to(e.duration))!=null?a:t?(s=to(t.executionTime))!=null?s:to(t.executionTimeMs):void 0}function Cx(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ma=class{constructor(t=Cx){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:Oi(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var s;if(!of(n)){tf.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=yx(t,n),r=this.now();if(mx.has(o)){this.startRun(r);return}if(fx.has(o)){this.run||this.startRun(r);return}if(gx.has(o)){if(!xx(o,n))return;let a=vx(n);if(!a)return;this.run||this.startRun(r);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=r),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+jl(i.visibleCharCount),l=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Oi(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(hx.has(o)){if(!this.run)return;let a=this.run,i=nf(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+jl(a.visibleCharCount),f=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:Oi(l,f),outputTokens:l,durationMs:f,source:d?"usage":"estimate"};return}if(bx.has(o)){if(!this.run)return;let a=this.run,i=nf(n),d=i!=null?i:a.exactOutputTokens+jl(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",f=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:Oi(d,f),outputTokens:d,durationMs:f,source:l},this.run=null;return}if(tf.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;if(r!==void 0&&r>=250)return r;let s=wx(n);return s!=null?s:o-t.startedAt}};function hs(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Sx={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},Ax={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Tx=["flowName","stepName","reasoningText","text","name","tool","toolName"],kx=100;function Ex(e,t){let n={...Sx,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Ax}function Mx(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Lx(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function Ix(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Rx(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let o=document.createElement("textarea");o.value=e,o.style.position="fixed",o.style.opacity="0",document.body.appendChild(o),o.select(),document.execCommand("copy"),document.body.removeChild(o),n()})}function Px(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function Wx(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Bx(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function Hx(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(i)return i}return a();function a(){let i=b("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=b("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=o,i.appendChild(d),i}}function Kl(e,t,n,o,r,s,a,i){var g;let d=r.has(e.id),l=b("div","persona-border-b persona-border-persona-divider persona-text-xs");hs(l,(g=o.classNames)==null?void 0:g.eventRow);let f=a.find(m=>m.renderEventStreamRow);if(f!=null&&f.renderEventStreamRow&&i){let m=f.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(m)return l.appendChild(m),l}return l.appendChild(u()),l;function u(){var U,G;let m=b("div",""),C=b("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");C.setAttribute("data-event-id",e.id);let v=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),E=Ee(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&v.appendChild(E);let L=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),I=(U=o.timestampFormat)!=null?U:"relative";L.textContent=I==="relative"?Mx(e.timestamp,n):Lx(e.timestamp);let R=null;o.showSequenceNumbers!==!1&&(R=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),R.textContent=String(t+1));let H=Ex(e.type,o.badgeColors),P=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");P.style.backgroundColor=H.bg,P.style.color=H.text,P.style.borderColor=H.text+"50",P.textContent=e.type;let w=(G=o.descriptionFields)!=null?G:Tx,x=Ix(e.payload,w),k=null;x&&(k=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),k.textContent=x);let S=b("div","persona-flex-1 persona-min-w-0"),T=b("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),_=Ee("clipboard","12px","currentColor",1.5);return _&&T.appendChild(_),T.addEventListener("click",async ge=>{ge.stopPropagation(),await Rx(Px(e)),T.innerHTML="";let ue=Ee("check","12px","currentColor",1.5);ue&&T.appendChild(ue),setTimeout(()=>{T.innerHTML="";let ce=Ee("clipboard","12px","currentColor",1.5);ce&&T.appendChild(ce)},1500)}),C.appendChild(v),C.appendChild(L),R&&C.appendChild(R),C.appendChild(P),k&&C.appendChild(k),C.appendChild(S),C.appendChild(T),m.appendChild(C),d&&m.appendChild(Hx(e,a,i)),m}}function rf(e){var C,v,E,L,I;let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,i=(C=r==null?void 0:r.features)==null?void 0:C.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(v=i==null?void 0:i.iconName)!=null?v:"arrow-down",f=(E=i==null?void 0:i.label)!=null?E:"",u=(I=(L=r==null?void 0:r.features)==null?void 0:L.eventStream)!=null?I:{},g=s.find(R=>R.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&r){let R=g.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>m().element,onClose:o});if(R)return{element:R,update:()=>{},destroy:()=>{}}}return m();function m(){let R=u.classNames,H=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");hs(H,R==null?void 0:R.panel);let P=[],w="",x="",k=null,S=[],T={},_=0,U=hi(),G=0,ge=0,ue=!1,ce=null,ke=!1,ve=0,He=new Set,Se=new Map,ie="",X="",re=null,be,he,j,se,Ie,ne=null,Z=null,oe=null;function at(){let Ce=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),le=b("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");hs(le,R==null?void 0:R.headerBar);let Ze=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Ze.textContent="Events",be=b("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),be.textContent="0",a){Z=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),Z.style.cursor="help";let wn=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");wn.textContent="Throughput",ne=b("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),ne.textContent="-- tok/s",oe=b("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),oe.style.display="none",oe.style.pointerEvents="none";let Cn=Z,bn=oe,Eo=()=>{if(!bn.textContent)return;let $n=Cn.getBoundingClientRect(),Un=Ce.getBoundingClientRect();bn.style.left=`${$n.left-Un.left}px`,bn.style.top=`${$n.bottom-Un.top+4}px`,bn.style.display="block"},St=()=>{bn.style.display="none"};Z.addEventListener("mouseenter",Eo),Z.addEventListener("mouseleave",St),Z.appendChild(wn),Z.appendChild(ne)}let Jt=b("div","persona-flex-1");he=b("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Kt=b("option","");Kt.value="",Kt.textContent="All events",he.appendChild(Kt),j=b("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),j.type="button",j.title="Copy All";let yn=Ee("clipboard-copy","12px","currentColor",1.5);yn&&j.appendChild(yn);let ft=b("span","persona-text-xs");ft.textContent="Copy All",j.appendChild(ft),le.appendChild(Ze),le.appendChild(be),Z&&le.appendChild(Z),le.appendChild(Jt),le.appendChild(he),le.appendChild(j);let Mt=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");hs(Mt,R==null?void 0:R.searchBar);let Je=Ee("search","14px","var(--persona-muted, #9ca3af)",1.5),zt=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Je&&zt.appendChild(Je),se=b("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),hs(se,R==null?void 0:R.searchInput),se.type="text",se.placeholder="Search event payloads...",Ie=b("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Ie.type="button",Ie.style.display="none";let an=Ee("x","12px","currentColor",2);return an&&Ie.appendChild(an),Mt.appendChild(zt),Mt.appendChild(se),Mt.appendChild(Ie),Ce.appendChild(le),Ce.appendChild(Mt),oe&&Ce.appendChild(oe),Ce}let it,Me=s.find(Ce=>Ce.renderEventStreamToolbar);if(Me!=null&&Me.renderEventStreamToolbar&&r){let Ce=Me.renderEventStreamToolbar({config:r,defaultRenderer:()=>at(),eventCount:t.getSize(),filteredCount:0,onFilterChange:le=>{w=le,sn(),D()},onSearchChange:le=>{x=le,sn(),D()}});it=Ce!=null?Ce:at()}else it=at();let de=b("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");de.style.display="none";function Xe(){if(!a||!ne||!Z)return;let Ce=a();ne.textContent=Wx(Ce);let le=Bx(Ce);oe&&(oe.textContent=le,le||(oe.style.display="none")),le?Z.setAttribute("aria-label",le):Z.removeAttribute("aria-label")}let We=b("div","persona-flex-1 persona-min-h-0 persona-relative"),q=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");q.style.height="100%";let me=b("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");hs(me,R==null?void 0:R.scrollIndicator),me.style.display="none",me.setAttribute("data-persona-scroll-to-bottom-has-label",f?"true":"false");let et=Ee(l,"14px","currentColor",2);et&&me.appendChild(et);let Et=b("span","");Et.textContent=f,me.appendChild(Et);let ee=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ee.style.display="none",We.appendChild(q),We.appendChild(ee),We.appendChild(me),H.setAttribute("tabindex","0"),H.appendChild(it),H.appendChild(de),H.appendChild(We);function ze(){let Ce=t.getAll(),le={};for(let ft of Ce)le[ft.type]=(le[ft.type]||0)+1;let Ze=Object.keys(le).sort(),Jt=Ze.length!==S.length||!Ze.every((ft,Mt)=>ft===S[Mt]),Kt=!Jt&&Ze.some(ft=>le[ft]!==T[ft]),Ln=Ce.length!==Object.values(T).reduce((ft,Mt)=>ft+Mt,0);if(!Jt&&!Kt&&!Ln||(S=Ze,T=le,!he))return;let yn=he.value;if(he.options[0].textContent="All events",Jt){for(;he.options.length>1;)he.remove(1);for(let ft of Ze){let Mt=b("option","");Mt.value=ft,Mt.textContent=`${ft} (${le[ft]||0})`,he.appendChild(Mt)}yn&&Ze.includes(yn)?he.value=yn:yn&&(he.value="",w="")}else for(let ft=1;ft<he.options.length;ft++){let Mt=he.options[ft];Mt.textContent=`${Mt.value} (${le[Mt.value]||0})`}}function Dn(){let Ce=t.getAll();if(w&&(Ce=Ce.filter(le=>le.type===w)),x){let le=x.toLowerCase();Ce=Ce.filter(Ze=>Ze.type.toLowerCase().includes(le)||Ze.payload.toLowerCase().includes(le))}return Ce}function Ht(){return w!==""||x!==""}function sn(){_=0,G=0,U.resume(),me.style.display="none"}function no(Ce){He.has(Ce)?He.delete(Ce):He.add(Ce),re=Ce;let le=q.scrollTop,Ze=U.isFollowing();ke=!0,U.pause(),D(),q.scrollTop=le,Ze&&U.resume(),ke=!1}function ko(){return Hr(q,50)}function D(){ge=Date.now(),ue=!1,Xe(),ze();let Ce=t.getEvictedCount();Ce>0?(de.textContent=`${Ce.toLocaleString()} older events truncated`,de.style.display=""):de.style.display="none",P=Dn();let le=P.length,Ze=t.getSize()>0;be&&(be.textContent=String(t.getSize())),le===0&&Ze&&Ht()?(ee.textContent=x?`No events matching '${x}'`:"No events matching filter",ee.style.display="",q.style.display="none"):(ee.style.display="none",q.style.display=""),j&&(j.title=Ht()?`Copy Filtered (${le})`:"Copy All"),d&&!U.isFollowing()&&le>_&&(G+=le-_,Et.textContent=f?`${f}${G>0?` (${G})`:""}`:"",me.style.display=""),_=le;let Jt=t.getAll(),Kt=Jt.length>0?Jt[0].timestamp:0,Ln=new Set(P.map(Mt=>Mt.id));for(let Mt of He)Ln.has(Mt)||He.delete(Mt);let yn=w!==ie||x!==X,ft=Se.size===0&&P.length>0;if(yn||ft||P.length===0){q.innerHTML="",Se.clear();let Mt=document.createDocumentFragment();for(let Je=0;Je<P.length;Je++){let zt=Kl(P[Je],Je,Kt,u,He,no,s,r);Se.set(P[Je].id,zt),Mt.appendChild(zt)}q.appendChild(Mt),ie=w,X=x,re=null}else{if(re!==null){let Je=Se.get(re);if(Je&&Je.parentNode===q){let zt=P.findIndex(an=>an.id===re);if(zt>=0){let an=Kl(P[zt],zt,Kt,u,He,no,s,r);q.insertBefore(an,Je),Je.remove(),Se.set(re,an)}}re=null}let Mt=new Set(P.map(Je=>Je.id));for(let[Je,zt]of Se)Mt.has(Je)||(zt.remove(),Se.delete(Je));for(let Je=0;Je<P.length;Je++){let zt=P[Je];if(!Se.has(zt.id)){let an=Kl(zt,Je,Kt,u,He,no,s,r);Se.set(zt.id,an),q.appendChild(an)}}}U.isFollowing()&&(q.scrollTop=q.scrollHeight)}function pe(){if(Date.now()-ge>=kx){ce!==null&&(cancelAnimationFrame(ce),ce=null),D();return}ue||(ue=!0,ce=requestAnimationFrame(()=>{ce=null,D()}))}let De=(Ce,le)=>{if(!j)return;j.innerHTML="";let Ze=Ee(Ce,"12px","currentColor",1.5);Ze&&j.appendChild(Ze);let Jt=b("span","persona-text-xs");Jt.textContent="Copy All",j.appendChild(Jt),setTimeout(()=>{j.innerHTML="";let Kt=Ee("clipboard-copy","12px","currentColor",1.5);Kt&&j.appendChild(Kt);let Ln=b("span","persona-text-xs");Ln.textContent="Copy All",j.appendChild(Ln),j.disabled=!1},le)},je=async()=>{if(j){j.disabled=!0;try{let Ce;Ht()?Ce=P:n?(Ce=await n(),Ce.length===0&&(Ce=t.getAll())):Ce=t.getAll();let le=Ce.map(Ze=>{try{return JSON.parse(Ze.payload)}catch{return Ze.payload}});await navigator.clipboard.writeText(JSON.stringify(le,null,2)),De("check",1500)}catch{De("x",1500)}}},Ne=()=>{he&&(w=he.value,sn(),D())},Ve=()=>{!se||!Ie||(Ie.style.display=se.value?"":"none",k&&clearTimeout(k),k=setTimeout(()=>{x=se.value,sn(),D()},150))},nt=()=>{!se||!Ie||(se.value="",x="",Ie.style.display="none",k&&clearTimeout(k),sn(),D())},Rt=()=>{if(ke)return;let Ce=q.scrollTop,{action:le,nextLastScrollTop:Ze}=bi({following:U.isFollowing(),currentScrollTop:Ce,lastScrollTop:ve,nearBottom:ko(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ve=Ze,le==="resume"?(U.resume(),G=0,me.style.display="none"):le==="pause"&&(U.pause(),d&&(Et.textContent=f,me.style.display=""))},jt=Ce=>{let le=yi({following:U.isFollowing(),deltaY:Ce.deltaY,nearBottom:ko(),resumeWhenNearBottom:!0});le==="pause"?(U.pause(),d&&(Et.textContent=f,me.style.display="")):le==="resume"&&(U.resume(),G=0,me.style.display="none")},Xt=()=>{d&&(q.scrollTop=q.scrollHeight,U.resume(),G=0,me.style.display="none")},K=Ce=>{let le=Ce.target;if(!le||le.closest("button"))return;let Ze=le.closest("[data-event-id]");if(!Ze)return;let Jt=Ze.getAttribute("data-event-id");Jt&&no(Jt)},vt=Ce=>{if((Ce.metaKey||Ce.ctrlKey)&&Ce.key==="f"){Ce.preventDefault(),se==null||se.focus(),se==null||se.select();return}Ce.key==="Escape"&&(se&&document.activeElement===se?(nt(),se.blur(),H.focus()):o&&o())};j&&j.addEventListener("click",je),he&&he.addEventListener("change",Ne),se&&se.addEventListener("input",Ve),Ie&&Ie.addEventListener("click",nt),q.addEventListener("scroll",Rt),q.addEventListener("wheel",jt,{passive:!0}),q.addEventListener("click",K),me.addEventListener("click",Xt),H.addEventListener("keydown",vt);function rt(){k&&clearTimeout(k),ce!==null&&(cancelAnimationFrame(ce),ce=null),ue=!1,Se.clear(),j&&j.removeEventListener("click",je),he&&he.removeEventListener("change",Ne),se&&se.removeEventListener("input",Ve),Ie&&Ie.removeEventListener("click",nt),q.removeEventListener("scroll",Rt),q.removeEventListener("wheel",jt),q.removeEventListener("click",K),me.removeEventListener("click",Xt),H.removeEventListener("keydown",vt)}return{element:H,update:pe,destroy:rt}}}function sf(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",o=typeof e.artifactId=="string"?e.artifactId:"",r=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),o&&i.setAttribute("data-open-artifact",o);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let f=document.createElement("div");f.className="persona-truncate persona-text-sm persona-font-medium",f.style.color="var(--persona-text, #1f2937)",f.textContent=n;let u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.style.color="var(--persona-muted, #9ca3af)",r==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(g);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(m)}else u.textContent=a;if(l.append(f,u),i.append(d,l),r==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${n}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",o),i.append(g)}return i}var af=(e,t)=>{var o,r,s;let n=(s=(r=(o=t==null?void 0:t.config)==null?void 0:o.features)==null?void 0:r.artifacts)==null?void 0:s.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",f=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>sf(e,t)});if(f)return f}return sf(e,t)};var Gl=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},_r=new Gl;_r.register("PersonaArtifactCard",af);function Dx(e){var r;let t=b("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=b("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify((r=e.props)!=null?r:{},null,2),t.appendChild(n),t.appendChild(o),t}function lf(e,t){var he,j,se,Ie;let n=(j=(he=e.features)==null?void 0:he.artifacts)==null?void 0:j.layout,r=((se=n==null?void 0:n.toolbarPreset)!=null?se:"default")==="document",s=(Ie=n==null?void 0:n.panePadding)==null?void 0:Ie.trim(),a=e.markdown?Qa(e.markdown):null,i=Za(e.sanitize),d=ne=>{let Z=a?a(ne):js(ne);return i?i(Z):Z},l=typeof document!="undefined"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,f=()=>{l==null||l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),_==null||_.hide()};l&&l.addEventListener("click",()=>{var ne;f(),(ne=t.onDismiss)==null||ne.call(t)});let u=b("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");u.setAttribute("data-persona-theme-zone","artifact-pane"),r&&u.classList.add("persona-artifact-pane-document");let g=b("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&g.classList.add("persona-artifact-toolbar-document");let m=b("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let C=b("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");C.type="button",C.textContent="Close",C.setAttribute("aria-label","Close artifacts panel"),C.addEventListener("click",()=>{var ne;f(),(ne=t.onDismiss)==null||ne.call(t)});let v="rendered",E=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),L=r?Mn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Mn({icon:"eye",label:"Rendered view"}),I=r?Mn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Mn({icon:"code-2",label:"Source"}),R=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),H=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,P=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,w=n==null?void 0:n.documentToolbarCopyMenuItems,x=!!(P&&w&&w.length>0),k=null,S,T=null,_=null;if(r&&(H||P)&&!x){if(S=H?Wl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Mn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P){let ne=Ee("chevron-down",14,"currentColor",2);ne&&S.appendChild(ne)}}else r&&x?(k=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),S=H?Wl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Mn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),T=Mn({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),k.append(S,T)):r?S=Mn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):S=Mn({icon:"copy",label:"Copy"});let U=r?Mn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Mn({icon:"refresh-cw",label:"Refresh"}),G=r?Mn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Mn({icon:"x",label:"Close"}),ge=()=>{var it,Me,de;let ne=(it=Se.find(Xe=>Xe.id===ie))!=null?it:Se[Se.length-1],Z=(Me=ne==null?void 0:ne.id)!=null?Me:null,oe=(ne==null?void 0:ne.artifactType)==="markdown"&&(de=ne.markdown)!=null?de:"",at=ne?JSON.stringify({component:ne.component,props:ne.props},null,2):"";return{markdown:oe,jsonPayload:at,id:Z}},ue=async()=>{var it;let{markdown:ne,jsonPayload:Z}=ge(),oe=(it=Se.find(Me=>Me.id===ie))!=null?it:Se[Se.length-1],at=(oe==null?void 0:oe.artifactType)==="markdown"?ne:oe?Z:"";try{await navigator.clipboard.writeText(at)}catch{}};if(S.addEventListener("click",async()=>{let ne=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(ne&&x){let{markdown:Z,jsonPayload:oe,id:at}=ge();try{await ne({actionId:"primary",artifactId:at,markdown:Z,jsonPayload:oe})}catch{}return}await ue()}),T&&(w!=null&&w.length)){let ne=()=>{var oe;return(oe=u.closest("[data-persona-root]"))!=null?oe:document.body},Z=()=>{_=cs({items:w.map(oe=>({id:oe.id,label:oe.label})),onSelect:async oe=>{let{markdown:at,jsonPayload:it,id:Me}=ge(),de=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{de?await de({actionId:oe,artifactId:Me,markdown:at,jsonPayload:it}):oe==="markdown"||oe==="md"?await navigator.clipboard.writeText(at):oe==="json"||oe==="source"?await navigator.clipboard.writeText(it):await navigator.clipboard.writeText(at||it)}catch{}},anchor:k!=null?k:T,position:"bottom-right",portal:ne()})};u.isConnected?Z():requestAnimationFrame(Z),T.addEventListener("click",oe=>{oe.stopPropagation(),_==null||_.toggle()})}U.addEventListener("click",async()=>{var ne;try{await((ne=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:ne.call(n))}catch{}re()}),G.addEventListener("click",()=>{var ne;f(),(ne=t.onDismiss)==null||ne.call(t)});let ce=()=>{r&&(L.setAttribute("aria-pressed",v==="rendered"?"true":"false"),I.setAttribute("aria-pressed",v==="source"?"true":"false"))};L.addEventListener("click",()=>{v="rendered",ce(),re()}),I.addEventListener("click",()=>{v="source",ce(),re()});let ke=b("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");r?(g.replaceChildren(),E.append(L,I),k?R.append(k,U,G):R.append(S,U,G),g.append(E,ke,R),ce()):(g.appendChild(m),g.appendChild(C)),s&&(g.style.paddingLeft=s,g.style.paddingRight=s);let ve=b("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),He=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(ve.style.paddingLeft=s,ve.style.paddingRight=s,He.style.padding=s),u.appendChild(g),u.appendChild(ve),u.appendChild(He);let Se=[],ie=null,X=!1,re=()=>{var at,it,Me,de;let ne=r&&Se.length<=1;ve.classList.toggle("persona-hidden",ne),ve.replaceChildren();for(let Xe of Se){let We=b("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");We.type="button",We.textContent=Xe.title||Xe.id.slice(0,8),Xe.id===ie&&We.classList.add("persona-bg-persona-container","persona-border-persona-border"),We.addEventListener("click",()=>t.onSelect(Xe.id)),ve.appendChild(We)}He.replaceChildren();let Z=ie&&Se.find(Xe=>Xe.id===ie)||Se[Se.length-1];if(!Z)return;if(r){let Xe=Z.artifactType==="markdown"?"MD":(at=Z.component)!=null?at:"Component",q=(Z.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ke.textContent=`${q} \xB7 ${Xe}`}else m.textContent="Artifacts";if(Z.artifactType==="markdown"){if(r&&v==="source"){let We=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");We.textContent=(it=Z.markdown)!=null?it:"",He.appendChild(We);return}let Xe=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Xe.innerHTML=d((Me=Z.markdown)!=null?Me:""),He.appendChild(Xe);return}let oe=Z.component?_r.get(Z.component):void 0;if(oe){let We={message:{id:Z.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let q=oe((de=Z.props)!=null?de:{},We);if(q){He.appendChild(q);return}}catch{}}He.appendChild(Dx(Z))},be=()=>{var Z;let ne=Se.length>0;if(u.classList.toggle("persona-hidden",!ne),l){let oe=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,it=((Z=oe==null?void 0:oe.classList.contains("persona-artifact-narrow-host"))!=null?Z:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;ne&&it&&X?(l.classList.remove("persona-hidden"),u.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:l,update(ne){var Z,oe,at;Se=ne.artifacts,ie=(at=(oe=ne.selectedId)!=null?oe:(Z=ne.artifacts[ne.artifacts.length-1])==null?void 0:Z.id)!=null?at:null,Se.length>0&&(X=!0),re(),be()},setMobileOpen(ne){X=ne,!ne&&l?(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):be()}}}function ho(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function cf(e,t){var s,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!ho(t))return;let n=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,o=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),r=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function Fx(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function Ni(e,t){var d,l,f,u,g,m,C,v,E,L;if(!ho(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),Fx(e),cf(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(f=n==null?void 0:n.splitGap)!=null?f:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(u=n==null?void 0:n.paneWidth)!=null?u:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(g=n==null?void 0:n.paneMaxWidth)!=null?g:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=(m=n==null?void 0:n.paneBackground)==null?void 0:m.trim();o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let r=(C=n==null?void 0:n.panePadding)==null?void 0:C.trim();r?e.style.setProperty("--persona-artifact-pane-padding",r):e.style.removeProperty("--persona-artifact-pane-padding");let s=(v=n==null?void 0:n.documentToolbarIconColor)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(E=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:E.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(L=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:L.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),cf(e,t)}var df=["panel","seamless"];function _i(e,t){var i,d,l,f,u,g;for(let m of df)e.classList.remove(`persona-artifact-appearance-${m}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!ho(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,o=(l=n==null?void 0:n.paneAppearance)!=null?l:"panel",r=df.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${r}`);let s=(f=n==null?void 0:n.paneBorderRadius)==null?void 0:f.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(u=n==null?void 0:n.paneShadow)==null?void 0:u.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((g=n.unifiedSplitOuterRadius)==null?void 0:g.trim())||s;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function pf(e,t){var n,o,r;return!t||!ho(e)?!1:((r=(o=(n=e.features)==null?void 0:n.artifacts)==null?void 0:o.layout)==null?void 0:r.expandLauncherPanelWhenOpen)!==!1}function Ox(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function Nx(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function _x(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Vx(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function uf(e,t){var a;let o=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function mf(e,t,n,o,r,s){let a=Ox(r,200),i=Vx(t,n,o,200);i=Math.max(a,i);let d=Nx(s);return d!==null&&(i=Math.min(i,d)),_x(e,a,i)}var ff={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Yl=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var C,v,E;if(s.dataset.enhanced==="true")return;let a=(C=s.dataset.tvForm)!=null?C:"init";s.dataset.enhanced="true";let i=(v=ff[a])!=null?v:ff.init;s.classList.add("persona-form-card","persona-space-y-4");let d=b("div","persona-space-y-1"),l=b("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let L=b("p","persona-text-sm persona-text-persona-muted");L.textContent=i.description,d.appendChild(L)}let f=document.createElement("form");f.className="persona-form-grid persona-space-y-3",i.fields.forEach(L=>{var w,x;let I=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");I.htmlFor=`${t.id}-${a}-${L.name}`;let R=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");R.textContent=L.label,I.appendChild(R);let H=(w=L.type)!=null?w:"text",P;H==="textarea"?(P=document.createElement("textarea"),P.rows=3):(P=document.createElement("input"),P.type=H),P.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",P.id=`${t.id}-${a}-${L.name}`,P.name=L.name,P.placeholder=(x=L.placeholder)!=null?x:"",L.required&&(P.required=!0),I.appendChild(P),f.appendChild(I)});let u=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=b("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(E=i.submitLabel)!=null?E:"Submit",u.appendChild(g),u.appendChild(m),f.appendChild(u),s.replaceChildren(d,f),f.addEventListener("submit",async L=>{var P,w;L.preventDefault();let I=(P=n.formEndpoint)!=null?P:"/form",R=new FormData(f),H={};R.forEach((x,k)=>{H[k]=x}),H.type=a,m.disabled=!0,g.textContent="Submitting\u2026";try{let x=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(H)});if(!x.ok)throw new Error(`Form submission failed (${x.status})`);let k=await x.json();g.textContent=(w=k.message)!=null?w:"Thanks! We'll be in touch soon.",k.success&&k.nextPrompt&&await o.sendMessage(String(k.nextPrompt))}catch(x){g.textContent=x instanceof Error?x.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var Xl=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var o;let n=this.plugins.get(t);n&&((o=n.onUnregister)==null||o.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var o,r;return((o=n.priority)!=null?o:0)-((r=t.priority)!=null?r:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},Jl=new Xl;var gf=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{var a;(a=e.get(r))==null||a.delete(s)};return{on:t,off:n,emit:(r,s)=>{var a;(a=e.get(r))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var $x=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Ux=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},Zl=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=$x(e),n=Ux(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},Ql=e=>typeof e=="string"?e:e==null?"":String(e),fa={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Ql(e.payload.text)},messageAndClick:(e,t)=>{var r;if(e.type!=="message_and_click")return;let n=e.payload,o=Ql(n.element);if(o&&((r=t.document)!=null&&r.querySelector)){let s=t.document.querySelector(o);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Ql(n.text)}}},hf=e=>Array.isArray(e)?e.map(t=>String(t)):[],ec=e=>{let t=new Set(hf(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(hf(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,f)=>l||(f==null?void 0:f({text:a,message:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),o();let d={action:i,message:s.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let f=()=>{e.emit("action:resubmit",d)},u=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:f});if(!u)continue;if(u.handled){let g=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:g,resubmit:u.resubmit}}}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",f)}return{text:"",persist:!0}},syncFromMetadata:n}};var zx=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},qx=e=>e.map(t=>({...t,streaming:!1})),jx=e=>e.map(t=>({...t,status:"complete"})),bf=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?zx(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?qx(n.messages):void 0,artifacts:n.artifacts?jx(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};import{parse as $0,STR as U0,OBJ as z0}from"partial-json";function yf(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=_r.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:i=>{r&&r(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function vf(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function xf(e){let t=vf(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function wf(e){let t=vf(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var Kx=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Cf(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=Kx}=e,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-csat",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Customer satisfaction feedback");let u=null,g=document.createElement("div");g.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,m.appendChild(C);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=r,m.appendChild(v),g.appendChild(m);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let L=[];for(let w=1;w<=5;w++){let x=document.createElement("button");x.type="button",x.className="persona-feedback-rating-btn persona-feedback-star-btn",x.setAttribute("role","radio"),x.setAttribute("aria-checked","false"),x.setAttribute("aria-label",`${w} star${w>1?"s":""}: ${l[w-1]}`),x.title=l[w-1],x.dataset.rating=String(w),x.innerHTML=`
|
|
27
27
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
28
28
|
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
|
|
29
29
|
</svg>
|
|
30
|
-
`,x.addEventListener("click",()=>{u=v,I.forEach((k,C)=>{let T=C<v;k.classList.toggle("selected",T),k.setAttribute("aria-checked",C===v-1?"true":"false")})}),I.push(x),M.appendChild(x)}g.appendChild(M);let L=null;if(d){let v=document.createElement("div");v.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),v.appendChild(L),g.appendChild(v)}let H=document.createElement("div");H.className="persona-feedback-actions";let D=document.createElement("button");D.type="button",D.className="persona-feedback-btn persona-feedback-btn-skip",D.textContent=i,D.addEventListener("click",()=>{n==null||n(),m.remove()});let W=document.createElement("button");return W.type="button",W.className="persona-feedback-btn persona-feedback-btn-submit",W.textContent=a,W.addEventListener("click",async()=>{if(u===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}W.disabled=!0,W.textContent="Submitting...";try{let v=(L==null?void 0:L.value.trim())||void 0;await t(u,v),m.remove()}catch(v){W.disabled=!1,W.textContent=a,console.error("[CSAT Feedback] Failed to submit:",v)}}),H.appendChild(D),H.appendChild(W),g.appendChild(H),m.appendChild(g),m}function Dm(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:m="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let g=null,p=document.createElement("div");p.className="persona-feedback-content";let w=document.createElement("div");w.className="persona-feedback-header";let S=document.createElement("h3");S.className="persona-feedback-title",S.textContent=o,w.appendChild(S);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=r,w.appendChild(M),p.appendChild(w);let I=document.createElement("div");I.className="persona-feedback-rating persona-feedback-rating-nps",I.setAttribute("role","radiogroup"),I.setAttribute("aria-label","Likelihood rating from 0 to 10");let L=document.createElement("div");L.className="persona-feedback-labels";let H=document.createElement("span");H.className="persona-feedback-label-low",H.textContent=l;let D=document.createElement("span");D.className="persona-feedback-label-high",D.textContent=m,L.appendChild(H),L.appendChild(D);let W=document.createElement("div");W.className="persona-feedback-numbers";let v=[];for(let F=0;F<=10;F++){let $=document.createElement("button");$.type="button",$.className="persona-feedback-rating-btn persona-feedback-number-btn",$.setAttribute("role","radio"),$.setAttribute("aria-checked","false"),$.setAttribute("aria-label",`Rating ${F} out of 10`),$.textContent=String(F),$.dataset.rating=String(F),F<=6?$.classList.add("persona-feedback-detractor"):F<=8?$.classList.add("persona-feedback-passive"):$.classList.add("persona-feedback-promoter"),$.addEventListener("click",()=>{g=F,v.forEach((j,me)=>{j.classList.toggle("selected",me===F),j.setAttribute("aria-checked",me===F?"true":"false")})}),v.push($),W.appendChild($)}I.appendChild(L),I.appendChild(W),p.appendChild(I);let x=null;if(d){let F=document.createElement("div");F.className="persona-feedback-comment-container",x=document.createElement("textarea"),x.className="persona-feedback-comment",x.placeholder=s,x.rows=3,x.setAttribute("aria-label","Additional comments"),F.appendChild(x),p.appendChild(F)}let k=document.createElement("div");k.className="persona-feedback-actions";let C=document.createElement("button");C.type="button",C.className="persona-feedback-btn persona-feedback-btn-skip",C.textContent=i,C.addEventListener("click",()=>{n==null||n(),u.remove()});let T=document.createElement("button");return T.type="button",T.className="persona-feedback-btn persona-feedback-btn-submit",T.textContent=a,T.addEventListener("click",async()=>{if(g===null){W.classList.add("persona-feedback-shake"),setTimeout(()=>W.classList.remove("persona-feedback-shake"),500);return}T.disabled=!0,T.textContent="Submitting...";try{let F=(x==null?void 0:x.value.trim())||void 0;await t(g,F),u.remove()}catch(F){T.disabled=!1,T.textContent=a,console.error("[NPS Feedback] Failed to submit:",F)}}),k.appendChild(C),k.appendChild(T),p.appendChild(k),u.appendChild(p),u}var ts="persona-chat-history",nx=30*1e3,ox={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function rx(e){var o,r,s;if(!e)return[];let t=[],n=Array.from((o=e.items)!=null?o:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(r=ox[i.type])!=null?r:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((s=e.files)!=null?s:[]))a.type.startsWith("image/")&&t.push(a);return t}function Li(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function sx(e){var t,n,o,r,s,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(r=(o=e.persist)==null?void 0:o.openState)!=null?r:!0,voiceState:(a=(s=e.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function ax(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Nl=e=>!e||typeof e!="object"?{}:{...e},Fm=e=>e.map(t=>({...t,streaming:!1})),Om=(e,t,n)=>{let o=e!=null&&e.markdown?$a(e.markdown):null,r=Ua(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&r&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var l,m,u;let a=(l=s.text)!=null?l:"",i=(m=s.message.rawContent)!=null?m:null;if(t){let g=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});g!==null&&(a=g.text,g.persist||(s.message.__skipPersist=!0),g.resubmit&&!s.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...s,text:a,raw:(u=i!=null?i:s.text)!=null?u:""}):o?d=o(a):d=Is(a),r?r(d):d}};function Nm(e){var i,d,l,m;let t=b("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",o=(d=e==null?void 0:e.iconSize)!=null?d:"48px",r=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(m=e==null?void 0:e.iconStrokeWidth)!=null?m:.5,a=Te(n,o,r,s);if(a&&t.appendChild(a),e!=null&&e.label){let u=b("span","persona-drop-overlay-label");u.textContent=e.label,t.appendChild(u)}return t}var _m=(e,t,n)=>{var ac,ic,lc,cc,dc,pc,uc,mc,fc,gc,hc,bc,yc,vc,xc,wc,Cc,Sc,Ac,Tc,kc,Ec,Mc,Lc,Ic,Rc,Pc,Wc,Bc,Hc,Dc,Fc,Oc,Nc,_c,Vc,$c,Uc,zc,qc,jc,Kc,Gc,Yc,Xc,Qc,Jc,Zc;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=Jp(t),r=Hl.getForInstance(o.plugins);o.components&&Mr.registerAll(o.components);let s=Mm(),i=o.persistState===!1?null:(ac=o.storageAdapter)!=null?ac:Im(),d={},l=null,m=!1,u=c=>{if(o.onStateLoaded)try{let f=o.onStateLoaded(c);if(f&&typeof f=="object"&&"state"in f){let{state:h,open:y}=f;return y&&(m=!0),h}return f}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",f)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(f=>{let h=f!=null?f:{messages:[],metadata:{}};return u(h)});else{let f=c!=null?c:{messages:[],metadata:{}},h=u(f);h.metadata&&(d=Nl(h.metadata)),(ic=h.messages)!=null&&ic.length&&(o={...o,initialMessages:h.messages}),(lc=h.artifacts)!=null&&lc.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(cc=h.selectedArtifactId)!=null?cc:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(o.onStateLoaded)try{let c=u({messages:[],metadata:{}});(dc=c.messages)!=null&&dc.length&&(o={...o,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let g=()=>d,p=c=>{var h;d=(h=c({...d}))!=null?h:{},Wr()},w=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Fl],S=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ea.message,ea.messageAndClick],M=Ol({parsers:w,handlers:S,getSessionMetadata:g,updateSessionMetadata:p,emit:s.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let I=(uc=(pc=o.launcher)==null?void 0:pc.enabled)!=null?uc:!0,L=(fc=(mc=o.launcher)==null?void 0:mc.autoExpand)!=null?fc:!1,H=(gc=o.autoFocusInput)!=null?gc:!1,D=L,W=I,v=(bc=(hc=o.layout)==null?void 0:hc.header)==null?void 0:bc.layout,x=!1,k=()=>js(o),C=()=>I||k(),T=k()?!1:I?L:!0,F=!1,$=null,j=()=>{F=!0,$&&clearTimeout($),$=setTimeout(()=>{F&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),F=!1)},1e4)},me=Om(o,M,j),se=(vc=(yc=o.features)==null?void 0:yc.showReasoning)!=null?vc:!0,fe=(wc=(xc=o.features)==null?void 0:xc.showToolCalls)!=null?wc:!0,ie=(Sc=(Cc=o.features)==null?void 0:Cc.showEventStreamToggle)!=null?Sc:!1,be=(Tc=(Ac=o.features)==null?void 0:Ac.scrollToBottom)!=null?Tc:{},ve=`${(Ec=typeof o.persistState=="object"?(kc=o.persistState)==null?void 0:kc.keyPrefix:void 0)!=null?Ec:"persona-"}event-stream`,Q=ie?new Js(ve):null,Le=(Ic=(Lc=(Mc=o.features)==null?void 0:Mc.eventStream)==null?void 0:Lc.maxEvents)!=null?Ic:2e3,Y=ie?new Qs(Le,Q):null,xe=ie?new Zs:null,Se=null,de=!1,we=null,ze=0;Q==null||Q.open().then(()=>Y==null?void 0:Y.restore()).catch(c=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let te={onCopy:c=>{var f,h;s.emit("message:copy",c),E!=null&&E.isClientTokenMode()&&E.submitMessageFeedback(c.id,"copy").catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",y)}),(h=(f=o.messageActions)==null?void 0:f.onCopy)==null||h.call(f,c)},onFeedback:c=>{var f,h;s.emit("message:feedback",c),E!=null&&E.isClientTokenMode()&&E.submitMessageFeedback(c.messageId,c.type).catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",y)}),(h=(f=o.messageActions)==null?void 0:f.onFeedback)==null||h.call(f,c)}},ne=(Rc=o.statusIndicator)!=null?Rc:{},re=c=>{var f,h,y,P;return c==="idle"?(f=ne.idleText)!=null?f:gn.idle:c==="connecting"?(h=ne.connectingText)!=null?h:gn.connecting:c==="connected"?(y=ne.connectedText)!=null?y:gn.connected:c==="error"?(P=ne.errorText)!=null?P:gn.error:gn[c]};function nt(c,f,h,y){if(y==="idle"&&h.idleLink){c.textContent="";let P=document.createElement("a");P.href=h.idleLink,P.target="_blank",P.rel="noopener noreferrer",P.textContent=f,P.style.color="inherit",P.style.textDecoration="none",c.appendChild(P)}else c.textContent=f}let{wrapper:ye,panel:le,pillRoot:Ue}=Qu(o),He=Ju(o,C()),{container:ce,body:G,messagesWrapper:Ve,suggestions:Et,textarea:pe,sendButton:ae,sendButtonWrapper:Ln,composerForm:Nt,statusText:ln,introTitle:Dn,introSubtitle:Jn,closeButton:qe,iconHolder:_,headerTitle:ke,headerSubtitle:De,header:Fe,footer:$e,actionsRow:dt,leftActions:ot,rightActions:At}=He,Vt=He.setSendButtonMode,q=He.micButton,_t=He.micButtonWrapper,Qe=He.attachmentButton,Ft=He.attachmentButtonWrapper,oe=He.attachmentInput,ge=He.attachmentPreviewsContainer;ce.classList.add("persona-relative"),G.classList.add("persona-relative");let xt=12,$t=()=>{var c;return(c=be.label)!=null?c:""},Jt=()=>{var c;return(c=be.iconName)!=null?c:"arrow-down"},yn=()=>be.enabled!==!1,Tt=b("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Tt.type="button",Tt.style.display="none",Tt.setAttribute("data-persona-scroll-to-bottom","true");let wt=b("span","persona-flex persona-items-center"),gt=b("span","");Tt.append(wt,gt),ce.appendChild(Tt);let bt=()=>{let f=$e.style.display==="none"?0:$e.offsetHeight;Tt.style.bottom=`${f+xt}px`};bt();let zt=()=>{let c=!!$t();Tt.setAttribute("aria-label",$t()||"Jump to latest"),Tt.title=$t(),Tt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),wt.innerHTML="";let f=Te(Jt(),"14px","currentColor",2);f?(wt.appendChild(f),wt.style.display=""):wt.style.display="none",gt.textContent=$t(),gt.style.display=c?"":"none"};zt();let et=null,Fn=null,Zn=r.find(c=>c.renderHeader);if(Zn!=null&&Zn.renderHeader){let c=Zn.renderHeader({config:o,defaultRenderer:()=>{let f=Ar({config:o,showClose:C()});return Gs(ce,f,o),f.header},onClose:()=>Bt(!1,"user")});if(c){let f=ce.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(c),Fe=c)}}let vn=()=>{var f,h,y,P;if(!Y)return;if(de=!0,!Se&&Y&&(Se=ym({buffer:Y,getFullHistory:()=>Y.getAllFromStore(),onClose:()=>On(),config:o,plugins:r,getThroughput:()=>{var N;return(N=xe==null?void 0:xe.getMetric())!=null?N:{status:"idle"}}})),Se&&(G.style.display="none",(f=$e.parentNode)==null||f.insertBefore(Se.element,$e),Se.update()),ut){ut.style.boxShadow=`inset 0 0 0 1.5px ${Mn.actionIconColor}`;let N=(P=(y=(h=o.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:P.toggleButtonActive;N&&N.split(/\s+/).forEach(V=>V&&ut.classList.add(V))}let c=()=>{if(!de)return;let N=Date.now();N-ze>=200&&(Se==null||Se.update(),ze=N),we=requestAnimationFrame(c)};ze=0,we=requestAnimationFrame(c),Ho(),s.emit("eventStream:opened",{timestamp:Date.now()})},On=()=>{var c,f,h;if(de){if(de=!1,Se&&Se.element.remove(),G.style.display="",ut){ut.style.boxShadow="";let y=(h=(f=(c=o.features)==null?void 0:c.eventStream)==null?void 0:f.classNames)==null?void 0:h.toggleButtonActive;y&&y.split(/\s+/).forEach(P=>P&&ut.classList.remove(P))}we!==null&&(cancelAnimationFrame(we),we=null),Ho(),s.emit("eventStream:closed",{timestamp:Date.now()})}},ut=null;if(ie){let c=(Wc=(Pc=o.features)==null?void 0:Pc.eventStream)==null?void 0:Wc.classNames,f="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");ut=b("button",f),ut.style.width="28px",ut.style.height="28px",ut.style.color=Mn.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let h=Te("activity","18px","currentColor",1.5);h&&ut.appendChild(h);let y=He.clearChatButtonWrapper,P=He.closeButtonWrapper,N=y||P;N&&N.parentNode===Fe?Fe.insertBefore(ut,N):Fe.appendChild(ut),ut.addEventListener("click",()=>{de?On():vn()})}let wo=c=>{var y,P,N;let f=o.attachments;if(!(f!=null&&f.enabled))return;let h=c.querySelector(".persona-attachment-previews");if(!h){h=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.style.display="none";let V=c.querySelector("[data-persona-composer-form]");V!=null&&V.parentNode?V.parentNode.insertBefore(h,V):c.insertBefore(h,c.firstChild)}if(!c.querySelector('input[type="file"]')){let V=b("input");V.type="file",V.accept=((y=f.allowedTypes)!=null?y:_o).join(","),V.multiple=((P=f.maxFiles)!=null?P:4)>1,V.style.display="none",V.setAttribute("aria-label",(N=f.buttonTooltipText)!=null?N:"Attach files"),c.appendChild(V)}},Nn=r.find(c=>c.renderComposer);if(Nn!=null&&Nn.renderComposer){let c=o.composer,f=Nn.renderComposer({config:o,defaultRenderer:()=>Ci({config:o}).footer,onSubmit:h=>{var V;if(!E||E.isStreaming())return;let y=h.trim(),P=(V=et==null?void 0:et.hasAttachments())!=null?V:!1;if(!y&&!P)return;gs();let N;P&&(N=[],N.push(...et.getContentParts()),y&&N.push(cl(y))),E.sendMessage(y,{contentParts:N}),P&&et.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{oe==null||oe.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:((Bc=o.voiceRecognition)==null?void 0:Bc.enabled)===!0?()=>{Fn==null||Fn()}:void 0});f&&($e.replaceWith(f),$e=f)}let ir=c=>{let f=c.querySelector("[data-persona-composer-form]"),h=c.querySelector("[data-persona-composer-input]"),y=c.querySelector("[data-persona-composer-submit]"),P=c.querySelector("[data-persona-composer-mic]"),N=c.querySelector("[data-persona-composer-status]");f&&(Nt=f),h&&(pe=h),y&&(ae=y),P&&(q=P,_t=P.parentElement),N&&(ln=N);let V=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");V&&(Et=V);let z=c.querySelector(".persona-attachment-button");z&&(Qe=z,Ft=z.parentElement),oe=c.querySelector('input[type="file"]'),ge=c.querySelector(".persona-attachment-previews");let O=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");O&&(dt=O)};wo($e),ir($e);let In=(Nc=(Hc=o.layout)==null?void 0:Hc.contentMaxWidth)!=null?Nc:k()?(Oc=(Fc=(Dc=o.launcher)==null?void 0:Dc.composerBar)==null?void 0:Fc.contentMaxWidth)!=null?Oc:"720px":void 0;if(In&&(Ve.style.maxWidth=In,Ve.style.marginLeft="auto",Ve.style.marginRight="auto",Ve.style.width="100%"),In&&Nt&&!k()&&(Nt.style.maxWidth=In,Nt.style.marginLeft="auto",Nt.style.marginRight="auto"),In&&Et&&!k()&&(Et.style.maxWidth=In,Et.style.marginLeft="auto",Et.style.marginRight="auto"),In&&ge&&!k()&&(ge.style.maxWidth=In,ge.style.marginLeft="auto",ge.style.marginRight="auto"),(_c=o.attachments)!=null&&_c.enabled&&oe&&ge){et=Os.fromConfig(o.attachments),et.setPreviewsContainer(ge),oe.addEventListener("change",h=>{let y=h.target;et==null||et.handleFileSelect(y.files),y.value=""});let c=o.attachments.dropOverlay,f=Nm(c);ce.appendChild(f)}(()=>{var y,P;let c=(P=(y=o.layout)==null?void 0:y.slots)!=null?P:{},f=N=>{switch(N){case"body-top":return ce.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ve;case"footer-top":return Et;case"composer":return Nt;case"footer-bottom":return ln;default:return null}},h=(N,V)=>{var z;switch(N){case"header-left":case"header-center":case"header-right":if(N==="header-left")Fe.insertBefore(V,Fe.firstChild);else if(N==="header-right")Fe.appendChild(V);else{let O=Fe.querySelector(".persona-flex-col");O?(z=O.parentNode)==null||z.insertBefore(V,O.nextSibling):Fe.appendChild(V)}break;case"body-top":{let O=G.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");O?O.replaceWith(V):G.insertBefore(V,G.firstChild);break}case"body-bottom":G.appendChild(V);break;case"footer-top":Et.replaceWith(V);break;case"footer-bottom":ln.replaceWith(V);break;default:break}};for(let[N,V]of Object.entries(c))if(V)try{let z=V({config:o,defaultContent:()=>f(N)});z&&h(N,z)}catch(z){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${N}":`,z)}})();let $o=c=>{let h=c.target.closest('button[data-expand-header="true"]');if(!h)return;let y=h.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!y)return;let P=y.getAttribute("data-message-id");if(!P)return;let N=h.getAttribute("data-bubble-type");N==="reasoning"?(Gr.has(P)?Gr.delete(P):Gr.add(P),tm(P,y)):N==="tool"&&(Yr.has(P)?Yr.delete(P):Yr.add(P),nm(P,y,o)),mo.delete(P)};Ve.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),$o(c))}),Ve.addEventListener("keydown",c=>{let f=c.target;(c.key==="Enter"||c.key===" ")&&f.closest('button[data-expand-header="true"]')&&(c.preventDefault(),$o(c))});let Lo=new Map;Ve.addEventListener("click",c=>{var V;let h=c.target.closest(".persona-message-action-btn[data-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.closest("[data-actions-for]");if(!y)return;let P=y.getAttribute("data-actions-for");if(!P)return;let N=h.getAttribute("data-action");if(N==="copy"){let O=E.getMessages().find(Ae=>Ae.id===P);if(O&&te.onCopy){let Ae=O.content||"";navigator.clipboard.writeText(Ae).then(()=>{h.classList.add("persona-message-action-success");let ue=Te("check",14,"currentColor",2);ue&&(h.innerHTML="",h.appendChild(ue)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Z=Te("copy",14,"currentColor",2);Z&&(h.innerHTML="",h.appendChild(Z))},2e3)}).catch(ue=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ue)}),te.onCopy(O)}}else if(N==="upvote"||N==="downvote"){let O=((V=Lo.get(P))!=null?V:null)===N,Ae=N==="upvote"?"thumbs-up":"thumbs-down";if(O){Lo.delete(P),h.classList.remove("persona-message-action-active");let ue=Te(Ae,14,"currentColor",2);ue&&(h.innerHTML="",h.appendChild(ue))}else{let ue=N==="upvote"?"downvote":"upvote",Z=y.querySelector(`[data-action="${ue}"]`);if(Z){Z.classList.remove("persona-message-action-active");let Xe=Te(ue==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Xe&&(Z.innerHTML="",Z.appendChild(Xe))}Lo.set(P,N),h.classList.add("persona-message-action-active");let he=Te(Ae,14,"currentColor",2);he&&(he.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(he)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ne=E.getMessages().find(tt=>tt.id===P);Ne&&te.onFeedback&&te.onFeedback({type:N,messageId:Ne.id,message:Ne})}}}),Ve.addEventListener("click",c=>{let h=c.target.closest("button[data-approval-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.closest(".persona-approval-bubble");if(!y)return;let P=y.getAttribute("data-message-id");if(!P)return;let N=h.getAttribute("data-approval-action");if(!N)return;let V=N==="approve"?"approved":"denied",O=E.getMessages().find(ue=>ue.id===P);if(!(O!=null&&O.approval))return;let Ae=y.querySelector("[data-approval-buttons]");Ae&&Ae.querySelectorAll("button").forEach(Z=>{Z.disabled=!0,Z.style.opacity="0.5",Z.style.cursor="not-allowed"}),O.approval.toolType==="webmcp"?E.resolveWebMcpApproval(P,V):E.resolveApproval(O.approval,V)});let yt=null,_n=null,Vn={artifacts:[],selectedId:null},xn=!1,It={current:null};Ve.addEventListener("click",c=>{var Z,he,Ee,Ne,tt;let h=c.target.closest("[data-download-artifact]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||((Ee=(he=(Z=o.features)==null?void 0:Z.artifacts)==null?void 0:he.onArtifactAction)==null?void 0:Ee.call(he,{type:"download",artifactId:y}))===!0)return;let N=E.getArtifactById(y),V=N==null?void 0:N.markdown,z=(N==null?void 0:N.title)||"artifact";if(!V){let Xe=h.closest("[data-open-artifact]"),at=Xe==null?void 0:Xe.closest("[data-message-id]"),it=at==null?void 0:at.getAttribute("data-message-id");if(it){let Re=E.getMessages().find(je=>je.id===it);if(Re!=null&&Re.rawContent)try{let je=JSON.parse(Re.rawContent);V=(Ne=je==null?void 0:je.props)==null?void 0:Ne.markdown,z=((tt=je==null?void 0:je.props)==null?void 0:tt.title)||z}catch{}}}if(!V)return;let O=new Blob([V],{type:"text/markdown"}),Ae=URL.createObjectURL(O),ue=document.createElement("a");ue.href=Ae,ue.download=`${z}.md`,ue.click(),URL.revokeObjectURL(Ae)}),Ve.addEventListener("click",c=>{var N,V,z;let h=c.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||((z=(V=(N=o.features)==null?void 0:N.artifacts)==null?void 0:V.onArtifactAction)==null?void 0:z.call(V,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),xn=!1,E.selectArtifact(y),zn())}),Ve.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let f=c.target;f.hasAttribute("data-open-artifact")&&(c.preventDefault(),f.click())});let eo=He.composerOverlay,to=(c,f,h)=>{var z,O,Ae,ue;let y=f.trim();if(!y||!It.current)return;let P=(z=c.getAttribute("data-tool-call-id"))!=null?z:"",N=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:P,answer:y,answers:h.structured,values:(O=h.values)!=null?O:h.source==="multi"?y.split(", "):[y],isFreeText:N,source:h.source},bubbles:!0,composed:!0})),Zr(eo,P);let V=It.current.getMessages().find(Z=>{var he;return((he=Z.toolCall)==null?void 0:he.id)===P});(Ae=V==null?void 0:V.agentMetadata)!=null&&Ae.awaitingLocalTool?It.current.resolveAskUserQuestion(V,(ue=h.structured)!=null?ue:y):It.current.sendMessage(y)},$n=c=>{var P;let f=It.current;if(!f)return;let h=(P=c.getAttribute("data-tool-call-id"))!=null?P:"",y=f.getMessages().find(N=>{var V;return((V=N.toolCall)==null?void 0:V.id)===h});y&&f.persistAskUserQuestionProgress(y,{answers:Si(c,y),currentIndex:lo(c)})},Uo=c=>Object.entries(c).map(([f,h])=>`${f}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Io=c=>{var P,N,V;if(((N=(P=o.features)==null?void 0:P.askUserQuestion)==null?void 0:N.groupedAutoAdvance)===!1)return;let f=lo(c),h=Jr(c);if(f>=h-1)return;let y=(V=It.current)==null?void 0:V.getMessages().find(z=>{var O;return((O=z.toolCall)==null?void 0:O.id)===c.getAttribute("data-tool-call-id")});y&&(Ti(c,y,o,f+1),$n(c))};eo.addEventListener("click",c=>{var N,V,z,O,Ae,ue,Z,he,Ee,Ne,tt,Xe,at,it;let h=c.target.closest("[data-ask-user-action]");if(!h)return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;let P=h.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),P==="dismiss"){let Pe=(N=y.getAttribute("data-tool-call-id"))!=null?N:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),Zr(eo,Pe);let Re=(V=It.current)==null?void 0:V.getMessages().find(je=>{var R;return((R=je.toolCall)==null?void 0:R.id)===Pe});(z=Re==null?void 0:Re.agentMetadata)!=null&&z.awaitingLocalTool&&((O=It.current)==null||O.markAskUserQuestionResolved(Re),(Ae=It.current)==null||Ae.resolveAskUserQuestion(Re,"(dismissed)"));return}if(P==="pick"){let Pe=h.getAttribute("data-option-label");if(!Pe)return;let Re=y.getAttribute("data-multi-select")==="true",je=sr(y);if(je&&Re){let R=kr(y)[lo(y)],Me=new Set(Array.isArray(R)?R:[]);Me.has(Pe)?Me.delete(Pe):Me.add(Pe),ar(y,Array.from(Me)),$n(y);return}if(je){ar(y,Pe),$n(y),Io(y);return}if(Re){let R=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",R?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!R);let Me=y.querySelector('[data-ask-user-action="submit-multi"]');Me&&(Me.disabled=Ml(y).length===0);return}to(y,Pe,{source:"pick",values:[Pe]});return}if(P==="submit-multi"){let Pe=Ml(y);if(Pe.length===0)return;to(y,Pe.join(", "),{source:"multi",values:Pe});return}if(P==="open-free-text"){let Pe=y.querySelector('[data-ask-free-text-row="true"]');if(Pe){Pe.classList.remove("persona-hidden");let Re=Pe.querySelector('[data-ask-free-text-input="true"]');Re==null||Re.focus()}return}if(P==="focus-free-text"){let Pe=y.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus();return}if(P==="submit-free-text"){let Pe=y.querySelector('[data-ask-free-text-input="true"]'),Re=(ue=Pe==null?void 0:Pe.value)!=null?ue:"";if(!Re.trim())return;if(sr(y)){ar(y,Re.trim()),$n(y),Io(y);return}to(y,Re,{source:"free-text"});return}if(P==="next"||P==="back"){if(!It.current)return;let Pe=(Z=y.getAttribute("data-tool-call-id"))!=null?Z:"",Re=It.current.getMessages().find(Ge=>{var Ce;return((Ce=Ge.toolCall)==null?void 0:Ce.id)===Pe});if(!Re)return;let je=y.querySelector('[data-ask-free-text-input="true"]'),R=(Ee=(he=je==null?void 0:je.value)==null?void 0:he.trim())!=null?Ee:"";if(R){let Ge=kr(y)[lo(y)];(typeof Ge!="string"||Ge!==R)&&ar(y,R)}let Me=P==="next"?1:-1,Be=lo(y)+Me;Ti(y,Re,o,Be),$n(y);return}if(P==="submit-all"){if(!It.current)return;let Pe=(Ne=y.getAttribute("data-tool-call-id"))!=null?Ne:"",Re=It.current.getMessages().find(Ge=>{var Ce;return((Ce=Ge.toolCall)==null?void 0:Ce.id)===Pe});if(!Re)return;let je=y.querySelector('[data-ask-free-text-input="true"]'),R=(Xe=(tt=je==null?void 0:je.value)==null?void 0:tt.trim())!=null?Xe:"";R&&ar(y,R);let Me=Si(y,Re);It.current.persistAskUserQuestionProgress(Re,{answers:Me,currentIndex:lo(y)});let Be=Uo(Me);to(y,Be||"(submitted)",{source:"submit-all",structured:Me});return}if(P==="skip"){if(!It.current)return;let Pe=(at=y.getAttribute("data-tool-call-id"))!=null?at:"",Re=It.current.getMessages().find(Ce=>{var Lt;return((Lt=Ce.toolCall)==null?void 0:Lt.id)===Pe});if(!Re)return;let je=sr(y),R=lo(y),Me=Jr(y),Be=R>=Me-1;if(!je){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),Zr(eo,Pe),(it=Re.agentMetadata)!=null&&it.awaitingLocalTool&&(It.current.markAskUserQuestionResolved(Re),It.current.resolveAskUserQuestion(Re,"(dismissed)"));return}ar(y,"");let Ge=y.querySelector('[data-ask-free-text-input="true"]');if(Ge&&(Ge.value=""),Be){let Ce=Si(y,Re),Lt=Uo(Ce);to(y,Lt||"(skipped)",{source:"submit-all",structured:Ce});return}Ti(y,Re,o,R+1),$n(y);return}}),eo.addEventListener("keydown",c=>{var N;if(c.key!=="Enter")return;let h=c.target;if(!((N=h.matches)!=null&&N.call(h,'[data-ask-free-text-input="true"]')))return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;c.preventDefault();let P=h.value;if(P.trim()){if(sr(y)){ar(y,P.trim()),$n(y),Io(y);return}to(y,P,{source:"free-text"})}});let zo=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let f=c.target;if((f==null?void 0:f.tagName)==="INPUT"||(f==null?void 0:f.tagName)==="TEXTAREA"||f!=null&&f.isContentEditable)return;let h=eo.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let y=Number(c.key),N=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];N&&(c.preventDefault(),N.click())};document.addEventListener("keydown",zo);let Un=null,Wt=null,wn=null,no=null,qo=()=>{};function Ro(){no==null||no(),no=null}let jo=()=>{var V;if(!Un||!Wt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),h=((V=e.ownerDocument.defaultView)!=null?V:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||h){Wt.style.removeProperty("position"),Wt.style.removeProperty("left"),Wt.style.removeProperty("top"),Wt.style.removeProperty("bottom"),Wt.style.removeProperty("width"),Wt.style.removeProperty("z-index");return}let y=Un.firstElementChild;if(!y||y===Wt)return;let P=10;Wt.style.position="absolute",Wt.style.top="0",Wt.style.bottom="0",Wt.style.width=`${P}px`,Wt.style.zIndex="5";let N=y.offsetWidth-P/2;Wt.style.left=`${Math.max(0,N)}px`},Co=()=>{},zn=()=>{var h,y,P,N,V;if(!yt||!co(o))return;Ei(e,o),Mi(e,o),Co();let c=(N=(P=(y=(h=o.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:P.narrowHostMaxWidth)!=null?N:520,f=le.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",f>0&&f<=c),yt.update(Vn),xn?(yt.setMobileOpen(!1),yt.element.classList.add("persona-hidden"),(V=yt.backdrop)==null||V.classList.add("persona-hidden")):Vn.artifacts.length>0&&(yt.element.classList.remove("persona-hidden"),yt.setMobileOpen(!0)),qo()};if(co(o)){le.style.position="relative";let c=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),f=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(ce),yt=wm(o,{onSelect:h=>{var y;return(y=It.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{xn=!0,zn()}}),yt.element.classList.add("persona-hidden"),Un=f,f.appendChild(c),f.appendChild(yt.element),yt.backdrop&&le.appendChild(yt.backdrop),le.appendChild(f),qo=()=>{var y,P,N,V;if(!Un||!yt)return;if(!(((N=(P=(y=o.features)==null?void 0:y.artifacts)==null?void 0:P.layout)==null?void 0:N.resizable)===!0)){wn==null||wn(),wn=null,Ro(),Wt&&(Wt.remove(),Wt=null),yt.element.style.removeProperty("width"),yt.element.style.removeProperty("maxWidth");return}if(!Wt){let z=b("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");z.setAttribute("role","separator"),z.setAttribute("aria-orientation","vertical"),z.setAttribute("aria-label","Resize artifacts panel"),z.tabIndex=0;let O=e.ownerDocument,Ae=(V=O.defaultView)!=null?V:window,ue=Z=>{var at,it;if(!yt||Z.button!==0||e.classList.contains("persona-artifact-narrow-host")||Ae.innerWidth<=640)return;Z.preventDefault(),Ro();let he=Z.clientX,Ee=yt.element.getBoundingClientRect().width,Ne=(it=(at=o.features)==null?void 0:at.artifacts)==null?void 0:it.layout,tt=Pe=>{let Re=Un.getBoundingClientRect().width,je=e.classList.contains("persona-artifact-appearance-seamless"),R=je?0:Tm(Un,Ae),Me=je?0:z.getBoundingClientRect().width||6,Be=Ee-(Pe.clientX-he),Ge=km(Be,Re,R,Me,Ne==null?void 0:Ne.resizableMinWidth,Ne==null?void 0:Ne.resizableMaxWidth);yt.element.style.width=`${Ge}px`,yt.element.style.maxWidth="none",jo()},Xe=()=>{O.removeEventListener("pointermove",tt),O.removeEventListener("pointerup",Xe),O.removeEventListener("pointercancel",Xe),no=null;try{z.releasePointerCapture(Z.pointerId)}catch{}};no=Xe,O.addEventListener("pointermove",tt),O.addEventListener("pointerup",Xe),O.addEventListener("pointercancel",Xe);try{z.setPointerCapture(Z.pointerId)}catch{}};z.addEventListener("pointerdown",ue),Wt=z,Un.insertBefore(z,yt.element),wn=()=>{z.removeEventListener("pointerdown",ue)}}if(Wt){let z=Vn.artifacts.length>0&&!xn;Wt.classList.toggle("persona-hidden",!z),jo()}},Co=()=>{var Ae,ue,Z,he,Ee,Ne,tt,Xe,at,it,Pe,Re,je,R;if(!I||!yt||((ue=(Ae=o.launcher)==null?void 0:Ae.sidebarMode)!=null?ue:!1)||pn(o)&&Mo(o).reveal==="emerge")return;let y=(Z=e.ownerDocument.defaultView)!=null?Z:window,P=(Ee=(he=o.launcher)==null?void 0:he.mobileFullscreen)!=null?Ee:!0,N=(tt=(Ne=o.launcher)==null?void 0:Ne.mobileBreakpoint)!=null?tt:640;if(P&&y.innerWidth<=N||!Am(o,I))return;let V=(it=(at=(Xe=o.launcher)==null?void 0:Xe.width)!=null?at:o.launcherWidth)!=null?it:io,z=(R=(je=(Re=(Pe=o.features)==null?void 0:Pe.artifacts)==null?void 0:Re.layout)==null?void 0:je.expandedPanelWidth)!=null?R:"min(720px, calc(100vw - 24px))";Vn.artifacts.length>0&&!xn?(le.style.width=z,le.style.maxWidth=z):(le.style.width=V,le.style.maxWidth=V)},typeof ResizeObserver!="undefined"&&(_n=new ResizeObserver(()=>{zn()}),_n.observe(le))}else le.appendChild(ce),k()&&Ue&&(He.peekBanner&&Ue.appendChild(He.peekBanner),Ue.appendChild($e));e.appendChild(ye),Ue&&e.appendChild(Ue);let po=()=>{var Ge,Ce,Lt,st,Xt,cn,Pt,An,dn,Je,lt,Tn,mn,mr,fr,gr,Nr,_r,qt,hr,nr,ht,Pn,Oo,kn,Wn,Ht,Ut;if(k()){le.style.width="100%",le.style.maxWidth="100%";let Dt=(Ce=(Ge=o.launcher)==null?void 0:Ge.composerBar)!=null?Ce:{},jt=ye.dataset.state==="expanded",Bn=(Lt=Dt.expandedSize)!=null?Lt:"anchored";if(!(jt&&Bn!=="fullscreen")){ce.style.background="",ce.style.border="",ce.style.borderRadius="",ce.style.overflow="",ce.style.boxShadow="";return}let en=(Xt=(st=o.theme)==null?void 0:st.components)==null?void 0:Xt.panel,To=Ma(o),No=(br,ka)=>{var Ss;return br==null||br===""?ka:(Ss=Vr(To,br))!=null?Ss:br},Sa="1px solid var(--persona-border)",Aa="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Ta="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ce.style.background="var(--persona-surface, #ffffff)",ce.style.border=No(en==null?void 0:en.border,Sa),ce.style.borderRadius=No(en==null?void 0:en.borderRadius,Ta),ce.style.boxShadow=No(en==null?void 0:en.shadow,Aa),ce.style.overflow="hidden";return}let c=pn(o),f=(Pt=(cn=o.launcher)==null?void 0:cn.sidebarMode)!=null?Pt:!1,h=c||f||((dn=(An=o.launcher)==null?void 0:An.fullHeight)!=null?dn:!1),y=((Je=o.launcher)==null?void 0:Je.enabled)===!1,P=(Tn=(lt=o.theme)==null?void 0:lt.components)==null?void 0:Tn.panel,N=Ma(o),V=(Dt,jt)=>{var Bn;return Dt==null||Dt===""?jt:(Bn=Vr(N,Dt))!=null?Bn:Dt},z=(mn=e.ownerDocument.defaultView)!=null?mn:window,O=(fr=(mr=o.launcher)==null?void 0:mr.mobileFullscreen)!=null?fr:!0,Ae=(Nr=(gr=o.launcher)==null?void 0:gr.mobileBreakpoint)!=null?Nr:640,ue=z.innerWidth<=Ae,Z=O&&ue&&I,he=(qt=(_r=o.launcher)==null?void 0:_r.position)!=null?qt:"bottom-left",Ee=he==="bottom-left"||he==="top-left",Ne=(nr=(hr=o.launcher)==null?void 0:hr.zIndex)!=null?nr:hn,tt=f||Z?"none":"1px solid var(--persona-border)",Xe=Z?"none":f?Ee?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!Z&&(Xe="none",tt="none");let at=f||Z?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",it=V(P==null?void 0:P.border,tt),Pe=V(P==null?void 0:P.shadow,Xe),Re=V(P==null?void 0:P.borderRadius,at),je=G.scrollTop;e.style.cssText="",ye.style.cssText="",le.style.cssText="",ce.style.cssText="",G.style.cssText="",$e.style.cssText="";let R=()=>{var jt;if(je<=0)return;((jt=G.ownerDocument.defaultView)!=null?jt:window).requestAnimationFrame(()=>{if(G.scrollTop===je)return;let Bn=G.scrollHeight-G.clientHeight;Bn<=0||(G.scrollTop=Math.min(je,Bn))})};if(Z){ye.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),ye.style.cssText=`
|
|
30
|
+
`,x.addEventListener("click",()=>{u=w,L.forEach((k,S)=>{let T=S<w;k.classList.toggle("selected",T),k.setAttribute("aria-checked",S===w-1?"true":"false")})}),L.push(x),E.appendChild(x)}g.appendChild(E);let I=null;if(d){let w=document.createElement("div");w.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=s,I.rows=3,I.setAttribute("aria-label","Additional comments"),w.appendChild(I),g.appendChild(w)}let R=document.createElement("div");R.className="persona-feedback-actions";let H=document.createElement("button");H.type="button",H.className="persona-feedback-btn persona-feedback-btn-skip",H.textContent=i,H.addEventListener("click",()=>{n==null||n(),f.remove()});let P=document.createElement("button");return P.type="button",P.className="persona-feedback-btn persona-feedback-btn-submit",P.textContent=a,P.addEventListener("click",async()=>{if(u===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}P.disabled=!0,P.textContent="Submitting...";try{let w=(I==null?void 0:I.value.trim())||void 0;await t(u,w),f.remove()}catch(w){P.disabled=!1,P.textContent=a,console.error("[CSAT Feedback] Failed to submit:",w)}}),R.appendChild(H),R.appendChild(P),g.appendChild(R),f.appendChild(g),f}function Sf(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:f="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let g=null,m=document.createElement("div");m.className="persona-feedback-content";let C=document.createElement("div");C.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=o,C.appendChild(v);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=r,C.appendChild(E),m.appendChild(C);let L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-nps",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Likelihood rating from 0 to 10");let I=document.createElement("div");I.className="persona-feedback-labels";let R=document.createElement("span");R.className="persona-feedback-label-low",R.textContent=l;let H=document.createElement("span");H.className="persona-feedback-label-high",H.textContent=f,I.appendChild(R),I.appendChild(H);let P=document.createElement("div");P.className="persona-feedback-numbers";let w=[];for(let _=0;_<=10;_++){let U=document.createElement("button");U.type="button",U.className="persona-feedback-rating-btn persona-feedback-number-btn",U.setAttribute("role","radio"),U.setAttribute("aria-checked","false"),U.setAttribute("aria-label",`Rating ${_} out of 10`),U.textContent=String(_),U.dataset.rating=String(_),_<=6?U.classList.add("persona-feedback-detractor"):_<=8?U.classList.add("persona-feedback-passive"):U.classList.add("persona-feedback-promoter"),U.addEventListener("click",()=>{g=_,w.forEach((G,ge)=>{G.classList.toggle("selected",ge===_),G.setAttribute("aria-checked",ge===_?"true":"false")})}),w.push(U),P.appendChild(U)}L.appendChild(I),L.appendChild(P),m.appendChild(L);let x=null;if(d){let _=document.createElement("div");_.className="persona-feedback-comment-container",x=document.createElement("textarea"),x.className="persona-feedback-comment",x.placeholder=s,x.rows=3,x.setAttribute("aria-label","Additional comments"),_.appendChild(x),m.appendChild(_)}let k=document.createElement("div");k.className="persona-feedback-actions";let S=document.createElement("button");S.type="button",S.className="persona-feedback-btn persona-feedback-btn-skip",S.textContent=i,S.addEventListener("click",()=>{n==null||n(),u.remove()});let T=document.createElement("button");return T.type="button",T.className="persona-feedback-btn persona-feedback-btn-submit",T.textContent=a,T.addEventListener("click",async()=>{if(g===null){P.classList.add("persona-feedback-shake"),setTimeout(()=>P.classList.remove("persona-feedback-shake"),500);return}T.disabled=!0,T.textContent="Submitting...";try{let _=(x==null?void 0:x.value.trim())||void 0;await t(g,_),u.remove()}catch(_){T.disabled=!1,T.textContent=a,console.error("[NPS Feedback] Failed to submit:",_)}}),k.appendChild(S),k.appendChild(T),m.appendChild(k),u.appendChild(m),u}var bs="persona-chat-history",Gx=30*1e3,Yx={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function Xx(e){var o,r,s;if(!e)return[];let t=[],n=Array.from((o=e.items)!=null?o:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(r=Yx[i.type])!=null?r:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((s=e.files)!=null?s:[]))a.type.startsWith("image/")&&t.push(a);return t}function Vi(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function Jx(e){var t,n,o,r,s,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(r=(o=e.persist)==null?void 0:o.openState)!=null?r:!0,voiceState:(a=(s=e.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function Qx(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var tc=e=>!e||typeof e!="object"?{}:{...e},Af=e=>e.map(t=>({...t,streaming:!1})),Tf=(e,t,n)=>{let o=e!=null&&e.markdown?Qa(e.markdown):null,r=Za(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&r&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var l,f,u;let a=(l=s.text)!=null?l:"",i=(f=s.message.rawContent)!=null?f:null;if(t){let g=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});g!==null&&(a=g.text,g.persist||(s.message.__skipPersist=!0),g.resubmit&&!s.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...s,text:a,raw:(u=i!=null?i:s.text)!=null?u:""}):o?d=o(a):d=js(a),r?r(d):d}};function kf(e){var i,d,l,f;let t=b("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",o=(d=e==null?void 0:e.iconSize)!=null?d:"48px",r=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(f=e==null?void 0:e.iconStrokeWidth)!=null?f:.5,a=Ee(n,o,r,s);if(a&&t.appendChild(a),e!=null&&e.label){let u=b("span","persona-drop-overlay-label");u.textContent=e.label,t.appendChild(u)}return t}var Ef=(e,t,n)=>{var Rc,Pc,Wc,Bc,Hc,Dc,Fc,Oc,Nc,_c,Vc,$c,Uc,zc,qc,jc,Kc,Gc,Yc,Xc,Jc,Qc,Zc,ed,td,nd,od,rd,sd,ad,id,ld,cd,dd,pd,ud,md,fd,gd,hd,bd,yd,vd,xd,wd,Cd,Sd,Ad,Td,kd;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=Mu(t),r=Jl.getForInstance(o.plugins);o.components&&_r.registerAll(o.components);let s=gf(),i=o.persistState===!1?null:(Rc=o.storageAdapter)!=null?Rc:bf(),d={},l=null,f=!1,u=c=>{if(o.onStateLoaded)try{let p=o.onStateLoaded(c);if(p&&typeof p=="object"&&"state"in p){let{state:h,open:y}=p;return y&&(f=!0),h}return p}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",p)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(p=>{let h=p!=null?p:{messages:[],metadata:{}};return u(h)});else{let p=c!=null?c:{messages:[],metadata:{}},h=u(p);h.metadata&&(d=tc(h.metadata)),(Pc=h.messages)!=null&&Pc.length&&(o={...o,initialMessages:h.messages}),(Wc=h.artifacts)!=null&&Wc.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(Bc=h.selectedArtifactId)!=null?Bc:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(o.onStateLoaded)try{let c=u({messages:[],metadata:{}});(Hc=c.messages)!=null&&Hc.length&&(o={...o,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let g=()=>d,m=c=>{var h;d=(h=c({...d}))!=null?h:{},Gr()},C=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Zl],v=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[fa.message,fa.messageAndClick],E=ec({parsers:C,handlers:v,getSessionMetadata:g,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null});E.syncFromMetadata();let L=(Fc=(Dc=o.launcher)==null?void 0:Dc.enabled)!=null?Fc:!0,I=(Nc=(Oc=o.launcher)==null?void 0:Oc.autoExpand)!=null?Nc:!1,R=(_c=o.autoFocusInput)!=null?_c:!1,H=I,P=L,w=($c=(Vc=o.layout)==null?void 0:Vc.header)==null?void 0:$c.layout,x=!1,k=()=>aa(o),S=()=>L||k(),T=k()?!1:L?I:!0,_=!1,U=null,G=()=>{_=!0,U&&clearTimeout(U),U=setTimeout(()=>{_&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),_=!1)},1e4)},ge=Tf(o,E,G),ue=(zc=(Uc=o.features)==null?void 0:Uc.showReasoning)!=null?zc:!0,ce=(jc=(qc=o.features)==null?void 0:qc.showToolCalls)!=null?jc:!0,ke=(Gc=(Kc=o.features)==null?void 0:Kc.showEventStreamToggle)!=null?Gc:!1,ve=(Xc=(Yc=o.features)==null?void 0:Yc.scrollToBottom)!=null?Xc:{},He=(Qc=(Jc=o.features)==null?void 0:Jc.scrollBehavior)!=null?Qc:{},ie=`${(ed=typeof o.persistState=="object"?(Zc=o.persistState)==null?void 0:Zc.keyPrefix:void 0)!=null?ed:"persona-"}event-stream`,X=ke?new ua(ie):null,re=(od=(nd=(td=o.features)==null?void 0:td.eventStream)==null?void 0:nd.maxEvents)!=null?od:2e3,be=ke?new pa(re,X):null,he=ke?new ma:null,j=null,se=!1,Ie=null,ne=0;X==null||X.open().then(()=>be==null?void 0:be.restore()).catch(c=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let Z={onCopy:c=>{var p,h;s.emit("message:copy",c),V!=null&&V.isClientTokenMode()&&V.submitMessageFeedback(c.id,"copy").catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",y)}),(h=(p=o.messageActions)==null?void 0:p.onCopy)==null||h.call(p,c)},onFeedback:c=>{var p,h;s.emit("message:feedback",c),V!=null&&V.isClientTokenMode()&&V.submitMessageFeedback(c.messageId,c.type).catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",y)}),(h=(p=o.messageActions)==null?void 0:p.onFeedback)==null||h.call(p,c)}},oe=(rd=o.statusIndicator)!=null?rd:{},at=c=>{var p,h,y,M;return c==="idle"?(p=oe.idleText)!=null?p:kn.idle:c==="connecting"?(h=oe.connectingText)!=null?h:kn.connecting:c==="connected"?(y=oe.connectedText)!=null?y:kn.connected:c==="error"?(M=oe.errorText)!=null?M:kn.error:kn[c]};function it(c,p,h,y){if(y==="idle"&&h.idleLink){c.textContent="";let M=document.createElement("a");M.href=h.idleLink,M.target="_blank",M.rel="noopener noreferrer",M.textContent=p,M.style.color="inherit",M.style.textDecoration="none",c.appendChild(M)}else c.textContent=p}let{wrapper:Me,panel:de,pillRoot:Xe}=Wm(o),We=Bm(o,S()),{container:q,body:me,messagesWrapper:et,suggestions:Et,textarea:ee,sendButton:ze,sendButtonWrapper:Dn,composerForm:Ht,statusText:sn,introTitle:no,introSubtitle:ko,closeButton:D,iconHolder:pe,headerTitle:De,headerSubtitle:je,header:Ne,footer:Ve,actionsRow:nt,leftActions:Rt,rightActions:jt}=We,Xt=We.setSendButtonMode,K=We.micButton,vt=We.micButtonWrapper,rt=We.attachmentButton,Ce=We.attachmentButtonWrapper,le=We.attachmentInput,Ze=We.attachmentPreviewsContainer;q.classList.add("persona-relative"),me.classList.add("persona-relative");let Jt=12,Kt=()=>{var c;return(c=ve.label)!=null?c:""},Ln=()=>{var c;return(c=ve.iconName)!=null?c:"arrow-down"},yn=()=>ve.enabled!==!1,ft=()=>{var c;return(c=He.mode)!=null?c:"follow"},Mt=()=>{var c;return(c=He.anchorTopOffset)!=null?c:16},Je=b("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Je.type="button",Je.style.display="none",Je.setAttribute("data-persona-scroll-to-bottom","true");let zt=b("span","persona-flex persona-items-center"),an=b("span",""),wn=b("span","");wn.setAttribute("data-persona-scroll-to-bottom-count",""),wn.style.display="none",Je.append(zt,an,wn),q.appendChild(Je);let Cn=b("div","persona-stream-anchor-spacer");Cn.setAttribute("aria-hidden","true"),Cn.setAttribute("data-persona-anchor-spacer",""),Cn.style.flexShrink="0",Cn.style.pointerEvents="none",Cn.style.height="0px",me.appendChild(Cn);let bn=()=>{let p=Ve.style.display==="none"?0:Ve.offsetHeight;Je.style.bottom=`${p+Jt}px`};bn();let Eo=()=>{let c=!!Kt();Je.setAttribute("aria-label",Kt()||"Jump to latest"),Je.title=Kt(),Je.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),zt.innerHTML="";let p=Ee(Ln(),"14px","currentColor",2);p?(zt.appendChild(p),zt.style.display=""):zt.style.display="none",an.textContent=Kt(),an.style.display=c?"":"none"};Eo();let St=null,$n=null,Un=r.find(c=>c.renderHeader);if(Un!=null&&Un.renderHeader){let c=Un.renderHeader({config:o,defaultRenderer:()=>{let p=Dr({config:o,showClose:S()});return la(q,p,o),p.header},onClose:()=>Ft(!1,"user")});if(c){let p=q.querySelector(".persona-border-b-persona-divider");p&&(p.replaceWith(c),Ne=c)}}let No=()=>{var p,h,y,M;if(!be)return;if(se=!0,!j&&be&&(j=rf({buffer:be,getFullHistory:()=>be.getAllFromStore(),onClose:()=>bo(),config:o,plugins:r,getThroughput:()=>{var O;return(O=he==null?void 0:he.getMetric())!=null?O:{status:"idle"}}})),j&&(me.style.display="none",(p=Ve.parentNode)==null||p.insertBefore(j.element,Ve),j.update()),xt){xt.style.boxShadow=`inset 0 0 0 1.5px ${Hn.actionIconColor}`;let O=(M=(y=(h=o.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:M.toggleButtonActive;O&&O.split(/\s+/).forEach(N=>N&&xt.classList.add(N))}let c=()=>{if(!se)return;let O=Date.now();O-ne>=200&&(j==null||j.update(),ne=O),Ie=requestAnimationFrame(c)};ne=0,Ie=requestAnimationFrame(c),Nn(),s.emit("eventStream:opened",{timestamp:Date.now()})},bo=()=>{var c,p,h;if(se){if(se=!1,j&&j.element.remove(),me.style.display="",xt){xt.style.boxShadow="";let y=(h=(p=(c=o.features)==null?void 0:c.eventStream)==null?void 0:p.classNames)==null?void 0:h.toggleButtonActive;y&&y.split(/\s+/).forEach(M=>M&&xt.classList.remove(M))}Ie!==null&&(cancelAnimationFrame(Ie),Ie=null),Nn(),s.emit("eventStream:closed",{timestamp:Date.now()})}},xt=null;if(ke){let c=(ad=(sd=o.features)==null?void 0:sd.eventStream)==null?void 0:ad.classNames,p="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");xt=b("button",p),xt.style.width="28px",xt.style.height="28px",xt.style.color=Hn.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let h=Ee("activity","18px","currentColor",1.5);h&&xt.appendChild(h);let y=We.clearChatButtonWrapper,M=We.closeButtonWrapper,O=y||M;O&&O.parentNode===Ne?Ne.insertBefore(xt,O):Ne.appendChild(xt),xt.addEventListener("click",()=>{se?bo():No()})}let br=c=>{var y,M,O;let p=o.attachments;if(!(p!=null&&p.enabled))return;let h=c.querySelector(".persona-attachment-previews");if(!h){h=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.style.display="none";let N=c.querySelector("[data-persona-composer-form]");N!=null&&N.parentNode?N.parentNode.insertBefore(h,N):c.insertBefore(h,c.firstChild)}if(!c.querySelector('input[type="file"]')){let N=b("input");N.type="file",N.accept=((y=p.allowedTypes)!=null?y:Yo).join(","),N.multiple=((M=p.maxFiles)!=null?M:4)>1,N.style.display="none",N.setAttribute("aria-label",(O=p.buttonTooltipText)!=null?O:"Attach files"),c.appendChild(N)}},Mo=r.find(c=>c.renderComposer);if(Mo!=null&&Mo.renderComposer){let c=o.composer,p=Mo.renderComposer({config:o,defaultRenderer:()=>Pi({config:o}).footer,onSubmit:h=>{var N;if(!V||V.isStreaming())return;let y=h.trim(),M=(N=St==null?void 0:St.hasAttachments())!=null?N:!1;if(!y&&!M)return;A();let O;M&&(O=[],O.push(...St.getContentParts()),y&&O.push(kl(y))),V.sendMessage(y,{contentParts:O}),M&&St.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{le==null||le.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:((id=o.voiceRecognition)==null?void 0:id.enabled)===!0?()=>{$n==null||$n()}:void 0});p&&(Ve.replaceWith(p),Ve=p)}let yr=c=>{let p=c.querySelector("[data-persona-composer-form]"),h=c.querySelector("[data-persona-composer-input]"),y=c.querySelector("[data-persona-composer-submit]"),M=c.querySelector("[data-persona-composer-mic]"),O=c.querySelector("[data-persona-composer-status]");p&&(Ht=p),h&&(ee=h),y&&(ze=y),M&&(K=M,vt=M.parentElement),O&&(sn=O);let N=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");N&&(Et=N);let z=c.querySelector(".persona-attachment-button");z&&(rt=z,Ce=z.parentElement),le=c.querySelector('input[type="file"]'),Ze=c.querySelector(".persona-attachment-previews");let F=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");F&&(nt=F)};br(Ve),yr(Ve);let Fn=(ud=(ld=o.layout)==null?void 0:ld.contentMaxWidth)!=null?ud:k()?(pd=(dd=(cd=o.launcher)==null?void 0:cd.composerBar)==null?void 0:dd.contentMaxWidth)!=null?pd:"720px":void 0;if(Fn&&(et.style.maxWidth=Fn,et.style.marginLeft="auto",et.style.marginRight="auto",et.style.width="100%"),Fn&&Ht&&!k()&&(Ht.style.maxWidth=Fn,Ht.style.marginLeft="auto",Ht.style.marginRight="auto"),Fn&&Et&&!k()&&(Et.style.maxWidth=Fn,Et.style.marginLeft="auto",Et.style.marginRight="auto"),Fn&&Ze&&!k()&&(Ze.style.maxWidth=Fn,Ze.style.marginLeft="auto",Ze.style.marginRight="auto"),(md=o.attachments)!=null&&md.enabled&&le&&Ze){St=ea.fromConfig(o.attachments),St.setPreviewsContainer(Ze),le.addEventListener("change",h=>{let y=h.target;St==null||St.handleFileSelect(y.files),y.value=""});let c=o.attachments.dropOverlay,p=kf(c);q.appendChild(p)}(()=>{var y,M;let c=(M=(y=o.layout)==null?void 0:y.slots)!=null?M:{},p=O=>{switch(O){case"body-top":return q.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return et;case"footer-top":return Et;case"composer":return Ht;case"footer-bottom":return sn;default:return null}},h=(O,N)=>{var z;switch(O){case"header-left":case"header-center":case"header-right":if(O==="header-left")Ne.insertBefore(N,Ne.firstChild);else if(O==="header-right")Ne.appendChild(N);else{let F=Ne.querySelector(".persona-flex-col");F?(z=F.parentNode)==null||z.insertBefore(N,F.nextSibling):Ne.appendChild(N)}break;case"body-top":{let F=me.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");F?F.replaceWith(N):me.insertBefore(N,me.firstChild);break}case"body-bottom":me.appendChild(N);break;case"footer-top":Et.replaceWith(N);break;case"footer-bottom":sn.replaceWith(N);break;default:break}};for(let[O,N]of Object.entries(c))if(N)try{let z=N({config:o,defaultContent:()=>p(O)});z&&h(O,z)}catch(z){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${O}":`,z)}})();let Qo=c=>{var N,z;let h=c.target.closest('button[data-expand-header="true"]');if(!h)return;let y=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!y)return;let M=y.getAttribute("data-message-id");if(!M)return;let O=h.getAttribute("data-bubble-type");if(O==="reasoning")ds.has(M)?ds.delete(M):ds.add(M),Fm(M,y);else if(O==="tool")ps.has(M)?ps.delete(M):ps.add(M),Om(M,y,o);else if(O==="approval"){let F=o.approval!==!1?o.approval:void 0,we=((N=F==null?void 0:F.detailsDisplay)!=null?N:"collapsed")==="expanded",fe=(z=Di.get(M))!=null?z:we;Di.set(M,!fe),Zm(M,y,o)}Uo.delete(M)};et.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Qo(c))}),et.addEventListener("keydown",c=>{let p=c.target;(c.key==="Enter"||c.key===" ")&&p.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Qo(c))});let _o=new Map;et.addEventListener("click",c=>{var N;let h=c.target.closest(".persona-message-action-btn[data-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.closest("[data-actions-for]");if(!y)return;let M=y.getAttribute("data-actions-for");if(!M)return;let O=h.getAttribute("data-action");if(O==="copy"){let F=V.getMessages().find(we=>we.id===M);if(F&&Z.onCopy){let we=F.content||"";navigator.clipboard.writeText(we).then(()=>{h.classList.add("persona-message-action-success");let fe=Ee("check",14,"currentColor",2);fe&&(h.innerHTML="",h.appendChild(fe)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let te=Ee("copy",14,"currentColor",2);te&&(h.innerHTML="",h.appendChild(te))},2e3)}).catch(fe=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",fe)}),Z.onCopy(F)}}else if(O==="upvote"||O==="downvote"){let F=((N=_o.get(M))!=null?N:null)===O,we=O==="upvote"?"thumbs-up":"thumbs-down";if(F){_o.delete(M),h.classList.remove("persona-message-action-active");let fe=Ee(we,14,"currentColor",2);fe&&(h.innerHTML="",h.appendChild(fe))}else{let fe=O==="upvote"?"downvote":"upvote",te=y.querySelector(`[data-action="${fe}"]`);if(te){te.classList.remove("persona-message-action-active");let qe=Ee(fe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);qe&&(te.innerHTML="",te.appendChild(qe))}_o.set(M,O),h.classList.add("persona-message-action-active");let Te=Ee(we,14,"currentColor",2);Te&&(Te.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(Te)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ae=V.getMessages().find(tt=>tt.id===M);Ae&&Z.onFeedback&&Z.onFeedback({type:O,messageId:Ae.id,message:Ae})}}}),et.addEventListener("click",c=>{let h=c.target.closest("button[data-approval-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.closest(".persona-approval-bubble");if(!y)return;let M=y.getAttribute("data-message-id");if(!M)return;let O=h.getAttribute("data-approval-action");if(!O)return;let N=O==="approve"?"approved":"denied",F=V.getMessages().find(fe=>fe.id===M);if(!(F!=null&&F.approval))return;let we=y.querySelector("[data-approval-buttons]");we&&we.querySelectorAll("button").forEach(te=>{te.disabled=!0,te.style.opacity="0.5",te.style.cursor="not-allowed"}),F.approval.toolType==="webmcp"?V.resolveWebMcpApproval(M,N):V.resolveApproval(F.approval,N)});let At=null,zn=null,qn={artifacts:[],selectedId:null},In=!1,It={current:null};et.addEventListener("click",c=>{var te,Te,_e,Ae,tt;let h=c.target.closest("[data-download-artifact]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||((_e=(Te=(te=o.features)==null?void 0:te.artifacts)==null?void 0:Te.onArtifactAction)==null?void 0:_e.call(Te,{type:"download",artifactId:y}))===!0)return;let O=V.getArtifactById(y),N=O==null?void 0:O.markdown,z=(O==null?void 0:O.title)||"artifact";if(!N){let qe=h.closest("[data-open-artifact]"),ct=qe==null?void 0:qe.closest("[data-message-id]"),dt=ct==null?void 0:ct.getAttribute("data-message-id");if(dt){let Le=V.getMessages().find(Ue=>Ue.id===dt);if(Le!=null&&Le.rawContent)try{let Ue=JSON.parse(Le.rawContent);N=(Ae=Ue==null?void 0:Ue.props)==null?void 0:Ae.markdown,z=((tt=Ue==null?void 0:Ue.props)==null?void 0:tt.title)||z}catch{}}}if(!N)return;let F=new Blob([N],{type:"text/markdown"}),we=URL.createObjectURL(F),fe=document.createElement("a");fe.href=we,fe.download=`${z}.md`,fe.click(),URL.revokeObjectURL(we)}),et.addEventListener("click",c=>{var O,N,z;let h=c.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||((z=(N=(O=o.features)==null?void 0:O.artifacts)==null?void 0:N.onArtifactAction)==null?void 0:z.call(N,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),In=!1,V.selectArtifact(y),Gn())}),et.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let p=c.target;p.hasAttribute("data-open-artifact")&&(c.preventDefault(),p.click())});let oo=We.composerOverlay,ro=(c,p,h)=>{var z,F,we,fe;let y=p.trim();if(!y||!It.current)return;let M=(z=c.getAttribute("data-tool-call-id"))!=null?z:"",O=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:M,answer:y,answers:h.structured,values:(F=h.values)!=null?F:h.source==="multi"?y.split(", "):[y],isFreeText:O,source:h.source},bubbles:!0,composed:!0})),gs(oo,M);let N=It.current.getMessages().find(te=>{var Te;return((Te=te.toolCall)==null?void 0:Te.id)===M});(we=N==null?void 0:N.agentMetadata)!=null&&we.awaitingLocalTool?It.current.resolveAskUserQuestion(N,(fe=h.structured)!=null?fe:y):It.current.sendMessage(y)},jn=c=>{var M;let p=It.current;if(!p)return;let h=(M=c.getAttribute("data-tool-call-id"))!=null?M:"",y=p.getMessages().find(O=>{var N;return((N=O.toolCall)==null?void 0:N.id)===h});y&&p.persistAskUserQuestionProgress(y,{answers:Wi(c,y),currentIndex:go(c)})},Zo=c=>Object.entries(c).map(([p,h])=>`${p}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Vo=c=>{var M,O,N;if(((O=(M=o.features)==null?void 0:M.askUserQuestion)==null?void 0:O.groupedAutoAdvance)===!1)return;let p=go(c),h=fs(c);if(p>=h-1)return;let y=(N=It.current)==null?void 0:N.getMessages().find(z=>{var F;return((F=z.toolCall)==null?void 0:F.id)===c.getAttribute("data-tool-call-id")});y&&(Hi(c,y,o,p+1),jn(c))};oo.addEventListener("click",c=>{var O,N,z,F,we,fe,te,Te,_e,Ae,tt,qe,ct,dt;let h=c.target.closest("[data-ask-user-action]");if(!h)return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;let M=h.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),M==="dismiss"){let Pe=(O=y.getAttribute("data-tool-call-id"))!=null?O:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),gs(oo,Pe);let Le=(N=It.current)==null?void 0:N.getMessages().find(Ue=>{var Ge;return((Ge=Ue.toolCall)==null?void 0:Ge.id)===Pe});(z=Le==null?void 0:Le.agentMetadata)!=null&&z.awaitingLocalTool&&((F=It.current)==null||F.markAskUserQuestionResolved(Le),(we=It.current)==null||we.resolveAskUserQuestion(Le,"(dismissed)"));return}if(M==="pick"){let Pe=h.getAttribute("data-option-label");if(!Pe)return;let Le=y.getAttribute("data-multi-select")==="true",Ue=gr(y);if(Ue&&Le){let Ge=Or(y)[go(y)],wt=new Set(Array.isArray(Ge)?Ge:[]);wt.has(Pe)?wt.delete(Pe):wt.add(Pe),hr(y,Array.from(wt)),jn(y);return}if(Ue){hr(y,Pe),jn(y),Vo(y);return}if(Le){let Ge=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Ge?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Ge);let wt=y.querySelector('[data-ask-user-action="submit-multi"]');wt&&(wt.disabled=ql(y).length===0);return}ro(y,Pe,{source:"pick",values:[Pe]});return}if(M==="submit-multi"){let Pe=ql(y);if(Pe.length===0)return;ro(y,Pe.join(", "),{source:"multi",values:Pe});return}if(M==="open-free-text"){let Pe=y.querySelector('[data-ask-free-text-row="true"]');if(Pe){Pe.classList.remove("persona-hidden");let Le=Pe.querySelector('[data-ask-free-text-input="true"]');Le==null||Le.focus()}return}if(M==="focus-free-text"){let Pe=y.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus();return}if(M==="submit-free-text"){let Pe=y.querySelector('[data-ask-free-text-input="true"]'),Le=(fe=Pe==null?void 0:Pe.value)!=null?fe:"";if(!Le.trim())return;if(gr(y)){hr(y,Le.trim()),jn(y),Vo(y);return}ro(y,Le,{source:"free-text"});return}if(M==="next"||M==="back"){if(!It.current)return;let Pe=(te=y.getAttribute("data-tool-call-id"))!=null?te:"",Le=It.current.getMessages().find(Be=>{var Fe;return((Fe=Be.toolCall)==null?void 0:Fe.id)===Pe});if(!Le)return;let Ue=y.querySelector('[data-ask-free-text-input="true"]'),Ge=(_e=(Te=Ue==null?void 0:Ue.value)==null?void 0:Te.trim())!=null?_e:"";if(Ge){let Be=Or(y)[go(y)];(typeof Be!="string"||Be!==Ge)&&hr(y,Ge)}let wt=M==="next"?1:-1,B=go(y)+wt;Hi(y,Le,o,B),jn(y);return}if(M==="submit-all"){if(!It.current)return;let Pe=(Ae=y.getAttribute("data-tool-call-id"))!=null?Ae:"",Le=It.current.getMessages().find(Be=>{var Fe;return((Fe=Be.toolCall)==null?void 0:Fe.id)===Pe});if(!Le)return;let Ue=y.querySelector('[data-ask-free-text-input="true"]'),Ge=(qe=(tt=Ue==null?void 0:Ue.value)==null?void 0:tt.trim())!=null?qe:"";Ge&&hr(y,Ge);let wt=Wi(y,Le);It.current.persistAskUserQuestionProgress(Le,{answers:wt,currentIndex:go(y)});let B=Zo(wt);ro(y,B||"(submitted)",{source:"submit-all",structured:wt});return}if(M==="skip"){if(!It.current)return;let Pe=(ct=y.getAttribute("data-tool-call-id"))!=null?ct:"",Le=It.current.getMessages().find(Fe=>{var ye;return((ye=Fe.toolCall)==null?void 0:ye.id)===Pe});if(!Le)return;let Ue=gr(y),Ge=go(y),wt=fs(y),B=Ge>=wt-1;if(!Ue){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),gs(oo,Pe),(dt=Le.agentMetadata)!=null&&dt.awaitingLocalTool&&(It.current.markAskUserQuestionResolved(Le),It.current.resolveAskUserQuestion(Le,"(dismissed)"));return}hr(y,"");let Be=y.querySelector('[data-ask-free-text-input="true"]');if(Be&&(Be.value=""),B){let Fe=Wi(y,Le),ye=Zo(Fe);ro(y,ye||"(skipped)",{source:"submit-all",structured:Fe});return}Hi(y,Le,o,Ge+1),jn(y);return}}),oo.addEventListener("keydown",c=>{var O;if(c.key!=="Enter")return;let h=c.target;if(!((O=h.matches)!=null&&O.call(h,'[data-ask-free-text-input="true"]')))return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;c.preventDefault();let M=h.value;if(M.trim()){if(gr(y)){hr(y,M.trim()),jn(y),Vo(y);return}ro(y,M,{source:"free-text"})}});let er=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let p=c.target;if((p==null?void 0:p.tagName)==="INPUT"||(p==null?void 0:p.tagName)==="TEXTAREA"||p!=null&&p.isContentEditable)return;let h=oo.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let y=Number(c.key),O=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];O&&(c.preventDefault(),O.click())};document.addEventListener("keydown",er);let Kn=null,Dt=null,Rn=null,so=null,tr=()=>{};function $o(){so==null||so(),so=null}let nr=()=>{var N;if(!Kn||!Dt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),h=((N=e.ownerDocument.defaultView)!=null?N:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||h){Dt.style.removeProperty("position"),Dt.style.removeProperty("left"),Dt.style.removeProperty("top"),Dt.style.removeProperty("bottom"),Dt.style.removeProperty("width"),Dt.style.removeProperty("z-index");return}let y=Kn.firstElementChild;if(!y||y===Dt)return;let M=10;Dt.style.position="absolute",Dt.style.top="0",Dt.style.bottom="0",Dt.style.width=`${M}px`,Dt.style.zIndex="5";let O=y.offsetWidth-M/2;Dt.style.left=`${Math.max(0,O)}px`},Lo=()=>{},Gn=()=>{var h,y,M,O,N;if(!At||!ho(o))return;Ni(e,o),_i(e,o),Lo();let c=(O=(M=(y=(h=o.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:M.narrowHostMaxWidth)!=null?O:520,p=de.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",p>0&&p<=c),At.update(qn),In?(At.setMobileOpen(!1),At.element.classList.add("persona-hidden"),(N=At.backdrop)==null||N.classList.add("persona-hidden")):qn.artifacts.length>0&&(At.element.classList.remove("persona-hidden"),At.setMobileOpen(!0)),tr()};if(ho(o)){de.style.position="relative";let c=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),p=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(q),At=lf(o,{onSelect:h=>{var y;return(y=It.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{In=!0,Gn()}}),At.element.classList.add("persona-hidden"),Kn=p,p.appendChild(c),p.appendChild(At.element),At.backdrop&&de.appendChild(At.backdrop),de.appendChild(p),tr=()=>{var y,M,O,N;if(!Kn||!At)return;if(!(((O=(M=(y=o.features)==null?void 0:y.artifacts)==null?void 0:M.layout)==null?void 0:O.resizable)===!0)){Rn==null||Rn(),Rn=null,$o(),Dt&&(Dt.remove(),Dt=null),At.element.style.removeProperty("width"),At.element.style.removeProperty("maxWidth");return}if(!Dt){let z=b("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");z.setAttribute("role","separator"),z.setAttribute("aria-orientation","vertical"),z.setAttribute("aria-label","Resize artifacts panel"),z.tabIndex=0;let F=e.ownerDocument,we=(N=F.defaultView)!=null?N:window,fe=te=>{var ct,dt;if(!At||te.button!==0||e.classList.contains("persona-artifact-narrow-host")||we.innerWidth<=640)return;te.preventDefault(),$o();let Te=te.clientX,_e=At.element.getBoundingClientRect().width,Ae=(dt=(ct=o.features)==null?void 0:ct.artifacts)==null?void 0:dt.layout,tt=Pe=>{let Le=Kn.getBoundingClientRect().width,Ue=e.classList.contains("persona-artifact-appearance-seamless"),Ge=Ue?0:uf(Kn,we),wt=Ue?0:z.getBoundingClientRect().width||6,B=_e-(Pe.clientX-Te),Be=mf(B,Le,Ge,wt,Ae==null?void 0:Ae.resizableMinWidth,Ae==null?void 0:Ae.resizableMaxWidth);At.element.style.width=`${Be}px`,At.element.style.maxWidth="none",nr()},qe=()=>{F.removeEventListener("pointermove",tt),F.removeEventListener("pointerup",qe),F.removeEventListener("pointercancel",qe),so=null;try{z.releasePointerCapture(te.pointerId)}catch{}};so=qe,F.addEventListener("pointermove",tt),F.addEventListener("pointerup",qe),F.addEventListener("pointercancel",qe);try{z.setPointerCapture(te.pointerId)}catch{}};z.addEventListener("pointerdown",fe),Dt=z,Kn.insertBefore(z,At.element),Rn=()=>{z.removeEventListener("pointerdown",fe)}}if(Dt){let z=qn.artifacts.length>0&&!In;Dt.classList.toggle("persona-hidden",!z),nr()}},Lo=()=>{var we,fe,te,Te,_e,Ae,tt,qe,ct,dt,Pe,Le,Ue,Ge;if(!L||!At||((fe=(we=o.launcher)==null?void 0:we.sidebarMode)!=null?fe:!1)||xn(o)&&Oo(o).reveal==="emerge")return;let y=(te=e.ownerDocument.defaultView)!=null?te:window,M=(_e=(Te=o.launcher)==null?void 0:Te.mobileFullscreen)!=null?_e:!0,O=(tt=(Ae=o.launcher)==null?void 0:Ae.mobileBreakpoint)!=null?tt:640;if(M&&y.innerWidth<=O||!pf(o,L))return;let N=(dt=(ct=(qe=o.launcher)==null?void 0:qe.width)!=null?ct:o.launcherWidth)!=null?dt:fo,z=(Ge=(Ue=(Le=(Pe=o.features)==null?void 0:Pe.artifacts)==null?void 0:Le.layout)==null?void 0:Ue.expandedPanelWidth)!=null?Ge:"min(720px, calc(100vw - 24px))";qn.artifacts.length>0&&!In?(de.style.width=z,de.style.maxWidth=z):(de.style.width=N,de.style.maxWidth=N)},typeof ResizeObserver!="undefined"&&(zn=new ResizeObserver(()=>{Gn()}),zn.observe(de))}else de.appendChild(q),k()&&Xe&&(We.peekBanner&&Xe.appendChild(We.peekBanner),Xe.appendChild(Ve));e.appendChild(Me),Xe&&e.appendChild(Xe);let yo=()=>{var Be,Fe,ye,_t,Ot,Gt,Ct,qt,Qn,on,Ye,Pt,cn,uo,Zn,Sr,Ar,es,ts,Yt,Tr,pr,ur,Go,ot,vn,Pn,rn;if(k()){de.style.width="100%",de.style.maxWidth="100%";let pt=(Fe=(Be=o.launcher)==null?void 0:Be.composerBar)!=null?Fe:{},bt=Me.dataset.state==="expanded",ut=(ye=pt.expandedSize)!=null?ye:"anchored";if(!(bt&&ut!=="fullscreen")){q.style.background="",q.style.border="",q.style.borderRadius="",q.style.overflow="",q.style.boxShadow="";return}let dn=(Ot=(_t=o.theme)==null?void 0:_t.components)==null?void 0:Ot.panel,Ho=Oa(o),pn=(Er,Da)=>{var Ns;return Er==null||Er===""?Da:(Ns=ns(Ho,Er))!=null?Ns:Er},Wn="1px solid var(--persona-border)",mo="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",kr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";q.style.background="var(--persona-surface, #ffffff)",q.style.border=pn(dn==null?void 0:dn.border,Wn),q.style.borderRadius=pn(dn==null?void 0:dn.borderRadius,kr),q.style.boxShadow=pn(dn==null?void 0:dn.shadow,mo),q.style.overflow="hidden";return}let c=xn(o),p=(Ct=(Gt=o.launcher)==null?void 0:Gt.sidebarMode)!=null?Ct:!1,h=c||p||((Qn=(qt=o.launcher)==null?void 0:qt.fullHeight)!=null?Qn:!1),y=((on=o.launcher)==null?void 0:on.enabled)===!1,M=(Pt=(Ye=o.theme)==null?void 0:Ye.components)==null?void 0:Pt.panel,O=Oa(o),N=(pt,bt)=>{var ut;return pt==null||pt===""?bt:(ut=ns(O,pt))!=null?ut:pt},z=(cn=e.ownerDocument.defaultView)!=null?cn:window,F=(Zn=(uo=o.launcher)==null?void 0:uo.mobileFullscreen)!=null?Zn:!0,we=(Ar=(Sr=o.launcher)==null?void 0:Sr.mobileBreakpoint)!=null?Ar:640,fe=z.innerWidth<=we,te=F&&fe&&L,Te=(ts=(es=o.launcher)==null?void 0:es.position)!=null?ts:"bottom-left",_e=Te==="bottom-left"||Te==="top-left",Ae=(Tr=(Yt=o.launcher)==null?void 0:Yt.zIndex)!=null?Tr:En,tt=p||te?"none":"1px solid var(--persona-border)",qe=te?"none":p?_e?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!te&&(qe="none",tt="none");let ct=p||te?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",dt=N(M==null?void 0:M.border,tt),Pe=N(M==null?void 0:M.shadow,qe),Le=N(M==null?void 0:M.borderRadius,ct),Ue=me.scrollTop;e.style.cssText="",Me.style.cssText="",de.style.cssText="",q.style.cssText="",me.style.cssText="",Ve.style.cssText="";let Ge=()=>{var bt;if(Ue<=0)return;((bt=me.ownerDocument.defaultView)!=null?bt:window).requestAnimationFrame(()=>{if(me.scrollTop===Ue)return;let ut=me.scrollHeight-me.clientHeight;ut<=0||(me.scrollTop=Math.min(Ue,ut))})};if(te){Me.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Me.style.cssText=`
|
|
31
31
|
position: fixed !important;
|
|
32
32
|
inset: 0 !important;
|
|
33
33
|
width: 100% !important;
|
|
@@ -37,9 +37,9 @@ _Details: ${n.message}_`:o}var Fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
37
37
|
padding: 0 !important;
|
|
38
38
|
display: flex !important;
|
|
39
39
|
flex-direction: column !important;
|
|
40
|
-
z-index: ${
|
|
40
|
+
z-index: ${Ae} !important;
|
|
41
41
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
42
|
-
`,
|
|
42
|
+
`,de.style.cssText=`
|
|
43
43
|
position: relative !important;
|
|
44
44
|
display: flex !important;
|
|
45
45
|
flex-direction: column !important;
|
|
@@ -52,7 +52,7 @@ _Details: ${n.message}_`:o}var Fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
52
52
|
padding: 0 !important;
|
|
53
53
|
box-shadow: none !important;
|
|
54
54
|
border-radius: 0 !important;
|
|
55
|
-
`,
|
|
55
|
+
`,q.style.cssText=`
|
|
56
56
|
display: flex !important;
|
|
57
57
|
flex-direction: column !important;
|
|
58
58
|
flex: 1 1 0% !important;
|
|
@@ -63,20 +63,20 @@ _Details: ${n.message}_`:o}var Fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
63
63
|
overflow: hidden !important;
|
|
64
64
|
border-radius: 0 !important;
|
|
65
65
|
border: none !important;
|
|
66
|
-
`,
|
|
66
|
+
`,me.style.flex="1 1 0%",me.style.minHeight="0",me.style.overflowY="auto",Ve.style.flexShrink="0",x=!0,Ge();return}let wt=(ur=(pr=o==null?void 0:o.launcher)==null?void 0:pr.width)!=null?ur:o==null?void 0:o.launcherWidth,B=wt!=null?wt:fo;if(!p&&!c)y&&h?(de.style.width="100%",de.style.maxWidth="100%"):(de.style.width=B,de.style.maxWidth=B);else if(c)if(Oo(o).reveal==="emerge"){let bt=Oo(o).width;de.style.width=bt,de.style.maxWidth=bt}else de.style.width="100%",de.style.maxWidth="100%";if(Lo(),de.style.boxShadow=Pe,de.style.borderRadius=Le,q.style.border=dt,q.style.borderRadius=Le,c&&!te&&(M==null?void 0:M.border)===void 0&&(q.style.border="none",Oo(o).side==="right"?q.style.borderLeft="1px solid var(--persona-border)":q.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",y&&(e.style.width="100%"),Me.style.display="flex",Me.style.flexDirection="column",Me.style.flex="1 1 0%",Me.style.minHeight="0",Me.style.maxHeight="100%",Me.style.height="100%",y&&(Me.style.overflow="hidden"),de.style.display="flex",de.style.flexDirection="column",de.style.flex="1 1 0%",de.style.minHeight="0",de.style.maxHeight="100%",de.style.height="100%",de.style.overflow="hidden",q.style.display="flex",q.style.flexDirection="column",q.style.flex="1 1 0%",q.style.minHeight="0",q.style.maxHeight="100%",q.style.overflow="hidden",me.style.flex="1 1 0%",me.style.minHeight="0",me.style.overflowY="auto",Ve.style.flexShrink="0"),Me.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!p&&!y&&!c&&((Go=To[Te])!=null?Go:To["bottom-right"]).split(" ").forEach(bt=>Me.classList.add(bt)),p){let pt=(vn=(ot=o.launcher)==null?void 0:ot.sidebarWidth)!=null?vn:"420px";Me.style.cssText=`
|
|
67
67
|
position: fixed !important;
|
|
68
68
|
top: 0 !important;
|
|
69
69
|
bottom: 0 !important;
|
|
70
|
-
width: ${
|
|
70
|
+
width: ${pt} !important;
|
|
71
71
|
height: 100vh !important;
|
|
72
72
|
max-height: 100vh !important;
|
|
73
73
|
margin: 0 !important;
|
|
74
74
|
padding: 0 !important;
|
|
75
75
|
display: flex !important;
|
|
76
76
|
flex-direction: column !important;
|
|
77
|
-
z-index: ${
|
|
78
|
-
${
|
|
79
|
-
`,
|
|
77
|
+
z-index: ${Ae} !important;
|
|
78
|
+
${_e?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
79
|
+
`,de.style.cssText=`
|
|
80
80
|
position: relative !important;
|
|
81
81
|
display: flex !important;
|
|
82
82
|
flex-direction: column !important;
|
|
@@ -88,8 +88,8 @@ _Details: ${n.message}_`:o}var Fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
88
88
|
margin: 0 !important;
|
|
89
89
|
padding: 0 !important;
|
|
90
90
|
box-shadow: ${Pe} !important;
|
|
91
|
-
border-radius: ${
|
|
92
|
-
`,
|
|
91
|
+
border-radius: ${Le} !important;
|
|
92
|
+
`,de.style.setProperty("width","100%","important"),de.style.setProperty("max-width","100%","important"),q.style.cssText=`
|
|
93
93
|
display: flex !important;
|
|
94
94
|
flex-direction: column !important;
|
|
95
95
|
flex: 1 1 0% !important;
|
|
@@ -98,13 +98,13 @@ _Details: ${n.message}_`:o}var Fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
98
98
|
min-height: 0 !important;
|
|
99
99
|
max-height: 100% !important;
|
|
100
100
|
overflow: hidden !important;
|
|
101
|
-
border-radius: ${
|
|
102
|
-
border: ${
|
|
103
|
-
|
|
101
|
+
border-radius: ${Le} !important;
|
|
102
|
+
border: ${dt} !important;
|
|
103
|
+
`,Ve.style.cssText=`
|
|
104
104
|
flex-shrink: 0 !important;
|
|
105
105
|
border-top: none !important;
|
|
106
106
|
padding: 8px 16px 12px 16px !important;
|
|
107
|
-
`}if(!y&&!c){let Dt="max-height: -moz-available !important; max-height: stretch !important;",jt=f?"":"padding-top: 1.25em !important;",Bn=f?"":`z-index: ${(Ut=(Ht=o.launcher)==null?void 0:Ht.zIndex)!=null?Ut:hn} !important;`;ye.style.cssText+=Dt+jt+Bn}R()};po(),$r(e,o),Ei(e,o),Mi(e,o);let ft=[];ft.push(()=>{document.removeEventListener("keydown",zo)});let Kt=null,Gt=null;ft.push(()=>{Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null}),_n&&ft.push(()=>{_n==null||_n.disconnect(),_n=null}),ft.push(()=>{wn==null||wn(),wn=null,Ro(),Wt&&(Wt.remove(),Wt=null),yt==null||yt.element.style.removeProperty("width"),yt==null||yt.element.style.removeProperty("maxWidth")}),ie&&ft.push(()=>{we!==null&&(cancelAnimationFrame(we),we=null),Se==null||Se.destroy(),Se=null,Y==null||Y.destroy(),Y=null,Q=null});let qn=null,Ko=()=>{qn&&(qn(),qn=null),o.colorScheme==="auto"&&(qn=ou(()=>{$r(e,o)}))};Ko(),ft.push(()=>{qn&&(qn(),qn=null)});let oo=(Vc=o.features)==null?void 0:Vc.streamAnimation;if(oo!=null&&oo.type&&oo.type!=="none"){let c=$s(oo.type,oo.plugins);c&&(ml(c,e),ft.push(()=>ju(e)))}let uo=fm(Et),jn=null,E,Kn=!1,mo=_u(),Po=new Map,So=new Map,as=0,fo=ai(),go=0,ho=null,Wo=!1,lr=!1,aa=4,is=24,ia=80,Pr=new Map,mt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ls=(Uc=($c=o.voiceRecognition)==null?void 0:$c.autoResume)!=null?Uc:!1,ro=c=>{s.emit("voice:state",{active:mt.active,source:c,timestamp:Date.now()})},Rn=()=>{p(c=>({...c,voiceState:{active:mt.active,timestamp:Date.now(),manuallyDeactivated:mt.manuallyDeactivated}}))},la=()=>{var y,P;if(((y=o.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=Nl(d.voiceState),f=!!c.active,h=Number((P=c.timestamp)!=null?P:0);mt.manuallyDeactivated=!!c.manuallyDeactivated,f&&Date.now()-h<nx&&setTimeout(()=>{var N,V;mt.active||(mt.manuallyDeactivated=!1,((V=(N=o.voiceRecognition)==null?void 0:N.provider)==null?void 0:V.type)==="runtype"?E.toggleVoice().then(()=>{mt.active=E.isVoiceActive(),ro("restore"),E.isVoiceActive()&&U()}):ur("restore"))},1e3)},ca=()=>E?Fm(E.getMessages()).filter(c=>!c.__skipPersist):[];function Wr(c){if(!(i!=null&&i.save))return;let h={messages:c?Fm(c):E?ca():[],metadata:d,artifacts:Vn.artifacts,selectedArtifactId:Vn.selectedId};try{let y=i.save(h);y instanceof Promise&&y.catch(P=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",P)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let Bo=null,da=()=>ye.querySelector("#persona-scroll-container")||G,cr=()=>{Bo!==null&&(cancelAnimationFrame(Bo),Bo=null),Wo=!1},cs=()=>{ho!==null&&(cancelAnimationFrame(ho),ho=null),lr=!1,cr()},Ho=()=>{if(!yn()||de){Tt.parentNode&&Tt.remove(),Tt.style.display="none";return}Tt.parentNode!==ce&&ce.appendChild(Tt),bt();let c=Ns(G)>0;Tt.style.display=fo.isFollowing()||!c?"none":""},ds=()=>{fo.pause()&&(cs(),Ho())},Go=()=>{fo.resume(),Ho()},Yo=(c=!1)=>{fo.isFollowing()&&(!c&&!Kn||(ho!==null&&(cancelAnimationFrame(ho),ho=null),lr=!0,ho=requestAnimationFrame(()=>{ho=null,lr=!1,fo.isFollowing()&&pa(da(),c?220:140)})))},pa=(c,f=500)=>{let h=c.scrollTop,y=Ns(c),P=y-h;if(Math.abs(P)<1){go=c.scrollTop;return}if(Math.abs(P)>=ia){cr(),Wo=!0,c.scrollTop=y,go=c.scrollTop,Wo=!1;return}cr();let N=performance.now();Wo=!0;let V=O=>1-Math.pow(1-O,3),z=O=>{if(!fo.isFollowing()){cr();return}let Ae=Ns(c);Ae!==y&&(y=Ae,P=y-h);let ue=O-N,Z=Math.min(ue/f,1),he=V(Z),Ee=h+P*he;c.scrollTop=Ee,go=c.scrollTop,Z<1?Bo=requestAnimationFrame(z):(c.scrollTop=y,go=c.scrollTop,Bo=null,Wo=!1)};Bo=requestAnimationFrame(z)},ua=c=>{let f=new Map;c.forEach(h=>{let y=Pr.get(h.id);f.set(h.id,{streaming:h.streaming,role:h.role}),!y&&h.role==="assistant"&&s.emit("assistant:message",h),h.role==="assistant"&&(y!=null&&y.streaming)&&h.streaming===!1&&s.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(y?h.approval.status!=="pending"&&s.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):s.emit("approval:requested",{approval:h.approval,message:h}))}),Pr.clear(),f.forEach((h,y)=>{Pr.set(y,h)})},dr=(c,f,h)=>{var Xe,at,it,Pe,Re,je;let y=document.createElement("div"),N=(()=>{var Me;let R=r.find(Be=>Be.renderLoadingIndicator);if(R!=null&&R.renderLoadingIndicator)return R.renderLoadingIndicator;if((Me=o.loadingIndicator)!=null&&Me.render)return o.loadingIndicator.render})(),V=(R,Me)=>Me==null?!1:typeof Me=="string"?(R.textContent=Me,!0):(R.appendChild(Me),!0),z=new Set,O=new Set,Ae=r.some(R=>R.renderAskUserQuestion),ue=[],Z=[],he=o.enableComponentStreaming!==!1;if(f.forEach(R=>{var An,dn,Je,lt,Tn,mn,mr,fr,gr,Nr,_r,qt,hr,nr;z.add(R.id);let Me=Ae&&Tr(R),Be=!Me&&R.role==="assistant"&&!R.variant&&he&&Wm(R);if(!Be&&So.has(R.id)){let ht=c.querySelector(`#wrapper-${R.id}`);ht==null||ht.removeAttribute("data-preserve-runtime"),So.delete(R.id)}let Ge=Tr(R)?`:${(An=R.agentMetadata)!=null&&An.askUserQuestionAnswered?"a":"u"}:${(dn=R.agentMetadata)!=null&&dn.askUserQuestionAnswers?Object.keys(R.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ce=Nu(R,as)+Ge,Lt=Me||Be?null:Vu(mo,R.id,Ce);if(Lt){y.appendChild(Lt.cloneNode(!0)),Tr(R)&&((Je=R.toolCall)!=null&&Je.id)&&((lt=R.agentMetadata)==null?void 0:lt.awaitingLocalTool)===!0&&!((Tn=R.agentMetadata)!=null&&Tn.askUserQuestionAnswered)&&(O.add(R.toolCall.id),Ai(R,o,He.composerOverlay));return}let st=null,Xt=r.find(ht=>!!(R.variant==="reasoning"&&ht.renderReasoning||R.variant==="tool"&&ht.renderToolCall||R.variant==="approval"&&ht.renderApproval||!R.variant&&ht.renderMessage)),cn=(mn=o.layout)==null?void 0:mn.messages;if(Tr(R)&&((mr=R.agentMetadata)==null?void 0:mr.askUserQuestionAnswered)===!0){Po.delete(R.id);let ht=c.querySelector(`#wrapper-${R.id}`);ht==null||ht.removeAttribute("data-preserve-runtime");return}if(Tr(R)&&((gr=(fr=o.features)==null?void 0:fr.askUserQuestion)==null?void 0:gr.enabled)!==!1){let ht=r.find(Pn=>typeof Pn.renderAskUserQuestion=="function");if(ht&&It.current){let Pn=Po.get(R.id),Oo=Pn!==Ce,kn=null;if(Oo){let{payload:Ut,complete:Dt}=Qr(R),jt=R.id,Bn=()=>{var Yn;return(Yn=It.current)==null?void 0:Yn.getMessages().find(en=>en.id===jt)};kn=ht.renderAskUserQuestion({message:R,payload:Ut,complete:Dt,resolve:Yn=>{var To;let en=Bn();en&&((To=It.current)==null||To.resolveAskUserQuestion(en,Yn))},dismiss:()=>{var en,To,No;let Yn=Bn();(en=Yn==null?void 0:Yn.agentMetadata)!=null&&en.awaitingLocalTool&&((To=It.current)==null||To.markAskUserQuestionResolved(Yn),(No=It.current)==null||No.resolveAskUserQuestion(Yn,"(dismissed)"))},config:o})}let Wn=Pn!=null;if(Oo&&kn===null&&!Wn){((Nr=R.agentMetadata)==null?void 0:Nr.awaitingLocalTool)===!0&&!((_r=R.agentMetadata)!=null&&_r.askUserQuestionAnswered)&&(O.add(R.toolCall.id),Ai(R,o,He.composerOverlay));return}let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${R.id}`,Ht.setAttribute("data-wrapper-id",R.id),Ht.setAttribute("data-ask-plugin-stub","true"),Ht.setAttribute("data-preserve-runtime","true"),y.appendChild(Ht),ue.push({messageId:R.id,fingerprint:Ce,bubble:kn});return}else{((qt=R.agentMetadata)==null?void 0:qt.awaitingLocalTool)===!0&&!((hr=R.agentMetadata)!=null&&hr.askUserQuestionAnswered)&&(O.add(R.toolCall.id),Ai(R,o,He.composerOverlay));return}}else if(Xt)if(R.variant==="reasoning"&&R.reasoning&&Xt.renderReasoning){if(!se)return;st=Xt.renderReasoning({message:R,defaultRenderer:()=>xl(R,o),config:o})}else if(R.variant==="tool"&&R.toolCall&&Xt.renderToolCall){if(!fe)return;st=Xt.renderToolCall({message:R,defaultRenderer:()=>wl(R,o),config:o})}else if(R.variant==="approval"&&R.approval&&Xt.renderApproval){if(o.approval===!1)return;st=Xt.renderApproval({message:R,defaultRenderer:()=>Ll(R,o),config:o})}else Xt.renderMessage&&(st=Xt.renderMessage({message:R,defaultRenderer:()=>{let ht=vl(R,h,cn,o.messageActions,te,{loadingIndicatorRenderer:N,widgetConfig:o});return R.role!=="user"&&Wl(ht,R,o,E),ht},config:o}));if(!st&&Be){let ht=Bm(R);if(ht){let Pn=So.get(R.id),Oo=Pn!==Ce,kn=o.wrapComponentDirectiveInBubble!==!1,Wn=null;if(Oo){let Ht=Rm(ht,{config:o,message:R,transform:h});if(Ht)if(kn){let Ut=document.createElement("div");if(Ut.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ut.id=`bubble-${R.id}`,Ut.setAttribute("data-message-id",R.id),R.content&&R.content.trim()){let Dt=document.createElement("div");Dt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Dt.innerHTML=h({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),Ut.appendChild(Dt)}Ut.appendChild(Ht),Wn=Ut}else{let Ut=document.createElement("div");if(Ut.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ut.id=`bubble-${R.id}`,Ut.setAttribute("data-message-id",R.id),Ut.setAttribute("data-persona-component-directive","true"),R.content&&R.content.trim()){let Dt=document.createElement("div");Dt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Dt.innerHTML=h({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),Ut.appendChild(Dt)}Ut.appendChild(Ht),Wn=Ut}}if(Wn||Pn!=null){let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${R.id}`,Ht.setAttribute("data-wrapper-id",R.id),Ht.setAttribute("data-component-directive-stub","true"),Ht.setAttribute("data-preserve-runtime","true"),kn||Ht.classList.add("persona-w-full"),y.appendChild(Ht),Z.push({messageId:R.id,fingerprint:Ce,bubble:Wn});return}}}if(!st)if(R.variant==="reasoning"&&R.reasoning){if(!se)return;st=xl(R,o)}else if(R.variant==="tool"&&R.toolCall){if(!fe)return;st=wl(R,o)}else if(R.variant==="approval"&&R.approval){if(o.approval===!1)return;st=Ll(R,o)}else{let ht=(nr=o.layout)==null?void 0:nr.messages;ht!=null&&ht.renderUserMessage&&R.role==="user"?st=ht.renderUserMessage({message:R,config:o,streaming:!!R.streaming}):ht!=null&&ht.renderAssistantMessage&&R.role==="assistant"?st=ht.renderAssistantMessage({message:R,config:o,streaming:!!R.streaming}):st=vl(R,h,ht,o.messageActions,te,{loadingIndicatorRenderer:N,widgetConfig:o}),R.role!=="user"&&st&&Wl(st,R,o,E)}let Pt=document.createElement("div");Pt.className="persona-flex",Pt.id=`wrapper-${R.id}`,Pt.setAttribute("data-wrapper-id",R.id),R.role==="user"&&Pt.classList.add("persona-justify-end"),(st==null?void 0:st.getAttribute("data-persona-component-directive"))==="true"&&Pt.classList.add("persona-w-full"),Pt.appendChild(st),$u(mo,R.id,Ce,Pt),y.appendChild(Pt)}),He.composerOverlay&&He.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Me=>{let Be=Me.getAttribute("data-persona-ask-sheet-for");Be&&!O.has(Be)&&Zr(He.composerOverlay,Be)}),(at=(Xe=o.features)==null?void 0:Xe.toolCallDisplay)!=null&&at.grouped){let R=[],Me=[];f.forEach(Be=>{if(Be.variant==="tool"&&Be.toolCall&&fe){Me.push(Be);return}Me.length>1&&R.push(Me),Me=[]}),Me.length>1&&R.push(Me),R.forEach((Be,Ge)=>{var dn,Je;let Ce=Be.map(lt=>Array.from(y.children).find(Tn=>Tn instanceof HTMLElement&&Tn.getAttribute("data-wrapper-id")===lt.id)).filter(lt=>!!lt);if(Ce.length<2)return;let Lt=document.createElement("div");Lt.className="persona-flex",Lt.id=`wrapper-tool-group-${Ge}-${Be[0].id}`,Lt.setAttribute("data-wrapper-id",`tool-group-${Ge}-${Be[0].id}`);let st=document.createElement("div");st.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",st.setAttribute("data-persona-tool-group","true");let Xt=document.createElement("div");Xt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let cn=`Called ${Be.length} tools`,Pt=(Je=(dn=o.toolCall)==null?void 0:dn.renderGroupedSummary)==null?void 0:Je.call(dn,{messages:Be,toolCalls:Be.map(lt=>lt.toolCall).filter(lt=>!!lt),defaultSummary:cn,config:o});V(Xt,Pt)||(Xt.textContent=cn);let An=document.createElement("div");An.className="persona-tool-group-stack persona-flex persona-flex-col",st.append(Xt,An),Lt.appendChild(st),Ce[0].before(Lt),Ce.forEach((lt,Tn)=>{let mn=document.createElement("div");mn.className="persona-tool-group-item persona-relative",mn.setAttribute("data-persona-tool-group-item","true"),Tn<Ce.length-1&&mn.setAttribute("data-persona-tool-group-connector","true"),mn.appendChild(lt),An.appendChild(mn)})})}Uu(mo,z);let Ee=f.some(R=>R.role==="assistant"&&R.streaming),Ne=f[f.length-1],tt=(Ne==null?void 0:Ne.role)==="assistant"&&!Ne.streaming&&Ne.variant!=="approval";if(Kn&&f.some(R=>R.role==="user")&&!Ee&&!tt){let R={config:o,streaming:!0,location:"standalone",defaultRenderer:Ys},Me=r.find(Ge=>Ge.renderLoadingIndicator),Be=null;if(Me!=null&&Me.renderLoadingIndicator&&(Be=Me.renderLoadingIndicator(R)),Be===null&&((it=o.loadingIndicator)!=null&&it.render)&&(Be=o.loadingIndicator.render(R)),Be===null&&(Be=Ys()),Be){let Ge=document.createElement("div"),Ce=((Pe=o.loadingIndicator)==null?void 0:Pe.showBubble)!==!1;Ge.className=Ce?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ge.setAttribute("data-typing-indicator","true"),Ge.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ge.appendChild(Be);let Lt=document.createElement("div");Lt.className="persona-flex",Lt.id="wrapper-typing-indicator",Lt.setAttribute("data-wrapper-id","typing-indicator"),Lt.appendChild(Ge),y.appendChild(Lt)}}if(!Kn&&f.length>0){let R=f[f.length-1],Me={config:o,lastMessage:R,messageCount:f.length},Be=r.find(Ce=>Ce.renderIdleIndicator),Ge=null;if(Be!=null&&Be.renderIdleIndicator&&(Ge=Be.renderIdleIndicator(Me)),Ge===null&&((Re=o.loadingIndicator)!=null&&Re.renderIdle)&&(Ge=o.loadingIndicator.renderIdle(Me)),Ge){let Ce=document.createElement("div"),Lt=((je=o.loadingIndicator)==null?void 0:je.showBubble)!==!1;Ce.className=Lt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ce.setAttribute("data-idle-indicator","true"),Ce.appendChild(Ge);let st=document.createElement("div");st.className="persona-flex",st.id="wrapper-idle-indicator",st.setAttribute("data-wrapper-id","idle-indicator"),st.appendChild(Ce),y.appendChild(st)}}if(ri(c,y),ue.length>0)for(let{messageId:R,fingerprint:Me,bubble:Be}of ue){let Ge=c.querySelector(`#wrapper-${R}`);Ge&&Be!==null&&(Ge.replaceChildren(Be),Ge.setAttribute("data-bubble-fp",Me),Po.set(R,Me))}if(Po.size>0)for(let R of Po.keys())z.has(R)||Po.delete(R);if(Z.length>0)for(let{messageId:R,fingerprint:Me,bubble:Be}of Z){let Ge=c.querySelector(`#wrapper-${R}`);Ge&&Be!==null&&(Ge.replaceChildren(Be),Ge.setAttribute("data-bubble-fp",Me),So.set(R,Me))}if(So.size>0)for(let R of So.keys())z.has(R)||So.delete(R)},Xo=null,ma=()=>{var h;if(Xo)return;let c=y=>{let P=y.composedPath();P.includes(ye)||Ue&&P.includes(Ue)||Bt(!1,"user")};Xo=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},ps=()=>{var f;if(!Xo)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("pointerdown",Xo,!0),Xo=null};ft.push(()=>ps());let Qo=null,fa=()=>{var h;if(Qo)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Bt(!1,"user"))};Qo=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},us=()=>{var f;if(!Qo)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("keydown",Qo,!0),Qo=null};ft.push(()=>us());let Jo=!1,ms=new Set,ga=()=>{var f,h,y,P;let c=(y=(h=(f=o.launcher)==null?void 0:f.composerBar)==null?void 0:h.peek)==null?void 0:y.streamAnimation;return c||((P=o.features)==null?void 0:P.streamAnimation)},Do=()=>{var at,it,Pe,Re;if(!k())return;let c=He.peekBanner,f=He.peekTextNode;if(!c||!f)return;if(T){c.classList.remove("persona-pill-peek--visible");return}let h=(at=E==null?void 0:E.getMessages())!=null?at:[],y;for(let je=h.length-1;je>=0;je--){let R=h[je];if(R.role==="assistant"&&R.content){y=R;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let P=y.content,N=!!y.streaming,V=ga(),z=ci(V),O=z.type!=="none"?$s(z.type,V==null?void 0:V.plugins):null,Ae=((it=O==null?void 0:O.isAnimating)==null?void 0:it.call(O,y))===!0,ue=O!==null&&(N||Ae);ue&&O&&!ms.has(O.name)&&(ml(O,e),ms.add(O.name));let Z=ue&&(O!=null&&O.containerClass)?O.containerClass:null,he=(Pe=f.dataset.personaPeekStreamClass)!=null?Pe:null;he&&he!==Z&&(f.classList.remove(he),delete f.dataset.personaPeekStreamClass),Z&&he!==Z&&(f.classList.add(Z),f.dataset.personaPeekStreamClass=Z),ue?(f.style.setProperty("--persona-stream-step",`${z.speed}ms`),f.style.setProperty("--persona-stream-duration",`${z.duration}ms`)):(f.style.removeProperty("--persona-stream-step"),f.style.removeProperty("--persona-stream-duration"));let Ee=ue?di(P,z.buffer,O,y,N):P;if(ue&&z.placeholder==="skeleton"&&N&&(!Ee||!Ee.trim())){let je=document.createElement("div"),R=zs();R.classList.add("persona-pill-peek__skeleton"),je.appendChild(R),ri(f,je)}else{let je=Math.max(0,Ee.length-100),R=Ee.length>100?Ee.slice(-100):Ee,Me=Is(R);if(!ue||!O){let Be=Ee.length>100?`\u2026${R}`:R;f.textContent!==Be&&(f.textContent=Be)}else{let Be=Me;(O.wrap==="char"||O.wrap==="word")&&(Be=Us(Me,O.wrap,`peek-${y.id}`,{skipTags:O.skipTags,startIndex:je}));let Ge=document.createElement("div");if(Ge.innerHTML=Be,O.useCaret&&R.length>0){let Ce=pi(),Lt=Ge.querySelectorAll(".persona-stream-char, .persona-stream-word"),st=Lt[Lt.length-1];st!=null&&st.parentNode?st.parentNode.insertBefore(Ce,st.nextSibling):Ge.appendChild(Ce)}ri(f,Ge),(Re=O.onAfterRender)==null||Re.call(O,{container:f,bubble:c,messageId:y.id,message:y,speed:z.speed,duration:z.duration})}}let Xe=Kn||Jo;c.classList.toggle("persona-pill-peek--visible",Xe)};if(k()){let c=He.peekBanner;if(c){let y=P=>{P.preventDefault(),P.stopPropagation(),Bt(!0,"user")};c.addEventListener("pointerdown",y),ft.push(()=>{c.removeEventListener("pointerdown",y)})}let f=()=>{Jo||(Jo=!0,Do())},h=()=>{Jo&&(Jo=!1,Do())};le.addEventListener("pointerenter",f),le.addEventListener("pointerleave",h),ft.push(()=>{le.removeEventListener("pointerenter",f),le.removeEventListener("pointerleave",h)}),Ue&&(Ue.addEventListener("pointerenter",f),Ue.addEventListener("pointerleave",h),ft.push(()=>{Ue.removeEventListener("pointerenter",f),Ue.removeEventListener("pointerleave",h)}))}let ha=c=>{var he,Ee,Ne,tt,Xe,at,it,Pe;let f=(Ee=(he=o.launcher)==null?void 0:he.composerBar)!=null?Ee:{},h=(Ne=f.expandedSize)!=null?Ne:"anchored",y=(tt=f.bottomOffset)!=null?tt:"16px",P=f.collapsedMaxWidth,N=(Xe=f.expandedMaxWidth)!=null?Xe:"880px",V=(at=f.expandedTopOffset)!=null?at:"5vh",z=(it=f.modalMaxWidth)!=null?it:"880px",O=(Pe=f.modalMaxHeight)!=null?Pe:"min(90vh, 800px)",Ae="calc(100vw - 32px)",ue="var(--persona-pill-area-height, 80px)",Z=ye.style;if(Z.left="",Z.right="",Z.top="",Z.bottom="",Z.transform="",Z.width="",Z.maxWidth="",Z.height="",Z.maxHeight="",Ue){let Re=Ue.style;Re.bottom=y,Re.width=P!=null?P:""}if(c&&h!=="fullscreen"){if(h==="modal"){Z.top="50%",Z.left="50%",Z.transform="translate(-50%, -50%)",Z.bottom="auto",Z.right="auto",Z.width=z,Z.maxWidth=Ae,Z.maxHeight=O,Z.height=O;return}Z.left="50%",Z.transform="translateX(-50%)",Z.bottom=`calc(${y} + ${ue})`,Z.top=V,Z.width=N,Z.maxWidth=Ae}},Zo=()=>{var O,Ae,ue,Z,he,Ee,Ne,tt;if(!C())return;if(k()){let at=(ue=((Ae=(O=o.launcher)==null?void 0:O.composerBar)!=null?Ae:{}).expandedSize)!=null?ue:"anchored",it=T?"expanded":"collapsed";ye.dataset.state=it,ye.dataset.expandedSize=at,Ue&&(Ue.dataset.state=it,Ue.dataset.expandedSize=at),ye.style.removeProperty("display"),ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ha(T),ce.style.display=T?"flex":"none",po(),T?(ma(),fa()):(ps(),us()),Do();return}let c=pn(o),f=(Z=e.ownerDocument.defaultView)!=null?Z:window,h=(Ee=(he=o.launcher)==null?void 0:he.mobileBreakpoint)!=null?Ee:640,y=(tt=(Ne=o.launcher)==null?void 0:Ne.mobileFullscreen)!=null?tt:!0,P=f.innerWidth<=h,N=y&&P&&I,V=Mo(o).reveal;T?(ye.style.removeProperty("display"),ye.style.display=c?"flex":"",ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-95","persona-opacity-0"),le.classList.add("persona-scale-100","persona-opacity-100"),Ie?Ie.element.style.display="none":Ye&&(Ye.style.display="none")):(c?c&&(V==="overlay"||V==="push")&&!N?(ye.style.removeProperty("display"),ye.style.display="flex",ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ye.style.setProperty("display","none","important"),ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ye.style.display="",ye.classList.add("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100"),le.classList.add("persona-scale-95","persona-opacity-0")),Ie?Ie.element.style.display=c?"none":"":Ye&&(Ye.style.display=c?"none":""))},Bt=(c,f="user")=>{var N,V;if(!C()||T===c)return;let h=T;T=c,Zo();let y=(()=>{var Ne,tt,Xe,at,it,Pe,Re,je,R,Me;let z=(tt=(Ne=o.launcher)==null?void 0:Ne.sidebarMode)!=null?tt:!1,O=(Xe=e.ownerDocument.defaultView)!=null?Xe:window,Ae=(it=(at=o.launcher)==null?void 0:at.mobileFullscreen)!=null?it:!0,ue=(Re=(Pe=o.launcher)==null?void 0:Pe.mobileBreakpoint)!=null?Re:640,Z=O.innerWidth<=ue,he=pn(o)&&Ae&&Z,Ee=k()&&((Me=(R=(je=o.launcher)==null?void 0:je.composerBar)==null?void 0:R.expandedSize)!=null?Me:"fullscreen")==="fullscreen";return z||Ae&&Z&&I||he||Ee})();if(T&&y){if(!Kt){let z=e.getRootNode(),O=z instanceof ShadowRoot?z.host:e.closest(".persona-host");O&&(Kt=fl(O,(V=(N=o.launcher)==null?void 0:N.zIndex)!=null?V:hn))}Gt||(Gt=gl(e.ownerDocument))}else T||(Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null);T&&(Rt(),Yo(!0));let P={open:T,source:f,timestamp:Date.now()};T&&!h?s.emit("widget:opened",P):!T&&h&&s.emit("widget:closed",P),s.emit("widget:state",{open:T,launcherEnabled:I,voiceActive:mt.active,streaming:E.isStreaming()})},Br=c=>{Vt(c?"stop":"send"),q&&(q.disabled=c),uo.buttons.forEach(f=>{f.disabled=c}),$e.dataset.personaComposerStreaming=c?"true":"false",$e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=c)})},Hr=()=>{mt.active||pe&&pe.focus()};s.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Hr(),200)});let fs=()=>{var h,y,P,N,V,z,O,Ae,ue,Z,he;Dn.textContent=(y=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",Jn.textContent=(N=(P=o.copy)==null?void 0:P.welcomeSubtitle)!=null?N:"Ask anything about your account or products.",pe.placeholder=(z=(V=o.copy)==null?void 0:V.inputPlaceholder)!=null?z:"How can I help...";let c=G.querySelector("[data-persona-intro-card]");if(c){let Ee=((O=o.copy)==null?void 0:O.showWelcomeCard)!==!1;c.style.display=Ee?"":"none",Ee?(G.classList.remove("persona-gap-3"),G.classList.add("persona-gap-6")):(G.classList.remove("persona-gap-6"),G.classList.add("persona-gap-3"))}!((ue=(Ae=o.sendButton)==null?void 0:Ae.useIcon)!=null&&ue)&&!(E!=null&&E.isStreaming())&&(ae.textContent=(he=(Z=o.copy)==null?void 0:Z.sendButtonLabel)!=null?he:"Send"),pe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',pe.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{p(f=>({...f,sessionId:c}))}});let Ao=null,ba=()=>{Ao==null&&(Ao=setInterval(()=>{let c=Ve.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Ao),Ao=null;return}let f=Date.now();c.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=ja(f-y))})},100))};if(E=new ni(o,{onMessagesChanged(c){dr(Ve,c,me),ba(),E&&(c.some(P=>P.role==="user")?uo.render([],E,pe,c):uo.render(o.suggestionChips,E,pe,c,o.suggestionChipsConfig)),Yo(!Kn),ua(c);let f=[...c].reverse().find(y=>y.role==="user"),h=mt.lastUserMessageId;f&&f.id!==h&&(mt.lastUserMessageId=f.id,s.emit("user:message",f)),mt.lastUserMessageWasVoice=!!(f!=null&&f.viaVoice),Wr(c),Do()},onStatusChanged(c){var y;let f=(y=o.statusIndicator)!=null?y:{};nt(ln,(P=>{var N,V,z,O;return P==="idle"?(N=f.idleText)!=null?N:gn.idle:P==="connecting"?(V=f.connectingText)!=null?V:gn.connecting:P==="connected"?(z=f.connectedText)!=null?z:gn.connected:P==="error"?(O=f.errorText)!=null?O:gn.error:gn[P]})(c),f,c)},onStreamingChanged(c){Kn=c,Br(c),E&&dr(Ve,E.getMessages(),me),c||Yo(!0),Do()},onVoiceStatusChanged(c){var f,h;if(((h=(f=o.voiceRecognition)==null?void 0:f.provider)==null?void 0:h.type)==="runtype")switch(c){case"listening":break;case"processing":ee(),B();break;case"speaking":ee(),J();break;default:c==="idle"&&E.isBargeInActive()?(ee(),U(),q==null||q.setAttribute("aria-label","End voice session")):(mt.active=!1,ee(),ro("system"),Rn());break}},onArtifactsState(c){Vn=c,zn(),Wr()}}),It.current=E,((qc=(zc=o.voiceRecognition)==null?void 0:zc.provider)==null?void 0:qc.type)==="runtype")try{E.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}o.clientToken&&E.initClientSession().catch(c=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(Y||o.onSSEEvent)&&E.setSSEEventCallback((c,f)=>{var h;(h=o.onSSEEvent)==null||h.call(o,c,f),xe==null||xe.processEvent(c,f),Y==null||Y.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(f)})}),l&&l.then(c=>{var f,h,y;c&&(c.metadata&&(d=Nl(c.metadata),M.syncFromMetadata()),(f=c.messages)!=null&&f.length&&E.hydrateMessages(c.messages),(h=c.artifacts)!=null&&h.length&&E.hydrateArtifacts(c.artifacts,(y=c.selectedArtifactId)!=null?y:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let gs=()=>{var f,h,y;!k()||T||!((y=(h=(f=o.launcher)==null?void 0:f.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||Bt(!0,"auto")},hs=c=>{var P;if(c.preventDefault(),E.isStreaming()){E.cancel(),xe==null||xe.reset(),Se==null||Se.update();return}let f=pe.value.trim(),h=(P=et==null?void 0:et.hasAttachments())!=null?P:!1;if(!f&&!h)return;gs();let y;h&&(y=[],y.push(...et.getContentParts()),f&&y.push(cl(f))),pe.value="",pe.style.height="auto",pr(),E.sendMessage(f,{contentParts:y}),h&&et.clearAttachments()},ya=()=>{var c;return((c=o.features)==null?void 0:c.composerHistory)!==!1},Dr={...si},Fr=!1,pr=()=>{Dr={...si}},va=()=>E.getMessages().filter(c=>c.role==="user").map(c=>{var f;return(f=c.content)!=null?f:""}).filter(c=>c.length>0),xa=c=>{if(!pe)return;Fr=!0,pe.value=c,pe.dispatchEvent(new Event("input",{bubbles:!0})),Fr=!1;let f=pe.value.length;pe.setSelectionRange(f,f)},bs=()=>{Fr||pr()},ys=c=>{if(pe){if(ya()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let f=pe.selectionStart===0&&pe.selectionEnd===0,h=Ou({direction:c.key==="ArrowUp"?"up":"down",history:va(),currentValue:pe.value,atStart:f,state:Dr});if(Dr=h.state,h.handled){c.preventDefault(),h.value!==void 0&&xa(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(E.isStreaming()){c.preventDefault();return}pr(),c.preventDefault(),ae.click()}}},vs=c=>{c.key!=="Escape"||c.isComposing||E.isStreaming()&&c.composedPath().includes(ce)&&(E.cancel(),xe==null||xe.reset(),Se==null||Se.update(),pr(),c.preventDefault(),c.stopImmediatePropagation())},xs=async c=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!et)return;let f=rx(c.clipboardData);f.length!==0&&(c.preventDefault(),await et.handleFiles(f))},Cn=null,Gn=!1,Fo=null,rt=null,ws=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ur=(c="user")=>{var N,V,z,O,Ae,ue,Z;if(Gn||E.isStreaming())return;let f=ws();if(!f)return;Cn=new f;let y=(V=((N=o.voiceRecognition)!=null?N:{}).pauseDuration)!=null?V:2e3;Cn.continuous=!0,Cn.interimResults=!0,Cn.lang="en-US";let P=pe.value;Cn.onresult=he=>{let Ee="",Ne="";for(let Xe=0;Xe<he.results.length;Xe++){let at=he.results[Xe],it=at[0].transcript;at.isFinal?Ee+=it+" ":Ne=it}let tt=P+Ee+Ne;pe.value=tt,Fo&&clearTimeout(Fo),(Ee||Ne)&&(Fo=window.setTimeout(()=>{let Xe=pe.value.trim();Xe&&Cn&&Gn&&(bo(),pe.value="",pe.style.height="auto",E.sendMessage(Xe,{viaVoice:!0}))},y))},Cn.onerror=he=>{he.error!=="no-speech"&&bo()},Cn.onend=()=>{if(Gn){let he=pe.value.trim();he&&he!==P.trim()&&(pe.value="",pe.style.height="auto",E.sendMessage(he,{viaVoice:!0})),bo()}};try{if(Cn.start(),Gn=!0,mt.active=!0,c!=="system"&&(mt.manuallyDeactivated=!1),ro(c),Rn(),q){let he=(z=o.voiceRecognition)!=null?z:{};rt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(O=he.iconName)!=null?O:"mic",iconSize:parseFloat((Z=(ue=he.iconSize)!=null?ue:(Ae=o.sendButton)==null?void 0:Ae.size)!=null?Z:"40")||24};let Ee=he.recordingBackgroundColor,Ne=he.recordingIconColor,tt=he.recordingBorderColor;if(q.classList.add("persona-voice-recording"),q.style.backgroundColor=Ee!=null?Ee:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=Ne!=null?Ne:"var(--persona-voice-recording-indicator, #ffffff)",Ne){let Xe=q.querySelector("svg");Xe&&Xe.setAttribute("stroke",Ne)}tt&&(q.style.borderColor=tt),q.setAttribute("aria-label","Stop voice recognition")}}catch{bo("system")}},bo=(c="user")=>{if(Gn){if(Gn=!1,Fo&&(clearTimeout(Fo),Fo=null),Cn){try{Cn.stop()}catch{}Cn=null}if(mt.active=!1,ro(c),Rn(),q){if(q.classList.remove("persona-voice-recording"),rt){q.style.backgroundColor=rt.backgroundColor,q.style.color=rt.color,q.style.borderColor=rt.borderColor;let f=q.querySelector("svg");f&&f.setAttribute("stroke",rt.color||"currentColor"),rt=null}q.setAttribute("aria-label","Start voice recognition")}}},wa=(c,f)=>{var at,it,Pe,Re,je,R,Me,Be;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((at=c==null?void 0:c.provider)==null?void 0:at.type)==="runtype";if(!(h||y))return null;let N=b("div","persona-send-button-wrapper"),V=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");V.type="button",V.setAttribute("aria-label","Start voice recognition");let z=(it=c==null?void 0:c.iconName)!=null?it:"mic",O=(Pe=f==null?void 0:f.size)!=null?Pe:"40px",Ae=(Re=c==null?void 0:c.iconSize)!=null?Re:O,ue=parseFloat(Ae)||24,Z=(je=c==null?void 0:c.backgroundColor)!=null?je:f==null?void 0:f.backgroundColor,he=(R=c==null?void 0:c.iconColor)!=null?R:f==null?void 0:f.textColor;V.style.width=Ae,V.style.height=Ae,V.style.minWidth=Ae,V.style.minHeight=Ae,V.style.fontSize="18px",V.style.lineHeight="1",he?V.style.color=he:V.style.color="var(--persona-text, #111827)";let Ne=Te(z,ue,he||"currentColor",1.5);Ne?V.appendChild(Ne):V.textContent="\u{1F3A4}",Z?V.style.backgroundColor=Z:V.style.backgroundColor="",c!=null&&c.borderWidth&&(V.style.borderWidth=c.borderWidth,V.style.borderStyle="solid"),c!=null&&c.borderColor&&(V.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(V.style.paddingLeft=c.paddingX,V.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(V.style.paddingTop=c.paddingY,V.style.paddingBottom=c.paddingY),N.appendChild(V);let tt=(Me=c==null?void 0:c.tooltipText)!=null?Me:"Start voice recognition";if(((Be=c==null?void 0:c.showTooltip)!=null?Be:!1)&&tt){let Ge=b("div","persona-send-button-tooltip");Ge.textContent=tt,N.appendChild(Ge)}return{micButton:V,micButtonWrapper:N}},er=()=>{var f,h,y,P,N;if(!q||rt)return;let c=(f=o.voiceRecognition)!=null?f:{};rt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(h=c.iconName)!=null?h:"mic",iconSize:parseFloat((N=(P=c.iconSize)!=null?P:(y=o.sendButton)==null?void 0:y.size)!=null?N:"40")||24}},Ke=(c,f)=>{var N,V,z,O,Ae;if(!q)return;let h=q.querySelector("svg");h&&h.remove();let y=(Ae=rt==null?void 0:rt.iconSize)!=null?Ae:parseFloat((O=(z=(N=o.voiceRecognition)==null?void 0:N.iconSize)!=null?z:(V=o.sendButton)==null?void 0:V.size)!=null?O:"40")||24,P=Te(c,y,f,1.5);P&&q.appendChild(P)},A=()=>{q&&q.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},U=()=>{var P;if(!q)return;er();let c=(P=o.voiceRecognition)!=null?P:{},f=c.recordingBackgroundColor,h=c.recordingIconColor,y=c.recordingBorderColor;if(A(),q.classList.add("persona-voice-recording"),q.style.backgroundColor=f!=null?f:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let N=q.querySelector("svg");N&&N.setAttribute("stroke",h)}y&&(q.style.borderColor=y),q.setAttribute("aria-label","Stop voice recognition")},B=()=>{var z,O,Ae,ue,Z,he,Ee,Ne;if(!q)return;er();let c=(z=o.voiceRecognition)!=null?z:{},f=E.getVoiceInterruptionMode(),h=(O=c.processingIconName)!=null?O:"loader",y=(ue=(Ae=c.processingIconColor)!=null?Ae:rt==null?void 0:rt.color)!=null?ue:"",P=(he=(Z=c.processingBackgroundColor)!=null?Z:rt==null?void 0:rt.backgroundColor)!=null?he:"",N=(Ne=(Ee=c.processingBorderColor)!=null?Ee:rt==null?void 0:rt.borderColor)!=null?Ne:"";A(),q.classList.add("persona-voice-processing"),q.style.backgroundColor=P,q.style.borderColor=N;let V=y||"currentColor";q.style.color=V,Ke(h,V),q.setAttribute("aria-label","Processing voice input"),f==="none"&&(q.style.cursor="default")},J=()=>{var Ae,ue,Z,he,Ee,Ne,tt,Xe,at,it,Pe,Re;if(!q)return;er();let c=(Ae=o.voiceRecognition)!=null?Ae:{},f=E.getVoiceInterruptionMode(),h=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",y=(ue=c.speakingIconName)!=null?ue:h,P=(Ne=c.speakingIconColor)!=null?Ne:f==="barge-in"?(he=(Z=c.recordingIconColor)!=null?Z:rt==null?void 0:rt.color)!=null?he:"":(Ee=rt==null?void 0:rt.color)!=null?Ee:"",N=(at=c.speakingBackgroundColor)!=null?at:f==="barge-in"?(tt=c.recordingBackgroundColor)!=null?tt:"var(--persona-voice-recording-bg, #ef4444)":(Xe=rt==null?void 0:rt.backgroundColor)!=null?Xe:"",V=(Re=c.speakingBorderColor)!=null?Re:f==="barge-in"?(it=c.recordingBorderColor)!=null?it:"":(Pe=rt==null?void 0:rt.borderColor)!=null?Pe:"";A(),q.classList.add("persona-voice-speaking"),q.style.backgroundColor=N,q.style.borderColor=V;let z=P||"currentColor";q.style.color=z,Ke(y,z);let O=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";q.setAttribute("aria-label",O),f==="none"&&(q.style.cursor="default"),f==="barge-in"&&q.classList.add("persona-voice-recording")},ee=()=>{var c,f,h;q&&(A(),rt&&(q.style.backgroundColor=(c=rt.backgroundColor)!=null?c:"",q.style.color=(f=rt.color)!=null?f:"",q.style.borderColor=(h=rt.borderColor)!=null?h:"",Ke(rt.iconName,rt.color||"currentColor"),rt=null),q.style.cursor="",q.setAttribute("aria-label","Start voice recognition"))},K=()=>{var c,f;if(((f=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"){let h=E.getVoiceStatus(),y=E.getVoiceInterruptionMode();if(y==="none"&&(h==="processing"||h==="speaking"))return;if(y==="cancel"&&(h==="processing"||h==="speaking")){E.stopVoicePlayback();return}if(E.isBargeInActive()){E.stopVoicePlayback(),E.deactivateBargeIn().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Rn(),ro("user"),ee()});return}E.toggleVoice().then(()=>{mt.active=E.isVoiceActive(),mt.manuallyDeactivated=!E.isVoiceActive(),Rn(),ro("user"),E.isVoiceActive()?U():ee()});return}if(Gn){let h=pe.value.trim();mt.manuallyDeactivated=!0,Rn(),bo("user"),h&&(pe.value="",pe.style.height="auto",E.sendMessage(h))}else mt.manuallyDeactivated=!1,Rn(),ur("user")};Fn=K,q&&(q.addEventListener("click",K),ft.push(()=>{var c,f;((f=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?(E.isVoiceActive()&&E.toggleVoice(),ee()):bo("system"),q&&q.removeEventListener("click",K)}));let We=s.on("assistant:complete",()=>{ls&&(mt.active||mt.manuallyDeactivated||ls==="assistant"&&!mt.lastUserMessageWasVoice||setTimeout(()=>{var c,f;!mt.active&&!mt.manuallyDeactivated&&(((f=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?E.toggleVoice().then(()=>{mt.active=E.isVoiceActive(),ro("auto"),E.isVoiceActive()&&U()}):ur("auto"))},600))});ft.push(We);let _e=s.on("action:resubmit",()=>{setTimeout(()=>{E&&!E.isStreaming()&&E.continueConversation()},100)});ft.push(_e);let Ze=()=>{Bt(!T,"user")},Ie=null,Ye=null;if(I&&!k()){let c=r.find(f=>f.renderLauncher);if(c!=null&&c.renderLauncher){let f=c.renderLauncher({config:o,defaultRenderer:()=>Ks(o,Ze).element,onToggle:Ze});f&&(Ye=f)}Ye||(Ie=Ks(o,Ze))}Ie?e.appendChild(Ie.element):Ye&&e.appendChild(Ye),Zo(),uo.render(o.suggestionChips,E,pe,void 0,o.suggestionChipsConfig),fs(),Br(E.isStreaming()),Yo(!0),la(),H&&(!I||k()?setTimeout(()=>Hr(),0):T&&setTimeout(()=>Hr(),200));let Rt=()=>{var O,Ae,ue,Z,he,Ee,Ne,tt,Xe,at,it,Pe,Re,je,R,Me,Be,Ge,Ce,Lt,st,Xt;if(k()){bt(),Zo();return}let c=pn(o),f=(Ae=(O=o.launcher)==null?void 0:O.sidebarMode)!=null?Ae:!1,h=c||f||((Z=(ue=o.launcher)==null?void 0:ue.fullHeight)!=null?Z:!1),y=(he=e.ownerDocument.defaultView)!=null?he:window,P=(Ne=(Ee=o.launcher)==null?void 0:Ee.mobileFullscreen)!=null?Ne:!0,N=(Xe=(tt=o.launcher)==null?void 0:tt.mobileBreakpoint)!=null?Xe:640,V=y.innerWidth<=N,z=P&&V&&I;try{if(z){po(),$r(e,o);return}if(x&&(x=!1,po(),$r(e,o)),!I&&!c){le.style.height="",le.style.width="";return}if(!f&&!c){let cn=(it=(at=o==null?void 0:o.launcher)==null?void 0:at.width)!=null?it:o==null?void 0:o.launcherWidth,Pt=cn!=null?cn:io;le.style.width=Pt,le.style.maxWidth=Pt}if(Co(),!h){let cn=y.innerHeight,Pt=64,An=(Re=(Pe=o.launcher)==null?void 0:Pe.heightOffset)!=null?Re:0,dn=Math.max(200,cn-Pt),Je=Math.min(640,dn),lt=Math.max(200,Je-An);le.style.height=`${lt}px`}}finally{if(bt(),Zo(),T&&I){let Pt=((je=e.ownerDocument.defaultView)!=null?je:window).innerWidth<=((Me=(R=o.launcher)==null?void 0:R.mobileBreakpoint)!=null?Me:640),An=(Ge=(Be=o.launcher)==null?void 0:Be.sidebarMode)!=null?Ge:!1,dn=(Lt=(Ce=o.launcher)==null?void 0:Ce.mobileFullscreen)!=null?Lt:!0,Je=pn(o)&&dn&&Pt,lt=An||dn&&Pt&&I||Je;if(lt&&!Gt){let Tn=e.getRootNode(),mn=Tn instanceof ShadowRoot?Tn.host:e.closest(".persona-host");mn&&!Kt&&(Kt=fl(mn,(Xt=(st=o.launcher)==null?void 0:st.zIndex)!=null?Xt:hn)),Gt=gl(e.ownerDocument)}else lt||(Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null)}}};Rt();let nn=(jc=e.ownerDocument.defaultView)!=null?jc:window;if(nn.addEventListener("resize",Rt),ft.push(()=>nn.removeEventListener("resize",Rt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{bt()});c.observe($e),ft.push(()=>c.disconnect())}go=G.scrollTop;let Ct=G.scrollHeight,Mt=()=>{let c=G.scrollTop,f=G.scrollHeight,h=f<Ct;Ct=f;let{action:y,nextLastScrollTop:P}=ii({following:fo.isFollowing(),currentScrollTop:c,lastScrollTop:go,nearBottom:_s(G,is),userScrollThreshold:aa,isAutoScrolling:Wo||lr||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(go=P,y==="resume"){Go();return}y==="pause"&&ds()};G.addEventListener("scroll",Mt,{passive:!0}),ft.push(()=>G.removeEventListener("scroll",Mt));let on=c=>{let f=li({following:fo.isFollowing(),deltaY:c.deltaY,nearBottom:_s(G,is),resumeWhenNearBottom:!0});f==="pause"?ds():f==="resume"&&Go()};G.addEventListener("wheel",on,{passive:!0}),ft.push(()=>G.removeEventListener("wheel",on)),Tt.addEventListener("click",()=>{G.scrollTop=G.scrollHeight,go=G.scrollTop,Go(),Yo(!0)}),ft.push(()=>Tt.remove()),ft.push(()=>{cs()});let un=()=>{qe&&(jn&&(qe.removeEventListener("click",jn),jn=null),C()?(qe.style.display="",jn=()=>{Bt(!1,"user")},qe.addEventListener("click",jn)):qe.style.display="none")};un(),(()=>{let{clearChatButton:c}=He;c&&c.addEventListener("click",()=>{E.clearMessages(),mo.clear(),Go(),Zr(He.composerOverlay);try{localStorage.removeItem(ts),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ts}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ts)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let f=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(f),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}d={},M.syncFromMetadata(),Y==null||Y.clear(),xe==null||xe.reset(),Se==null||Se.update()})})(),Nt&&Nt.addEventListener("submit",hs),pe==null||pe.addEventListener("keydown",ys),pe==null||pe.addEventListener("input",bs),pe==null||pe.addEventListener("paste",xs);let Yt=(Kc=e.ownerDocument)!=null?Kc:document;Yt.addEventListener("keydown",vs,!0);let so="persona-attachment-drop-active",Cs=0,qi=()=>{Cs=0,ce.classList.remove(so)},Or=()=>{var c;return((c=o.attachments)==null?void 0:c.enabled)===!0&&et!==null},ec=c=>{!Li(c.dataTransfer)||!Or()||(Cs++,Cs===1&&ce.classList.add(so))},tc=c=>{!Li(c.dataTransfer)||!Or()||(Cs--,Cs<=0&&qi())},nc=c=>{!Li(c.dataTransfer)||!Or()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},oc=c=>{var h;if(!Li(c.dataTransfer)||!Or())return;c.preventDefault(),c.stopPropagation(),qi();let f=Array.from((h=c.dataTransfer.files)!=null?h:[]);f.length!==0&&et.handleFiles(f)},tr=!0;ce.addEventListener("dragenter",ec,tr),ce.addEventListener("dragleave",tc,tr),e.addEventListener("dragover",nc,tr),e.addEventListener("drop",oc,tr);let Ca=e.ownerDocument,rc=c=>{Or()&&c.preventDefault()},sc=c=>{Or()&&c.preventDefault()};Ca.addEventListener("dragover",rc),Ca.addEventListener("drop",sc),ft.push(()=>{Nt&&Nt.removeEventListener("submit",hs),pe==null||pe.removeEventListener("keydown",ys),pe==null||pe.removeEventListener("input",bs),pe==null||pe.removeEventListener("paste",xs),Yt.removeEventListener("keydown",vs,!0)}),ft.push(()=>{ce.removeEventListener("dragenter",ec,tr),ce.removeEventListener("dragleave",tc,tr),e.removeEventListener("dragover",nc,tr),e.removeEventListener("drop",oc,tr),Ca.removeEventListener("dragover",rc),Ca.removeEventListener("drop",sc),qi()}),ft.push(()=>{E.cancel()}),Ie?ft.push(()=>{Ie==null||Ie.destroy()}):Ye&&ft.push(()=>{Ye==null||Ye.remove()});let Zt={update(c){var en,To,No,Sa,Aa,Ta,br,ka,Ss,ed,td,nd,od,rd,sd,ad,id,ld,cd,dd,pd,ud,md,fd,gd,hd,bd,yd,vd,xd,wd,Cd,Sd,Ad,Td,kd,Ed,Md,Ld,Id,Rd,Pd,Wd,Bd,Hd,Dd,Fd,Od,Nd,_d,Vd,$d,Ud,zd,qd,jd,Kd,Gd,Yd,Xd,Qd,Jd,Zd,ep,tp,np,op,rp,sp,ap,ip,lp,cp,dp,pp,up,mp,fp,gp,hp,bp,yp,vp,xp,wp,Cp,Sp,Ap,Tp,kp,Ep,Mp,Lp,Ip,Rp,Pp,Wp,Bp,Hp,Dp,Fp,Op,Np,_p,Vp,$p,Up,zp,qp,jp,Kp,Gp,Yp;let f=o.toolCall,h=o.messageActions,y=(en=o.layout)==null?void 0:en.messages,P=o.colorScheme,N=o.loadingIndicator,V=o.iterationDisplay,z=(To=o.features)==null?void 0:To.showReasoning,O=(No=o.features)==null?void 0:No.showToolCalls,Ae=(Sa=o.features)==null?void 0:Sa.toolCallDisplay,ue=(Aa=o.features)==null?void 0:Aa.reasoningDisplay;o={...o,...c},po(),$r(e,o),Ei(e,o),Mi(e,o),zn(),o.colorScheme!==P&&Ko();let Z=Hl.getForInstance(o.plugins);r.length=0,r.push(...Z),I=(br=(Ta=o.launcher)==null?void 0:Ta.enabled)!=null?br:!0,L=(Ss=(ka=o.launcher)==null?void 0:ka.autoExpand)!=null?Ss:!1,se=(td=(ed=o.features)==null?void 0:ed.showReasoning)!=null?td:!0,fe=(od=(nd=o.features)==null?void 0:nd.showToolCalls)!=null?od:!0,be=(sd=(rd=o.features)==null?void 0:rd.scrollToBottom)!=null?sd:{},zt(),Ho();let he=ie;if(ie=(id=(ad=o.features)==null?void 0:ad.showEventStreamToggle)!=null?id:!1,ie&&!he){if(Y||(Q=new Js(ve),Y=new Qs(Le,Q),xe=xe!=null?xe:new Zs,Q.open().then(()=>Y==null?void 0:Y.restore()).catch(()=>{}),E.setSSEEventCallback((X,vt)=>{var Ot;(Ot=o.onSSEEvent)==null||Ot.call(o,X,vt),xe==null||xe.processEvent(X,vt),Y.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:X,timestamp:Date.now(),payload:JSON.stringify(vt)})})),!ut&&Fe){let X=(cd=(ld=o.features)==null?void 0:ld.eventStream)==null?void 0:cd.classNames,vt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(X!=null&&X.toggleButton?" "+X.toggleButton:"");ut=b("button",vt),ut.style.width="28px",ut.style.height="28px",ut.style.color=Mn.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let Ot=Te("activity","18px","currentColor",1.5);Ot&&ut.appendChild(Ot);let ct=He.clearChatButtonWrapper,kt=He.closeButtonWrapper,rn=ct||kt;rn&&rn.parentNode===Fe?Fe.insertBefore(ut,rn):Fe.appendChild(ut),ut.addEventListener("click",()=>{de?On():vn()})}}else!ie&&he&&(On(),ut&&(ut.remove(),ut=null),Y==null||Y.clear(),Q==null||Q.destroy(),Y=null,Q=null,xe==null||xe.reset(),xe=null);if(((dd=o.launcher)==null?void 0:dd.enabled)===!1&&Ie&&(Ie.destroy(),Ie=null),((pd=o.launcher)==null?void 0:pd.enabled)===!1&&Ye&&(Ye.remove(),Ye=null),((ud=o.launcher)==null?void 0:ud.enabled)!==!1&&!Ie&&!Ye){let X=r.find(vt=>vt.renderLauncher);if(X!=null&&X.renderLauncher){let vt=X.renderLauncher({config:o,defaultRenderer:()=>Ks(o,Ze).element,onToggle:Ze});vt&&(Ye=vt,e.appendChild(Ye))}Ye||(Ie=Ks(o,Ze),e.appendChild(Ie.element))}Ie&&Ie.update(o),ke&&((md=o.launcher)==null?void 0:md.title)!==void 0&&(ke.textContent=o.launcher.title),De&&((fd=o.launcher)==null?void 0:fd.subtitle)!==void 0&&(De.textContent=o.launcher.subtitle);let Ee=(gd=o.layout)==null?void 0:gd.header;if((Ee==null?void 0:Ee.layout)!==v&&Fe){let X=Ee?gi(o,Ee,{showClose:C(),onClose:()=>Bt(!1,"user")}):Ar({config:o,showClose:C(),onClose:()=>Bt(!1,"user")});Fe.replaceWith(X.header),Fe=X.header,_=X.iconHolder,ke=X.headerTitle,De=X.headerSubtitle,qe=X.closeButton,v=Ee==null?void 0:Ee.layout}else if(Ee&&(_&&(_.style.display=Ee.showIcon===!1?"none":""),ke&&(ke.style.display=Ee.showTitle===!1?"none":""),De&&(De.style.display=Ee.showSubtitle===!1?"none":""),qe&&(qe.style.display=Ee.showCloseButton===!1?"none":""),He.clearChatButtonWrapper)){let X=Ee.showClearChat;if(X!==void 0){He.clearChatButtonWrapper.style.display=X?"":"none";let{closeButtonWrapper:vt}=He;vt&&!vt.classList.contains("persona-absolute")&&(X?vt.classList.remove("persona-ml-auto"):vt.classList.add("persona-ml-auto"))}}let tt=((hd=o.layout)==null?void 0:hd.showHeader)!==!1;Fe&&(Fe.style.display=tt?"":"none");let Xe=((bd=o.layout)==null?void 0:bd.showFooter)!==!1;$e&&($e.style.display=Xe?"":"none"),bt(),Ho(),I!==W?I?Bt(L,"auto"):(T=!0,Zo()):L!==D&&Bt(L,"auto"),D=L,W=I,Rt(),un();let Pe=JSON.stringify(c.toolCall)!==JSON.stringify(f),Re=JSON.stringify(o.messageActions)!==JSON.stringify(h),je=JSON.stringify((yd=o.layout)==null?void 0:yd.messages)!==JSON.stringify(y),R=((vd=o.loadingIndicator)==null?void 0:vd.render)!==(N==null?void 0:N.render)||((xd=o.loadingIndicator)==null?void 0:xd.renderIdle)!==(N==null?void 0:N.renderIdle)||((wd=o.loadingIndicator)==null?void 0:wd.showBubble)!==(N==null?void 0:N.showBubble),Me=o.iterationDisplay!==V,Be=((Sd=(Cd=o.features)==null?void 0:Cd.showReasoning)!=null?Sd:!0)!==(z!=null?z:!0)||((Td=(Ad=o.features)==null?void 0:Ad.showToolCalls)!=null?Td:!0)!==(O!=null?O:!0)||JSON.stringify((kd=o.features)==null?void 0:kd.toolCallDisplay)!==JSON.stringify(Ae)||JSON.stringify((Ed=o.features)==null?void 0:Ed.reasoningDisplay)!==JSON.stringify(ue);(Pe||Re||je||R||Me||Be)&&E&&(as++,dr(Ve,E.getMessages(),me));let Ce=(Md=o.launcher)!=null?Md:{},Lt=(Ld=Ce.headerIconHidden)!=null?Ld:!1,st=(Rd=(Id=o.layout)==null?void 0:Id.header)==null?void 0:Rd.showIcon,Xt=Lt||st===!1,cn=Ce.headerIconName,Pt=(Pd=Ce.headerIconSize)!=null?Pd:"48px";if(_){let X=ce.querySelector(".persona-border-b-persona-divider"),vt=X==null?void 0:X.querySelector(".persona-flex-col");if(Xt)_.style.display="none",X&&vt&&!X.contains(vt)&&X.insertBefore(vt,X.firstChild);else{if(_.style.display="",_.style.height=Pt,_.style.width=Pt,X&&vt&&(X.contains(_)?_.nextSibling!==vt&&(_.remove(),X.insertBefore(_,vt)):X.insertBefore(_,vt)),cn){let ct=parseFloat(Pt)||24,kt=Te(cn,ct*.6,"#ffffff",2);kt?_.replaceChildren(kt):_.textContent=(Wd=Ce.agentIconText)!=null?Wd:"\u{1F4AC}"}else if(Ce.iconUrl){let ct=_.querySelector("img");if(ct)ct.src=Ce.iconUrl,ct.style.height=Pt,ct.style.width=Pt;else{let kt=document.createElement("img");kt.src=Ce.iconUrl,kt.alt="",kt.className="persona-rounded-xl persona-object-cover",kt.style.height=Pt,kt.style.width=Pt,_.replaceChildren(kt)}}else{let ct=_.querySelector("svg"),kt=_.querySelector("img");(ct||kt)&&_.replaceChildren(),_.textContent=(Bd=Ce.agentIconText)!=null?Bd:"\u{1F4AC}"}let Ot=_.querySelector("img");Ot&&(Ot.style.height=Pt,Ot.style.width=Pt)}}let An=(Dd=(Hd=o.layout)==null?void 0:Hd.header)==null?void 0:Dd.showTitle,dn=(Od=(Fd=o.layout)==null?void 0:Fd.header)==null?void 0:Od.showSubtitle;if(ke&&(ke.style.display=An===!1?"none":""),De&&(De.style.display=dn===!1?"none":""),qe){((_d=(Nd=o.layout)==null?void 0:Nd.header)==null?void 0:_d.showCloseButton)===!1?qe.style.display="none":qe.style.display="";let vt=(Vd=Ce.closeButtonSize)!=null?Vd:"32px",Ot=($d=Ce.closeButtonPlacement)!=null?$d:"inline";qe.style.height=vt,qe.style.width=vt;let{closeButtonWrapper:ct}=He,kt=Ot==="top-right",rn=ct==null?void 0:ct.classList.contains("persona-absolute");if(ct&&kt!==rn)if(ct.remove(),kt)ct.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ce.style.position="relative",ce.appendChild(ct);else{let pt=(zd=(Ud=Ce.clearChat)==null?void 0:Ud.placement)!=null?zd:"inline",sn=(jd=(qd=Ce.clearChat)==null?void 0:qd.enabled)!=null?jd:!0;ct.className=sn&&pt==="inline"?"":"persona-ml-auto";let Hn=ce.querySelector(".persona-border-b-persona-divider");Hn&&Hn.appendChild(ct)}if(qe.style.color=Ce.closeButtonColor||Mn.actionIconColor,Ce.closeButtonBackgroundColor?(qe.style.backgroundColor=Ce.closeButtonBackgroundColor,qe.classList.remove("hover:persona-bg-gray-100")):(qe.style.backgroundColor="",qe.classList.add("hover:persona-bg-gray-100")),Ce.closeButtonBorderWidth||Ce.closeButtonBorderColor){let pt=Ce.closeButtonBorderWidth||"0px",sn=Ce.closeButtonBorderColor||"transparent";qe.style.border=`${pt} solid ${sn}`,qe.classList.remove("persona-border-none")}else qe.style.border="",qe.classList.add("persona-border-none");Ce.closeButtonBorderRadius?(qe.style.borderRadius=Ce.closeButtonBorderRadius,qe.classList.remove("persona-rounded-full")):(qe.style.borderRadius="",qe.classList.add("persona-rounded-full")),Ce.closeButtonPaddingX?(qe.style.paddingLeft=Ce.closeButtonPaddingX,qe.style.paddingRight=Ce.closeButtonPaddingX):(qe.style.paddingLeft="",qe.style.paddingRight=""),Ce.closeButtonPaddingY?(qe.style.paddingTop=Ce.closeButtonPaddingY,qe.style.paddingBottom=Ce.closeButtonPaddingY):(qe.style.paddingTop="",qe.style.paddingBottom="");let fn=(Kd=Ce.closeButtonIconName)!=null?Kd:"x",yo=(Gd=Ce.closeButtonIconText)!=null?Gd:"\xD7";qe.innerHTML="";let En=Te(fn,"28px","currentColor",1);En?qe.appendChild(En):qe.textContent=yo;let Qt=(Yd=Ce.closeButtonTooltipText)!=null?Yd:"Close chat",Xn=(Xd=Ce.closeButtonShowTooltip)!=null?Xd:!0;if(qe.setAttribute("aria-label",Qt),ct&&(ct._cleanupTooltip&&(ct._cleanupTooltip(),delete ct._cleanupTooltip),Xn&&Qt)){let pt=null,sn=()=>{if(pt||!qe)return;let yr=qe.ownerDocument,As=yr.body;if(!As)return;pt=Eo(yr,"div","persona-clear-chat-tooltip"),pt.textContent=Qt;let Ts=Eo(yr,"div");Ts.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Ts);let vr=qe.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(or),pt.style.left=`${vr.left+vr.width/2}px`,pt.style.top=`${vr.top-8}px`,pt.style.transform="translate(-50%, -100%)",As.appendChild(pt)},Hn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};ct.addEventListener("mouseenter",sn),ct.addEventListener("mouseleave",Hn),qe.addEventListener("focus",sn),qe.addEventListener("blur",Hn),ct._cleanupTooltip=()=>{Hn(),ct&&(ct.removeEventListener("mouseenter",sn),ct.removeEventListener("mouseleave",Hn)),qe&&(qe.removeEventListener("focus",sn),qe.removeEventListener("blur",Hn))}}}let{clearChatButton:Je,clearChatButtonWrapper:lt}=He;if(Je){let X=(Qd=Ce.clearChat)!=null?Qd:{},vt=(Jd=X.enabled)!=null?Jd:!0,Ot=(ep=(Zd=o.layout)==null?void 0:Zd.header)==null?void 0:ep.showClearChat,ct=Ot!==void 0?Ot:vt,kt=(tp=X.placement)!=null?tp:"inline";if(lt){lt.style.display=ct?"":"none";let{closeButtonWrapper:rn}=He;!k()&&rn&&!rn.classList.contains("persona-absolute")&&(ct?rn.classList.remove("persona-ml-auto"):rn.classList.add("persona-ml-auto"));let fn=kt==="top-right",yo=lt.classList.contains("persona-absolute");if(!k()&&fn!==yo&&ct){if(lt.remove(),fn)lt.className="persona-absolute persona-top-4 persona-z-50",lt.style.right="48px",ce.style.position="relative",ce.appendChild(lt);else{lt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",lt.style.right="";let Qt=ce.querySelector(".persona-border-b-persona-divider"),Xn=He.closeButtonWrapper;Qt&&Xn&&Xn.parentElement===Qt?Qt.insertBefore(lt,Xn):Qt&&Qt.appendChild(lt)}let En=He.closeButtonWrapper;En&&!En.classList.contains("persona-absolute")&&(fn?En.classList.add("persona-ml-auto"):En.classList.remove("persona-ml-auto"))}}if(ct){if(!k()){let pt=(np=X.size)!=null?np:"32px";Je.style.height=pt,Je.style.width=pt}let rn=(op=X.iconName)!=null?op:"refresh-cw",fn=(rp=X.iconColor)!=null?rp:"";Je.style.color=fn||Mn.actionIconColor,Je.innerHTML="";let yo=k()?"14px":"20px",En=Te(rn,yo,"currentColor",2);if(En&&Je.appendChild(En),X.backgroundColor?(Je.style.backgroundColor=X.backgroundColor,Je.classList.remove("hover:persona-bg-gray-100")):(Je.style.backgroundColor="",Je.classList.add("hover:persona-bg-gray-100")),X.borderWidth||X.borderColor){let pt=X.borderWidth||"0px",sn=X.borderColor||"transparent";Je.style.border=`${pt} solid ${sn}`,Je.classList.remove("persona-border-none")}else Je.style.border="",Je.classList.add("persona-border-none");X.borderRadius?(Je.style.borderRadius=X.borderRadius,Je.classList.remove("persona-rounded-full")):(Je.style.borderRadius="",Je.classList.add("persona-rounded-full")),X.paddingX?(Je.style.paddingLeft=X.paddingX,Je.style.paddingRight=X.paddingX):(Je.style.paddingLeft="",Je.style.paddingRight=""),X.paddingY?(Je.style.paddingTop=X.paddingY,Je.style.paddingBottom=X.paddingY):(Je.style.paddingTop="",Je.style.paddingBottom="");let Qt=(sp=X.tooltipText)!=null?sp:"Clear chat",Xn=(ap=X.showTooltip)!=null?ap:!0;if(Je.setAttribute("aria-label",Qt),lt&&(lt._cleanupTooltip&&(lt._cleanupTooltip(),delete lt._cleanupTooltip),Xn&&Qt)){let pt=null,sn=()=>{if(pt||!Je)return;let yr=Je.ownerDocument,As=yr.body;if(!As)return;pt=Eo(yr,"div","persona-clear-chat-tooltip"),pt.textContent=Qt;let Ts=Eo(yr,"div");Ts.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Ts);let vr=Je.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(or),pt.style.left=`${vr.left+vr.width/2}px`,pt.style.top=`${vr.top-8}px`,pt.style.transform="translate(-50%, -100%)",As.appendChild(pt)},Hn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};lt.addEventListener("mouseenter",sn),lt.addEventListener("mouseleave",Hn),Je.addEventListener("focus",sn),Je.addEventListener("blur",Hn),lt._cleanupTooltip=()=>{Hn(),lt&&(lt.removeEventListener("mouseenter",sn),lt.removeEventListener("mouseleave",Hn)),Je&&(Je.removeEventListener("focus",sn),Je.removeEventListener("blur",Hn))}}}}let Tn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Fl],mn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ea.message,ea.messageAndClick];M=Ol({parsers:Tn,handlers:mn,getSessionMetadata:g,updateSessionMetadata:p,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),me=Om(o,M,j),E.updateConfig(o),dr(Ve,E.getMessages(),me),uo.render(o.suggestionChips,E,pe,void 0,o.suggestionChipsConfig),fs(),Br(E.isStreaming());let mr=((ip=o.voiceRecognition)==null?void 0:ip.enabled)===!0,fr=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),gr=((cp=(lp=o.voiceRecognition)==null?void 0:lp.provider)==null?void 0:cp.type)==="runtype";if(mr&&(fr||gr))if(!q||!_t){let X=wa(o.voiceRecognition,o.sendButton);X&&(q=X.micButton,_t=X.micButtonWrapper,At.insertBefore(_t,Ln),q.addEventListener("click",K),q.disabled=E.isStreaming())}else{let X=(dp=o.voiceRecognition)!=null?dp:{},vt=(pp=o.sendButton)!=null?pp:{},Ot=(up=X.iconName)!=null?up:"mic",ct=(mp=vt.size)!=null?mp:"40px",kt=(fp=X.iconSize)!=null?fp:ct,rn=parseFloat(kt)||24;q.style.width=kt,q.style.height=kt,q.style.minWidth=kt,q.style.minHeight=kt;let fn=(hp=(gp=X.iconColor)!=null?gp:vt.textColor)!=null?hp:"currentColor";q.innerHTML="";let yo=Te(Ot,rn,fn,2);yo?q.appendChild(yo):q.textContent="\u{1F3A4}";let En=(bp=X.backgroundColor)!=null?bp:vt.backgroundColor;En?q.style.backgroundColor=En:q.style.backgroundColor="",fn?q.style.color=fn:q.style.color="var(--persona-text, #111827)",X.borderWidth?(q.style.borderWidth=X.borderWidth,q.style.borderStyle="solid"):(q.style.borderWidth="",q.style.borderStyle=""),X.borderColor?q.style.borderColor=X.borderColor:q.style.borderColor="",X.paddingX?(q.style.paddingLeft=X.paddingX,q.style.paddingRight=X.paddingX):(q.style.paddingLeft="",q.style.paddingRight=""),X.paddingY?(q.style.paddingTop=X.paddingY,q.style.paddingBottom=X.paddingY):(q.style.paddingTop="",q.style.paddingBottom="");let Qt=_t==null?void 0:_t.querySelector(".persona-send-button-tooltip"),Xn=(yp=X.tooltipText)!=null?yp:"Start voice recognition";if(((vp=X.showTooltip)!=null?vp:!1)&&Xn)if(Qt)Qt.textContent=Xn,Qt.style.display="";else{let sn=document.createElement("div");sn.className="persona-send-button-tooltip",sn.textContent=Xn,_t==null||_t.insertBefore(sn,q)}else Qt&&(Qt.style.display="none");_t.style.display="",q.disabled=E.isStreaming()}else q&&_t&&(_t.style.display="none",((wp=(xp=o.voiceRecognition)==null?void 0:xp.provider)==null?void 0:wp.type)==="runtype"?E.isVoiceActive()&&E.toggleVoice():Gn&&bo());if(((Cp=o.attachments)==null?void 0:Cp.enabled)===!0)if(!Ft||!Qe){let X=(Sp=o.attachments)!=null?Sp:{},Ot=(Tp=((Ap=o.sendButton)!=null?Ap:{}).size)!=null?Tp:"40px";ge||(ge=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ge.style.display="none",Nt.insertBefore(ge,pe)),oe||(oe=document.createElement("input"),oe.type="file",oe.accept=((kp=X.allowedTypes)!=null?kp:_o).join(","),oe.multiple=((Ep=X.maxFiles)!=null?Ep:4)>1,oe.style.display="none",oe.setAttribute("aria-label","Attach files"),Nt.insertBefore(oe,pe)),Ft=b("div","persona-send-button-wrapper"),Qe=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Qe.type="button",Qe.setAttribute("aria-label",(Mp=X.buttonTooltipText)!=null?Mp:"Attach file");let ct=(Lp=X.buttonIconName)!=null?Lp:"paperclip",kt=Ot,rn=parseFloat(kt)||40,fn=Math.round(rn*.6);Qe.style.width=kt,Qe.style.height=kt,Qe.style.minWidth=kt,Qe.style.minHeight=kt,Qe.style.fontSize="18px",Qe.style.lineHeight="1",Qe.style.backgroundColor="transparent",Qe.style.color="var(--persona-primary, #111827)",Qe.style.border="none",Qe.style.borderRadius="6px",Qe.style.transition="background-color 0.15s ease",Qe.addEventListener("mouseenter",()=>{Qe.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Qe.addEventListener("mouseleave",()=>{Qe.style.backgroundColor="transparent"});let yo=Te(ct,fn,"currentColor",1.5);yo?Qe.appendChild(yo):Qe.textContent="\u{1F4CE}",Qe.addEventListener("click",Xn=>{Xn.preventDefault(),oe==null||oe.click()}),Ft.appendChild(Qe);let En=(Ip=X.buttonTooltipText)!=null?Ip:"Attach file",Qt=b("div","persona-send-button-tooltip");Qt.textContent=En,Ft.appendChild(Qt),ot.append(Ft),!et&&oe&&ge&&(et=Os.fromConfig(X),et.setPreviewsContainer(ge),oe.addEventListener("change",async()=>{et&&(oe!=null&&oe.files)&&(await et.handleFileSelect(oe.files),oe.value="")})),ce.querySelector(".persona-attachment-drop-overlay")||ce.appendChild(Nm(X.dropOverlay))}else{Ft.style.display="";let X=(Rp=o.attachments)!=null?Rp:{};oe&&(oe.accept=((Pp=X.allowedTypes)!=null?Pp:_o).join(","),oe.multiple=((Wp=X.maxFiles)!=null?Wp:4)>1),et&&et.updateConfig({allowedTypes:X.allowedTypes,maxFileSize:X.maxFileSize,maxFiles:X.maxFiles})}else Ft&&(Ft.style.display="none"),et&&et.clearAttachments(),(Bp=ce.querySelector(".persona-attachment-drop-overlay"))==null||Bp.remove();let qt=(Hp=o.sendButton)!=null?Hp:{},hr=(Dp=qt.useIcon)!=null?Dp:!1,nr=(Fp=qt.iconText)!=null?Fp:"\u2191",ht=qt.iconName,Pn=(Op=qt.tooltipText)!=null?Op:"Send message",Oo=(Np=qt.showTooltip)!=null?Np:!1,kn=(_p=qt.size)!=null?_p:"40px",Wn=qt.backgroundColor,Ht=qt.textColor;if(hr){if(ae.style.width=kn,ae.style.height=kn,ae.style.minWidth=kn,ae.style.minHeight=kn,ae.style.fontSize="18px",ae.style.lineHeight="1",ae.innerHTML="",Ht?ae.style.color=Ht:ae.style.color="var(--persona-button-primary-fg, #ffffff)",ht){let X=parseFloat(kn)||24,vt=(Ht==null?void 0:Ht.trim())||"currentColor",Ot=Te(ht,X,vt,2);Ot?ae.appendChild(Ot):ae.textContent=nr}else ae.textContent=nr;ae.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Wn?(ae.style.backgroundColor=Wn,ae.classList.remove("persona-bg-persona-primary")):(ae.style.backgroundColor="",ae.classList.add("persona-bg-persona-primary"))}else ae.textContent=($p=(Vp=o.copy)==null?void 0:Vp.sendButtonLabel)!=null?$p:"Send",ae.style.width="",ae.style.height="",ae.style.minWidth="",ae.style.minHeight="",ae.style.fontSize="",ae.style.lineHeight="",ae.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Wn?(ae.style.backgroundColor=Wn,ae.classList.remove("persona-bg-persona-accent")):ae.classList.add("persona-bg-persona-accent"),Ht?ae.style.color=Ht:ae.classList.add("persona-text-white");qt.borderWidth?(ae.style.borderWidth=qt.borderWidth,ae.style.borderStyle="solid"):(ae.style.borderWidth="",ae.style.borderStyle=""),qt.borderColor?ae.style.borderColor=qt.borderColor:ae.style.borderColor="",qt.paddingX?(ae.style.paddingLeft=qt.paddingX,ae.style.paddingRight=qt.paddingX):(ae.style.paddingLeft="",ae.style.paddingRight=""),qt.paddingY?(ae.style.paddingTop=qt.paddingY,ae.style.paddingBottom=qt.paddingY):(ae.style.paddingTop="",ae.style.paddingBottom="");let Ut=Ln==null?void 0:Ln.querySelector(".persona-send-button-tooltip");if(Oo&&Pn)if(Ut)Ut.textContent=Pn,Ut.style.display="";else{let X=document.createElement("div");X.className="persona-send-button-tooltip",X.textContent=Pn,Ln==null||Ln.insertBefore(X,ae)}else Ut&&(Ut.style.display="none");let Dt=(Kp=(Up=o.layout)==null?void 0:Up.contentMaxWidth)!=null?Kp:k()?(jp=(qp=(zp=o.launcher)==null?void 0:zp.composerBar)==null?void 0:qp.contentMaxWidth)!=null?jp:"720px":void 0;Dt?(Ve.style.maxWidth=Dt,Ve.style.marginLeft="auto",Ve.style.marginRight="auto",Ve.style.width="100%",Nt&&(Nt.style.maxWidth=Dt,Nt.style.marginLeft="auto",Nt.style.marginRight="auto"),Et&&(Et.style.maxWidth=Dt,Et.style.marginLeft="auto",Et.style.marginRight="auto")):(Ve.style.maxWidth="",Ve.style.marginLeft="",Ve.style.marginRight="",Ve.style.width="",Nt&&(Nt.style.maxWidth="",Nt.style.marginLeft="",Nt.style.marginRight=""),Et&&(Et.style.maxWidth="",Et.style.marginLeft="",Et.style.marginRight=""));let jt=(Gp=o.statusIndicator)!=null?Gp:{},Bn=(Yp=jt.visible)!=null?Yp:!0;if(ln.style.display=Bn?"":"none",E){let X=E.getStatus();nt(ln,(Ot=>{var ct,kt,rn,fn;return Ot==="idle"?(ct=jt.idleText)!=null?ct:gn.idle:Ot==="connecting"?(kt=jt.connectingText)!=null?kt:gn.connecting:Ot==="connected"?(rn=jt.connectedText)!=null?rn:gn.connected:Ot==="error"?(fn=jt.errorText)!=null?fn:gn.error:gn[Ot]})(X),jt,X)}ln.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Yn=jt.align==="left"?"persona-text-left":jt.align==="center"?"persona-text-center":"persona-text-right";ln.classList.add(Yn)},open(){C()&&Bt(!0,"api")},close(){C()&&Bt(!1,"api")},toggle(){C()&&Bt(!T,"api")},clearChat(){xn=!1,E.clearMessages(),mo.clear(),Go();try{localStorage.removeItem(ts),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ts}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ts)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let f=i.clear();f instanceof Promise&&f.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",f)}d={},M.syncFromMetadata(),Y==null||Y.clear(),xe==null||xe.reset(),Se==null||Se.update()},setMessage(c){return!pe||E.isStreaming()?!1:(!T&&C()&&Bt(!0,"system"),pe.value=c,pe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(E.isStreaming())return!1;let f=(c==null?void 0:c.trim())||pe.value.trim();return f?(!T&&C()&&Bt(!0,"system"),pe.value="",pe.style.height="auto",E.sendMessage(f),!0):!1},startVoiceRecognition(){var f,h;return E.isStreaming()?!1:((h=(f=o.voiceRecognition)==null?void 0:f.provider)==null?void 0:h.type)==="runtype"?(E.isVoiceActive()||(!T&&C()&&Bt(!0,"system"),mt.manuallyDeactivated=!1,Rn(),E.toggleVoice().then(()=>{mt.active=E.isVoiceActive(),ro("user"),E.isVoiceActive()&&U()})),!0):Gn?!0:ws()?(!T&&C()&&Bt(!0,"system"),mt.manuallyDeactivated=!1,Rn(),ur("user"),!0):!1},stopVoiceRecognition(){var c,f;return((f=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?E.isVoiceActive()?(E.toggleVoice().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Rn(),ro("user"),ee()}),!0):!1:Gn?(mt.manuallyDeactivated=!0,Rn(),bo("user"),!0):!1},injectMessage(c){return!T&&C()&&Bt(!0,"system"),E.injectMessage(c)},injectAssistantMessage(c){!T&&C()&&Bt(!0,"system");let f=E.injectAssistantMessage(c);return F&&(F=!1,$&&(clearTimeout($),$=null),setTimeout(()=>{E&&!E.isStreaming()&&E.continueConversation()},100)),f},injectUserMessage(c){return!T&&C()&&Bt(!0,"system"),E.injectUserMessage(c)},injectSystemMessage(c){return!T&&C()&&Bt(!0,"system"),E.injectSystemMessage(c)},injectMessageBatch(c){return!T&&C()&&Bt(!0,"system"),E.injectMessageBatch(c)},injectComponentDirective(c){return!T&&C()&&Bt(!0,"system"),E.injectComponentDirective(c)},injectTestMessage(c){!T&&C()&&Bt(!0,"system"),E.injectTestEvent(c)},async connectStream(c,f){return E.connectStream(c,f)},__pushEventStreamEvent(c){Y&&(xe==null||xe.processEvent(c.type,c.payload),Y.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!ie||!Y||vn()},hideEventStream(){de&&On()},isEventStreamVisible(){return de},showArtifacts(){co(o)&&(xn=!1,zn(),yt==null||yt.setMobileOpen(!0))},hideArtifacts(){co(o)&&(xn=!0,zn())},upsertArtifact(c){return co(o)?(xn=!1,E.upsertArtifact(c)):null},selectArtifact(c){co(o)&&E.selectArtifact(c)},clearArtifacts(){co(o)&&E.clearArtifacts()},getArtifacts(){var c;return(c=E==null?void 0:E.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=E==null?void 0:E.getSelectedArtifactId())!=null?c:null},focusInput(){return I&&!T&&!k()||!pe?!1:(pe.focus(),!0)},async resolveApproval(c,f){let y=E.getMessages().find(P=>{var N;return P.variant==="approval"&&((N=P.approval)==null?void 0:N.id)===c});if(!(y!=null&&y.approval))throw new Error(`Approval not found: ${c}`);if(y.approval.toolType==="webmcp"){E.resolveWebMcpApproval(y.id,f);return}return E.resolveApproval(y.approval,f)},getMessages(){return E.getMessages()},getStatus(){return E.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){p(c)},on(c,f){return s.on(c,f)},off(c,f){s.off(c,f)},isOpen(){return C()&&T},isVoiceActive(){return mt.active},getState(){return{open:C()&&T,launcherEnabled:I,voiceActive:mt.active,streaming:E.isStreaming()}},showCSATFeedback(c){!T&&C()&&Bt(!0,"system");let f=Ve.querySelector(".persona-feedback-container");f&&f.remove();let h=Hm({onSubmit:async(y,P)=>{var N;E.isClientTokenMode()&&await E.submitCSATFeedback(y,P),(N=c==null?void 0:c.onSubmit)==null||N.call(c,y,P)},onDismiss:c==null?void 0:c.onDismiss,...c});Ve.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!T&&C()&&Bt(!0,"system");let f=Ve.querySelector(".persona-feedback-container");f&&f.remove();let h=Dm({onSubmit:async(y,P)=>{var N;E.isClientTokenMode()&&await E.submitNPSFeedback(y,P),(N=c==null?void 0:c.onSubmit)==null||N.call(c,y,P)},onDismiss:c==null?void 0:c.onDismiss,...c});Ve.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,f){return E.submitCSATFeedback(c,f)},async submitNPSFeedback(c,f){return E.submitNPSFeedback(c,f)},destroy(){Ao!=null&&(clearInterval(Ao),Ao=null),ft.forEach(c=>c()),ye.remove(),Ue==null||Ue.remove(),Ie==null||Ie.destroy(),Ye==null||Ye.remove(),jn&&qe.removeEventListener("click",jn)}};if((((Gc=n==null?void 0:n.debugTools)!=null?Gc:!1)||!!o.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,f={controller:Zt,getMessages:Zt.getMessages,getStatus:Zt.getStatus,getMetadata:Zt.getPersistentMetadata,updateMetadata:Zt.updatePersistentMetadata,clearHistory:()=>Zt.clearChat(),setVoiceActive:h=>h?Zt.startVoiceRecognition():Zt.stopVoiceRecognition()};window.AgentWidgetBrowser=f,ft.push(()=>{window.AgentWidgetBrowser===f&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),f=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&Zt.focusInput()};if(window.addEventListener("persona:focusInput",f),ft.push(()=>{window.removeEventListener("persona:focusInput",f)}),ie){let z=Ae=>{let ue=Ae.detail;(!(ue!=null&&ue.instanceId)||ue.instanceId===c)&&Zt.showEventStream()},O=Ae=>{let ue=Ae.detail;(!(ue!=null&&ue.instanceId)||ue.instanceId===c)&&Zt.hideEventStream()};window.addEventListener("persona:showEventStream",z),window.addEventListener("persona:hideEventStream",O),ft.push(()=>{window.removeEventListener("persona:showEventStream",z),window.removeEventListener("persona:hideEventStream",O)})}let h=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&Zt.showArtifacts()},y=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&Zt.hideArtifacts()},P=z=>{let O=z.detail;O!=null&&O.instanceId&&O.instanceId!==c||O!=null&&O.artifact&&Zt.upsertArtifact(O.artifact)},N=z=>{let O=z.detail;O!=null&&O.instanceId&&O.instanceId!==c||typeof(O==null?void 0:O.id)=="string"&&Zt.selectArtifact(O.id)},V=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&Zt.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",P),window.addEventListener("persona:selectArtifact",N),window.addEventListener("persona:clearArtifacts",V),ft.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",P),window.removeEventListener("persona:selectArtifact",N),window.removeEventListener("persona:clearArtifacts",V)})}let ao=sx(o.persistState);if(ao&&C()){let c=ax(ao.storage),f=`${ao.keyPrefix}widget-open`,h=`${ao.keyPrefix}widget-voice`,y=`${ao.keyPrefix}widget-voice-mode`;if(c){let P=((Yc=ao.persist)==null?void 0:Yc.openState)&&c.getItem(f)==="true",N=((Xc=ao.persist)==null?void 0:Xc.voiceState)&&c.getItem(h)==="true",V=((Qc=ao.persist)==null?void 0:Qc.voiceState)&&c.getItem(y)==="true";if(P&&setTimeout(()=>{Zt.open(),setTimeout(()=>{var z;if(N||V)Zt.startVoiceRecognition();else if((z=ao.persist)!=null&&z.focusInput){let O=e.querySelector("textarea");O&&O.focus()}},100)},0),(Jc=ao.persist)!=null&&Jc.openState&&(s.on("widget:opened",()=>{c.setItem(f,"true")}),s.on("widget:closed",()=>{c.setItem(f,"false")})),(Zc=ao.persist)!=null&&Zc.voiceState&&(s.on("voice:state",z=>{c.setItem(h,z.active?"true":"false")}),s.on("user:message",z=>{c.setItem(y,z.viaVoice?"true":"false")})),ao.clearOnChatClear){let z=()=>{c.removeItem(f),c.removeItem(h),c.removeItem(y)},O=()=>z();window.addEventListener("persona:clear-chat",O),ft.push(()=>{window.removeEventListener("persona:clear-chat",O)})}}}return m&&C()&&setTimeout(()=>{Zt.open()},0),Do(),Zt};var ix=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},Vm=(e,t)=>{var o,r;let n=(r=(o=t==null?void 0:t.launcher)==null?void 0:o.enabled)!=null?r:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},Ul=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},$m=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Ul(e)},_l=e=>{e.style.transition=""},Vl=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform=""},$l=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ii=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},lx=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},cx=(e,t,n,o,r,s)=>{let a=s?t:e;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},Um=(e,t,n,o,r,s,a)=>{var w,S,M,I,L,H;let i=Mo(s),d=i.reveal==="push";lx(e,t,n,o,d),cx(e,t,n,o,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,m=(S=(w=s==null?void 0:s.launcher)==null?void 0:w.mobileFullscreen)!=null?S:!0,u=(I=(M=s==null?void 0:s.launcher)==null?void 0:M.mobileBreakpoint)!=null?I:640,g=l!=null?l.innerWidth<=u:!1;if(m&&g&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Vl(t),_l(o),$m(o),$l(n),Ii(r,o),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String((H=(L=s==null?void 0:s.launcher)==null?void 0:L.zIndex)!=null?H:hn),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),$m(o),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Vl(t),_l(o),$l(n),Ii(r,o);let D=i.animate?"transform 180ms ease":"none",W=i.side==="right"?"translateX(100%)":"translateX(-100%)",v=a?"translateX(0)":W;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=D,o.style.transform=v,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",i.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",_l(o),Ul(o),Ii(r,o);let D=ix(i.width,e.clientWidth),W=Math.max(0,e.clientWidth),v=i.animate?"transform 180ms ease":"none",x=i.side==="right"?a?`translateX(-${D}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${D}px)`;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${W+D}px`,t.style.transition=v,t.style.transform=x,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${W}px`,n.style.maxWidth=`${W}px`,n.style.minWidth=`${W}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.position="relative",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Vl(t),Ul(o),$l(n),Ii(r,o);let D=i.reveal==="emerge";D?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let W=a?i.width:"0px",v=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",x=!a;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${W}`,o.style.width=W,o.style.maxWidth=W,o.style.minWidth=W,o.style.minHeight="0",o.style.position="relative",o.style.overflow=D||x?"hidden":"visible",o.style.transition=v,D&&(o.style.alignItems=i.side==="right"?"flex-start":"flex-end",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.boxSizing="border-box")}},dx=(e,t)=>{let n=e.ownerDocument.createElement("div");return Vm(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Vm(n,o)},destroy(){n.remove()}}},px=(e,t)=>{var L,H,D,W;let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),m=n.createElement("div"),u=(H=(L=t==null?void 0:t.launcher)==null?void 0:L.enabled)==null||H?(W=(D=t==null?void 0:t.launcher)==null?void 0:D.autoExpand)!=null?W:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",m.dataset.personaDockRole="host",l.appendChild(m),o.insertBefore(a,e),d.appendChild(e);let g=null,p=()=>{g==null||g.disconnect(),g=null},w=()=>{p(),Mo(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{Um(a,i,d,l,m,t,u)}),g.observe(a))},S=()=>{Um(a,i,d,l,m,t,u),w()},M=a.ownerDocument.defaultView,I=()=>{S()};return M==null||M.addEventListener("resize",I),Mo(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),S(),{mode:"docked",host:m,shell:a,syncWidgetState(v){let x=v.launcherEnabled?v.open:!0;u!==x&&(u=x,S())},updateConfig(v){var x,k;t=v,((k=(x=t==null?void 0:t.launcher)==null?void 0:x.enabled)!=null?k:!0)===!1&&(u=!0),S()},destroy(){M==null||M.removeEventListener("resize",I),p(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},zm=(e,t)=>pn(t)?px(e,t):dx(e,t);var ns={desktop:{w:1280,h:800},mobile:{w:390,h:844}},zl=.15,ql=1.5,Ri="persona-preview-shell-theme",qm={load:()=>null,save:()=>{},clear:()=>{}},jm=["How do I get started?","Pricing & plans","Talk to support"];function Pi(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Km(e){return e==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function jl(e){let t=Km(e);return`* { box-sizing: border-box; }
|
|
107
|
+
`}if(!y&&!c){let pt="max-height: -moz-available !important; max-height: stretch !important;",bt=p?"":"padding-top: 1.25em !important;",ut=p?"":`z-index: ${(rn=(Pn=o.launcher)==null?void 0:Pn.zIndex)!=null?rn:En} !important;`;Me.style.cssText+=pt+bt+ut}Ge()};yo(),os(e,o),Ni(e,o),_i(e,o);let ht=[];ht.push(()=>{document.removeEventListener("keydown",er)});let Qt=null,Zt=null;ht.push(()=>{Qt==null||Qt(),Qt=null,Zt==null||Zt(),Zt=null}),zn&&ht.push(()=>{zn==null||zn.disconnect(),zn=null}),ht.push(()=>{Rn==null||Rn(),Rn=null,$o(),Dt&&(Dt.remove(),Dt=null),At==null||At.element.style.removeProperty("width"),At==null||At.element.style.removeProperty("maxWidth")}),ke&&ht.push(()=>{Ie!==null&&(cancelAnimationFrame(Ie),Ie=null),j==null||j.destroy(),j=null,be==null||be.destroy(),be=null,X=null});let Yn=null,or=()=>{Yn&&(Yn(),Yn=null),o.colorScheme==="auto"&&(Yn=Wu(()=>{os(e,o)}))};or(),ht.push(()=>{Yn&&(Yn(),Yn=null)});let xe=(fd=o.features)==null?void 0:fd.streamAnimation;if(xe!=null&&xe.type&&xe.type!=="none"){let c=na(xe.type,xe.plugins);c&&(Il(c,e),ht.push(()=>Mm(e)))}let ao=ef(Et),io=null,V,Io=!1,Uo=vm(),zo=new Map,Ro=new Map,vo=new Map,Cs=0,Xn=hi(),Jn=0,xo=null,wo=!1,vr=!1,qo=0,Sn=null,Po=null,zr=!1,xr=!1,qr=null,xa=4,jr=24,wa=80,Kr=new Map,yt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ss=(hd=(gd=o.voiceRecognition)==null?void 0:gd.autoResume)!=null?hd:!1,lo=c=>{s.emit("voice:state",{active:yt.active,source:c,timestamp:Date.now()})},On=()=>{m(c=>({...c,voiceState:{active:yt.active,timestamp:Date.now(),manuallyDeactivated:yt.manuallyDeactivated}}))},Ca=()=>{var y,M;if(((y=o.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=tc(d.voiceState),p=!!c.active,h=Number((M=c.timestamp)!=null?M:0);yt.manuallyDeactivated=!!c.manuallyDeactivated,p&&Date.now()-h<Gx&&setTimeout(()=>{var O,N;yt.active||(yt.manuallyDeactivated=!1,((N=(O=o.voiceRecognition)==null?void 0:O.provider)==null?void 0:N.type)==="runtype"?V.toggleVoice().then(()=>{yt.active=V.isVoiceActive(),lo("restore"),V.isVoiceActive()&&Ds()}):mn("restore"))},1e3)},Sa=()=>V?Af(V.getMessages()).filter(c=>!c.__skipPersist):[];function Gr(c){if(!(i!=null&&i.save))return;let h={messages:c?Af(c):V?Sa():[],metadata:d,artifacts:qn.artifacts,selectedArtifactId:qn.selectedId};try{let y=i.save(h);y instanceof Promise&&y.catch(M=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",M)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let jo=null,As=()=>Me.querySelector("#persona-scroll-container")||me,rr=()=>{jo!==null&&(cancelAnimationFrame(jo),jo=null),wo=!1},Ts=()=>{xo!==null&&(cancelAnimationFrame(xo),xo=null),vr=!1,rr()},ks=()=>{qo>0?(wn.textContent=String(qo),wn.style.display="",Je.setAttribute("aria-label",`${Kt()||"Jump to latest"} (${qo} new)`)):(wn.textContent="",wn.style.display="none",Je.setAttribute("aria-label",Kt()||"Jump to latest"))},Es=()=>{qo!==0&&(qo=0,ks())},Ms=()=>ft()==="follow"?!Xn.isFollowing():!Hr(me,jr),Nn=()=>{if(!yn()||se){Je.parentNode&&Je.remove(),Je.style.display="none";return}Je.parentNode!==q&&q.appendChild(Je),bn();let p=Xo(me)>0&&Ms();p||Es(),Je.style.display=p?"":"none"},Yr=()=>{Xn.pause()&&(Ts(),Nn())},Wo=()=>{Xn.resume(),Es(),Nn()},Bo=(c=!1)=>{ft()==="follow"&&Xn.isFollowing()&&(!c&&!Io||(xo!==null&&(cancelAnimationFrame(xo),xo=null),vr=!0,xo=requestAnimationFrame(()=>{xo=null,vr=!1,Xn.isFollowing()&&Aa(As(),c?220:140)})))},Ls=(c,p,h,y=()=>!0)=>{let M=c.scrollTop,O=p(),N=O-M;rr();let z=performance.now();wo=!0;let F=fe=>1-Math.pow(1-fe,3),we=fe=>{if(!y()){rr();return}let te=p();te!==O&&(O=te,N=O-M);let Te=fe-z,_e=Math.min(Te/h,1),Ae=F(_e),tt=M+N*Ae;c.scrollTop=tt,Jn=c.scrollTop,_e<1?jo=requestAnimationFrame(we):(c.scrollTop=O,Jn=c.scrollTop,jo=null,wo=!1)};jo=requestAnimationFrame(we)},Aa=(c,p=500)=>{let h=Xo(c)-c.scrollTop;if(Math.abs(h)<1){Jn=c.scrollTop;return}if(Math.abs(h)>=wa){rr(),wo=!0,c.scrollTop=Xo(c),Jn=c.scrollTop,wo=!1;return}Ls(c,()=>Xo(c),p,()=>Xn.isFollowing())},Is=()=>{let c=As();wo=!0,c.scrollTop=Xo(c),Jn=c.scrollTop,wo=!1,Nn()},Rs=c=>{Cn.style.height=`${Math.max(0,Math.round(c))}px`,Sn&&(Sn.spacerHeight=Math.max(0,c))},wr=()=>{Po!==null&&(cancelAnimationFrame(Po),Po=null),rr(),Sn=null,Cn.style.height="0px"},Ta=c=>{Po!==null&&cancelAnimationFrame(Po),Po=requestAnimationFrame(()=>{var we;Po=null;let p=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(c):c.replace(/"/g,'\\"'),h=me.querySelector(`[data-message-id="${p}"]`);if(!h)return;let y=0,M=h;for(;M&&M!==me;)y+=M.offsetTop,M=M.offsetParent;let O=(we=Sn==null?void 0:Sn.spacerHeight)!=null?we:0,N=me.scrollHeight-O,{targetScrollTop:z,spacerHeight:F}=Am({anchorOffsetTop:y,topOffset:Mt(),viewportHeight:me.clientHeight,contentHeight:N});Sn={initialSpacerHeight:F,contentHeightAtAnchor:N,spacerHeight:F},Rs(F),Ls(me,()=>z,220)})},ka=()=>{if(ft()==="follow"){if(!Xn.isFollowing()||Hr(me,1))return;Bo(!Io);return}if(Sn&&Sn.initialSpacerHeight>0){let c=me.scrollHeight-Sn.spacerHeight,p=Tm({initialSpacerHeight:Sn.initialSpacerHeight,contentHeightAtAnchor:Sn.contentHeightAtAnchor,currentContentHeight:c});p!==Sn.spacerHeight&&Rs(p)}Nn()},Ea=c=>{let p=ft();p==="follow"?(Wo(),Bo(!0)):p==="anchor-top"&&Ta(c)},Ma=c=>{let p=new Map;c.forEach(h=>{let y=Kr.get(h.id);p.set(h.id,{streaming:h.streaming,role:h.role}),!y&&h.role==="assistant"&&(s.emit("assistant:message",h),!xr&&ft()!=="anchor-top"&&Ms()&&(qo+=1,ks(),Nn())),h.role==="assistant"&&(y!=null&&y.streaming)&&h.streaming===!1&&s.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(y?h.approval.status!=="pending"&&s.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):s.emit("approval:requested",{approval:h.approval,message:h}))}),Kr.clear(),p.forEach((h,y)=>{Kr.set(y,h)})},Cr=(c,p,h)=>{var dt,Pe,Le,Ue,Ge,wt;let y=document.createElement("div"),O=(()=>{var Be;let B=r.find(Fe=>Fe.renderLoadingIndicator);if(B!=null&&B.renderLoadingIndicator)return B.renderLoadingIndicator;if((Be=o.loadingIndicator)!=null&&Be.render)return o.loadingIndicator.render})(),N=(B,Be)=>Be==null?!1:typeof Be=="string"?(B.textContent=Be,!0):(B.appendChild(Be),!0),z=new Set,F=new Set,we=r.some(B=>B.renderAskUserQuestion),fe=[],te=[],Te=o.enableComponentStreaming!==!1,_e=r.some(B=>B.renderApproval)&&o.approval!==!1,Ae=[];if(p.forEach(B=>{var Ye,Pt,cn,uo,Zn,Sr,Ar,es,ts,Yt,Tr,pr,ur,Go;z.add(B.id);let Be=we&&Fr(B),Fe=_e&&B.variant==="approval"&&!!B.approval,ye=!Be&&B.role==="assistant"&&!B.variant&&Te&&xf(B);if(!Fe&&vo.has(B.id)){let ot=c.querySelector(`#wrapper-${B.id}`);ot==null||ot.removeAttribute("data-preserve-runtime"),vo.delete(B.id)}if(!ye&&Ro.has(B.id)){let ot=c.querySelector(`#wrapper-${B.id}`);ot==null||ot.removeAttribute("data-preserve-runtime"),Ro.delete(B.id)}let _t=Fr(B)?`:${(Ye=B.agentMetadata)!=null&&Ye.askUserQuestionAnswered?"a":"u"}:${(Pt=B.agentMetadata)!=null&&Pt.askUserQuestionAnswers?Object.keys(B.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ot=ym(B,Cs)+_t,Gt=Be||Fe||ye?null:xm(Uo,B.id,Ot);if(Gt){y.appendChild(Gt.cloneNode(!0)),Fr(B)&&((cn=B.toolCall)!=null&&cn.id)&&((uo=B.agentMetadata)==null?void 0:uo.awaitingLocalTool)===!0&&!((Zn=B.agentMetadata)!=null&&Zn.askUserQuestionAnswered)&&(F.add(B.toolCall.id),Bi(B,o,We.composerOverlay));return}let Ct=null,qt=r.find(ot=>!!(B.variant==="reasoning"&&ot.renderReasoning||B.variant==="tool"&&ot.renderToolCall||!B.variant&&ot.renderMessage)),Qn=(Sr=o.layout)==null?void 0:Sr.messages;if(Fr(B)&&((Ar=B.agentMetadata)==null?void 0:Ar.askUserQuestionAnswered)===!0){zo.delete(B.id);let ot=c.querySelector(`#wrapper-${B.id}`);ot==null||ot.removeAttribute("data-preserve-runtime");return}if(Fr(B)&&((ts=(es=o.features)==null?void 0:es.askUserQuestion)==null?void 0:ts.enabled)!==!1){let ot=r.find(vn=>typeof vn.renderAskUserQuestion=="function");if(ot&&It.current){let vn=zo.get(B.id),Pn=vn!==Ot,rn=null;if(Pn){let{payload:ut,complete:_n}=ms(B),dn=B.id,Ho=()=>{var pn;return(pn=It.current)==null?void 0:pn.getMessages().find(Wn=>Wn.id===dn)};rn=ot.renderAskUserQuestion({message:B,payload:ut,complete:_n,resolve:pn=>{var mo;let Wn=Ho();Wn&&((mo=It.current)==null||mo.resolveAskUserQuestion(Wn,pn))},dismiss:()=>{var Wn,mo,kr;let pn=Ho();(Wn=pn==null?void 0:pn.agentMetadata)!=null&&Wn.awaitingLocalTool&&((mo=It.current)==null||mo.markAskUserQuestionResolved(pn),(kr=It.current)==null||kr.resolveAskUserQuestion(pn,"(dismissed)"))},config:o})}let pt=vn!=null;if(Pn&&rn===null&&!pt){((Yt=B.agentMetadata)==null?void 0:Yt.awaitingLocalTool)===!0&&!((Tr=B.agentMetadata)!=null&&Tr.askUserQuestionAnswered)&&(F.add(B.toolCall.id),Bi(B,o,We.composerOverlay));return}let bt=document.createElement("div");bt.className="persona-flex",bt.id=`wrapper-${B.id}`,bt.setAttribute("data-wrapper-id",B.id),bt.setAttribute("data-ask-plugin-stub","true"),bt.setAttribute("data-preserve-runtime","true"),y.appendChild(bt),fe.push({messageId:B.id,fingerprint:Ot,bubble:rn});return}else{((pr=B.agentMetadata)==null?void 0:pr.awaitingLocalTool)===!0&&!((ur=B.agentMetadata)!=null&&ur.askUserQuestionAnswered)&&(F.add(B.toolCall.id),Bi(B,o,We.composerOverlay));return}}else if(Fe){let ot=r.find(pt=>typeof pt.renderApproval=="function"),Pn=vo.get(B.id)!==Ot,rn=null;if(Pn&&(ot!=null&&ot.renderApproval)){let pt=B.id,bt=(ut,_n)=>{var Ho,pn,Wn;let dn=(Ho=It.current)==null?void 0:Ho.getMessages().find(mo=>mo.id===pt);dn!=null&&dn.approval&&(dn.approval.toolType==="webmcp"?(pn=It.current)==null||pn.resolveWebMcpApproval(dn.id,ut):(Wn=It.current)==null||Wn.resolveApproval(dn.approval,ut,_n))};rn=ot.renderApproval({message:B,defaultRenderer:()=>Fi(B,o),config:o,approve:ut=>bt("approved",ut),deny:ut=>bt("denied",ut)})}if(Pn&&rn===null){let pt=c.querySelector(`#wrapper-${B.id}`);pt==null||pt.removeAttribute("data-preserve-runtime"),vo.delete(B.id),Ct=Fi(B,o)}else{let pt=document.createElement("div");pt.className="persona-flex",pt.id=`wrapper-${B.id}`,pt.setAttribute("data-wrapper-id",B.id),pt.setAttribute("data-approval-plugin-stub","true"),pt.setAttribute("data-preserve-runtime","true"),y.appendChild(pt),Ae.push({messageId:B.id,fingerprint:Ot,bubble:rn});return}}else if(qt)if(B.variant==="reasoning"&&B.reasoning&&qt.renderReasoning){if(!ue)return;Ct=qt.renderReasoning({message:B,defaultRenderer:()=>Fl(B,o),config:o})}else if(B.variant==="tool"&&B.toolCall&&qt.renderToolCall){if(!ce)return;Ct=qt.renderToolCall({message:B,defaultRenderer:()=>Ol(B,o),config:o})}else qt.renderMessage&&(Ct=qt.renderMessage({message:B,defaultRenderer:()=>{let ot=Dl(B,h,Qn,o.messageActions,Z,{loadingIndicatorRenderer:O,widgetConfig:o});return B.role!=="user"&&Yl(ot,B,o,V),ot},config:o}));if(!Ct&&ye){let ot=wf(B);if(ot){let vn=Ro.get(B.id),Pn=vn!==Ot,rn=o.wrapComponentDirectiveInBubble!==!1,pt=null;if(Pn){let bt=yf(ot,{config:o,message:B,transform:h});if(bt)if(rn){let ut=document.createElement("div");if(ut.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),ut.id=`bubble-${B.id}`,ut.setAttribute("data-message-id",B.id),B.content&&B.content.trim()){let _n=document.createElement("div");_n.className="persona-mb-3 persona-text-sm persona-leading-relaxed",_n.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),ut.appendChild(_n)}ut.appendChild(bt),pt=ut}else{let ut=document.createElement("div");if(ut.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",ut.id=`bubble-${B.id}`,ut.setAttribute("data-message-id",B.id),ut.setAttribute("data-persona-component-directive","true"),B.content&&B.content.trim()){let _n=document.createElement("div");_n.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",_n.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),ut.appendChild(_n)}ut.appendChild(bt),pt=ut}}if(pt||vn!=null){let bt=document.createElement("div");bt.className="persona-flex",bt.id=`wrapper-${B.id}`,bt.setAttribute("data-wrapper-id",B.id),bt.setAttribute("data-component-directive-stub","true"),bt.setAttribute("data-preserve-runtime","true"),rn||bt.classList.add("persona-w-full"),y.appendChild(bt),te.push({messageId:B.id,fingerprint:Ot,bubble:pt});return}}}if(!Ct)if(B.variant==="reasoning"&&B.reasoning){if(!ue)return;Ct=Fl(B,o)}else if(B.variant==="tool"&&B.toolCall){if(!ce)return;Ct=Ol(B,o)}else if(B.variant==="approval"&&B.approval){if(o.approval===!1)return;Ct=Fi(B,o)}else{let ot=(Go=o.layout)==null?void 0:Go.messages;ot!=null&&ot.renderUserMessage&&B.role==="user"?Ct=ot.renderUserMessage({message:B,config:o,streaming:!!B.streaming}):ot!=null&&ot.renderAssistantMessage&&B.role==="assistant"?Ct=ot.renderAssistantMessage({message:B,config:o,streaming:!!B.streaming}):Ct=Dl(B,h,ot,o.messageActions,Z,{loadingIndicatorRenderer:O,widgetConfig:o}),B.role!=="user"&&Ct&&Yl(Ct,B,o,V)}let on=document.createElement("div");on.className="persona-flex",on.id=`wrapper-${B.id}`,on.setAttribute("data-wrapper-id",B.id),B.role==="user"&&on.classList.add("persona-justify-end"),(Ct==null?void 0:Ct.getAttribute("data-persona-component-directive"))==="true"&&on.classList.add("persona-w-full"),on.appendChild(Ct),wm(Uo,B.id,Ot,on),y.appendChild(on)}),We.composerOverlay&&We.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Be=>{let Fe=Be.getAttribute("data-persona-ask-sheet-for");Fe&&!F.has(Fe)&&gs(We.composerOverlay,Fe)}),(Pe=(dt=o.features)==null?void 0:dt.toolCallDisplay)!=null&&Pe.grouped){let B=[],Be=[];p.forEach(Fe=>{if(Fe.variant==="tool"&&Fe.toolCall&&ce){Be.push(Fe);return}Be.length>1&&B.push(Be),Be=[]}),Be.length>1&&B.push(Be),B.forEach((Fe,ye)=>{var Ye,Pt;let _t=Fe.map(cn=>Array.from(y.children).find(uo=>uo instanceof HTMLElement&&uo.getAttribute("data-wrapper-id")===cn.id)).filter(cn=>!!cn);if(_t.length<2)return;let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id=`wrapper-tool-group-${ye}-${Fe[0].id}`,Ot.setAttribute("data-wrapper-id",`tool-group-${ye}-${Fe[0].id}`);let Gt=document.createElement("div");Gt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Gt.setAttribute("data-persona-tool-group","true");let Ct=document.createElement("div");Ct.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let qt=`Called ${Fe.length} tools`,Qn=(Pt=(Ye=o.toolCall)==null?void 0:Ye.renderGroupedSummary)==null?void 0:Pt.call(Ye,{messages:Fe,toolCalls:Fe.map(cn=>cn.toolCall).filter(cn=>!!cn),defaultSummary:qt,config:o});N(Ct,Qn)||(Ct.textContent=qt);let on=document.createElement("div");on.className="persona-tool-group-stack persona-flex persona-flex-col",Gt.append(Ct,on),Ot.appendChild(Gt),_t[0].before(Ot),_t.forEach((cn,uo)=>{let Zn=document.createElement("div");Zn.className="persona-tool-group-item persona-relative",Zn.setAttribute("data-persona-tool-group-item","true"),uo<_t.length-1&&Zn.setAttribute("data-persona-tool-group-connector","true"),Zn.appendChild(cn),on.appendChild(Zn)})})}Cm(Uo,z);let tt=p.some(B=>B.role==="assistant"&&B.streaming),qe=p[p.length-1],ct=(qe==null?void 0:qe.role)==="assistant"&&!qe.streaming&&qe.variant!=="approval";if(Io&&p.some(B=>B.role==="user")&&!tt&&!ct){let B={config:o,streaming:!0,location:"standalone",defaultRenderer:ca},Be=r.find(ye=>ye.renderLoadingIndicator),Fe=null;if(Be!=null&&Be.renderLoadingIndicator&&(Fe=Be.renderLoadingIndicator(B)),Fe===null&&((Le=o.loadingIndicator)!=null&&Le.render)&&(Fe=o.loadingIndicator.render(B)),Fe===null&&(Fe=ca()),Fe){let ye=document.createElement("div"),_t=((Ue=o.loadingIndicator)==null?void 0:Ue.showBubble)!==!1;ye.className=_t?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),ye.setAttribute("data-typing-indicator","true"),ye.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",ye.appendChild(Fe);let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id="wrapper-typing-indicator",Ot.setAttribute("data-wrapper-id","typing-indicator"),Ot.appendChild(ye),y.appendChild(Ot)}}if(!Io&&p.length>0){let B=p[p.length-1],Be={config:o,lastMessage:B,messageCount:p.length},Fe=r.find(_t=>_t.renderIdleIndicator),ye=null;if(Fe!=null&&Fe.renderIdleIndicator&&(ye=Fe.renderIdleIndicator(Be)),ye===null&&((Ge=o.loadingIndicator)!=null&&Ge.renderIdle)&&(ye=o.loadingIndicator.renderIdle(Be)),ye){let _t=document.createElement("div"),Ot=((wt=o.loadingIndicator)==null?void 0:wt.showBubble)!==!1;_t.className=Ot?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),_t.setAttribute("data-idle-indicator","true"),_t.appendChild(ye);let Gt=document.createElement("div");Gt.className="persona-flex",Gt.id="wrapper-idle-indicator",Gt.setAttribute("data-wrapper-id","idle-indicator"),Gt.appendChild(_t),y.appendChild(Gt)}}if(fi(c,y),fe.length>0)for(let{messageId:B,fingerprint:Be,bubble:Fe}of fe){let ye=c.querySelector(`#wrapper-${B}`);ye&&Fe!==null&&(ye.replaceChildren(Fe),ye.setAttribute("data-bubble-fp",Be),zo.set(B,Be))}if(zo.size>0)for(let B of zo.keys())z.has(B)||zo.delete(B);if(te.length>0)for(let{messageId:B,fingerprint:Be,bubble:Fe}of te){let ye=c.querySelector(`#wrapper-${B}`);ye&&Fe!==null&&(ye.replaceChildren(Fe),ye.setAttribute("data-bubble-fp",Be),Ro.set(B,Be))}if(Ro.size>0)for(let B of Ro.keys())z.has(B)||Ro.delete(B);if(Ae.length>0)for(let{messageId:B,fingerprint:Be,bubble:Fe}of Ae){let ye=c.querySelector(`#wrapper-${B}`);ye&&Fe!==null&&(ye.replaceChildren(Fe),ye.setAttribute("data-bubble-fp",Be),vo.set(B,Be))}if(vo.size>0)for(let B of vo.keys())z.has(B)||vo.delete(B)},sr=null,La=()=>{var h;if(sr)return;let c=y=>{let M=y.composedPath();M.includes(Me)||Xe&&M.includes(Xe)||Ft(!1,"user")};sr=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},Ps=()=>{var p;if(!sr)return;((p=e.ownerDocument)!=null?p:document).removeEventListener("pointerdown",sr,!0),sr=null};ht.push(()=>Ps());let ar=null,Ia=()=>{var h;if(ar)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Ft(!1,"user"))};ar=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},Ws=()=>{var p;if(!ar)return;((p=e.ownerDocument)!=null?p:document).removeEventListener("keydown",ar,!0),ar=null};ht.push(()=>Ws());let ir=!1,Bs=new Set,Ra=()=>{var p,h,y,M;let c=(y=(h=(p=o.launcher)==null?void 0:p.composerBar)==null?void 0:h.peek)==null?void 0:y.streamAnimation;return c||((M=o.features)==null?void 0:M.streamAnimation)},Ko=()=>{var ct,dt,Pe,Le;if(!k())return;let c=We.peekBanner,p=We.peekTextNode;if(!c||!p)return;if(T){c.classList.remove("persona-pill-peek--visible");return}let h=(ct=V==null?void 0:V.getMessages())!=null?ct:[],y;for(let Ue=h.length-1;Ue>=0;Ue--){let Ge=h[Ue];if(Ge.role==="assistant"&&Ge.content){y=Ge;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let M=y.content,O=!!y.streaming,N=Ra(),z=vi(N),F=z.type!=="none"?na(z.type,N==null?void 0:N.plugins):null,we=((dt=F==null?void 0:F.isAnimating)==null?void 0:dt.call(F,y))===!0,fe=F!==null&&(O||we);fe&&F&&!Bs.has(F.name)&&(Il(F,e),Bs.add(F.name));let te=fe&&(F!=null&&F.containerClass)?F.containerClass:null,Te=(Pe=p.dataset.personaPeekStreamClass)!=null?Pe:null;Te&&Te!==te&&(p.classList.remove(Te),delete p.dataset.personaPeekStreamClass),te&&Te!==te&&(p.classList.add(te),p.dataset.personaPeekStreamClass=te),fe?(p.style.setProperty("--persona-stream-step",`${z.speed}ms`),p.style.setProperty("--persona-stream-duration",`${z.duration}ms`)):(p.style.removeProperty("--persona-stream-step"),p.style.removeProperty("--persona-stream-duration"));let _e=fe?xi(M,z.buffer,F,y,O):M;if(fe&&z.placeholder==="skeleton"&&O&&(!_e||!_e.trim())){let Ue=document.createElement("div"),Ge=ra();Ge.classList.add("persona-pill-peek__skeleton"),Ue.appendChild(Ge),fi(p,Ue)}else{let Ue=Math.max(0,_e.length-100),Ge=_e.length>100?_e.slice(-100):_e,wt=js(Ge);if(!fe||!F){let B=_e.length>100?`\u2026${Ge}`:Ge;p.textContent!==B&&(p.textContent=B)}else{let B=wt;(F.wrap==="char"||F.wrap==="word")&&(B=oa(wt,F.wrap,`peek-${y.id}`,{skipTags:F.skipTags,startIndex:Ue}));let Be=document.createElement("div");if(Be.innerHTML=B,F.useCaret&&Ge.length>0){let Fe=wi(),ye=Be.querySelectorAll(".persona-stream-char, .persona-stream-word"),_t=ye[ye.length-1];_t!=null&&_t.parentNode?_t.parentNode.insertBefore(Fe,_t.nextSibling):Be.appendChild(Fe)}fi(p,Be),(Le=F.onAfterRender)==null||Le.call(F,{container:p,bubble:c,messageId:y.id,message:y,speed:z.speed,duration:z.duration})}}let qe=Io||ir;c.classList.toggle("persona-pill-peek--visible",qe)};if(k()){let c=We.peekBanner;if(c){let y=M=>{M.preventDefault(),M.stopPropagation(),Ft(!0,"user")};c.addEventListener("pointerdown",y),ht.push(()=>{c.removeEventListener("pointerdown",y)})}let p=()=>{ir||(ir=!0,Ko())},h=()=>{ir&&(ir=!1,Ko())};de.addEventListener("pointerenter",p),de.addEventListener("pointerleave",h),ht.push(()=>{de.removeEventListener("pointerenter",p),de.removeEventListener("pointerleave",h)}),Xe&&(Xe.addEventListener("pointerenter",p),Xe.addEventListener("pointerleave",h),ht.push(()=>{Xe.removeEventListener("pointerenter",p),Xe.removeEventListener("pointerleave",h)}))}let Pa=c=>{var Te,_e,Ae,tt,qe,ct,dt,Pe;let p=(_e=(Te=o.launcher)==null?void 0:Te.composerBar)!=null?_e:{},h=(Ae=p.expandedSize)!=null?Ae:"anchored",y=(tt=p.bottomOffset)!=null?tt:"16px",M=p.collapsedMaxWidth,O=(qe=p.expandedMaxWidth)!=null?qe:"880px",N=(ct=p.expandedTopOffset)!=null?ct:"5vh",z=(dt=p.modalMaxWidth)!=null?dt:"880px",F=(Pe=p.modalMaxHeight)!=null?Pe:"min(90vh, 800px)",we="calc(100vw - 32px)",fe="var(--persona-pill-area-height, 80px)",te=Me.style;if(te.left="",te.right="",te.top="",te.bottom="",te.transform="",te.width="",te.maxWidth="",te.height="",te.maxHeight="",Xe){let Le=Xe.style;Le.bottom=y,Le.width=M!=null?M:""}if(c&&h!=="fullscreen"){if(h==="modal"){te.top="50%",te.left="50%",te.transform="translate(-50%, -50%)",te.bottom="auto",te.right="auto",te.width=z,te.maxWidth=we,te.maxHeight=F,te.height=F;return}te.left="50%",te.transform="translateX(-50%)",te.bottom=`calc(${y} + ${fe})`,te.top=N,te.width=O,te.maxWidth=we}},lr=()=>{var F,we,fe,te,Te,_e,Ae,tt;if(!S())return;if(k()){let ct=(fe=((we=(F=o.launcher)==null?void 0:F.composerBar)!=null?we:{}).expandedSize)!=null?fe:"anchored",dt=T?"expanded":"collapsed";Me.dataset.state=dt,Me.dataset.expandedSize=ct,Xe&&(Xe.dataset.state=dt,Xe.dataset.expandedSize=ct),Me.style.removeProperty("display"),Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Pa(T),q.style.display=T?"flex":"none",yo(),T?(La(),Ia()):(Ps(),Ws()),Ko();return}let c=xn(o),p=(te=e.ownerDocument.defaultView)!=null?te:window,h=(_e=(Te=o.launcher)==null?void 0:Te.mobileBreakpoint)!=null?_e:640,y=(tt=(Ae=o.launcher)==null?void 0:Ae.mobileFullscreen)!=null?tt:!0,M=p.innerWidth<=h,O=y&&M&&L,N=Oo(o).reveal;T?(Me.style.removeProperty("display"),Me.style.display=c?"flex":"",Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-95","persona-opacity-0"),de.classList.add("persona-scale-100","persona-opacity-100"),en?en.element.style.display="none":tn&&(tn.style.display="none")):(c?c&&(N==="overlay"||N==="push")&&!O?(Me.style.removeProperty("display"),Me.style.display="flex",Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Me.style.setProperty("display","none","important"),Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Me.style.display="",Me.classList.add("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100"),de.classList.add("persona-scale-95","persona-opacity-0")),en?en.element.style.display=c?"none":"":tn&&(tn.style.display=c?"none":""))},Ft=(c,p="user")=>{var O,N;if(!S()||T===c)return;let h=T;T=c,lr();let y=(()=>{var Ae,tt,qe,ct,dt,Pe,Le,Ue,Ge,wt;let z=(tt=(Ae=o.launcher)==null?void 0:Ae.sidebarMode)!=null?tt:!1,F=(qe=e.ownerDocument.defaultView)!=null?qe:window,we=(dt=(ct=o.launcher)==null?void 0:ct.mobileFullscreen)!=null?dt:!0,fe=(Le=(Pe=o.launcher)==null?void 0:Pe.mobileBreakpoint)!=null?Le:640,te=F.innerWidth<=fe,Te=xn(o)&&we&&te,_e=k()&&((wt=(Ge=(Ue=o.launcher)==null?void 0:Ue.composerBar)==null?void 0:Ge.expandedSize)!=null?wt:"fullscreen")==="fullscreen";return z||we&&te&&L||Te||_e})();if(T&&y){if(!Qt){let z=e.getRootNode(),F=z instanceof ShadowRoot?z.host:e.closest(".persona-host");F&&(Qt=Rl(F,(N=(O=o.launcher)==null?void 0:O.zIndex)!=null?N:En))}Zt||(Zt=Pl(e.ownerDocument))}else T||(Qt==null||Qt(),Qt=null,Zt==null||Zt(),Zt=null);T&&(Fs(),ft()==="follow"?Bo(!0):Is());let M={open:T,source:p,timestamp:Date.now()};T&&!h?s.emit("widget:opened",M):!T&&h&&s.emit("widget:closed",M),s.emit("widget:state",{open:T,launcherEnabled:L,voiceActive:yt.active,streaming:V.isStreaming()})},Xr=c=>{Xt(c?"stop":"send"),K&&(K.disabled=c),ao.buttons.forEach(p=>{p.disabled=c}),Ve.dataset.personaComposerStreaming=c?"true":"false",Ve.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(p=>{(p instanceof HTMLButtonElement||p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement||p instanceof HTMLSelectElement)&&(p.disabled=c)})},Jr=()=>{yt.active||ee&&ee.focus()};s.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Jr(),200)});let Hs=()=>{var h,y,M,O,N,z,F,we,fe,te,Te;no.textContent=(y=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",ko.textContent=(O=(M=o.copy)==null?void 0:M.welcomeSubtitle)!=null?O:"Ask anything about your account or products.",ee.placeholder=(z=(N=o.copy)==null?void 0:N.inputPlaceholder)!=null?z:"How can I help...";let c=me.querySelector("[data-persona-intro-card]");if(c){let _e=((F=o.copy)==null?void 0:F.showWelcomeCard)!==!1;c.style.display=_e?"":"none",_e?(me.classList.remove("persona-gap-3"),me.classList.add("persona-gap-6")):(me.classList.remove("persona-gap-6"),me.classList.add("persona-gap-3"))}!((fe=(we=o.sendButton)==null?void 0:we.useIcon)!=null&&fe)&&!(V!=null&&V.isStreaming())&&(ze.textContent=(Te=(te=o.copy)==null?void 0:te.sendButtonLabel)!=null?Te:"Send"),ee.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ee.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{m(p=>({...p,sessionId:c}))}});let co=null,Ke=()=>{co==null&&(co=setInterval(()=>{let c=et.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(co),co=null;return}let p=Date.now();c.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=ni(p-y))})},100))};if(V=new ui(o,{onMessagesChanged(c){var y;Cr(et,c,ge),Ke(),V&&(c.some(O=>O.role==="user")?ao.render([],V,ee,c):ao.render(o.suggestionChips,V,ee,c,o.suggestionChipsConfig)),Bo(!Io),Ma(c);let p=[...c].reverse().find(M=>M.role==="user");c.length===0&&wr(),!zr||xr?(zr=!0,qr=(y=p==null?void 0:p.id)!=null?y:null):p&&p.id!==qr&&(qr=p.id,Ea(p.id));let h=yt.lastUserMessageId;p&&p.id!==h&&(yt.lastUserMessageId=p.id,s.emit("user:message",p)),yt.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),Gr(c),Ko()},onStatusChanged(c){var y;let p=(y=o.statusIndicator)!=null?y:{};it(sn,(M=>{var O,N,z,F;return M==="idle"?(O=p.idleText)!=null?O:kn.idle:M==="connecting"?(N=p.connectingText)!=null?N:kn.connecting:M==="connected"?(z=p.connectedText)!=null?z:kn.connected:M==="error"?(F=p.errorText)!=null?F:kn.error:kn[M]})(c),p,c)},onStreamingChanged(c){Io=c,Xr(c),V&&Cr(et,V.getMessages(),ge),c||Bo(!0),Ko()},onVoiceStatusChanged(c){var p,h;if(((h=(p=o.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype")switch(c){case"listening":break;case"processing":cr(),Jf();break;case"speaking":cr(),Qf();break;default:c==="idle"&&V.isBargeInActive()?(cr(),Ds(),K==null||K.setAttribute("aria-label","End voice session")):(yt.active=!1,cr(),lo("system"),On());break}},onArtifactsState(c){qn=c,Gn(),Gr()}}),It.current=V,zr=!0,((yd=(bd=o.voiceRecognition)==null?void 0:bd.provider)==null?void 0:yd.type)==="runtype")try{V.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}o.clientToken&&V.initClientSession().catch(c=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(be||o.onSSEEvent)&&V.setSSEEventCallback((c,p)=>{var h;(h=o.onSSEEvent)==null||h.call(o,c,p),he==null||he.processEvent(c,p),be==null||be.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(p)})}),l&&l.then(c=>{var p,h,y;if(c){if(c.metadata&&(d=tc(c.metadata),E.syncFromMetadata()),(p=c.messages)!=null&&p.length){xr=!0;try{V.hydrateMessages(c.messages)}finally{xr=!1}}(h=c.artifacts)!=null&&h.length&&V.hydrateArtifacts(c.artifacts,(y=c.selectedArtifactId)!=null?y:null)}}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let A=()=>{var p,h,y;!k()||T||!((y=(h=(p=o.launcher)==null?void 0:p.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||Ft(!0,"auto")},$=c=>{var M;if(c.preventDefault(),V.isStreaming()){V.cancel(),he==null||he.reset(),j==null||j.update();return}let p=ee.value.trim(),h=(M=St==null?void 0:St.hasAttachments())!=null?M:!1;if(!p&&!h)return;A();let y;h&&(y=[],y.push(...St.getContentParts()),p&&y.push(kl(p))),ee.value="",ee.style.height="auto",Y(),V.sendMessage(p,{contentParts:y}),h&&St.clearAttachments()},W=()=>{var c;return((c=o.features)==null?void 0:c.composerHistory)!==!1},Q={...gi},ae=!1,Y=()=>{Q={...gi}},Re=()=>V.getMessages().filter(c=>c.role==="user").map(c=>{var p;return(p=c.content)!=null?p:""}).filter(c=>c.length>0),Oe=c=>{if(!ee)return;ae=!0,ee.value=c,ee.dispatchEvent(new Event("input",{bubbles:!0})),ae=!1;let p=ee.value.length;ee.setSelectionRange(p,p)},st=()=>{ae||Y()},Qe=c=>{if(ee){if(W()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let p=ee.selectionStart===0&&ee.selectionEnd===0,h=bm({direction:c.key==="ArrowUp"?"up":"down",history:Re(),currentValue:ee.value,atStart:p,state:Q});if(Q=h.state,h.handled){c.preventDefault(),h.value!==void 0&&Oe(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(V.isStreaming()){c.preventDefault();return}Y(),c.preventDefault(),ze.click()}}},Bt=c=>{c.key!=="Escape"||c.isComposing||V.isStreaming()&&c.composedPath().includes(q)&&(V.cancel(),he==null||he.reset(),j==null||j.update(),Y(),c.preventDefault(),c.stopImmediatePropagation())},Vt=async c=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!St)return;let p=Xx(c.clipboardData);p.length!==0&&(c.preventDefault(),await St.handleFiles(p))},Nt=null,lt=!1,Tt=null,$e=null,An=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,mn=(c="user")=>{var O,N,z,F,we,fe,te;if(lt||V.isStreaming())return;let p=An();if(!p)return;Nt=new p;let y=(N=((O=o.voiceRecognition)!=null?O:{}).pauseDuration)!=null?N:2e3;Nt.continuous=!0,Nt.interimResults=!0,Nt.lang="en-US";let M=ee.value;Nt.onresult=Te=>{let _e="",Ae="";for(let qe=0;qe<Te.results.length;qe++){let ct=Te.results[qe],dt=ct[0].transcript;ct.isFinal?_e+=dt+" ":Ae=dt}let tt=M+_e+Ae;ee.value=tt,Tt&&clearTimeout(Tt),(_e||Ae)&&(Tt=window.setTimeout(()=>{let qe=ee.value.trim();qe&&Nt&<&&($t(),ee.value="",ee.style.height="auto",V.sendMessage(qe,{viaVoice:!0}))},y))},Nt.onerror=Te=>{Te.error!=="no-speech"&&$t()},Nt.onend=()=>{if(lt){let Te=ee.value.trim();Te&&Te!==M.trim()&&(ee.value="",ee.style.height="auto",V.sendMessage(Te,{viaVoice:!0})),$t()}};try{if(Nt.start(),lt=!0,yt.active=!0,c!=="system"&&(yt.manuallyDeactivated=!1),lo(c),On(),K){let Te=(z=o.voiceRecognition)!=null?z:{};$e={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:(F=Te.iconName)!=null?F:"mic",iconSize:parseFloat((te=(fe=Te.iconSize)!=null?fe:(we=o.sendButton)==null?void 0:we.size)!=null?te:"40")||24};let _e=Te.recordingBackgroundColor,Ae=Te.recordingIconColor,tt=Te.recordingBorderColor;if(K.classList.add("persona-voice-recording"),K.style.backgroundColor=_e!=null?_e:"var(--persona-voice-recording-bg, #ef4444)",K.style.color=Ae!=null?Ae:"var(--persona-voice-recording-indicator, #ffffff)",Ae){let qe=K.querySelector("svg");qe&&qe.setAttribute("stroke",Ae)}tt&&(K.style.borderColor=tt),K.setAttribute("aria-label","Stop voice recognition")}}catch{$t("system")}},$t=(c="user")=>{if(lt){if(lt=!1,Tt&&(clearTimeout(Tt),Tt=null),Nt){try{Nt.stop()}catch{}Nt=null}if(yt.active=!1,lo(c),On(),K){if(K.classList.remove("persona-voice-recording"),$e){K.style.backgroundColor=$e.backgroundColor,K.style.color=$e.color,K.style.borderColor=$e.borderColor;let p=K.querySelector("svg");p&&p.setAttribute("stroke",$e.color||"currentColor"),$e=null}K.setAttribute("aria-label","Start voice recognition")}}},Co=(c,p)=>{var ct,dt,Pe,Le,Ue,Ge,wt,B;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((ct=c==null?void 0:c.provider)==null?void 0:ct.type)==="runtype";if(!(h||y))return null;let O=b("div","persona-send-button-wrapper"),N=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");N.type="button",N.setAttribute("aria-label","Start voice recognition");let z=(dt=c==null?void 0:c.iconName)!=null?dt:"mic",F=(Pe=p==null?void 0:p.size)!=null?Pe:"40px",we=(Le=c==null?void 0:c.iconSize)!=null?Le:F,fe=parseFloat(we)||24,te=(Ue=c==null?void 0:c.backgroundColor)!=null?Ue:p==null?void 0:p.backgroundColor,Te=(Ge=c==null?void 0:c.iconColor)!=null?Ge:p==null?void 0:p.textColor;N.style.width=we,N.style.height=we,N.style.minWidth=we,N.style.minHeight=we,N.style.fontSize="18px",N.style.lineHeight="1",Te?N.style.color=Te:N.style.color="var(--persona-text, #111827)";let Ae=Ee(z,fe,Te||"currentColor",1.5);Ae?N.appendChild(Ae):N.textContent="\u{1F3A4}",te?N.style.backgroundColor=te:N.style.backgroundColor="",c!=null&&c.borderWidth&&(N.style.borderWidth=c.borderWidth,N.style.borderStyle="solid"),c!=null&&c.borderColor&&(N.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(N.style.paddingLeft=c.paddingX,N.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(N.style.paddingTop=c.paddingY,N.style.paddingBottom=c.paddingY),O.appendChild(N);let tt=(wt=c==null?void 0:c.tooltipText)!=null?wt:"Start voice recognition";if(((B=c==null?void 0:c.showTooltip)!=null?B:!1)&&tt){let Be=b("div","persona-send-button-tooltip");Be.textContent=tt,O.appendChild(Be)}return{micButton:N,micButtonWrapper:O}},ol=()=>{var p,h,y,M,O;if(!K||$e)return;let c=(p=o.voiceRecognition)!=null?p:{};$e={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:(h=c.iconName)!=null?h:"mic",iconSize:parseFloat((O=(M=c.iconSize)!=null?M:(y=o.sendButton)==null?void 0:y.size)!=null?O:"40")||24}},rl=(c,p)=>{var O,N,z,F,we;if(!K)return;let h=K.querySelector("svg");h&&h.remove();let y=(we=$e==null?void 0:$e.iconSize)!=null?we:parseFloat((F=(z=(O=o.voiceRecognition)==null?void 0:O.iconSize)!=null?z:(N=o.sendButton)==null?void 0:N.size)!=null?F:"40")||24,M=Ee(c,y,p,1.5);M&&K.appendChild(M)},Wa=()=>{K&&K.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Ds=()=>{var M;if(!K)return;ol();let c=(M=o.voiceRecognition)!=null?M:{},p=c.recordingBackgroundColor,h=c.recordingIconColor,y=c.recordingBorderColor;if(Wa(),K.classList.add("persona-voice-recording"),K.style.backgroundColor=p!=null?p:"var(--persona-voice-recording-bg, #ef4444)",K.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let O=K.querySelector("svg");O&&O.setAttribute("stroke",h)}y&&(K.style.borderColor=y),K.setAttribute("aria-label","Stop voice recognition")},Jf=()=>{var z,F,we,fe,te,Te,_e,Ae;if(!K)return;ol();let c=(z=o.voiceRecognition)!=null?z:{},p=V.getVoiceInterruptionMode(),h=(F=c.processingIconName)!=null?F:"loader",y=(fe=(we=c.processingIconColor)!=null?we:$e==null?void 0:$e.color)!=null?fe:"",M=(Te=(te=c.processingBackgroundColor)!=null?te:$e==null?void 0:$e.backgroundColor)!=null?Te:"",O=(Ae=(_e=c.processingBorderColor)!=null?_e:$e==null?void 0:$e.borderColor)!=null?Ae:"";Wa(),K.classList.add("persona-voice-processing"),K.style.backgroundColor=M,K.style.borderColor=O;let N=y||"currentColor";K.style.color=N,rl(h,N),K.setAttribute("aria-label","Processing voice input"),p==="none"&&(K.style.cursor="default")},Qf=()=>{var we,fe,te,Te,_e,Ae,tt,qe,ct,dt,Pe,Le;if(!K)return;ol();let c=(we=o.voiceRecognition)!=null?we:{},p=V.getVoiceInterruptionMode(),h=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",y=(fe=c.speakingIconName)!=null?fe:h,M=(Ae=c.speakingIconColor)!=null?Ae:p==="barge-in"?(Te=(te=c.recordingIconColor)!=null?te:$e==null?void 0:$e.color)!=null?Te:"":(_e=$e==null?void 0:$e.color)!=null?_e:"",O=(ct=c.speakingBackgroundColor)!=null?ct:p==="barge-in"?(tt=c.recordingBackgroundColor)!=null?tt:"var(--persona-voice-recording-bg, #ef4444)":(qe=$e==null?void 0:$e.backgroundColor)!=null?qe:"",N=(Le=c.speakingBorderColor)!=null?Le:p==="barge-in"?(dt=c.recordingBorderColor)!=null?dt:"":(Pe=$e==null?void 0:$e.borderColor)!=null?Pe:"";Wa(),K.classList.add("persona-voice-speaking"),K.style.backgroundColor=O,K.style.borderColor=N;let z=M||"currentColor";K.style.color=z,rl(y,z);let F=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";K.setAttribute("aria-label",F),p==="none"&&(K.style.cursor="default"),p==="barge-in"&&K.classList.add("persona-voice-recording")},cr=()=>{var c,p,h;K&&(Wa(),$e&&(K.style.backgroundColor=(c=$e.backgroundColor)!=null?c:"",K.style.color=(p=$e.color)!=null?p:"",K.style.borderColor=(h=$e.borderColor)!=null?h:"",rl($e.iconName,$e.color||"currentColor"),$e=null),K.style.cursor="",K.setAttribute("aria-label","Start voice recognition"))},Ba=()=>{var c,p;if(((p=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:p.type)==="runtype"){let h=V.getVoiceStatus(),y=V.getVoiceInterruptionMode();if(y==="none"&&(h==="processing"||h==="speaking"))return;if(y==="cancel"&&(h==="processing"||h==="speaking")){V.stopVoicePlayback();return}if(V.isBargeInActive()){V.stopVoicePlayback(),V.deactivateBargeIn().then(()=>{yt.active=!1,yt.manuallyDeactivated=!0,On(),lo("user"),cr()});return}V.toggleVoice().then(()=>{yt.active=V.isVoiceActive(),yt.manuallyDeactivated=!V.isVoiceActive(),On(),lo("user"),V.isVoiceActive()?Ds():cr()});return}if(lt){let h=ee.value.trim();yt.manuallyDeactivated=!0,On(),$t("user"),h&&(ee.value="",ee.style.height="auto",V.sendMessage(h))}else yt.manuallyDeactivated=!1,On(),mn("user")};$n=Ba,K&&(K.addEventListener("click",Ba),ht.push(()=>{var c,p;((p=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:p.type)==="runtype"?(V.isVoiceActive()&&V.toggleVoice(),cr()):$t("system"),K&&K.removeEventListener("click",Ba)}));let Zf=s.on("assistant:complete",()=>{Ss&&(yt.active||yt.manuallyDeactivated||Ss==="assistant"&&!yt.lastUserMessageWasVoice||setTimeout(()=>{var c,p;!yt.active&&!yt.manuallyDeactivated&&(((p=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:p.type)==="runtype"?V.toggleVoice().then(()=>{yt.active=V.isVoiceActive(),lo("auto"),V.isVoiceActive()&&Ds()}):mn("auto"))},600))});ht.push(Zf);let eg=s.on("action:resubmit",()=>{setTimeout(()=>{V&&!V.isStreaming()&&V.continueConversation()},100)});ht.push(eg);let Qr=()=>{Ft(!T,"user")},en=null,tn=null;if(L&&!k()){let c=r.find(p=>p.renderLauncher);if(c!=null&&c.renderLauncher){let p=c.renderLauncher({config:o,defaultRenderer:()=>ia(o,Qr).element,onToggle:Qr});p&&(tn=p)}tn||(en=ia(o,Qr))}en?e.appendChild(en.element):tn&&e.appendChild(tn),lr(),ao.render(o.suggestionChips,V,ee,void 0,o.suggestionChipsConfig),Hs(),Xr(V.isStreaming()),ft()==="follow"?Bo(!0):Is(),Ca(),R&&(!L||k()?setTimeout(()=>Jr(),0):T&&setTimeout(()=>Jr(),200));let Fs=()=>{var F,we,fe,te,Te,_e,Ae,tt,qe,ct,dt,Pe,Le,Ue,Ge,wt,B,Be,Fe,ye,_t,Ot;if(k()){bn(),lr();return}let c=xn(o),p=(we=(F=o.launcher)==null?void 0:F.sidebarMode)!=null?we:!1,h=c||p||((te=(fe=o.launcher)==null?void 0:fe.fullHeight)!=null?te:!1),y=(Te=e.ownerDocument.defaultView)!=null?Te:window,M=(Ae=(_e=o.launcher)==null?void 0:_e.mobileFullscreen)!=null?Ae:!0,O=(qe=(tt=o.launcher)==null?void 0:tt.mobileBreakpoint)!=null?qe:640,N=y.innerWidth<=O,z=M&&N&&L;try{if(z){yo(),os(e,o);return}if(x&&(x=!1,yo(),os(e,o)),!L&&!c){de.style.height="",de.style.width="";return}if(!p&&!c){let Gt=(dt=(ct=o==null?void 0:o.launcher)==null?void 0:ct.width)!=null?dt:o==null?void 0:o.launcherWidth,Ct=Gt!=null?Gt:fo;de.style.width=Ct,de.style.maxWidth=Ct}if(Lo(),!h){let Gt=y.innerHeight,Ct=64,qt=(Le=(Pe=o.launcher)==null?void 0:Pe.heightOffset)!=null?Le:0,Qn=Math.max(200,Gt-Ct),on=Math.min(640,Qn),Ye=Math.max(200,on-qt);de.style.height=`${Ye}px`}}finally{if(bn(),lr(),T&&L){let Ct=((Ue=e.ownerDocument.defaultView)!=null?Ue:window).innerWidth<=((wt=(Ge=o.launcher)==null?void 0:Ge.mobileBreakpoint)!=null?wt:640),qt=(Be=(B=o.launcher)==null?void 0:B.sidebarMode)!=null?Be:!1,Qn=(ye=(Fe=o.launcher)==null?void 0:Fe.mobileFullscreen)!=null?ye:!0,on=xn(o)&&Qn&&Ct,Ye=qt||Qn&&Ct&&L||on;if(Ye&&!Zt){let Pt=e.getRootNode(),cn=Pt instanceof ShadowRoot?Pt.host:e.closest(".persona-host");cn&&!Qt&&(Qt=Rl(cn,(Ot=(_t=o.launcher)==null?void 0:_t.zIndex)!=null?Ot:En)),Zt=Pl(e.ownerDocument)}else Ye||(Qt==null||Qt(),Qt=null,Zt==null||Zt(),Zt=null)}}};Fs();let hc=(vd=e.ownerDocument.defaultView)!=null?vd:window;if(hc.addEventListener("resize",Fs),ht.push(()=>hc.removeEventListener("resize",Fs)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{bn()});c.observe(Ve),ht.push(()=>c.disconnect())}Jn=me.scrollTop;let bc=Xo(me),tg=()=>{let c=me.getRootNode(),p=typeof c.getSelection=="function"?c.getSelection():null;return p!=null?p:me.ownerDocument.getSelection()},sl=()=>Sm(tg(),me),yc=()=>{let c=me.scrollTop,p=Xo(me),h=p<bc;if(bc=p,ft()!=="follow"){Jn=c,Nn();return}let{action:y,nextLastScrollTop:M}=bi({following:Xn.isFollowing(),currentScrollTop:c,lastScrollTop:Jn,nearBottom:Hr(me,jr),userScrollThreshold:xa,isAutoScrolling:wo||vr||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Jn=M,y==="resume"){sl()||Wo();return}y==="pause"&&Yr()};if(me.addEventListener("scroll",yc,{passive:!0}),ht.push(()=>me.removeEventListener("scroll",yc)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{ka()});c.observe(et),c.observe(me),ht.push(()=>c.disconnect())}let vc=()=>{ft()==="follow"&&Xn.isFollowing()&&sl()&&Yr()},xc=me.ownerDocument;xc.addEventListener("selectionchange",vc),ht.push(()=>{xc.removeEventListener("selectionchange",vc)});let wc=c=>{if(ft()!=="follow")return;let p=yi({following:Xn.isFollowing(),deltaY:c.deltaY,nearBottom:Hr(me,jr),resumeWhenNearBottom:!0});p==="pause"?Yr():p==="resume"&&!sl()&&Wo()};me.addEventListener("wheel",wc,{passive:!0}),ht.push(()=>me.removeEventListener("wheel",wc)),Je.addEventListener("click",()=>{wr(),me.scrollTop=me.scrollHeight,Jn=me.scrollTop,Wo(),Bo(!0),Nn()}),ht.push(()=>Je.remove()),ht.push(()=>{Ts(),wr()});let Cc=()=>{D&&(io&&(D.removeEventListener("click",io),io=null),S()?(D.style.display="",io=()=>{Ft(!1,"user")},D.addEventListener("click",io)):D.style.display="none")};Cc(),(()=>{let{clearChatButton:c}=We;c&&c.addEventListener("click",()=>{V.clearMessages(),Uo.clear(),Wo(),gs(We.composerOverlay);try{localStorage.removeItem(bs),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${bs}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==bs)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let p=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}d={},E.syncFromMetadata(),be==null||be.clear(),he==null||he.reset(),j==null||j.update()})})(),Ht&&Ht.addEventListener("submit",$),ee==null||ee.addEventListener("keydown",Qe),ee==null||ee.addEventListener("input",st),ee==null||ee.addEventListener("paste",Vt);let Sc=(xd=e.ownerDocument)!=null?xd:document;Sc.addEventListener("keydown",Bt,!0);let Ac="persona-attachment-drop-active",Os=0,al=()=>{Os=0,q.classList.remove(Ac)},Zr=()=>{var c;return((c=o.attachments)==null?void 0:c.enabled)===!0&&St!==null},Tc=c=>{!Vi(c.dataTransfer)||!Zr()||(Os++,Os===1&&q.classList.add(Ac))},kc=c=>{!Vi(c.dataTransfer)||!Zr()||(Os--,Os<=0&&al())},Ec=c=>{!Vi(c.dataTransfer)||!Zr()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Mc=c=>{var h;if(!Vi(c.dataTransfer)||!Zr())return;c.preventDefault(),c.stopPropagation(),al();let p=Array.from((h=c.dataTransfer.files)!=null?h:[]);p.length!==0&&St.handleFiles(p)},dr=!0;q.addEventListener("dragenter",Tc,dr),q.addEventListener("dragleave",kc,dr),e.addEventListener("dragover",Ec,dr),e.addEventListener("drop",Mc,dr);let Ha=e.ownerDocument,Lc=c=>{Zr()&&c.preventDefault()},Ic=c=>{Zr()&&c.preventDefault()};Ha.addEventListener("dragover",Lc),Ha.addEventListener("drop",Ic),ht.push(()=>{Ht&&Ht.removeEventListener("submit",$),ee==null||ee.removeEventListener("keydown",Qe),ee==null||ee.removeEventListener("input",st),ee==null||ee.removeEventListener("paste",Vt),Sc.removeEventListener("keydown",Bt,!0)}),ht.push(()=>{q.removeEventListener("dragenter",Tc,dr),q.removeEventListener("dragleave",kc,dr),e.removeEventListener("dragover",Ec,dr),e.removeEventListener("drop",Mc,dr),Ha.removeEventListener("dragover",Lc),Ha.removeEventListener("drop",Ic),al()}),ht.push(()=>{V.cancel()}),en?ht.push(()=>{en==null||en.destroy()}):tn&&ht.push(()=>{tn==null||tn.remove()});let ln={update(c){var Ho,pn,Wn,mo,kr,Er,Da,Ns,Ed,Md,Ld,Id,Rd,Pd,Wd,Bd,Hd,Dd,Fd,Od,Nd,_d,Vd,$d,Ud,zd,qd,jd,Kd,Gd,Yd,Xd,Jd,Qd,Zd,ep,tp,np,op,rp,sp,ap,ip,lp,cp,dp,pp,up,mp,fp,gp,hp,bp,yp,vp,xp,wp,Cp,Sp,Ap,Tp,kp,Ep,Mp,Lp,Ip,Rp,Pp,Wp,Bp,Hp,Dp,Fp,Op,Np,_p,Vp,$p,Up,zp,qp,jp,Kp,Gp,Yp,Xp,Jp,Qp,Zp,eu,tu,nu,ou,ru,su,au,iu,lu,cu,du,pu,uu,mu,fu,gu,hu,bu,yu,vu,xu,wu,Cu,Su,Au,Tu;let p=o.toolCall,h=o.messageActions,y=(Ho=o.layout)==null?void 0:Ho.messages,M=o.colorScheme,O=o.loadingIndicator,N=o.iterationDisplay,z=(pn=o.features)==null?void 0:pn.showReasoning,F=(Wn=o.features)==null?void 0:Wn.showToolCalls,we=(mo=o.features)==null?void 0:mo.toolCallDisplay,fe=(kr=o.features)==null?void 0:kr.reasoningDisplay;o={...o,...c},yo(),os(e,o),Ni(e,o),_i(e,o),Gn(),o.colorScheme!==M&&or();let te=Jl.getForInstance(o.plugins);r.length=0,r.push(...te),L=(Da=(Er=o.launcher)==null?void 0:Er.enabled)!=null?Da:!0,I=(Ed=(Ns=o.launcher)==null?void 0:Ns.autoExpand)!=null?Ed:!1,ue=(Ld=(Md=o.features)==null?void 0:Md.showReasoning)!=null?Ld:!0,ce=(Rd=(Id=o.features)==null?void 0:Id.showToolCalls)!=null?Rd:!0,ve=(Wd=(Pd=o.features)==null?void 0:Pd.scrollToBottom)!=null?Wd:{};let Te=ft();He=(Hd=(Bd=o.features)==null?void 0:Bd.scrollBehavior)!=null?Hd:{},Te!==ft()&&(wr(),Wo()),Eo(),Nn();let _e=ke;if(ke=(Fd=(Dd=o.features)==null?void 0:Dd.showEventStreamToggle)!=null?Fd:!1,ke&&!_e){if(be||(X=new ua(ie),be=new pa(re,X),he=he!=null?he:new ma,X.open().then(()=>be==null?void 0:be.restore()).catch(()=>{}),V.setSSEEventCallback((J,kt)=>{var Ut;(Ut=o.onSSEEvent)==null||Ut.call(o,J,kt),he==null||he.processEvent(J,kt),be.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:J,timestamp:Date.now(),payload:JSON.stringify(kt)})})),!xt&&Ne){let J=(Nd=(Od=o.features)==null?void 0:Od.eventStream)==null?void 0:Nd.classNames,kt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(J!=null&&J.toggleButton?" "+J.toggleButton:"");xt=b("button",kt),xt.style.width="28px",xt.style.height="28px",xt.style.color=Hn.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let Ut=Ee("activity","18px","currentColor",1.5);Ut&&xt.appendChild(Ut);let mt=We.clearChatButtonWrapper,Wt=We.closeButtonWrapper,fn=mt||Wt;fn&&fn.parentNode===Ne?Ne.insertBefore(xt,fn):Ne.appendChild(xt),xt.addEventListener("click",()=>{se?bo():No()})}}else!ke&&_e&&(bo(),xt&&(xt.remove(),xt=null),be==null||be.clear(),X==null||X.destroy(),be=null,X=null,he==null||he.reset(),he=null);if(((_d=o.launcher)==null?void 0:_d.enabled)===!1&&en&&(en.destroy(),en=null),((Vd=o.launcher)==null?void 0:Vd.enabled)===!1&&tn&&(tn.remove(),tn=null),(($d=o.launcher)==null?void 0:$d.enabled)!==!1&&!en&&!tn){let J=r.find(kt=>kt.renderLauncher);if(J!=null&&J.renderLauncher){let kt=J.renderLauncher({config:o,defaultRenderer:()=>ia(o,Qr).element,onToggle:Qr});kt&&(tn=kt,e.appendChild(tn))}tn||(en=ia(o,Qr),e.appendChild(en.element))}en&&en.update(o),De&&((Ud=o.launcher)==null?void 0:Ud.title)!==void 0&&(De.textContent=o.launcher.title),je&&((zd=o.launcher)==null?void 0:zd.subtitle)!==void 0&&(je.textContent=o.launcher.subtitle);let Ae=(qd=o.layout)==null?void 0:qd.header;if((Ae==null?void 0:Ae.layout)!==w&&Ne){let J=Ae?Ti(o,Ae,{showClose:S(),onClose:()=>Ft(!1,"user")}):Dr({config:o,showClose:S(),onClose:()=>Ft(!1,"user")});Ne.replaceWith(J.header),Ne=J.header,pe=J.iconHolder,De=J.headerTitle,je=J.headerSubtitle,D=J.closeButton,w=Ae==null?void 0:Ae.layout}else if(Ae&&(pe&&(pe.style.display=Ae.showIcon===!1?"none":""),De&&(De.style.display=Ae.showTitle===!1?"none":""),je&&(je.style.display=Ae.showSubtitle===!1?"none":""),D&&(D.style.display=Ae.showCloseButton===!1?"none":""),We.clearChatButtonWrapper)){let J=Ae.showClearChat;if(J!==void 0){We.clearChatButtonWrapper.style.display=J?"":"none";let{closeButtonWrapper:kt}=We;kt&&!kt.classList.contains("persona-absolute")&&(J?kt.classList.remove("persona-ml-auto"):kt.classList.add("persona-ml-auto"))}}let qe=((jd=o.layout)==null?void 0:jd.showHeader)!==!1;Ne&&(Ne.style.display=qe?"":"none");let ct=((Kd=o.layout)==null?void 0:Kd.showFooter)!==!1;Ve&&(Ve.style.display=ct?"":"none"),bn(),Nn(),L!==P?L?Ft(I,"auto"):(T=!0,lr()):I!==H&&Ft(I,"auto"),H=I,P=L,Fs(),Cc();let Le=JSON.stringify(c.toolCall)!==JSON.stringify(p),Ue=JSON.stringify(o.messageActions)!==JSON.stringify(h),Ge=JSON.stringify((Gd=o.layout)==null?void 0:Gd.messages)!==JSON.stringify(y),wt=((Yd=o.loadingIndicator)==null?void 0:Yd.render)!==(O==null?void 0:O.render)||((Xd=o.loadingIndicator)==null?void 0:Xd.renderIdle)!==(O==null?void 0:O.renderIdle)||((Jd=o.loadingIndicator)==null?void 0:Jd.showBubble)!==(O==null?void 0:O.showBubble),B=o.iterationDisplay!==N,Be=((Zd=(Qd=o.features)==null?void 0:Qd.showReasoning)!=null?Zd:!0)!==(z!=null?z:!0)||((tp=(ep=o.features)==null?void 0:ep.showToolCalls)!=null?tp:!0)!==(F!=null?F:!0)||JSON.stringify((np=o.features)==null?void 0:np.toolCallDisplay)!==JSON.stringify(we)||JSON.stringify((op=o.features)==null?void 0:op.reasoningDisplay)!==JSON.stringify(fe);(Le||Ue||Ge||wt||B||Be)&&V&&(Cs++,Cr(et,V.getMessages(),ge));let ye=(rp=o.launcher)!=null?rp:{},_t=(sp=ye.headerIconHidden)!=null?sp:!1,Ot=(ip=(ap=o.layout)==null?void 0:ap.header)==null?void 0:ip.showIcon,Gt=_t||Ot===!1,Ct=ye.headerIconName,qt=(lp=ye.headerIconSize)!=null?lp:"48px";if(pe){let J=q.querySelector(".persona-border-b-persona-divider"),kt=J==null?void 0:J.querySelector(".persona-flex-col");if(Gt)pe.style.display="none",J&&kt&&!J.contains(kt)&&J.insertBefore(kt,J.firstChild);else{if(pe.style.display="",pe.style.height=qt,pe.style.width=qt,J&&kt&&(J.contains(pe)?pe.nextSibling!==kt&&(pe.remove(),J.insertBefore(pe,kt)):J.insertBefore(pe,kt)),Ct){let mt=parseFloat(qt)||24,Wt=Ee(Ct,mt*.6,"#ffffff",2);Wt?pe.replaceChildren(Wt):pe.textContent=(cp=ye.agentIconText)!=null?cp:"\u{1F4AC}"}else if(ye.iconUrl){let mt=pe.querySelector("img");if(mt)mt.src=ye.iconUrl,mt.style.height=qt,mt.style.width=qt;else{let Wt=document.createElement("img");Wt.src=ye.iconUrl,Wt.alt="",Wt.className="persona-rounded-xl persona-object-cover",Wt.style.height=qt,Wt.style.width=qt,pe.replaceChildren(Wt)}}else{let mt=pe.querySelector("svg"),Wt=pe.querySelector("img");(mt||Wt)&&pe.replaceChildren(),pe.textContent=(dp=ye.agentIconText)!=null?dp:"\u{1F4AC}"}let Ut=pe.querySelector("img");Ut&&(Ut.style.height=qt,Ut.style.width=qt)}}let Qn=(up=(pp=o.layout)==null?void 0:pp.header)==null?void 0:up.showTitle,on=(fp=(mp=o.layout)==null?void 0:mp.header)==null?void 0:fp.showSubtitle;if(De&&(De.style.display=Qn===!1?"none":""),je&&(je.style.display=on===!1?"none":""),D){((hp=(gp=o.layout)==null?void 0:gp.header)==null?void 0:hp.showCloseButton)===!1?D.style.display="none":D.style.display="";let kt=(bp=ye.closeButtonSize)!=null?bp:"32px",Ut=(yp=ye.closeButtonPlacement)!=null?yp:"inline";D.style.height=kt,D.style.width=kt;let{closeButtonWrapper:mt}=We,Wt=Ut==="top-right",fn=mt==null?void 0:mt.classList.contains("persona-absolute");if(mt&&Wt!==fn)if(mt.remove(),Wt)mt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",q.style.position="relative",q.appendChild(mt);else{let gt=(xp=(vp=ye.clearChat)==null?void 0:vp.placement)!=null?xp:"inline",gn=(Cp=(wp=ye.clearChat)==null?void 0:wp.enabled)!=null?Cp:!0;mt.className=gn&>==="inline"?"":"persona-ml-auto";let Vn=q.querySelector(".persona-border-b-persona-divider");Vn&&Vn.appendChild(mt)}if(D.style.color=ye.closeButtonColor||Hn.actionIconColor,ye.closeButtonBackgroundColor?(D.style.backgroundColor=ye.closeButtonBackgroundColor,D.classList.remove("hover:persona-bg-gray-100")):(D.style.backgroundColor="",D.classList.add("hover:persona-bg-gray-100")),ye.closeButtonBorderWidth||ye.closeButtonBorderColor){let gt=ye.closeButtonBorderWidth||"0px",gn=ye.closeButtonBorderColor||"transparent";D.style.border=`${gt} solid ${gn}`,D.classList.remove("persona-border-none")}else D.style.border="",D.classList.add("persona-border-none");ye.closeButtonBorderRadius?(D.style.borderRadius=ye.closeButtonBorderRadius,D.classList.remove("persona-rounded-full")):(D.style.borderRadius="",D.classList.add("persona-rounded-full")),ye.closeButtonPaddingX?(D.style.paddingLeft=ye.closeButtonPaddingX,D.style.paddingRight=ye.closeButtonPaddingX):(D.style.paddingLeft="",D.style.paddingRight=""),ye.closeButtonPaddingY?(D.style.paddingTop=ye.closeButtonPaddingY,D.style.paddingBottom=ye.closeButtonPaddingY):(D.style.paddingTop="",D.style.paddingBottom="");let Tn=(Sp=ye.closeButtonIconName)!=null?Sp:"x",So=(Ap=ye.closeButtonIconText)!=null?Ap:"\xD7";D.innerHTML="";let Bn=Ee(Tn,"28px","currentColor",1);Bn?D.appendChild(Bn):D.textContent=So;let nn=(Tp=ye.closeButtonTooltipText)!=null?Tp:"Close chat",eo=(kp=ye.closeButtonShowTooltip)!=null?kp:!0;if(D.setAttribute("aria-label",nn),mt&&(mt._cleanupTooltip&&(mt._cleanupTooltip(),delete mt._cleanupTooltip),eo&&nn)){let gt=null,gn=()=>{if(gt||!D)return;let Mr=D.ownerDocument,_s=Mr.body;if(!_s)return;gt=Fo(Mr,"div","persona-clear-chat-tooltip"),gt.textContent=nn;let Vs=Fo(Mr,"div");Vs.className="persona-clear-chat-tooltip-arrow",gt.appendChild(Vs);let Lr=D.getBoundingClientRect();gt.style.position="fixed",gt.style.zIndex=String(mr),gt.style.left=`${Lr.left+Lr.width/2}px`,gt.style.top=`${Lr.top-8}px`,gt.style.transform="translate(-50%, -100%)",_s.appendChild(gt)},Vn=()=>{gt&>.parentNode&&(gt.parentNode.removeChild(gt),gt=null)};mt.addEventListener("mouseenter",gn),mt.addEventListener("mouseleave",Vn),D.addEventListener("focus",gn),D.addEventListener("blur",Vn),mt._cleanupTooltip=()=>{Vn(),mt&&(mt.removeEventListener("mouseenter",gn),mt.removeEventListener("mouseleave",Vn)),D&&(D.removeEventListener("focus",gn),D.removeEventListener("blur",Vn))}}}let{clearChatButton:Ye,clearChatButtonWrapper:Pt}=We;if(Ye){let J=(Ep=ye.clearChat)!=null?Ep:{},kt=(Mp=J.enabled)!=null?Mp:!0,Ut=(Ip=(Lp=o.layout)==null?void 0:Lp.header)==null?void 0:Ip.showClearChat,mt=Ut!==void 0?Ut:kt,Wt=(Rp=J.placement)!=null?Rp:"inline";if(Pt){Pt.style.display=mt?"":"none";let{closeButtonWrapper:fn}=We;!k()&&fn&&!fn.classList.contains("persona-absolute")&&(mt?fn.classList.remove("persona-ml-auto"):fn.classList.add("persona-ml-auto"));let Tn=Wt==="top-right",So=Pt.classList.contains("persona-absolute");if(!k()&&Tn!==So&&mt){if(Pt.remove(),Tn)Pt.className="persona-absolute persona-top-4 persona-z-50",Pt.style.right="48px",q.style.position="relative",q.appendChild(Pt);else{Pt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Pt.style.right="";let nn=q.querySelector(".persona-border-b-persona-divider"),eo=We.closeButtonWrapper;nn&&eo&&eo.parentElement===nn?nn.insertBefore(Pt,eo):nn&&nn.appendChild(Pt)}let Bn=We.closeButtonWrapper;Bn&&!Bn.classList.contains("persona-absolute")&&(Tn?Bn.classList.add("persona-ml-auto"):Bn.classList.remove("persona-ml-auto"))}}if(mt){if(!k()){let gt=(Pp=J.size)!=null?Pp:"32px";Ye.style.height=gt,Ye.style.width=gt}let fn=(Wp=J.iconName)!=null?Wp:"refresh-cw",Tn=(Bp=J.iconColor)!=null?Bp:"";Ye.style.color=Tn||Hn.actionIconColor,Ye.innerHTML="";let So=k()?"14px":"20px",Bn=Ee(fn,So,"currentColor",2);if(Bn&&Ye.appendChild(Bn),J.backgroundColor?(Ye.style.backgroundColor=J.backgroundColor,Ye.classList.remove("hover:persona-bg-gray-100")):(Ye.style.backgroundColor="",Ye.classList.add("hover:persona-bg-gray-100")),J.borderWidth||J.borderColor){let gt=J.borderWidth||"0px",gn=J.borderColor||"transparent";Ye.style.border=`${gt} solid ${gn}`,Ye.classList.remove("persona-border-none")}else Ye.style.border="",Ye.classList.add("persona-border-none");J.borderRadius?(Ye.style.borderRadius=J.borderRadius,Ye.classList.remove("persona-rounded-full")):(Ye.style.borderRadius="",Ye.classList.add("persona-rounded-full")),J.paddingX?(Ye.style.paddingLeft=J.paddingX,Ye.style.paddingRight=J.paddingX):(Ye.style.paddingLeft="",Ye.style.paddingRight=""),J.paddingY?(Ye.style.paddingTop=J.paddingY,Ye.style.paddingBottom=J.paddingY):(Ye.style.paddingTop="",Ye.style.paddingBottom="");let nn=(Hp=J.tooltipText)!=null?Hp:"Clear chat",eo=(Dp=J.showTooltip)!=null?Dp:!0;if(Ye.setAttribute("aria-label",nn),Pt&&(Pt._cleanupTooltip&&(Pt._cleanupTooltip(),delete Pt._cleanupTooltip),eo&&nn)){let gt=null,gn=()=>{if(gt||!Ye)return;let Mr=Ye.ownerDocument,_s=Mr.body;if(!_s)return;gt=Fo(Mr,"div","persona-clear-chat-tooltip"),gt.textContent=nn;let Vs=Fo(Mr,"div");Vs.className="persona-clear-chat-tooltip-arrow",gt.appendChild(Vs);let Lr=Ye.getBoundingClientRect();gt.style.position="fixed",gt.style.zIndex=String(mr),gt.style.left=`${Lr.left+Lr.width/2}px`,gt.style.top=`${Lr.top-8}px`,gt.style.transform="translate(-50%, -100%)",_s.appendChild(gt)},Vn=()=>{gt&>.parentNode&&(gt.parentNode.removeChild(gt),gt=null)};Pt.addEventListener("mouseenter",gn),Pt.addEventListener("mouseleave",Vn),Ye.addEventListener("focus",gn),Ye.addEventListener("blur",Vn),Pt._cleanupTooltip=()=>{Vn(),Pt&&(Pt.removeEventListener("mouseenter",gn),Pt.removeEventListener("mouseleave",Vn)),Ye&&(Ye.removeEventListener("focus",gn),Ye.removeEventListener("blur",Vn))}}}}let cn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Zl],uo=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[fa.message,fa.messageAndClick];E=ec({parsers:cn,handlers:uo,getSessionMetadata:g,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),ge=Tf(o,E,G),V.updateConfig(o),Cr(et,V.getMessages(),ge),ao.render(o.suggestionChips,V,ee,void 0,o.suggestionChipsConfig),Hs(),Xr(V.isStreaming());let Zn=((Fp=o.voiceRecognition)==null?void 0:Fp.enabled)===!0,Sr=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Ar=((Np=(Op=o.voiceRecognition)==null?void 0:Op.provider)==null?void 0:Np.type)==="runtype";if(Zn&&(Sr||Ar))if(!K||!vt){let J=Co(o.voiceRecognition,o.sendButton);J&&(K=J.micButton,vt=J.micButtonWrapper,jt.insertBefore(vt,Dn),K.addEventListener("click",Ba),K.disabled=V.isStreaming())}else{let J=(_p=o.voiceRecognition)!=null?_p:{},kt=(Vp=o.sendButton)!=null?Vp:{},Ut=($p=J.iconName)!=null?$p:"mic",mt=(Up=kt.size)!=null?Up:"40px",Wt=(zp=J.iconSize)!=null?zp:mt,fn=parseFloat(Wt)||24;K.style.width=Wt,K.style.height=Wt,K.style.minWidth=Wt,K.style.minHeight=Wt;let Tn=(jp=(qp=J.iconColor)!=null?qp:kt.textColor)!=null?jp:"currentColor";K.innerHTML="";let So=Ee(Ut,fn,Tn,2);So?K.appendChild(So):K.textContent="\u{1F3A4}";let Bn=(Kp=J.backgroundColor)!=null?Kp:kt.backgroundColor;Bn?K.style.backgroundColor=Bn:K.style.backgroundColor="",Tn?K.style.color=Tn:K.style.color="var(--persona-text, #111827)",J.borderWidth?(K.style.borderWidth=J.borderWidth,K.style.borderStyle="solid"):(K.style.borderWidth="",K.style.borderStyle=""),J.borderColor?K.style.borderColor=J.borderColor:K.style.borderColor="",J.paddingX?(K.style.paddingLeft=J.paddingX,K.style.paddingRight=J.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),J.paddingY?(K.style.paddingTop=J.paddingY,K.style.paddingBottom=J.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let nn=vt==null?void 0:vt.querySelector(".persona-send-button-tooltip"),eo=(Gp=J.tooltipText)!=null?Gp:"Start voice recognition";if(((Yp=J.showTooltip)!=null?Yp:!1)&&eo)if(nn)nn.textContent=eo,nn.style.display="";else{let gn=document.createElement("div");gn.className="persona-send-button-tooltip",gn.textContent=eo,vt==null||vt.insertBefore(gn,K)}else nn&&(nn.style.display="none");vt.style.display="",K.disabled=V.isStreaming()}else K&&vt&&(vt.style.display="none",((Jp=(Xp=o.voiceRecognition)==null?void 0:Xp.provider)==null?void 0:Jp.type)==="runtype"?V.isVoiceActive()&&V.toggleVoice():lt&&$t());if(((Qp=o.attachments)==null?void 0:Qp.enabled)===!0)if(!Ce||!rt){let J=(Zp=o.attachments)!=null?Zp:{},Ut=(tu=((eu=o.sendButton)!=null?eu:{}).size)!=null?tu:"40px";Ze||(Ze=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ze.style.display="none",Ht.insertBefore(Ze,ee)),le||(le=document.createElement("input"),le.type="file",le.accept=((nu=J.allowedTypes)!=null?nu:Yo).join(","),le.multiple=((ou=J.maxFiles)!=null?ou:4)>1,le.style.display="none",le.setAttribute("aria-label","Attach files"),Ht.insertBefore(le,ee)),Ce=b("div","persona-send-button-wrapper"),rt=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),rt.type="button",rt.setAttribute("aria-label",(ru=J.buttonTooltipText)!=null?ru:"Attach file");let mt=(su=J.buttonIconName)!=null?su:"paperclip",Wt=Ut,fn=parseFloat(Wt)||40,Tn=Math.round(fn*.6);rt.style.width=Wt,rt.style.height=Wt,rt.style.minWidth=Wt,rt.style.minHeight=Wt,rt.style.fontSize="18px",rt.style.lineHeight="1",rt.style.backgroundColor="transparent",rt.style.color="var(--persona-primary, #111827)",rt.style.border="none",rt.style.borderRadius="6px",rt.style.transition="background-color 0.15s ease",rt.addEventListener("mouseenter",()=>{rt.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),rt.addEventListener("mouseleave",()=>{rt.style.backgroundColor="transparent"});let So=Ee(mt,Tn,"currentColor",1.5);So?rt.appendChild(So):rt.textContent="\u{1F4CE}",rt.addEventListener("click",eo=>{eo.preventDefault(),le==null||le.click()}),Ce.appendChild(rt);let Bn=(au=J.buttonTooltipText)!=null?au:"Attach file",nn=b("div","persona-send-button-tooltip");nn.textContent=Bn,Ce.appendChild(nn),Rt.append(Ce),!St&&le&&Ze&&(St=ea.fromConfig(J),St.setPreviewsContainer(Ze),le.addEventListener("change",async()=>{St&&(le!=null&&le.files)&&(await St.handleFileSelect(le.files),le.value="")})),q.querySelector(".persona-attachment-drop-overlay")||q.appendChild(kf(J.dropOverlay))}else{Ce.style.display="";let J=(iu=o.attachments)!=null?iu:{};le&&(le.accept=((lu=J.allowedTypes)!=null?lu:Yo).join(","),le.multiple=((cu=J.maxFiles)!=null?cu:4)>1),St&&St.updateConfig({allowedTypes:J.allowedTypes,maxFileSize:J.maxFileSize,maxFiles:J.maxFiles})}else Ce&&(Ce.style.display="none"),St&&St.clearAttachments(),(du=q.querySelector(".persona-attachment-drop-overlay"))==null||du.remove();let Yt=(pu=o.sendButton)!=null?pu:{},Tr=(uu=Yt.useIcon)!=null?uu:!1,pr=(mu=Yt.iconText)!=null?mu:"\u2191",ur=Yt.iconName,Go=(fu=Yt.tooltipText)!=null?fu:"Send message",ot=(gu=Yt.showTooltip)!=null?gu:!1,vn=(hu=Yt.size)!=null?hu:"40px",Pn=Yt.backgroundColor,rn=Yt.textColor;if(Tr){if(ze.style.width=vn,ze.style.height=vn,ze.style.minWidth=vn,ze.style.minHeight=vn,ze.style.fontSize="18px",ze.style.lineHeight="1",ze.innerHTML="",rn?ze.style.color=rn:ze.style.color="var(--persona-button-primary-fg, #ffffff)",ur){let J=parseFloat(vn)||24,kt=(rn==null?void 0:rn.trim())||"currentColor",Ut=Ee(ur,J,kt,2);Ut?ze.appendChild(Ut):ze.textContent=pr}else ze.textContent=pr;ze.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Pn?(ze.style.backgroundColor=Pn,ze.classList.remove("persona-bg-persona-primary")):(ze.style.backgroundColor="",ze.classList.add("persona-bg-persona-primary"))}else ze.textContent=(yu=(bu=o.copy)==null?void 0:bu.sendButtonLabel)!=null?yu:"Send",ze.style.width="",ze.style.height="",ze.style.minWidth="",ze.style.minHeight="",ze.style.fontSize="",ze.style.lineHeight="",ze.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Pn?(ze.style.backgroundColor=Pn,ze.classList.remove("persona-bg-persona-accent")):ze.classList.add("persona-bg-persona-accent"),rn?ze.style.color=rn:ze.classList.add("persona-text-white");Yt.borderWidth?(ze.style.borderWidth=Yt.borderWidth,ze.style.borderStyle="solid"):(ze.style.borderWidth="",ze.style.borderStyle=""),Yt.borderColor?ze.style.borderColor=Yt.borderColor:ze.style.borderColor="",Yt.paddingX?(ze.style.paddingLeft=Yt.paddingX,ze.style.paddingRight=Yt.paddingX):(ze.style.paddingLeft="",ze.style.paddingRight=""),Yt.paddingY?(ze.style.paddingTop=Yt.paddingY,ze.style.paddingBottom=Yt.paddingY):(ze.style.paddingTop="",ze.style.paddingBottom="");let pt=Dn==null?void 0:Dn.querySelector(".persona-send-button-tooltip");if(ot&&Go)if(pt)pt.textContent=Go,pt.style.display="";else{let J=document.createElement("div");J.className="persona-send-button-tooltip",J.textContent=Go,Dn==null||Dn.insertBefore(J,ze)}else pt&&(pt.style.display="none");let bt=(Su=(vu=o.layout)==null?void 0:vu.contentMaxWidth)!=null?Su:k()?(Cu=(wu=(xu=o.launcher)==null?void 0:xu.composerBar)==null?void 0:wu.contentMaxWidth)!=null?Cu:"720px":void 0;bt?(et.style.maxWidth=bt,et.style.marginLeft="auto",et.style.marginRight="auto",et.style.width="100%",Ht&&(Ht.style.maxWidth=bt,Ht.style.marginLeft="auto",Ht.style.marginRight="auto"),Et&&(Et.style.maxWidth=bt,Et.style.marginLeft="auto",Et.style.marginRight="auto")):(et.style.maxWidth="",et.style.marginLeft="",et.style.marginRight="",et.style.width="",Ht&&(Ht.style.maxWidth="",Ht.style.marginLeft="",Ht.style.marginRight=""),Et&&(Et.style.maxWidth="",Et.style.marginLeft="",Et.style.marginRight=""));let ut=(Au=o.statusIndicator)!=null?Au:{},_n=(Tu=ut.visible)!=null?Tu:!0;if(sn.style.display=_n?"":"none",V){let J=V.getStatus();it(sn,(Ut=>{var mt,Wt,fn,Tn;return Ut==="idle"?(mt=ut.idleText)!=null?mt:kn.idle:Ut==="connecting"?(Wt=ut.connectingText)!=null?Wt:kn.connecting:Ut==="connected"?(fn=ut.connectedText)!=null?fn:kn.connected:Ut==="error"?(Tn=ut.errorText)!=null?Tn:kn.error:kn[Ut]})(J),ut,J)}sn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let dn=ut.align==="left"?"persona-text-left":ut.align==="center"?"persona-text-center":"persona-text-right";sn.classList.add(dn)},open(){S()&&Ft(!0,"api")},close(){S()&&Ft(!1,"api")},toggle(){S()&&Ft(!T,"api")},clearChat(){In=!1,V.clearMessages(),Uo.clear(),Wo();try{localStorage.removeItem(bs),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${bs}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==bs)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let p=i.clear();p instanceof Promise&&p.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}d={},E.syncFromMetadata(),be==null||be.clear(),he==null||he.reset(),j==null||j.update()},setMessage(c){return!ee||V.isStreaming()?!1:(!T&&S()&&Ft(!0,"system"),ee.value=c,ee.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(V.isStreaming())return!1;let p=(c==null?void 0:c.trim())||ee.value.trim();return p?(!T&&S()&&Ft(!0,"system"),ee.value="",ee.style.height="auto",V.sendMessage(p),!0):!1},startVoiceRecognition(){var p,h;return V.isStreaming()?!1:((h=(p=o.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype"?(V.isVoiceActive()||(!T&&S()&&Ft(!0,"system"),yt.manuallyDeactivated=!1,On(),V.toggleVoice().then(()=>{yt.active=V.isVoiceActive(),lo("user"),V.isVoiceActive()&&Ds()})),!0):lt?!0:An()?(!T&&S()&&Ft(!0,"system"),yt.manuallyDeactivated=!1,On(),mn("user"),!0):!1},stopVoiceRecognition(){var c,p;return((p=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:p.type)==="runtype"?V.isVoiceActive()?(V.toggleVoice().then(()=>{yt.active=!1,yt.manuallyDeactivated=!0,On(),lo("user"),cr()}),!0):!1:lt?(yt.manuallyDeactivated=!0,On(),$t("user"),!0):!1},injectMessage(c){return!T&&S()&&Ft(!0,"system"),V.injectMessage(c)},injectAssistantMessage(c){!T&&S()&&Ft(!0,"system");let p=V.injectAssistantMessage(c);return _&&(_=!1,U&&(clearTimeout(U),U=null),setTimeout(()=>{V&&!V.isStreaming()&&V.continueConversation()},100)),p},injectUserMessage(c){return!T&&S()&&Ft(!0,"system"),V.injectUserMessage(c)},injectSystemMessage(c){return!T&&S()&&Ft(!0,"system"),V.injectSystemMessage(c)},injectMessageBatch(c){return!T&&S()&&Ft(!0,"system"),V.injectMessageBatch(c)},injectComponentDirective(c){return!T&&S()&&Ft(!0,"system"),V.injectComponentDirective(c)},injectTestMessage(c){!T&&S()&&Ft(!0,"system"),V.injectTestEvent(c)},async connectStream(c,p){return V.connectStream(c,p)},__pushEventStreamEvent(c){be&&(he==null||he.processEvent(c.type,c.payload),be.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!ke||!be||No()},hideEventStream(){se&&bo()},isEventStreamVisible(){return se},showArtifacts(){ho(o)&&(In=!1,Gn(),At==null||At.setMobileOpen(!0))},hideArtifacts(){ho(o)&&(In=!0,Gn())},upsertArtifact(c){return ho(o)?(In=!1,V.upsertArtifact(c)):null},selectArtifact(c){ho(o)&&V.selectArtifact(c)},clearArtifacts(){ho(o)&&V.clearArtifacts()},getArtifacts(){var c;return(c=V==null?void 0:V.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=V==null?void 0:V.getSelectedArtifactId())!=null?c:null},focusInput(){return L&&!T&&!k()||!ee?!1:(ee.focus(),!0)},async resolveApproval(c,p,h){let M=V.getMessages().find(O=>{var N;return O.variant==="approval"&&((N=O.approval)==null?void 0:N.id)===c});if(!(M!=null&&M.approval))throw new Error(`Approval not found: ${c}`);if(M.approval.toolType==="webmcp"){V.resolveWebMcpApproval(M.id,p);return}return V.resolveApproval(M.approval,p,h)},getMessages(){return V.getMessages()},getStatus(){return V.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){m(c)},on(c,p){return s.on(c,p)},off(c,p){s.off(c,p)},isOpen(){return S()&&T},isVoiceActive(){return yt.active},getState(){return{open:S()&&T,launcherEnabled:L,voiceActive:yt.active,streaming:V.isStreaming()}},showCSATFeedback(c){!T&&S()&&Ft(!0,"system");let p=et.querySelector(".persona-feedback-container");p&&p.remove();let h=Cf({onSubmit:async(y,M)=>{var O;V.isClientTokenMode()&&await V.submitCSATFeedback(y,M),(O=c==null?void 0:c.onSubmit)==null||O.call(c,y,M)},onDismiss:c==null?void 0:c.onDismiss,...c});et.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!T&&S()&&Ft(!0,"system");let p=et.querySelector(".persona-feedback-container");p&&p.remove();let h=Sf({onSubmit:async(y,M)=>{var O;V.isClientTokenMode()&&await V.submitNPSFeedback(y,M),(O=c==null?void 0:c.onSubmit)==null||O.call(c,y,M)},onDismiss:c==null?void 0:c.onDismiss,...c});et.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,p){return V.submitCSATFeedback(c,p)},async submitNPSFeedback(c,p){return V.submitNPSFeedback(c,p)},destroy(){co!=null&&(clearInterval(co),co=null),ht.forEach(c=>c()),Me.remove(),Xe==null||Xe.remove(),en==null||en.destroy(),tn==null||tn.remove(),io&&D.removeEventListener("click",io)}};if((((wd=n==null?void 0:n.debugTools)!=null?wd:!1)||!!o.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,p={controller:ln,getMessages:ln.getMessages,getStatus:ln.getStatus,getMetadata:ln.getPersistentMetadata,updateMetadata:ln.updatePersistentMetadata,clearHistory:()=>ln.clearChat(),setVoiceActive:h=>h?ln.startVoiceRecognition():ln.stopVoiceRecognition()};window.AgentWidgetBrowser=p,ht.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),p=z=>{let F=z.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&ln.focusInput()};if(window.addEventListener("persona:focusInput",p),ht.push(()=>{window.removeEventListener("persona:focusInput",p)}),ke){let z=we=>{let fe=we.detail;(!(fe!=null&&fe.instanceId)||fe.instanceId===c)&&ln.showEventStream()},F=we=>{let fe=we.detail;(!(fe!=null&&fe.instanceId)||fe.instanceId===c)&&ln.hideEventStream()};window.addEventListener("persona:showEventStream",z),window.addEventListener("persona:hideEventStream",F),ht.push(()=>{window.removeEventListener("persona:showEventStream",z),window.removeEventListener("persona:hideEventStream",F)})}let h=z=>{let F=z.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&ln.showArtifacts()},y=z=>{let F=z.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&ln.hideArtifacts()},M=z=>{let F=z.detail;F!=null&&F.instanceId&&F.instanceId!==c||F!=null&&F.artifact&&ln.upsertArtifact(F.artifact)},O=z=>{let F=z.detail;F!=null&&F.instanceId&&F.instanceId!==c||typeof(F==null?void 0:F.id)=="string"&&ln.selectArtifact(F.id)},N=z=>{let F=z.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&ln.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",M),window.addEventListener("persona:selectArtifact",O),window.addEventListener("persona:clearArtifacts",N),ht.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",M),window.removeEventListener("persona:selectArtifact",O),window.removeEventListener("persona:clearArtifacts",N)})}let po=Jx(o.persistState);if(po&&S()){let c=Qx(po.storage),p=`${po.keyPrefix}widget-open`,h=`${po.keyPrefix}widget-voice`,y=`${po.keyPrefix}widget-voice-mode`;if(c){let M=((Cd=po.persist)==null?void 0:Cd.openState)&&c.getItem(p)==="true",O=((Sd=po.persist)==null?void 0:Sd.voiceState)&&c.getItem(h)==="true",N=((Ad=po.persist)==null?void 0:Ad.voiceState)&&c.getItem(y)==="true";if(M&&setTimeout(()=>{ln.open(),setTimeout(()=>{var z;if(O||N)ln.startVoiceRecognition();else if((z=po.persist)!=null&&z.focusInput){let F=e.querySelector("textarea");F&&F.focus()}},100)},0),(Td=po.persist)!=null&&Td.openState&&(s.on("widget:opened",()=>{c.setItem(p,"true")}),s.on("widget:closed",()=>{c.setItem(p,"false")})),(kd=po.persist)!=null&&kd.voiceState&&(s.on("voice:state",z=>{c.setItem(h,z.active?"true":"false")}),s.on("user:message",z=>{c.setItem(y,z.viaVoice?"true":"false")})),po.clearOnChatClear){let z=()=>{c.removeItem(p),c.removeItem(h),c.removeItem(y)},F=()=>z();window.addEventListener("persona:clear-chat",F),ht.push(()=>{window.removeEventListener("persona:clear-chat",F)})}}}return f&&S()&&setTimeout(()=>{ln.open()},0),Ko(),ln};var Zx=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},Mf=(e,t)=>{var o,r;let n=(r=(o=t==null?void 0:t.launcher)==null?void 0:o.enabled)!=null?r:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},sc=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Lf=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",sc(e)},nc=e=>{e.style.transition=""},oc=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform=""},rc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},$i=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},ew=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},tw=(e,t,n,o,r,s)=>{let a=s?t:e;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},If=(e,t,n,o,r,s,a)=>{var C,v,E,L,I,R;let i=Oo(s),d=i.reveal==="push";ew(e,t,n,o,d),tw(e,t,n,o,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,f=(v=(C=s==null?void 0:s.launcher)==null?void 0:C.mobileFullscreen)!=null?v:!0,u=(L=(E=s==null?void 0:s.launcher)==null?void 0:E.mobileBreakpoint)!=null?L:640,g=l!=null?l.innerWidth<=u:!1;if(f&&g&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),oc(t),nc(o),Lf(o),rc(n),$i(r,o),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String((R=(I=s==null?void 0:s.launcher)==null?void 0:I.zIndex)!=null?R:En),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Lf(o),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",oc(t),nc(o),rc(n),$i(r,o);let H=i.animate?"transform 180ms ease":"none",P=i.side==="right"?"translateX(100%)":"translateX(-100%)",w=a?"translateX(0)":P;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=H,o.style.transform=w,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",i.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",nc(o),sc(o),$i(r,o);let H=Zx(i.width,e.clientWidth),P=Math.max(0,e.clientWidth),w=i.animate?"transform 180ms ease":"none",x=i.side==="right"?a?`translateX(-${H}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${H}px)`;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${P+H}px`,t.style.transition=w,t.style.transform=x,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${P}px`,n.style.maxWidth=`${P}px`,n.style.minWidth=`${P}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.position="relative",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",oc(t),sc(o),rc(n),$i(r,o);let H=i.reveal==="emerge";H?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let P=a?i.width:"0px",w=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",x=!a;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${P}`,o.style.width=P,o.style.maxWidth=P,o.style.minWidth=P,o.style.minHeight="0",o.style.position="relative",o.style.overflow=H||x?"hidden":"visible",o.style.transition=w,H&&(o.style.alignItems=i.side==="right"?"flex-start":"flex-end",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.boxSizing="border-box")}},nw=(e,t)=>{let n=e.ownerDocument.createElement("div");return Mf(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Mf(n,o)},destroy(){n.remove()}}},ow=(e,t)=>{var I,R,H,P;let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),f=n.createElement("div"),u=(R=(I=t==null?void 0:t.launcher)==null?void 0:I.enabled)==null||R?(P=(H=t==null?void 0:t.launcher)==null?void 0:H.autoExpand)!=null?P:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",f.dataset.personaDockRole="host",l.appendChild(f),o.insertBefore(a,e),d.appendChild(e);let g=null,m=()=>{g==null||g.disconnect(),g=null},C=()=>{m(),Oo(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{If(a,i,d,l,f,t,u)}),g.observe(a))},v=()=>{If(a,i,d,l,f,t,u),C()},E=a.ownerDocument.defaultView,L=()=>{v()};return E==null||E.addEventListener("resize",L),Oo(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),v(),{mode:"docked",host:f,shell:a,syncWidgetState(w){let x=w.launcherEnabled?w.open:!0;u!==x&&(u=x,v())},updateConfig(w){var x,k;t=w,((k=(x=t==null?void 0:t.launcher)==null?void 0:x.enabled)!=null?k:!0)===!1&&(u=!0),v()},destroy(){E==null||E.removeEventListener("resize",L),m(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},Rf=(e,t)=>xn(t)?ow(e,t):nw(e,t);var ys={desktop:{w:1280,h:800},mobile:{w:390,h:844}},ac=.15,ic=1.5,Ui="persona-preview-shell-theme",Pf={load:()=>null,save:()=>{},clear:()=>{}},Wf=["How do I get started?","Pricing & plans","Talk to support"];function zi(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Bf(e){return e==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function lc(e){let t=Bf(e);return`* { box-sizing: border-box; }
|
|
108
108
|
html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
|
|
109
109
|
html { color-scheme: ${e}; }
|
|
110
110
|
body { font-family: system-ui, sans-serif; background: ${t.pageBg}; }
|
|
@@ -128,7 +128,7 @@ _Details: ${n.message}_`:o}var Fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
128
128
|
.preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
|
|
129
129
|
.preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
|
|
130
130
|
.preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${t.cardBg}; box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
|
|
131
|
-
.preview-workspace-card.short { height: 96px; }`}function
|
|
131
|
+
.preview-workspace-card.short { height: 96px; }`}function cc(e,t){let n=e.contentDocument;if(!(n!=null&&n.documentElement))return;let o=n.getElementById(Ui);o||(o=n.createElement("style"),o.id=Ui,n.head.appendChild(o)),o.textContent=lc(t)}var Hf=`
|
|
132
132
|
<div class="preview-iframe-mock" aria-hidden="true">
|
|
133
133
|
<div class="preview-iframe-chrome">
|
|
134
134
|
<span class="preview-iframe-dot"></span>
|
|
@@ -147,7 +147,7 @@ _Details: ${n.message}_`:o}var Fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
147
147
|
<div class="preview-iframe-line body"></div>
|
|
148
148
|
<div class="preview-iframe-line body"></div>
|
|
149
149
|
</div>
|
|
150
|
-
</div>`,
|
|
150
|
+
</div>`,Df=`
|
|
151
151
|
<div class="preview-workspace-content-shell" aria-hidden="true">
|
|
152
152
|
<div class="preview-iframe-line hero"></div>
|
|
153
153
|
<div class="preview-iframe-line body"></div>
|
|
@@ -160,8 +160,8 @@ _Details: ${n.message}_`:o}var Fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
160
160
|
<div class="preview-workspace-card short"></div>
|
|
161
161
|
<div class="preview-workspace-card short"></div>
|
|
162
162
|
</div>
|
|
163
|
-
</div>`;function
|
|
164
|
-
${
|
|
163
|
+
</div>`;function dc(e,t,n,o){let r=`
|
|
164
|
+
${Hf}
|
|
165
165
|
<div style="position:fixed;inset:0;z-index:9999;"><div id="${e}" data-mount-id="${e}"></div></div>`,s=`
|
|
166
166
|
<div class="preview-workspace-shell">
|
|
167
167
|
<div class="preview-workspace-topbar">
|
|
@@ -173,7 +173,7 @@ _Details: ${n.message}_`:o}var Fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
173
173
|
</div>
|
|
174
174
|
<div class="preview-workspace-body">
|
|
175
175
|
<div id="preview-content-${e}" class="preview-workspace-content" data-mount-id="${e}">
|
|
176
|
-
${
|
|
176
|
+
${Df}
|
|
177
177
|
</div>
|
|
178
178
|
</div>
|
|
179
179
|
</div>`;return`<!DOCTYPE html>
|
|
@@ -181,19 +181,19 @@ _Details: ${n.message}_`:o}var Fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
181
181
|
<head>
|
|
182
182
|
<meta charset="UTF-8">
|
|
183
183
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
184
|
-
<link rel="stylesheet" href="${
|
|
185
|
-
<style id="${
|
|
184
|
+
<link rel="stylesheet" href="${zi(o)}">
|
|
185
|
+
<style id="${Ui}">${lc(t)}</style>
|
|
186
186
|
</head>
|
|
187
187
|
<body>
|
|
188
188
|
${n?s:r}
|
|
189
189
|
</body>
|
|
190
|
-
</html>`}var
|
|
190
|
+
</html>`}var rw={"user-message":"User message","assistant-message":"Assistant message","assistant-code-block":"Assistant \u2014 code block","assistant-markdown-table":"Assistant \u2014 markdown table","assistant-image":"Assistant \u2014 image","reasoning-streaming":"Reasoning (streaming)","reasoning-complete":"Reasoning (complete)","tool-running":"Tool call (running)","tool-complete":"Tool call (complete)","approval-request":"Approval request"};function sw(e){return rw[e]}function pc(e,t=0){let n=new Date(Date.now()-Math.max(0,60-t)*1e3).toISOString(),o=`${e}-${t}`;switch(e){case"user-message":return{id:`preview-seq-user-${o}`,role:"user",content:"Can you continue with the next step?",createdAt:n};case"assistant-message":return{id:`preview-seq-assistant-${o}`,role:"assistant",content:"Absolutely. I can keep going and explain what happens next.",createdAt:n};case"assistant-code-block":return{id:`preview-seq-assistant-code-${o}`,role:"assistant",content:["Here's how you'd wire up a streaming animation:","","```ts","import { createAgentExperience } from '@runtypelabs/persona';","","createAgentExperience(el, {"," features: {",' streamAnimation: { type: "letter-rise", speed: 120 },'," },","});","```","","Swap the `type` value to try the other presets."].join(`
|
|
191
191
|
`),createdAt:n};case"assistant-markdown-table":return{id:`preview-seq-assistant-table-${o}`,role:"assistant",content:["Here are the built-in streaming animations at a glance:","","| Preset | Wrap unit | Best for |","| ------------ | --------- | --------------------------- |","| Typewriter | Character | Classic terminal feel |","| Letter rise | Character | Soft, staggered entrance |","| Word fade | Word | Longer-form assistant replies |","| Pop bubble | Bubble | Short, punchy affirmations |"].join(`
|
|
192
192
|
`),createdAt:n};case"assistant-image":return{id:`preview-seq-assistant-image-${o}`,role:"assistant",content:["Here's the reference diagram you asked for \u2014 let me know if you'd like a different view:","","","","The gradient shows how per-unit delays stagger across the reply."].join(`
|
|
193
|
-
`),createdAt:n};case"reasoning-streaming":return{id:`preview-seq-reasoning-stream-${o}`,role:"assistant",content:"",createdAt:n,streaming:!0,variant:"reasoning",reasoning:{id:`preview-reasoning-stream-${o}`,status:"streaming",chunks:["Thinking through the next step in the workflow..."]}};case"reasoning-complete":return{id:`preview-seq-reasoning-complete-${o}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"reasoning",reasoning:{id:`preview-reasoning-complete-${o}`,status:"complete",chunks:["Reviewed the requirements and finalized the reasoning output."],durationMs:1200}};case"tool-complete":return{id:`preview-seq-tool-complete-${o}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"tool",toolCall:{id:`preview-tool-complete-${o}`,name:"Create build instructions",status:"complete",chunks:["Prepared the build instructions and validated the inputs."],result:{ok:!0},duration:420}};default:return{id:`preview-seq-tool-running-${o}`,role:"assistant",content:"",createdAt:n,streaming:!0,variant:"tool",toolCall:{id:`preview-tool-running-${o}`,name:"Get platform documentation",status:"running",chunks:["Fetching the relevant platform documentation..."]}}}}function
|
|
194
|
-
${
|
|
195
|
-
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${
|
|
196
|
-
</div>`,
|
|
193
|
+
`),createdAt:n};case"reasoning-streaming":return{id:`preview-seq-reasoning-stream-${o}`,role:"assistant",content:"",createdAt:n,streaming:!0,variant:"reasoning",reasoning:{id:`preview-reasoning-stream-${o}`,status:"streaming",chunks:["Thinking through the next step in the workflow..."]}};case"reasoning-complete":return{id:`preview-seq-reasoning-complete-${o}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"reasoning",reasoning:{id:`preview-reasoning-complete-${o}`,status:"complete",chunks:["Reviewed the requirements and finalized the reasoning output."],durationMs:1200}};case"approval-request":{let r=`preview-approval-${o}`;return{id:`approval-${r}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"approval",approval:{id:r,status:"pending",agentId:"preview-agent",executionId:`preview-exec-${o}`,toolName:"add_to_cart",description:"Add the selected item to the shopping cart. Approve to let the assistant continue.",parameters:{items:[{productEntityId:129,quantity:1}]}}}}case"tool-complete":return{id:`preview-seq-tool-complete-${o}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"tool",toolCall:{id:`preview-tool-complete-${o}`,name:"Create build instructions",status:"complete",chunks:["Prepared the build instructions and validated the inputs."],result:{ok:!0},duration:420}};default:return{id:`preview-seq-tool-running-${o}`,role:"assistant",content:"",createdAt:n,streaming:!0,variant:"tool",toolCall:{id:`preview-tool-running-${o}`,name:"Get platform documentation",status:"running",chunks:["Fetching the relevant platform documentation..."]}}}}function aw(e,t){return[...e,pc(t,e.length)]}function Ff(e){return e==="assistant-message"||e==="assistant-code-block"||e==="assistant-markdown-table"||e==="assistant-image"}function iw(e,t,n){var d,l;let o=pc(e,t);if(!Ff(e)||typeof o.content!="string")return[{message:o,delayMs:0,done:!0}];let r=Math.max(1,(d=n==null?void 0:n.chunkSize)!=null?d:24),s=Math.max(0,(l=n==null?void 0:n.delayMs)!=null?l:42),a=o.content,i=[];i.push({message:{...o,content:"",streaming:!0},delayMs:0,done:!1});for(let f=r;f<a.length;f+=r)i.push({message:{...o,content:a.slice(0,f),streaming:!0},delayMs:s,done:!1});return i.push({message:{...o,content:a,streaming:!1},delayMs:s,done:!0}),i}var lw=()=>[{id:"preview-adv-1",role:"user",content:"Can you create the product and gather the docs?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-adv-2",role:"assistant",content:"",createdAt:new Date(Date.now()-15e4).toISOString(),streaming:!0,variant:"reasoning",reasoning:{id:"preview-reasoning",status:"streaming",chunks:["Now let me get the Persona embed documentation and builtin tools catalog."]}},{id:"preview-adv-3",role:"assistant",content:"",createdAt:new Date(Date.now()-12e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-1",name:"Load tools",status:"running",chunks:["Loaded tools, used Runtype integration"]}},{id:"preview-adv-4",role:"assistant",content:"",createdAt:new Date(Date.now()-9e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-2",name:"Get platform documentation",status:"running",chunks:["Get platform documentation"]}},{id:"preview-adv-5",role:"assistant",content:"I loaded the tools and fetched the docs. Next I can assemble the product details.",createdAt:new Date(Date.now()-3e4).toISOString()}],cw=e=>{var t,n,o,r,s,a,i,d;return!!((n=(t=e==null?void 0:e.features)==null?void 0:t.toolCallDisplay)!=null&&n.activePreview||(r=(o=e==null?void 0:e.features)==null?void 0:o.toolCallDisplay)!=null&&r.grouped||(a=(s=e==null?void 0:e.features)==null?void 0:s.toolCallDisplay)!=null&&a.collapsedMode&&e.features.toolCallDisplay.collapsedMode!=="tool-call"||(d=(i=e==null?void 0:e.features)==null?void 0:i.reasoningDisplay)!=null&&d.activePreview)};function Of(e,t,n=[]){return e==="home"?[{id:"preview-home-1",role:"assistant",content:"Hi there! How can we help today?",createdAt:new Date().toISOString()}]:e==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:e==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:e==="conversation"&&cw(t)?[...lw(),...n]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...n]}function uc(e,t,n=[]){var s,a;let o={...e.launcher,enabled:!0,autoExpand:t!=="minimized"},r={...e,launcher:o,suggestionChips:t==="home"?(s=e.suggestionChips)!=null&&s.length?e.suggestionChips:Wf:e.suggestionChips,initialMessages:Of(t,e,n),storageAdapter:Pf};return t==="artifact"&&(r.features={...r.features,artifacts:{...(a=r.features)==null?void 0:a.artifacts,enabled:!0}}),r}function Vr(e,t){var s,a,i,d;let n=e.theme?un(e.theme,{validate:!1}):un(),o=(s=e.scene)!=null?s:"conversation",r={...Lt,...e.config,theme:n,darkTheme:e.darkTheme,colorScheme:(i=t!=null?t:(a=e.config)==null?void 0:a.colorScheme)!=null?i:"light"};return uc(r,o,(d=e.appendedMessages)!=null?d:[])}function dw(e,t,n){var a,i,d;let o=e.theme?un(e.theme,{validate:!1}):un(),r=(a=e.scene)!=null?a:"conversation",s={...Lt,...e.config,theme:o,darkTheme:e.darkTheme,colorScheme:(d=n!=null?n:(i=e.config)==null?void 0:i.colorScheme)!=null?d:"light"};return uc(s,r,t)}function Nf(e){var o,r,s,a,i;let t=(o=e.compareMode)!=null?o:"off",n=(r=e.shellMode)!=null?r:"light";if(t==="themes")return[{mountId:"preview-light",label:"Light",config:Vr(e,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Vr(e,"dark"),shellMode:"dark"}];if(t==="baseline"&&(e.baselineConfig||e.baselineTheme)){let d={...e,config:(s=e.baselineConfig)!=null?s:e.config,theme:(a=e.baselineTheme)!=null?a:e.theme,darkTheme:(i=e.baselineDarkTheme)!=null?i:e.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:Vr(d,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Vr(e,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Vr(e,n),shellMode:n}]}function pw(e,t){let n={...t},o=[],r=[],s=null,a=!1,i=1,d=1,l=0;function f(){var I;return(I=n.device)!=null?I:"desktop"}function u(){var I;return(I=n.zoom)!=null?I:i}function g(){var T,_;let I=getComputedStyle(e),R=parseFloat(I.paddingLeft)+parseFloat(I.paddingRight),H=parseFloat(I.paddingTop)+parseFloat(I.paddingBottom),P=40,w=((T=n.compareMode)!=null?T:"off")!=="off",x=(e.clientWidth-R-P)/(w?2:1),k=e.clientHeight-H-P;if(x<=0||k<=0)return 1;let S=(_=ys[f()])!=null?_:ys.desktop;return Math.min(x/S.w,k/S.h,1)}function m(){var H,P,w;i=g();let I=Math.max(ac,Math.min(ic,u()));d=I;let R=Array.from(e.querySelectorAll(".preview-iframe-wrapper"));for(let x of R){let k=(H=x.dataset.device)!=null?H:"desktop",S=(P=ys[k])!=null?P:ys.desktop;x.style.width=`${S.w*I}px`,x.style.height=`${S.h*I}px`,k==="mobile"&&(x.style.borderRadius=`${32*I}px`);let T=x.querySelector("iframe");T&&(T.style.width=`${S.w}px`,T.style.height=`${S.h}px`,T.style.transformOrigin="top left",T.style.transition="none",T.style.transform=`scale(${I})`)}(w=n.onScaleChange)==null||w.call(n,I)}function C(){var I;(I=n.onBeforeDestroy)==null||I.call(n);for(let R of o)R.destroy();for(let R of r)R();o=[],r=[]}function v(){return Array.from(e.querySelectorAll("iframe[data-mount-id]"))}function E(){var ce,ke,ve,He;if(a)return;C();let I=++l,R=Nf(n),H=f(),P=((ce=n.compareMode)!=null?ce:"off")!=="off",w=((ke=n.scene)!=null?ke:"conversation")==="minimized",x=(ve=n.widgetCssPath)!=null?ve:"/widget-dist/widget.css",k=(He=n.buildSrcdoc)!=null?He:dc,S=H==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",T=Se=>`<div class="${S}" data-mount-id="${Se.mountId}" data-device="${H}" data-shell-mode="${Se.shellMode}">
|
|
194
|
+
${P?`<div class="preview-frame-meta"><span class="preview-frame-label">${zi(Se.label)}</span></div>`:""}
|
|
195
|
+
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${Se.mountId}"></iframe>
|
|
196
|
+
</div>`,_=P?`<div class="preview-compare-grid">${R.map(Se=>`<div class="preview-compare-cell">${T(Se)}</div>`).join("")}</div>`:`<div class="preview-single">${T(R[0])}</div>`;n.morphContainer?n.morphContainer(e,_):e.innerHTML=_,m();let U=v(),G=0,ge=U.length,ue=()=>{var ie,X,re,be,he;if(a||I!==l)return;for(let j of U){let se=j.dataset.mountId;if(!se||!j.contentDocument)continue;let Ie=R.find(it=>it.mountId===se);if(!Ie)continue;let ne=()=>{},Z=xn(Ie.config),oe=Z?(()=>{var q;let it=(q=j.contentDocument)==null?void 0:q.getElementById(`preview-content-${se}`);if(!it)return null;let Me=Rf(it,Ie.config),de=j.contentDocument.createElement("div");de.id=se,de.style.height="100%",de.style.display="flex",de.style.flexDirection="column",de.style.flex="1",de.style.minHeight="0",Me.host.appendChild(de);let Xe=()=>Me.syncWidgetState(at.getState()),We=ne;return ne=()=>{Me.destroy(),We()},de.__syncDock=Xe,de.__hostLayout=Me,de})():j.contentDocument.getElementById(se);if(!oe)continue;let at=Ef(oe,Ie.config);if(o.push(at),Z&&oe.__syncDock){let it=oe.__syncDock,Me=at.on("widget:opened",it),de=at.on("widget:closed",it),Xe=ne;ne=()=>{Me(),de(),Xe()},it()}r.push(ne),w&&at.close()}if(((ie=n.scene)!=null?ie:"conversation")==="artifact"||(be=(re=(X=n.config)==null?void 0:X.features)==null?void 0:re.artifacts)!=null&&be.enabled)for(let j of o)j.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
|
|
197
197
|
|
|
198
198
|
This is a preview of the artifact sidebar.
|
|
199
199
|
|
|
@@ -201,4 +201,4 @@ This is a preview of the artifact sidebar.
|
|
|
201
201
|
|
|
202
202
|
- Markdown rendering
|
|
203
203
|
- Document toolbar
|
|
204
|
-
- Resizable panes`});(Se=n.onAfterMount)==null||Se.call(n,{iframes:$,controllers:[...o]})};for(let ve of $){let Q=ve.dataset.mountId;if(!Q)continue;let Le=H.find(Y=>Y.mountId===Q);Le&&(ve.addEventListener("load",()=>{j++,j>=me&&se()},{once:!0}),ve.srcdoc=k(Q,Le.shellMode,pn(Le.config),x))}me===0&&se()}function I(){var D;if(a)return;let L=Jm(n);if(o.length!==L.length){M();return}if(L.some(W=>{let v=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${W.mountId}"]`);return!v||v.dataset.shellMode!==W.shellMode})){M();return}o.forEach((W,v)=>{var x;W.update(L[v].config),((x=n.scene)!=null?x:"conversation")==="minimized"&&W.close()});for(let W of L){let v=e.querySelector(`iframe[data-mount-id="${W.mountId}"]`);v&&Kl(v,W.shellMode)}(D=n.onAfterUpdate)==null||D.call(n,{iframes:S(),controllers:[...o]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||p()}),s.observe(e)),M(),{update(L){if(a)return;let H=L.device!==void 0&&L.device!==n.device||L.scene!==void 0&&L.scene!==n.scene||L.compareMode!==void 0&&L.compareMode!==n.compareMode||L.widgetCssPath!==void 0&&L.widgetCssPath!==n.widgetCssPath;n={...n,...L},H?M():I()},destroy(){a||(a=!0,w(),s==null||s.disconnect(),e.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},p())},getIframes(){return S()},getScale(){return d},setZoom(L){a||(n={...n,zoom:L},p())}}}function Vo(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}var Bi={black:"#000000",white:"#ffffff",red:"#ff0000",green:"#008000",lime:"#00ff00",blue:"#0000ff",yellow:"#ffff00",cyan:"#00ffff",aqua:"#00ffff",magenta:"#ff00ff",fuchsia:"#ff00ff",silver:"#c0c0c0",gray:"#808080",grey:"#808080",maroon:"#800000",olive:"#808000",purple:"#800080",teal:"#008080",navy:"#000080",orange:"#ffa500",pink:"#ffc0cb",hotpink:"#ff69b4",gold:"#ffd700",indigo:"#4b0082",violet:"#ee82ee",brown:"#a52a2a",beige:"#f5f5dc",ivory:"#fffff0",khaki:"#f0e68c",coral:"#ff7f50",salmon:"#fa8072",tomato:"#ff6347",crimson:"#dc143c",turquoise:"#40e0d0",lavender:"#e6e6fa",plum:"#dda0dd",orchid:"#da70d6",tan:"#d2b48c",chocolate:"#d2691e",sienna:"#a0522d",slategray:"#708090",slategrey:"#708090",steelblue:"#4682b4",royalblue:"#4169e1",dodgerblue:"#1e90ff",skyblue:"#87ceeb",lightblue:"#add8e6",midnightblue:"#191970",forestgreen:"#228b22",seagreen:"#2e8b57",limegreen:"#32cd32",olivedrab:"#6b8e23",darkgreen:"#006400",emerald:"#50c878",mint:"#3eb489",goldenrod:"#daa520",firebrick:"#b22222",darkred:"#8b0000",indianred:"#cd5c5c",deeppink:"#ff1493",mediumpurple:"#9370db",rebeccapurple:"#663399",darkviolet:"#9400d3",slateblue:"#6a5acd",cornflowerblue:"#6495ed",teal2:"#008080",charcoal:"#36454f",graphite:"#3b3b3b",transparent:"transparent"},xx=/^rgba?\(\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*(,\s*(0|1|0?\.\d+|\d{1,3}%)\s*)?\)$/;function wx(e){return xx.test(e)}function os(e){if(typeof e!="string"||e.trim()==="")throw new Error('Color must be a non-empty string (e.g. "#2563eb" or "blue").');let t=e.trim().toLowerCase(),n=Bi[t];if(n)return n;let o=Es(t);if(Qi(o)||o==="transparent"||wx(o))return o;throw new Error(`"${e}" is not a recognized color. Pass a hex value like "#ef4444" or a CSS color name (e.g. ${Object.keys(Bi).slice(0,6).join(", ")}).`)}var Hi=Ia.map(e=>e==="gray"?"neutral":e),Cx={...Object.fromEntries(Hi.map(e=>[e,e])),gray:"neutral",grey:"neutral"};function Di(e,t=!0){let n=String(e!=null?e:"").trim().toLowerCase(),o=Cx[n];if(!o||!t&&o==="neutral"){let r=t?"primary, secondary, accent, neutral":"primary, secondary, accent";throw new Error(`Unknown color family "${e}". Valid families: ${r}.`)}return o}function Fi(e){let t=String(e!=null?e:"solid").trim().toLowerCase();if(t==="solid"||t==="soft")return t;throw new Error(`Unknown intensity "${e}". Valid intensities: solid, soft.`)}function Oi(e){let t=String(e!=null?e:"").trim().toLowerCase();if(t==="light"||t==="dark"||t==="auto")return t;if(t==="system")return"auto";throw new Error(`Unknown color scheme "${e}". Valid: light, dark, auto.`)}var Sx={sharp:"sharp",square:"sharp",none:"sharp",default:"default",normal:"default",rounded:"rounded",round:"rounded",soft:"rounded",pill:"pill",circle:"pill",full:"pill"};function Ni(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=Sx[t];if(!n)throw new Error(`Unknown roundness "${e}". Valid: sharp, default, rounded, pill.`);return n}function _i(e){if(typeof e=="number"&&Number.isFinite(e))return`${e}px`;if(typeof e=="string"&&e.trim()!==""){let t=e.trim();if(t==="9999px"||/^(100%|9999px)$/.test(t))return"9999px";let n=Yi(t);return Xi(n.value,n.unit)}throw new Error('Radius must be a number (px) or a CSS length string like "0.5rem".')}function Vi(e){for(let t of zr){let n=t.fields.find(o=>o.id===e);if(n!=null&&n.options){let o={};for(let r of n.options){let s=r.value.split(".").pop();s&&(o[s]=r.value)}return o}}return{}}var Zm=Vi("typo-font-family"),ta=Vi("typo-font-size"),na=Vi("typo-font-weight"),Wi=Vi("typo-line-height"),ef={...Zm,monospace:Zm.mono},tf={...ta,small:ta.sm,md:ta.base,medium:ta.base,large:ta.lg},nf={...na,400:na.normal,500:na.medium,600:na.semibold,700:na.bold},of={...Wi,"1.25":Wi.tight,"1.5":Wi.normal,"1.625":Wi.relaxed};function rf(e,t,n){let o=String(e!=null?e:"").trim().toLowerCase(),r=t[o];if(!r){let s=[...new Set(Object.values(t).map(a=>a.split(".").pop()))].join(", ");throw new Error(`Unknown ${n} "${e}". Valid: ${s}.`)}return r}var sf="theme.palette.radius.";function Ax(){var t;let e={pill:{sm:"9999px",md:"9999px",lg:"9999px",xl:"9999px",full:"9999px"}};for(let n of zr)for(let o of(t=n.presets)!=null?t:[]){let r=o.id.match(/^radius-(\w+)$/);if(!r)continue;let s={};for(let[a,i]of Object.entries(o.values))a.startsWith(sf)&&typeof i=="string"&&(s[a.slice(sf.length)]=i);e[r[1]]=s}return e}var ra=Ax(),af=["sm","md","lg","xl","full"];function Ui(e,t,n="theme",o=0){if(o>6)return null;let r=e.get(`${n}.${t}`);return typeof r!="string"||r===""?n==="darkTheme"?Ui(e,t,"theme",o):null:r.startsWith("#")||r.startsWith("rgb")||r==="transparent"?r:r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components.")?Ui(e,r,n,o+1):null}function $i(e,t){let n=e.get(t);if(typeof n!="string")return"unknown";let o=n.split(".");return o[o.length-1]||String(n)}function rs(e){return e.replace(/^role-/,"")}function Tx(e){for(let[t,n]of Object.entries(ra))if(af.every(o=>e[o]===n[o]))return t;return"custom"}function Ir(e){var o,r;let t={};for(let s of af)t[s]=String((o=e.get(`theme.palette.radius.${s}`))!=null?o:"");let n={};for(let s of wr)n[rs(s.roleId)]=tl(a=>e.get(`theme.${a}`),s);return{brand:{primary:Ql(e.get("theme.palette.colors.primary.500")),secondary:Ql(e.get("theme.palette.colors.secondary.500")),accent:Ql(e.get("theme.palette.colors.accent.500"))},roles:n,typography:{fontFamily:$i(e,"theme.semantic.typography.fontFamily"),fontSize:$i(e,"theme.semantic.typography.fontSize"),fontWeight:$i(e,"theme.semantic.typography.fontWeight"),lineHeight:$i(e,"theme.semantic.typography.lineHeight")},roundness:{style:Tx(t),radius:t},colorScheme:String((r=e.get("colorScheme"))!=null?r:"light"),history:{index:e.getHistoryIndex(),canUndo:e.canUndo(),canRedo:e.canRedo()}}}function Ql(e){return typeof e=="string"&&e!==""?e:null}var oa=[{key:"user-message",label:"User message text",fg:"components.message.user.text",bg:"components.message.user.background"},{key:"assistant-message",label:"Assistant message text",fg:"components.message.assistant.text",bg:"components.message.assistant.background"},{key:"header",label:"Header title",fg:"components.header.titleForeground",bg:"components.header.background"},{key:"primary-button",label:"Primary button label",fg:"components.button.primary.foreground",bg:"components.button.primary.background"},{key:"input",label:"Input placeholder",fg:"components.input.placeholder",bg:"components.input.background"},{key:"link",label:"Link text",fg:"components.markdown.link.foreground",bg:"semantic.colors.background"},{key:"scroll",label:"Scroll-to-bottom icon",fg:"components.scrollToBottom.foreground",bg:"components.scrollToBottom.background"},{key:"body",label:"Body text on background",fg:"semantic.colors.text",bg:"semantic.colors.background"},{key:"surface",label:"Body text on surface",fg:"semantic.colors.text",bg:"semantic.colors.surface"}];function lf(e){let t=new Set(e.targets.map(n=>n.path));return oa.filter(n=>t.has(n.fg)||t.has(n.bg)).map(n=>n.key)}var kx={AA:4.5,AAA:7};function Ex(e){return Math.round(e*100)/100}function Mx(e,t,n,o,r){let s=e.get(`${r}.${t}`);if(typeof s!="string")return null;let a=s.match(/^palette\.colors\.(\w+)\.(\d+)$/);if(!a)return null;let i=a[1],d=Ur.indexOf(a[2]),l=null,m=1/0;return Ur.forEach((u,g)=>{let p=e.get(`${r}.palette.colors.${i}.${u}`);if(!(typeof p!="string"||!(p.startsWith("#")||p.startsWith("rgb")))&&La(p,n)>=o){let w=d>=0?Math.abs(g-d):g;w<m&&(m=w,l=`palette.colors.${i}.${u}`)}}),l}function sa(e,t="AA",n="both",o){let r=kx[t],s=n==="both"?["light","dark"]:[n],a=o?oa.filter(d=>o.includes(d.key)):oa,i=[];for(let d of s){let l=d==="light"?"theme":"darkTheme";for(let m of a){let u=Ui(e,m.fg,l),g=Ui(e,m.bg,l);if(!u||!g)continue;let p=Ex(La(u,g)),w=p>=r,S={pair:m.key,label:m.label,variant:d,fg:u,bg:g,ratio:p,threshold:r,passes:w};if(!w){let M=Mx(e,m.fg,g,r,l);M&&(S.suggestion=M)}i.push(S)}}return{level:t,checks:i,failures:i.filter(d=>!d.passes)}}function ss(e,t,n="light",o="AA"){return t.length===0?[]:sa(e,o,n,t).failures.map(s=>({code:"contrast",pair:s.pair,variant:s.variant,ratio:s.ratio,threshold:s.threshold,message:`${s.label} (${s.variant}) has a contrast ratio of ${s.ratio}:1, below the ${o} threshold of ${s.threshold}:1${s.suggestion?`. Try ${s.suggestion} for the foreground.`:"."}`}))}var an={};for(let e of wr){let t=rs(e.roleId);an[t]=e,an[e.roleId]=e}Object.assign(an,{surface:an.surfaces,background:an.surfaces,backgrounds:an.surfaces,user:an["user-messages"],"user-message":an["user-messages"],assistant:an["assistant-messages"],"assistant-message":an["assistant-messages"],actions:an["primary-actions"],buttons:an["primary-actions"],composer:an.input,links:an["links-focus"],focus:an["links-focus"],border:an.borders,dividers:an.borders,scroll:an["scroll-to-bottom"]});function Lx(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=an[t];if(!n){let o=wr.map(r=>rs(r.roleId)).join(", ");throw new Error(`Unknown role "${e}". Valid roles: ${o}.`)}return n}function cf(){let e=new Map,t=n=>{for(let o of n)for(let r of o.fields)e.has(r.id)||e.set(r.id,r)};for(let n of ol)t(n.sections);for(let n of Va)t(n.sections);return e}var Ix={voice:"voiceRecognition.enabled",artifacts:"features.artifacts.enabled",attachments:"attachments.enabled",toolCalls:"features.showToolCalls",reasoning:"features.showReasoning",feedback:"messageActions.enabled"},Rx={avatars:"layout.messages.avatar.show",timestamps:"layout.messages.timestamp.show",showHeader:"layout.showHeader",messageStyle:"layout.messages.layout"},Jl=["bottom-right","bottom-left","top-right","top-left"],Zl=["bubble","flat","minimal"],Px={title:"copy.welcomeTitle",subtitle:"copy.welcomeSubtitle",placeholder:"copy.inputPlaceholder",sendLabel:"copy.sendButtonLabel"};function df(e,t){var W;let n=(W=t==null?void 0:t.editTarget)!=null?W:"both",o=null,r=v=>v&&typeof v=="object"?v:{},s=(v,x,k=n)=>{let C={};return(k==="light"||k==="both")&&(C[`theme.${v}`]=x),(k==="dark"||k==="both")&&(C[`darkTheme.${v}`]=x),C},a=v=>{if(n==="both")return v;let x={};for(let[k,C]of Object.entries(v))(n==="light"&&k.startsWith("theme.")||n==="dark"&&k.startsWith("darkTheme."))&&(x[k]=C);return x},i=()=>n==="dark"?"dark":"light",d=(v,x=[])=>Vo({ok:!0,summary:Ir(e),warnings:x,applied:v});return[{name:"get_theme_overview",title:"Get current theme & what is editable",description:"Read the current widget theme (brand colors, per-role color assignments, typography, roundness, color scheme, undo/redo state), the available presets, and the high-level levers you can change. Call this FIRST before editing.",annotations:{readOnlyHint:!0},inputSchema:{type:"object",properties:{verbosity:{type:"string",enum:["summary","full"],description:"Use 'full' to also include the field-id index for set_theme_fields."}},additionalProperties:!1},execute(v){let{verbosity:x}=r(v),k={summary:Ir(e),availableRoles:wr.map(C=>({role:rs(C.roleId),helper:C.helper})),availableFamilies:Hi,presets:Ls.map(C=>{var T;return{id:C.id,name:C.name,description:C.description,tags:(T=C.tags)!=null?T:[]}}),tools:[{tool:"set_brand_colors",hint:"Recolor the palette (primary/secondary/accent) \u2014 auto-generates shade scales."},{tool:"assign_color_role",hint:"Recolor a region (header, user/assistant messages, actions, input, links, borders, surfaces, scroll) with a family + intensity."},{tool:"set_typography",hint:"Set font family, size, weight, line height."},{tool:"set_roundness",hint:"Set corner roundness (sharp/default/rounded/pill) or granular radii."},{tool:"set_color_scheme",hint:"Set light/dark/auto and which variant edits target."},{tool:"apply_preset",hint:"Apply a complete built-in preset."},{tool:"configure_widget",hint:"Toggle launcher position, features, and layout."},{tool:"set_copy_and_suggestions",hint:"Set welcome copy, placeholder, and suggestion chips."},{tool:"set_theme_fields",hint:"Advanced escape hatch: set any field by id or dot-path."},{tool:"check_contrast",hint:"Audit WCAG contrast across key text/background pairs."},{tool:"manage_session",hint:"Undo, redo, reset, or export the theme."}]};return x==="full"&&(o!=null||(o=cf()),k.fieldIndex=Array.from(o.values()).map(C=>{var T;return{id:C.id,path:C.path,type:C.type,label:C.label,options:(T=C.options)==null?void 0:T.map(F=>F.value)}})),Vo(k)}},{name:"set_brand_colors",title:"Set brand colors",description:'Set one or more brand colors (primary, secondary, accent). Each color auto-generates a full 50\u2013950 shade scale and applies to the light and dark themes (per the current edit target). Accepts hex ("#2563eb", "2563eb", "#18f"), rgb()/rgba() ("rgb(37, 99, 235)"), or CSS color names ("blue", "slateblue").',inputSchema:{type:"object",properties:{primary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},secondary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},accent:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."}},additionalProperties:!1},execute(v){let x=r(v),k=["primary","secondary","accent"],C={},T={};for(let $ of k){if(x[$]===void 0)continue;let j=os(x[$]);T[$]=j;let me=Zi(j);for(let se of Ur){let fe=me[se];fe!==void 0&&Object.assign(C,s(`palette.colors.${$}.${se}`,fe))}}if(Object.keys(T).length===0)throw new Error("Provide at least one of: primary, secondary, accent.");e.setBatch(C);let F=ss(e,["primary-button","user-message"],i());return d(T,F)}},{name:"assign_color_role",title:"Assign a color family to an interface role",description:"Recolor a semantic region of the widget by choosing a palette family and intensity. One call writes all related tokens (background, text, border, icon) consistently. Roles: header, user-messages, assistant-messages, primary-actions, input, links, borders, surfaces, scroll-to-bottom. Families: primary, secondary, accent, neutral. Intensity: solid (bold) or soft (tinted).",inputSchema:{type:"object",properties:{role:{type:"string",description:'Interface role, e.g. "header" or "user-messages".'},family:{type:"string",enum:Hi},intensity:{type:"string",enum:["solid","soft"],description:"Defaults to 'solid'."}},required:["role","family"],additionalProperties:!1},execute(v){let x=r(v),k=Lx(x.role),C=Di(x.family,!0),T=Fi(x.intensity),F=a(_a(C,T,k)),$=Object.keys(F).length;e.setBatch(F);let j=ss(e,lf(k),i());return d({role:rs(k.roleId),family:C,intensity:T,tokensWritten:$},j)}},{name:"set_typography",title:"Set typography",description:"Set font family, base size, weight, and line height in one call. fontFamily: sans|serif|mono. fontSize: xs|sm|base|lg|xl. fontWeight: normal|medium|semibold|bold (or 400\u2013700). lineHeight: tight|normal|relaxed (or 1.25/1.5/1.625).",inputSchema:{type:"object",properties:{fontFamily:{type:"string"},fontSize:{type:"string"},fontWeight:{type:["string","number"]},lineHeight:{type:["string","number"]}},additionalProperties:!1},execute(v){let x=r(v),k={},C={},T=(F,$)=>{var me;if(x[F]===void 0)return;let j=rf(x[F],$,F);C[F]=(me=j.split(".").pop())!=null?me:j,Object.assign(k,s(`semantic.typography.${F}`,j))};if(T("fontFamily",ef),T("fontSize",tf),T("fontWeight",nf),T("lineHeight",of),Object.keys(C).length===0)throw new Error("Provide at least one of: fontFamily, fontSize, fontWeight, lineHeight.");return e.setBatch(k),d(C)}},{name:"set_roundness",title:"Set corner roundness",description:"Set overall corner roundness with a keyword (sharp, default, rounded, pill) which maps the full radius scale, OR pass granular radius values. Provide at least one of `style` or `radius`.",inputSchema:{type:"object",properties:{style:{type:"string",enum:["sharp","default","rounded","pill"]},radius:{type:"object",description:"Granular overrides (px number or CSS length).",properties:{sm:{type:["string","number"]},md:{type:["string","number"]},lg:{type:["string","number"]},xl:{type:["string","number"]},full:{type:["string","number"]}},additionalProperties:!1}},additionalProperties:!1},execute(v){let x=r(v),k={},C={};if(x.style!==void 0){let T=Ni(x.style);C.style=T;for(let[F,$]of Object.entries(ra[T]))Object.assign(k,s(`palette.radius.${F}`,$))}if(x.radius!==void 0){let T=r(x.radius),F={};for(let $ of["sm","md","lg","xl","full"]){if(T[$]===void 0)continue;let j=_i(T[$]);F[$]=j,Object.assign(k,s(`palette.radius.${$}`,j))}C.radius=F}if(Object.keys(k).length===0)throw new Error("Provide `style` (sharp|default|rounded|pill) or a `radius` object.");return e.setBatch(k),d(C)}},{name:"set_color_scheme",title:"Set color scheme",description:"Set the shipped widget color scheme (light, dark, or auto/follow-system). Optionally set `editTarget` to choose which theme variant subsequent styling edits write to (light, dark, or both \u2014 default both).",inputSchema:{type:"object",properties:{scheme:{type:"string",enum:["light","dark","auto"]},editTarget:{type:"string",enum:["light","dark","both"]}},additionalProperties:!1},execute(v){let x=r(v),k={};if(x.scheme!==void 0){let C=Oi(x.scheme);e.set("colorScheme",C),k.scheme=C}if(x.editTarget!==void 0){let C=String(x.editTarget).trim().toLowerCase();if(C!=="light"&&C!=="dark"&&C!=="both")throw new Error(`Unknown editTarget "${x.editTarget}". Valid: light, dark, both.`);n=C,k.editTarget=C}if(Object.keys(k).length===0)throw new Error("Provide `scheme` and/or `editTarget`.");return Vo({ok:!0,summary:Ir(e),warnings:[],applied:k,editTarget:n})}},{name:"apply_preset",title:"Apply a built-in theme preset",description:"Apply a complete built-in preset, replacing theme tokens. Call get_theme_overview to list preset ids.",inputSchema:{type:"object",properties:{presetId:{type:"string"}},required:["presetId"],additionalProperties:!1},execute(v){let{presetId:x}=r(v),k=rl(String(x!=null?x:""));if(!k){let $=Ls.map(j=>j.id).join(", ");throw new Error(`Unknown preset "${x}". Valid presets: ${$}.`)}let C=tn(k.theme,{validate:!1}),T={...e.getConfig()};k.darkTheme&&(T.darkTheme=tn(k.darkTheme,{validate:!1})),k.toolCall&&(T.toolCall=k.toolCall),e.setFullConfig(T,C);let F=ss(e,["body","assistant-message"],"light");return d({appliedPreset:{id:k.id,name:k.name}},F)}},{name:"configure_widget",title:"Configure launcher, features, and layout",description:"Toggle non-theme widget configuration. launcherPosition: bottom-right|bottom-left|top-right|top-left. features: { voice, artifacts, attachments, toolCalls, reasoning, feedback } booleans. layout: { avatars, timestamps, showHeader } booleans and messageStyle: bubble|flat|minimal.",inputSchema:{type:"object",properties:{launcherPosition:{type:"string",enum:Jl},features:{type:"object",properties:{voice:{type:"boolean"},artifacts:{type:"boolean"},attachments:{type:"boolean"},toolCalls:{type:"boolean"},reasoning:{type:"boolean"},feedback:{type:"boolean"}},additionalProperties:!1},layout:{type:"object",properties:{avatars:{type:"boolean"},timestamps:{type:"boolean"},showHeader:{type:"boolean"},messageStyle:{type:"string",enum:Zl}},additionalProperties:!1}},additionalProperties:!1},execute(v){var $,j,me;let x=r(v),k={},C={};if(x.launcherPosition!==void 0){let se=String(x.launcherPosition);if(!Jl.includes(se))throw new Error(`Unknown launcherPosition "${se}". Valid: ${Jl.join(", ")}.`);k["launcher.position"]=se,C.launcherPosition=se}let T=r(x.features);for(let[se,fe]of Object.entries(Ix))T[se]!==void 0&&(k[fe]=!!T[se],($=C.features)!=null||(C.features={}),C.features[se]=!!T[se]);let F=r(x.layout);for(let[se,fe]of Object.entries(Rx))if(F[se]!==void 0)if(se==="messageStyle"){let ie=String(F[se]);if(!Zl.includes(ie))throw new Error(`Unknown messageStyle "${ie}". Valid: ${Zl.join(", ")}.`);k[fe]=ie,(j=C.layout)!=null||(C.layout={}),C.layout[se]=ie}else k[fe]=!!F[se],(me=C.layout)!=null||(C.layout={}),C.layout[se]=!!F[se];if(Object.keys(k).length===0)throw new Error("Provide launcherPosition, features, and/or layout.");return e.setBatch(k),d(C)}},{name:"set_copy_and_suggestions",title:"Set welcome copy and suggestion chips",description:"Set the widget welcome copy and suggestion chips. title/subtitle are the welcome card text; placeholder is the input placeholder; sendLabel is the send button label; suggestions is an array of suggestion-chip strings (replaces the existing list).",inputSchema:{type:"object",properties:{title:{type:"string"},subtitle:{type:"string"},placeholder:{type:"string"},sendLabel:{type:"string"},suggestions:{type:"array",items:{type:"string"}}},additionalProperties:!1},execute(v){let x=r(v),k={},C={};for(let[T,F]of Object.entries(Px))x[T]!==void 0&&(k[F]=String(x[T]),C[T]=String(x[T]));if(x.suggestions!==void 0){if(!Array.isArray(x.suggestions))throw new Error("`suggestions` must be an array of strings.");let T=x.suggestions.filter(F=>typeof F=="string");k.suggestionChips=T,C.suggestions=T}if(Object.keys(k).length===0)throw new Error("Provide at least one of: title, subtitle, placeholder, sendLabel, suggestions.");return e.setBatch(k),d(C)}},{name:"set_theme_fields",title:"Set theme fields by id or path (advanced)",description:'Advanced escape hatch: set individual editor fields by field id (see get_theme_overview verbosity:"full") \u2014 theme field ids follow the current edit target (light/dark/both) \u2014 or by raw dot-path (theme.* / darkTheme.* / a config path), which is written as-is. Use only when a higher-level tool does not cover the need. Values are validated against the field metadata.',inputSchema:{type:"object",properties:{updates:{type:"array",items:{type:"object",properties:{field:{type:"string",description:"Field id or dot-path."},value:{type:["string","number","boolean"]}},required:["field","value"],additionalProperties:!1}}},required:["updates"],additionalProperties:!1},execute(v){var F;let{updates:x}=r(v);if(!Array.isArray(x)||x.length===0)throw new Error("`updates` must be a non-empty array of { field, value }.");o!=null||(o=cf());let k={},C=[];for(let $ of x){let j=r($),me=String((F=j.field)!=null?F:"");try{let se=o.get(me),fe=se?se.path:me;if(!se&&!/^(theme|darkTheme)\.|\./.test(fe))throw new Error(`Unknown field "${me}". Pass a known field id or a dot-path (e.g. theme.palette.radius.md).`);let ie=Wx(se,j.value);if(se&&fe.startsWith("theme.")){let be=s(fe.slice(6),ie);Object.assign(k,be),C.push({field:me,resolvedPath:Object.keys(be),ok:!0})}else k[fe]=ie,C.push({field:me,resolvedPath:fe,ok:!0})}catch(se){C.push({field:me,ok:!1,error:se.message})}}let T=C.filter($=>$.ok);return Object.keys(k).length>0&&e.setBatch(k),Vo({ok:T.length>0,summary:Ir(e),warnings:[],applied:{updates:C}})}},{name:"check_contrast",title:"Check accessibility contrast",description:"Run WCAG contrast checks over the key text/background pairs (message text, header title, input/body text, primary button). Returns each ratio, whether it passes, and a suggested foreground shade for failures.",annotations:{readOnlyHint:!0},inputSchema:{type:"object",properties:{level:{type:"string",enum:["AA","AAA"],description:"Defaults to 'AA'."},variant:{type:"string",enum:["light","dark","both"],description:"Defaults to 'both'."}},additionalProperties:!1},execute(v){let x=r(v),k=x.level==="AAA"?"AAA":"AA",C=x.variant==="light"||x.variant==="dark"?x.variant:"both",T=sa(e,k,C);return Vo({level:T.level,passing:T.checks.length-T.failures.length,total:T.checks.length,checks:T.checks,failures:T.failures})}},{name:"manage_session",title:"Undo, redo, reset, or export the theme",description:'Session action. "undo"/"redo" step through edit history; "reset" restores defaults; "export" returns the embeddable theme snapshot (config + theme JSON) with no side effects.',inputSchema:{type:"object",properties:{action:{type:"string",enum:["undo","redo","reset","export"]}},required:["action"],additionalProperties:!1},execute(v){let{action:x}=r(v);switch(x){case"undo":return e.undo(),d({action:"undo"});case"redo":return e.redo(),d({action:"redo"});case"reset":return e.resetToDefaults(),d({action:"reset"});case"export":return Vo({ok:!0,snapshot:e.exportSnapshot()});default:throw new Error(`Unknown action "${x}". Valid: undo, redo, reset, export.`)}}}]}function Wx(e,t){if(!e)return t;switch(e.type){case"color":return e.parseValue?e.parseValue(os(t)):os(t);case"toggle":return typeof t=="boolean"?t:t==="true"||t===1;case"slider":{let n=Number(t);if(!Number.isFinite(n))throw new Error(`"${e.id}" expects a number.`);if(e.slider){let{min:o,max:r}=e.slider;if(n<o||n>r)throw new Error(`"${e.id}" must be between ${o} and ${r}.`)}return e.parseValue?e.parseValue(n):n}case"select":{let n=String(t);if(e.options&&!e.options.some(o=>o.value===n))throw new Error(`"${e.id}" must be one of: ${e.options.map(o=>o.value).join(", ")}.`);return e.parseValue?e.parseValue(n):n}default:return e.parseValue?e.parseValue(t):t}}export{yu as ADVANCED_TOKENS_SECTION,wr as ALL_ROLES,ol as ALL_TABS,fu as BRAND_PALETTE_SECTION,xu as BUILT_IN_PRESETS,Vf as COLORS_SECTIONS,el as COLOR_FAMILIES,pu as COMPONENTS_SECTIONS,du as COMPONENT_COLOR_SECTIONS,cu as COMPONENT_SHAPE_SECTIONS,uu as CONFIGURE_SECTIONS,Va as CONFIGURE_SUB_GROUPS,oa as CONTRAST_PAIRS,Bi as CSS_NAMED_COLORS,ns as DEVICE_DIMENSIONS,jm as HOME_SUGGESTION_CHIPS,hu as INTERFACE_ROLES_SECTION,Gm as MOCK_BROWSER_CONTENT,Ym as MOCK_WORKSPACE_CONTENT,Nf as PALETTE_SECTION,qm as PREVIEW_STORAGE_ADAPTER,ra as RADIUS_PRESETS,Ba as ROLE_ASSISTANT_MESSAGES,Na as ROLE_BORDERS,Ia as ROLE_FAMILIES,kf as ROLE_FAMILY_LABELS,Pa as ROLE_HEADER,Fa as ROLE_INPUT,ko as ROLE_INTENSITIES,Oa as ROLE_LINKS_FOCUS,Ha as ROLE_PRIMARY_ACTIONS,Da as ROLE_SCROLL_TO_BOTTOM,Ra as ROLE_SURFACES,Wa as ROLE_USER_MESSAGES,_f as SEMANTIC_COLORS_SECTION,Ur as SHADE_KEYS,Ri as SHELL_STYLE_ID,bu as STATUS_COLORS_SECTION,gu as STATUS_PALETTE_SECTION,zr as STYLE_SECTIONS,Sg as STYLE_SECTIONS_V2,Ls as THEME_EDITOR_PRESETS,mu as THEME_SECTION,Gi as ThemeEditorState,ql as ZOOM_MAX,zl as ZOOM_MIN,fx as appendPreviewTranscriptEntry,Xl as applySceneConfig,Kl as applyShellTheme,Lr as buildPreviewConfig,yx as buildPreviewConfigWithMessages,jl as buildShellCss,Gl as buildSrcdoc,Ir as buildSummary,gx as buildTranscriptStreamFrames,os as coerceColor,Di as coerceFamily,Fi as coerceIntensity,_i as coerceRadius,Ni as coerceRoundnessStyle,Oi as coerceScheme,Sf as convertFromPx,Cf as convertToPx,Qm as createPreviewMessages,Yl as createPreviewTranscriptEntry,df as createThemeEditorTools,vx as createThemePreview,tl as detectRoleAssignment,Pi as escapeHtml,Tg as findSection,Xi as formatCssValue,Zi as generateColorScale,mx as getPreviewTranscriptPresetLabel,Km as getShellPalette,rl as getThemeEditorPreset,ru as hexToHsl,su as hslToHex,Qi as isValidHex,Es as normalizeColorValue,Af as paletteColorPath,Yi as parseCssValue,Xm as presetStreamsText,ss as quickContrastWarnings,_a as resolveRoleAssignment,au as resolveThemeColorPath,Ji as rgbToHex,sa as runContrastChecks,kg as scopeSection,Tf as tokenRefDisplayName,Vo as toolResult,La as wcagContrastRatio};
|
|
204
|
+
- Resizable panes`});(he=n.onAfterMount)==null||he.call(n,{iframes:U,controllers:[...o]})};for(let Se of U){let ie=Se.dataset.mountId;if(!ie)continue;let X=R.find(re=>re.mountId===ie);X&&(Se.addEventListener("load",()=>{G++,G>=ge&&ue()},{once:!0}),Se.srcdoc=k(ie,X.shellMode,xn(X.config),x))}ge===0&&ue()}function L(){var H;if(a)return;let I=Nf(n);if(o.length!==I.length){E();return}if(I.some(P=>{let w=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${P.mountId}"]`);return!w||w.dataset.shellMode!==P.shellMode})){E();return}o.forEach((P,w)=>{var x;P.update(I[w].config),((x=n.scene)!=null?x:"conversation")==="minimized"&&P.close()});for(let P of I){let w=e.querySelector(`iframe[data-mount-id="${P.mountId}"]`);w&&cc(w,P.shellMode)}(H=n.onAfterUpdate)==null||H.call(n,{iframes:v(),controllers:[...o]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||m()}),s.observe(e)),E(),{update(I){if(a)return;let R=I.device!==void 0&&I.device!==n.device||I.scene!==void 0&&I.scene!==n.scene||I.compareMode!==void 0&&I.compareMode!==n.compareMode||I.widgetCssPath!==void 0&&I.widgetCssPath!==n.widgetCssPath;n={...n,...I},R?E():L()},destroy(){a||(a=!0,C(),s==null||s.disconnect(),e.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},m())},getIframes(){return v()},getScale(){return d},setZoom(I){a||(n={...n,zoom:I},m())}}}function Jo(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}var ji={black:"#000000",white:"#ffffff",red:"#ff0000",green:"#008000",lime:"#00ff00",blue:"#0000ff",yellow:"#ffff00",cyan:"#00ffff",aqua:"#00ffff",magenta:"#ff00ff",fuchsia:"#ff00ff",silver:"#c0c0c0",gray:"#808080",grey:"#808080",maroon:"#800000",olive:"#808000",purple:"#800080",teal:"#008080",navy:"#000080",orange:"#ffa500",pink:"#ffc0cb",hotpink:"#ff69b4",gold:"#ffd700",indigo:"#4b0082",violet:"#ee82ee",brown:"#a52a2a",beige:"#f5f5dc",ivory:"#fffff0",khaki:"#f0e68c",coral:"#ff7f50",salmon:"#fa8072",tomato:"#ff6347",crimson:"#dc143c",turquoise:"#40e0d0",lavender:"#e6e6fa",plum:"#dda0dd",orchid:"#da70d6",tan:"#d2b48c",chocolate:"#d2691e",sienna:"#a0522d",slategray:"#708090",slategrey:"#708090",steelblue:"#4682b4",royalblue:"#4169e1",dodgerblue:"#1e90ff",skyblue:"#87ceeb",lightblue:"#add8e6",midnightblue:"#191970",forestgreen:"#228b22",seagreen:"#2e8b57",limegreen:"#32cd32",olivedrab:"#6b8e23",darkgreen:"#006400",emerald:"#50c878",mint:"#3eb489",goldenrod:"#daa520",firebrick:"#b22222",darkred:"#8b0000",indianred:"#cd5c5c",deeppink:"#ff1493",mediumpurple:"#9370db",rebeccapurple:"#663399",darkviolet:"#9400d3",slateblue:"#6a5acd",cornflowerblue:"#6495ed",teal2:"#008080",charcoal:"#36454f",graphite:"#3b3b3b",transparent:"transparent"},uw=/^rgba?\(\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*(,\s*(0|1|0?\.\d+|\d{1,3}%)\s*)?\)$/;function mw(e){return uw.test(e)}function vs(e){if(typeof e!="string"||e.trim()==="")throw new Error('Color must be a non-empty string (e.g. "#2563eb" or "blue").');let t=e.trim().toLowerCase(),n=ji[t];if(n)return n;let o=Us(t);if(ul(o)||o==="transparent"||mw(o))return o;throw new Error(`"${e}" is not a recognized color. Pass a hex value like "#ef4444" or a CSS color name (e.g. ${Object.keys(ji).slice(0,6).join(", ")}).`)}var Ki=_a.map(e=>e==="gray"?"neutral":e),fw={...Object.fromEntries(Ki.map(e=>[e,e])),gray:"neutral",grey:"neutral"};function Gi(e,t=!0){let n=String(e!=null?e:"").trim().toLowerCase(),o=fw[n];if(!o||!t&&o==="neutral"){let r=t?"primary, secondary, accent, neutral":"primary, secondary, accent";throw new Error(`Unknown color family "${e}". Valid families: ${r}.`)}return o}function Yi(e){let t=String(e!=null?e:"solid").trim().toLowerCase();if(t==="solid"||t==="soft")return t;throw new Error(`Unknown intensity "${e}". Valid intensities: solid, soft.`)}function Xi(e){let t=String(e!=null?e:"").trim().toLowerCase();if(t==="light"||t==="dark"||t==="auto")return t;if(t==="system")return"auto";throw new Error(`Unknown color scheme "${e}". Valid: light, dark, auto.`)}var gw={sharp:"sharp",square:"sharp",none:"sharp",default:"default",normal:"default",rounded:"rounded",round:"rounded",soft:"rounded",pill:"pill",circle:"pill",full:"pill"};function Ji(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=gw[t];if(!n)throw new Error(`Unknown roundness "${e}". Valid: sharp, default, rounded, pill.`);return n}function Qi(e){if(typeof e=="number"&&Number.isFinite(e))return`${e}px`;if(typeof e=="string"&&e.trim()!==""){let t=e.trim();if(t==="9999px"||/^(100%|9999px)$/.test(t))return"9999px";let n=dl(t);return pl(n.value,n.unit)}throw new Error('Radius must be a number (px) or a CSS length string like "0.5rem".')}function Zi(e){for(let t of as){let n=t.fields.find(o=>o.id===e);if(n!=null&&n.options){let o={};for(let r of n.options){let s=r.value.split(".").pop();s&&(o[s]=r.value)}return o}}return{}}var _f=Zi("typo-font-family"),ga=Zi("typo-font-size"),ha=Zi("typo-font-weight"),qi=Zi("typo-line-height"),Vf={..._f,monospace:_f.mono},$f={...ga,small:ga.sm,md:ga.base,medium:ga.base,large:ga.lg},Uf={...ha,400:ha.normal,500:ha.medium,600:ha.semibold,700:ha.bold},zf={...qi,"1.25":qi.tight,"1.5":qi.normal,"1.625":qi.relaxed};function qf(e,t,n){let o=String(e!=null?e:"").trim().toLowerCase(),r=t[o];if(!r){let s=[...new Set(Object.values(t).map(a=>a.split(".").pop()))].join(", ");throw new Error(`Unknown ${n} "${e}". Valid: ${s}.`)}return r}var jf="theme.palette.radius.";function hw(){var t;let e={pill:{sm:"9999px",md:"9999px",lg:"9999px",xl:"9999px",full:"9999px"}};for(let n of as)for(let o of(t=n.presets)!=null?t:[]){let r=o.id.match(/^radius-(\w+)$/);if(!r)continue;let s={};for(let[a,i]of Object.entries(o.values))a.startsWith(jf)&&typeof i=="string"&&(s[a.slice(jf.length)]=i);e[r[1]]=s}return e}var ya=hw(),Kf=["sm","md","lg","xl","full"];function tl(e,t,n="theme",o=0){if(o>6)return null;let r=e.get(`${n}.${t}`);return typeof r!="string"||r===""?n==="darkTheme"?tl(e,t,"theme",o):null:r.startsWith("#")||r.startsWith("rgb")||r==="transparent"?r:r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components.")?tl(e,r,n,o+1):null}function el(e,t){let n=e.get(t);if(typeof n!="string")return"unknown";let o=n.split(".");return o[o.length-1]||String(n)}function xs(e){return e.replace(/^role-/,"")}function bw(e){for(let[t,n]of Object.entries(ya))if(Kf.every(o=>e[o]===n[o]))return t;return"custom"}function $r(e){var o,r;let t={};for(let s of Kf)t[s]=String((o=e.get(`theme.palette.radius.${s}`))!=null?o:"");let n={};for(let s of Rr)n[xs(s.roleId)]=hl(a=>e.get(`theme.${a}`),s);return{brand:{primary:mc(e.get("theme.palette.colors.primary.500")),secondary:mc(e.get("theme.palette.colors.secondary.500")),accent:mc(e.get("theme.palette.colors.accent.500"))},roles:n,typography:{fontFamily:el(e,"theme.semantic.typography.fontFamily"),fontSize:el(e,"theme.semantic.typography.fontSize"),fontWeight:el(e,"theme.semantic.typography.fontWeight"),lineHeight:el(e,"theme.semantic.typography.lineHeight")},roundness:{style:bw(t),radius:t},colorScheme:String((r=e.get("colorScheme"))!=null?r:"light"),history:{index:e.getHistoryIndex(),canUndo:e.canUndo(),canRedo:e.canRedo()}}}function mc(e){return typeof e=="string"&&e!==""?e:null}var ba=[{key:"user-message",label:"User message text",fg:"components.message.user.text",bg:"components.message.user.background"},{key:"assistant-message",label:"Assistant message text",fg:"components.message.assistant.text",bg:"components.message.assistant.background"},{key:"header",label:"Header title",fg:"components.header.titleForeground",bg:"components.header.background"},{key:"primary-button",label:"Primary button label",fg:"components.button.primary.foreground",bg:"components.button.primary.background"},{key:"input",label:"Input placeholder",fg:"components.input.placeholder",bg:"components.input.background"},{key:"link",label:"Link text",fg:"components.markdown.link.foreground",bg:"semantic.colors.background"},{key:"scroll",label:"Scroll-to-bottom icon",fg:"components.scrollToBottom.foreground",bg:"components.scrollToBottom.background"},{key:"body",label:"Body text on background",fg:"semantic.colors.text",bg:"semantic.colors.background"},{key:"surface",label:"Body text on surface",fg:"semantic.colors.text",bg:"semantic.colors.surface"}];function Gf(e){let t=new Set(e.targets.map(n=>n.path));return ba.filter(n=>t.has(n.fg)||t.has(n.bg)).map(n=>n.key)}var yw={AA:4.5,AAA:7};function vw(e){return Math.round(e*100)/100}function xw(e,t,n,o,r){let s=e.get(`${r}.${t}`);if(typeof s!="string")return null;let a=s.match(/^palette\.colors\.(\w+)\.(\d+)$/);if(!a)return null;let i=a[1],d=rs.indexOf(a[2]),l=null,f=1/0;return rs.forEach((u,g)=>{let m=e.get(`${r}.palette.colors.${i}.${u}`);if(!(typeof m!="string"||!(m.startsWith("#")||m.startsWith("rgb")))&&Na(m,n)>=o){let C=d>=0?Math.abs(g-d):g;C<f&&(f=C,l=`palette.colors.${i}.${u}`)}}),l}function va(e,t="AA",n="both",o){let r=yw[t],s=n==="both"?["light","dark"]:[n],a=o?ba.filter(d=>o.includes(d.key)):ba,i=[];for(let d of s){let l=d==="light"?"theme":"darkTheme";for(let f of a){let u=tl(e,f.fg,l),g=tl(e,f.bg,l);if(!u||!g)continue;let m=vw(Na(u,g)),C=m>=r,v={pair:f.key,label:f.label,variant:d,fg:u,bg:g,ratio:m,threshold:r,passes:C};if(!C){let E=xw(e,f.fg,g,r,l);E&&(v.suggestion=E)}i.push(v)}}return{level:t,checks:i,failures:i.filter(d=>!d.passes)}}function ws(e,t,n="light",o="AA"){return t.length===0?[]:va(e,o,n,t).failures.map(s=>({code:"contrast",pair:s.pair,variant:s.variant,ratio:s.ratio,threshold:s.threshold,message:`${s.label} (${s.variant}) has a contrast ratio of ${s.ratio}:1, below the ${o} threshold of ${s.threshold}:1${s.suggestion?`. Try ${s.suggestion} for the foreground.`:"."}`}))}var hn={};for(let e of Rr){let t=xs(e.roleId);hn[t]=e,hn[e.roleId]=e}Object.assign(hn,{surface:hn.surfaces,background:hn.surfaces,backgrounds:hn.surfaces,user:hn["user-messages"],"user-message":hn["user-messages"],assistant:hn["assistant-messages"],"assistant-message":hn["assistant-messages"],actions:hn["primary-actions"],buttons:hn["primary-actions"],composer:hn.input,links:hn["links-focus"],focus:hn["links-focus"],border:hn.borders,dividers:hn.borders,scroll:hn["scroll-to-bottom"]});function ww(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=hn[t];if(!n){let o=Rr.map(r=>xs(r.roleId)).join(", ");throw new Error(`Unknown role "${e}". Valid roles: ${o}.`)}return n}function Yf(){let e=new Map,t=n=>{for(let o of n)for(let r of o.fields)e.has(r.id)||e.set(r.id,r)};for(let n of vl)t(n.sections);for(let n of Ja)t(n.sections);return e}var Cw={voice:"voiceRecognition.enabled",artifacts:"features.artifacts.enabled",attachments:"attachments.enabled",toolCalls:"features.showToolCalls",reasoning:"features.showReasoning",feedback:"messageActions.enabled"},Sw={avatars:"layout.messages.avatar.show",timestamps:"layout.messages.timestamp.show",showHeader:"layout.showHeader",messageStyle:"layout.messages.layout"},fc=["bottom-right","bottom-left","top-right","top-left"],gc=["bubble","flat","minimal"],Aw={title:"copy.welcomeTitle",subtitle:"copy.welcomeSubtitle",placeholder:"copy.inputPlaceholder",sendLabel:"copy.sendButtonLabel"};function Xf(e,t){var P;let n=(P=t==null?void 0:t.editTarget)!=null?P:"both",o=null,r=w=>w&&typeof w=="object"?w:{},s=(w,x,k=n)=>{let S={};return(k==="light"||k==="both")&&(S[`theme.${w}`]=x),(k==="dark"||k==="both")&&(S[`darkTheme.${w}`]=x),S},a=w=>{if(n==="both")return w;let x={};for(let[k,S]of Object.entries(w))(n==="light"&&k.startsWith("theme.")||n==="dark"&&k.startsWith("darkTheme."))&&(x[k]=S);return x},i=()=>n==="dark"?"dark":"light",d=(w,x=[])=>Jo({ok:!0,summary:$r(e),warnings:x,applied:w});return[{name:"get_theme_overview",title:"Get current theme & what is editable",description:"Read the current widget theme (brand colors, per-role color assignments, typography, roundness, color scheme, undo/redo state), the available presets, and the high-level levers you can change. Call this FIRST before editing.",annotations:{readOnlyHint:!0},inputSchema:{type:"object",properties:{verbosity:{type:"string",enum:["summary","full"],description:"Use 'full' to also include the field-id index for set_theme_fields."}},additionalProperties:!1},execute(w){let{verbosity:x}=r(w),k={summary:$r(e),availableRoles:Rr.map(S=>({role:xs(S.roleId),helper:S.helper})),availableFamilies:Ki,presets:qs.map(S=>{var T;return{id:S.id,name:S.name,description:S.description,tags:(T=S.tags)!=null?T:[]}}),tools:[{tool:"set_brand_colors",hint:"Recolor the palette (primary/secondary/accent) \u2014 auto-generates shade scales."},{tool:"assign_color_role",hint:"Recolor a region (header, user/assistant messages, actions, input, links, borders, surfaces, scroll) with a family + intensity."},{tool:"set_typography",hint:"Set font family, size, weight, line height."},{tool:"set_roundness",hint:"Set corner roundness (sharp/default/rounded/pill) or granular radii."},{tool:"set_color_scheme",hint:"Set light/dark/auto and which variant edits target."},{tool:"apply_preset",hint:"Apply a complete built-in preset."},{tool:"configure_widget",hint:"Toggle launcher position, features, and layout."},{tool:"set_copy_and_suggestions",hint:"Set welcome copy, placeholder, and suggestion chips."},{tool:"set_theme_fields",hint:"Advanced escape hatch: set any field by id or dot-path."},{tool:"check_contrast",hint:"Audit WCAG contrast across key text/background pairs."},{tool:"manage_session",hint:"Undo, redo, reset, or export the theme."}]};return x==="full"&&(o!=null||(o=Yf()),k.fieldIndex=Array.from(o.values()).map(S=>{var T;return{id:S.id,path:S.path,type:S.type,label:S.label,options:(T=S.options)==null?void 0:T.map(_=>_.value)}})),Jo(k)}},{name:"set_brand_colors",title:"Set brand colors",description:'Set one or more brand colors (primary, secondary, accent). Each color auto-generates a full 50\u2013950 shade scale and applies to the light and dark themes (per the current edit target). Accepts hex ("#2563eb", "2563eb", "#18f"), rgb()/rgba() ("rgb(37, 99, 235)"), or CSS color names ("blue", "slateblue").',inputSchema:{type:"object",properties:{primary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},secondary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},accent:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."}},additionalProperties:!1},execute(w){let x=r(w),k=["primary","secondary","accent"],S={},T={};for(let U of k){if(x[U]===void 0)continue;let G=vs(x[U]);T[U]=G;let ge=fl(G);for(let ue of rs){let ce=ge[ue];ce!==void 0&&Object.assign(S,s(`palette.colors.${U}.${ue}`,ce))}}if(Object.keys(T).length===0)throw new Error("Provide at least one of: primary, secondary, accent.");e.setBatch(S);let _=ws(e,["primary-button","user-message"],i());return d(T,_)}},{name:"assign_color_role",title:"Assign a color family to an interface role",description:"Recolor a semantic region of the widget by choosing a palette family and intensity. One call writes all related tokens (background, text, border, icon) consistently. Roles: header, user-messages, assistant-messages, primary-actions, input, links, borders, surfaces, scroll-to-bottom. Families: primary, secondary, accent, neutral. Intensity: solid (bold) or soft (tinted).",inputSchema:{type:"object",properties:{role:{type:"string",description:'Interface role, e.g. "header" or "user-messages".'},family:{type:"string",enum:Ki},intensity:{type:"string",enum:["solid","soft"],description:"Defaults to 'solid'."}},required:["role","family"],additionalProperties:!1},execute(w){let x=r(w),k=ww(x.role),S=Gi(x.family,!0),T=Yi(x.intensity),_=a(Xa(S,T,k)),U=Object.keys(_).length;e.setBatch(_);let G=ws(e,Gf(k),i());return d({role:xs(k.roleId),family:S,intensity:T,tokensWritten:U},G)}},{name:"set_typography",title:"Set typography",description:"Set font family, base size, weight, and line height in one call. fontFamily: sans|serif|mono. fontSize: xs|sm|base|lg|xl. fontWeight: normal|medium|semibold|bold (or 400\u2013700). lineHeight: tight|normal|relaxed (or 1.25/1.5/1.625).",inputSchema:{type:"object",properties:{fontFamily:{type:"string"},fontSize:{type:"string"},fontWeight:{type:["string","number"]},lineHeight:{type:["string","number"]}},additionalProperties:!1},execute(w){let x=r(w),k={},S={},T=(_,U)=>{var ge;if(x[_]===void 0)return;let G=qf(x[_],U,_);S[_]=(ge=G.split(".").pop())!=null?ge:G,Object.assign(k,s(`semantic.typography.${_}`,G))};if(T("fontFamily",Vf),T("fontSize",$f),T("fontWeight",Uf),T("lineHeight",zf),Object.keys(S).length===0)throw new Error("Provide at least one of: fontFamily, fontSize, fontWeight, lineHeight.");return e.setBatch(k),d(S)}},{name:"set_roundness",title:"Set corner roundness",description:"Set overall corner roundness with a keyword (sharp, default, rounded, pill) which maps the full radius scale, OR pass granular radius values. Provide at least one of `style` or `radius`.",inputSchema:{type:"object",properties:{style:{type:"string",enum:["sharp","default","rounded","pill"]},radius:{type:"object",description:"Granular overrides (px number or CSS length).",properties:{sm:{type:["string","number"]},md:{type:["string","number"]},lg:{type:["string","number"]},xl:{type:["string","number"]},full:{type:["string","number"]}},additionalProperties:!1}},additionalProperties:!1},execute(w){let x=r(w),k={},S={};if(x.style!==void 0){let T=Ji(x.style);S.style=T;for(let[_,U]of Object.entries(ya[T]))Object.assign(k,s(`palette.radius.${_}`,U))}if(x.radius!==void 0){let T=r(x.radius),_={};for(let U of["sm","md","lg","xl","full"]){if(T[U]===void 0)continue;let G=Qi(T[U]);_[U]=G,Object.assign(k,s(`palette.radius.${U}`,G))}S.radius=_}if(Object.keys(k).length===0)throw new Error("Provide `style` (sharp|default|rounded|pill) or a `radius` object.");return e.setBatch(k),d(S)}},{name:"set_color_scheme",title:"Set color scheme",description:"Set the shipped widget color scheme (light, dark, or auto/follow-system). Optionally set `editTarget` to choose which theme variant subsequent styling edits write to (light, dark, or both \u2014 default both).",inputSchema:{type:"object",properties:{scheme:{type:"string",enum:["light","dark","auto"]},editTarget:{type:"string",enum:["light","dark","both"]}},additionalProperties:!1},execute(w){let x=r(w),k={};if(x.scheme!==void 0){let S=Xi(x.scheme);e.set("colorScheme",S),k.scheme=S}if(x.editTarget!==void 0){let S=String(x.editTarget).trim().toLowerCase();if(S!=="light"&&S!=="dark"&&S!=="both")throw new Error(`Unknown editTarget "${x.editTarget}". Valid: light, dark, both.`);n=S,k.editTarget=S}if(Object.keys(k).length===0)throw new Error("Provide `scheme` and/or `editTarget`.");return Jo({ok:!0,summary:$r(e),warnings:[],applied:k,editTarget:n})}},{name:"apply_preset",title:"Apply a built-in theme preset",description:"Apply a complete built-in preset, replacing theme tokens. Call get_theme_overview to list preset ids.",inputSchema:{type:"object",properties:{presetId:{type:"string"}},required:["presetId"],additionalProperties:!1},execute(w){let{presetId:x}=r(w),k=xl(String(x!=null?x:""));if(!k){let U=qs.map(G=>G.id).join(", ");throw new Error(`Unknown preset "${x}". Valid presets: ${U}.`)}let S=un(k.theme,{validate:!1}),T={...e.getConfig()};k.darkTheme&&(T.darkTheme=un(k.darkTheme,{validate:!1})),k.toolCall&&(T.toolCall=k.toolCall),e.setFullConfig(T,S);let _=ws(e,["body","assistant-message"],"light");return d({appliedPreset:{id:k.id,name:k.name}},_)}},{name:"configure_widget",title:"Configure launcher, features, and layout",description:"Toggle non-theme widget configuration. launcherPosition: bottom-right|bottom-left|top-right|top-left. features: { voice, artifacts, attachments, toolCalls, reasoning, feedback } booleans. layout: { avatars, timestamps, showHeader } booleans and messageStyle: bubble|flat|minimal.",inputSchema:{type:"object",properties:{launcherPosition:{type:"string",enum:fc},features:{type:"object",properties:{voice:{type:"boolean"},artifacts:{type:"boolean"},attachments:{type:"boolean"},toolCalls:{type:"boolean"},reasoning:{type:"boolean"},feedback:{type:"boolean"}},additionalProperties:!1},layout:{type:"object",properties:{avatars:{type:"boolean"},timestamps:{type:"boolean"},showHeader:{type:"boolean"},messageStyle:{type:"string",enum:gc}},additionalProperties:!1}},additionalProperties:!1},execute(w){var U,G,ge;let x=r(w),k={},S={};if(x.launcherPosition!==void 0){let ue=String(x.launcherPosition);if(!fc.includes(ue))throw new Error(`Unknown launcherPosition "${ue}". Valid: ${fc.join(", ")}.`);k["launcher.position"]=ue,S.launcherPosition=ue}let T=r(x.features);for(let[ue,ce]of Object.entries(Cw))T[ue]!==void 0&&(k[ce]=!!T[ue],(U=S.features)!=null||(S.features={}),S.features[ue]=!!T[ue]);let _=r(x.layout);for(let[ue,ce]of Object.entries(Sw))if(_[ue]!==void 0)if(ue==="messageStyle"){let ke=String(_[ue]);if(!gc.includes(ke))throw new Error(`Unknown messageStyle "${ke}". Valid: ${gc.join(", ")}.`);k[ce]=ke,(G=S.layout)!=null||(S.layout={}),S.layout[ue]=ke}else k[ce]=!!_[ue],(ge=S.layout)!=null||(S.layout={}),S.layout[ue]=!!_[ue];if(Object.keys(k).length===0)throw new Error("Provide launcherPosition, features, and/or layout.");return e.setBatch(k),d(S)}},{name:"set_copy_and_suggestions",title:"Set welcome copy and suggestion chips",description:"Set the widget welcome copy and suggestion chips. title/subtitle are the welcome card text; placeholder is the input placeholder; sendLabel is the send button label; suggestions is an array of suggestion-chip strings (replaces the existing list).",inputSchema:{type:"object",properties:{title:{type:"string"},subtitle:{type:"string"},placeholder:{type:"string"},sendLabel:{type:"string"},suggestions:{type:"array",items:{type:"string"}}},additionalProperties:!1},execute(w){let x=r(w),k={},S={};for(let[T,_]of Object.entries(Aw))x[T]!==void 0&&(k[_]=String(x[T]),S[T]=String(x[T]));if(x.suggestions!==void 0){if(!Array.isArray(x.suggestions))throw new Error("`suggestions` must be an array of strings.");let T=x.suggestions.filter(_=>typeof _=="string");k.suggestionChips=T,S.suggestions=T}if(Object.keys(k).length===0)throw new Error("Provide at least one of: title, subtitle, placeholder, sendLabel, suggestions.");return e.setBatch(k),d(S)}},{name:"set_theme_fields",title:"Set theme fields by id or path (advanced)",description:'Advanced escape hatch: set individual editor fields by field id (see get_theme_overview verbosity:"full") \u2014 theme field ids follow the current edit target (light/dark/both) \u2014 or by raw dot-path (theme.* / darkTheme.* / a config path), which is written as-is. Use only when a higher-level tool does not cover the need. Values are validated against the field metadata.',inputSchema:{type:"object",properties:{updates:{type:"array",items:{type:"object",properties:{field:{type:"string",description:"Field id or dot-path."},value:{type:["string","number","boolean"]}},required:["field","value"],additionalProperties:!1}}},required:["updates"],additionalProperties:!1},execute(w){var _;let{updates:x}=r(w);if(!Array.isArray(x)||x.length===0)throw new Error("`updates` must be a non-empty array of { field, value }.");o!=null||(o=Yf());let k={},S=[];for(let U of x){let G=r(U),ge=String((_=G.field)!=null?_:"");try{let ue=o.get(ge),ce=ue?ue.path:ge;if(!ue&&!/^(theme|darkTheme)\.|\./.test(ce))throw new Error(`Unknown field "${ge}". Pass a known field id or a dot-path (e.g. theme.palette.radius.md).`);let ke=Tw(ue,G.value);if(ue&&ce.startsWith("theme.")){let ve=s(ce.slice(6),ke);Object.assign(k,ve),S.push({field:ge,resolvedPath:Object.keys(ve),ok:!0})}else k[ce]=ke,S.push({field:ge,resolvedPath:ce,ok:!0})}catch(ue){S.push({field:ge,ok:!1,error:ue.message})}}let T=S.filter(U=>U.ok);return Object.keys(k).length>0&&e.setBatch(k),Jo({ok:T.length>0,summary:$r(e),warnings:[],applied:{updates:S}})}},{name:"check_contrast",title:"Check accessibility contrast",description:"Run WCAG contrast checks over the key text/background pairs (message text, header title, input/body text, primary button). Returns each ratio, whether it passes, and a suggested foreground shade for failures.",annotations:{readOnlyHint:!0},inputSchema:{type:"object",properties:{level:{type:"string",enum:["AA","AAA"],description:"Defaults to 'AA'."},variant:{type:"string",enum:["light","dark","both"],description:"Defaults to 'both'."}},additionalProperties:!1},execute(w){let x=r(w),k=x.level==="AAA"?"AAA":"AA",S=x.variant==="light"||x.variant==="dark"?x.variant:"both",T=va(e,k,S);return Jo({level:T.level,passing:T.checks.length-T.failures.length,total:T.checks.length,checks:T.checks,failures:T.failures})}},{name:"manage_session",title:"Undo, redo, reset, or export the theme",description:'Session action. "undo"/"redo" step through edit history; "reset" restores defaults; "export" returns the embeddable theme snapshot (config + theme JSON) with no side effects.',inputSchema:{type:"object",properties:{action:{type:"string",enum:["undo","redo","reset","export"]}},required:["action"],additionalProperties:!1},execute(w){let{action:x}=r(w);switch(x){case"undo":return e.undo(),d({action:"undo"});case"redo":return e.redo(),d({action:"redo"});case"reset":return e.resetToDefaults(),d({action:"reset"});case"export":return Jo({ok:!0,snapshot:e.exportSnapshot()});default:throw new Error(`Unknown action "${x}". Valid: undo, redo, reset, export.`)}}}]}function Tw(e,t){if(!e)return t;switch(e.type){case"color":return e.parseValue?e.parseValue(vs(t)):vs(t);case"toggle":return typeof t=="boolean"?t:t==="true"||t===1;case"slider":{let n=Number(t);if(!Number.isFinite(n))throw new Error(`"${e.id}" expects a number.`);if(e.slider){let{min:o,max:r}=e.slider;if(n<o||n>r)throw new Error(`"${e.id}" must be between ${o} and ${r}.`)}return e.parseValue?e.parseValue(n):n}case"select":{let n=String(t);if(e.options&&!e.options.some(o=>o.value===n))throw new Error(`"${e.id}" must be one of: ${e.options.map(o=>o.value).join(", ")}.`);return e.parseValue?e.parseValue(n):n}default:return e.parseValue?e.parseValue(t):t}}export{Yu as ADVANCED_TOKENS_SECTION,Rr as ALL_ROLES,vl as ALL_TABS,qu as BRAND_PALETTE_SECTION,Ju as BUILT_IN_PRESETS,Pg as COLORS_SECTIONS,gl as COLOR_FAMILIES,$u as COMPONENTS_SECTIONS,Vu as COMPONENT_COLOR_SECTIONS,_u as COMPONENT_SHAPE_SECTIONS,Uu as CONFIGURE_SECTIONS,Ja as CONFIGURE_SUB_GROUPS,ba as CONTRAST_PAIRS,ji as CSS_NAMED_COLORS,ys as DEVICE_DIMENSIONS,Wf as HOME_SUGGESTION_CHIPS,Ku as INTERFACE_ROLES_SECTION,Hf as MOCK_BROWSER_CONTENT,Df as MOCK_WORKSPACE_CONTENT,Ig as PALETTE_SECTION,Pf as PREVIEW_STORAGE_ADAPTER,ya as RADIUS_PRESETS,za as ROLE_ASSISTANT_MESSAGES,Ya as ROLE_BORDERS,_a as ROLE_FAMILIES,bg as ROLE_FAMILY_LABELS,$a as ROLE_HEADER,Ka as ROLE_INPUT,Do as ROLE_INTENSITIES,Ga as ROLE_LINKS_FOCUS,qa as ROLE_PRIMARY_ACTIONS,ja as ROLE_SCROLL_TO_BOTTOM,Va as ROLE_SURFACES,Ua as ROLE_USER_MESSAGES,Rg as SEMANTIC_COLORS_SECTION,rs as SHADE_KEYS,Ui as SHELL_STYLE_ID,Gu as STATUS_COLORS_SECTION,ju as STATUS_PALETTE_SECTION,as as STYLE_SECTIONS,gh as STYLE_SECTIONS_V2,qs as THEME_EDITOR_PRESETS,zu as THEME_SECTION,cl as ThemeEditorState,ic as ZOOM_MAX,ac as ZOOM_MIN,aw as appendPreviewTranscriptEntry,uc as applySceneConfig,cc as applyShellTheme,Vr as buildPreviewConfig,dw as buildPreviewConfigWithMessages,lc as buildShellCss,dc as buildSrcdoc,$r as buildSummary,iw as buildTranscriptStreamFrames,vs as coerceColor,Gi as coerceFamily,Yi as coerceIntensity,Qi as coerceRadius,Ji as coerceRoundnessStyle,Xi as coerceScheme,fg as convertFromPx,mg as convertToPx,Of as createPreviewMessages,pc as createPreviewTranscriptEntry,Xf as createThemeEditorTools,pw as createThemePreview,hl as detectRoleAssignment,zi as escapeHtml,bh as findSection,pl as formatCssValue,fl as generateColorScale,sw as getPreviewTranscriptPresetLabel,Bf as getShellPalette,xl as getThemeEditorPreset,Bu as hexToHsl,Hu as hslToHex,ul as isValidHex,Us as normalizeColorValue,gg as paletteColorPath,dl as parseCssValue,Ff as presetStreamsText,ws as quickContrastWarnings,Xa as resolveRoleAssignment,Du as resolveThemeColorPath,ml as rgbToHex,va as runContrastChecks,yh as scopeSection,hg as tokenRefDisplayName,Jo as toolResult,Na as wcagContrastRatio};
|