@runtypelabs/persona 3.23.0 → 3.24.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/dist/index.cjs +34 -34
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +16 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.global.js +48 -48
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +35 -35
- package/dist/index.js.map +1 -1
- package/dist/theme-editor.cjs +17 -17
- package/dist/theme-editor.js +21 -21
- package/package.json +1 -1
- package/src/client.test.ts +261 -0
- package/src/client.ts +103 -25
- package/src/session.ts +4 -0
- package/src/types.ts +17 -0
- package/src/webmcp-bridge.test.ts +80 -0
- package/src/webmcp-bridge.ts +68 -0
package/dist/theme-editor.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
var Yp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ts(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];Yp(s)&&Yp(r)?n[o]=Ts(s,r):n[o]=r}return n}var io="min(440px, calc(100vw - 24px))",Aa="440px",kt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:io,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Xp(e,t){if(!(!e&&!t))return e?t?Ts(e,t):e:t}function Qp(e){var t,n,o,r,s,a,i,d,l,u,p,g,m,w,x,M,P,W,H,_,B;return e?{...kt,...e,theme:Xp(kt.theme,e.theme),darkTheme:Xp(kt.darkTheme,e.darkTheme),launcher:{...kt.launcher,...e.launcher,dock:{...(t=kt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(o=kt.launcher)==null?void 0:o.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...kt.copy,...e.copy},sendButton:{...kt.sendButton,...e.sendButton},statusIndicator:{...kt.statusIndicator,...e.statusIndicator},voiceRecognition:{...kt.voiceRecognition,...e.voiceRecognition},features:(()=>{var we,We,ye,Z,Ee,X,Ae,ge;let v=(we=kt.features)==null?void 0:we.artifacts,C=(We=e.features)==null?void 0:We.artifacts,E=(ye=kt.features)==null?void 0:ye.scrollToBottom,S=(Z=e.features)==null?void 0:Z.scrollToBottom,k=(Ee=kt.features)==null?void 0:Ee.streamAnimation,D=(X=e.features)==null?void 0:X.streamAnimation,$=(Ae=kt.features)==null?void 0:Ae.askUserQuestion,q=(ge=e.features)==null?void 0:ge.askUserQuestion,me=v===void 0&&C===void 0?void 0:{...v,...C,layout:{...v==null?void 0:v.layout,...C==null?void 0:C.layout}},re=E===void 0&&S===void 0?void 0:{...E,...S},be=k===void 0&&D===void 0?void 0:{...k,...D},ie=$===void 0&&q===void 0?void 0:{...$,...q,styles:{...$==null?void 0:$.styles,...q==null?void 0:q.styles}};return{...kt.features,...e.features,...re!==void 0?{scrollToBottom:re}:{},...me!==void 0?{artifacts:me}:{},...be!==void 0?{streamAnimation:be}:{},...ie!==void 0?{askUserQuestion:ie}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:kt.suggestionChips,suggestionChipsConfig:{...kt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...kt.layout,...e.layout,header:{...(a=kt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=kt.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(p=(u=kt.layout)==null?void 0:u.messages)==null?void 0:p.avatar,...(m=(g=e.layout)==null?void 0:g.messages)==null?void 0:m.avatar},timestamp:{...(x=(w=kt.layout)==null?void 0:w.messages)==null?void 0:x.timestamp,...(P=(M=e.layout)==null?void 0:M.messages)==null?void 0:P.timestamp}},slots:{...(W=kt.layout)==null?void 0:W.slots,...(H=e.layout)==null?void 0:H.slots}},markdown:{...kt.markdown,...e.markdown,options:{...(_=kt.markdown)==null?void 0:_.options,...(B=e.markdown)==null?void 0:B.options}},messageActions:{...kt.messageActions,...e.messageActions}}:kt}var af={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"}},lf={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"}},cf={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:Aa,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Vr(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Vr(e,o):o}function Jp(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let i=`${r}.${s}`;if(typeof a=="string"){let d=Vr(e,a);d!==void 0&&(t[i]={path:i,value:d,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function df(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function Zp(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=Zp(s,r):n[o]=r}return n}function pf(e,t){return t?Zp(e,t):e}function nn(e,t={}){var r,s,a,i,d,l,u,p,g,m,w,x,M;let n={palette:af,semantic:lf,components:cf},o={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(u=e==null?void 0:e.semantic)==null?void 0:u.colors,interactive:{...n.semantic.colors.interactive,...(g=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:g.interactive},feedback:{...n.semantic.colors.feedback,...(w=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:w.feedback}},spacing:{...n.semantic.spacing,...(x=e==null?void 0:e.semantic)==null?void 0:x.spacing},typography:{...n.semantic.typography,...(M=e==null?void 0:e.semantic)==null?void 0:M.typography}},components:pf(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let P=df(o);if(!P.valid)throw new Error(`Theme validation failed: ${P.errors.map(W=>W.message).join(", ")}`)}if(t.plugins)for(let P of t.plugins)o=P.transform(o);return o}function eu(e){var x,M,P,W,H,_,B,v,C,E,S,k,D,$,q,me,re,be,ie,we,We,ye,Z,Ee,X,Ae,ge,le,ue,je,j,oe,Re,tt,fe,ce,_e,Le,de,Y,Ve,Ct,Q,Fe,Ln,Ft,ln,Dn,Jn,O,se,He,Xe,Oe,Ne,ot,St,Nt,jt,K,ft,nt,$t,ae,ve,wt,_t,Jt,vn,Et,At,ht,yt,Ut,Ze,Fn,Zn,xn,On,ut,wo,Nn,ar,In,Ir,$o,Lo,vt,_n,Vn,wn,Rt,eo,to,$n,Uo,Io,zo,Un,Wt,Cn,no,qo,Ro,jo,Co,zn,po,gt,Kt,Gt,qn,Ko,oo,uo,jn;let t=Jp(e),n={};for(let[T,Kn]of Object.entries(t)){let mo=T.replace(/\./g,"-");n[`--persona-${mo}`]=Kn.value}n["--persona-primary"]=(x=n["--persona-semantic-colors-primary"])!=null?x: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"]=(P=n["--persona-semantic-colors-accent"])!=null?P:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(W=n["--persona-semantic-colors-surface"])!=null?W: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"]=(_=n["--persona-semantic-colors-container"])!=null?_:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(B=n["--persona-semantic-colors-text"])!=null?B:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(v=n["--persona-semantic-colors-text-muted"])!=null?v:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(C=n["--persona-semantic-colors-text-inverse"])!=null?C:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(E=n["--persona-semantic-colors-border"])!=null?E:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(S=n["--persona-semantic-colors-divider"])!=null?S:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(k=n["--persona-components-voice-recording-indicator"])!=null?k:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(D=n["--persona-components-voice-recording-background"])!=null?D: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"]=(q=n["--persona-components-voice-speaking-icon"])!=null?q: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"]=(re=n["--persona-components-approval-requested-border"])!=null?re:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(be=n["--persona-components-approval-requested-text"])!=null?be: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"]=(we=n["--persona-components-approval-deny-background"])!=null?we:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(We=n["--persona-components-attachment-image-background"])!=null?We:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(ye=n["--persona-components-attachment-image-border"])!=null?ye:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(Z=n["--persona-semantic-typography-fontFamily"])!=null?Z:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(Ee=n["--persona-semantic-typography-fontSize"])!=null?Ee:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(X=n["--persona-semantic-typography-fontWeight"])!=null?X:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(Ae=n["--persona-semantic-typography-lineHeight"])!=null?Ae: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"]=(ge=n["--persona-palette-radius-sm"])!=null?ge:"0.125rem",n["--persona-radius-md"]=(le=n["--persona-palette-radius-md"])!=null?le:"0.375rem",n["--persona-radius-lg"]=(ue=n["--persona-palette-radius-lg"])!=null?ue:"0.5rem",n["--persona-radius-xl"]=(je=n["--persona-palette-radius-xl"])!=null?je:"0.75rem",n["--persona-radius-full"]=(j=n["--persona-palette-radius-full"])!=null?j:"9999px",n["--persona-launcher-radius"]=(Re=(oe=n["--persona-components-launcher-borderRadius"])!=null?oe:n["--persona-palette-radius-full"])!=null?Re:"9999px",n["--persona-launcher-bg"]=(tt=n["--persona-components-launcher-background"])!=null?tt:n["--persona-primary"],n["--persona-launcher-fg"]=(fe=n["--persona-components-launcher-foreground"])!=null?fe:n["--persona-text-inverse"],n["--persona-launcher-border"]=(ce=n["--persona-components-launcher-border"])!=null?ce:n["--persona-border"],n["--persona-button-primary-bg"]=(_e=n["--persona-components-button-primary-background"])!=null?_e:n["--persona-primary"],n["--persona-button-primary-fg"]=(Le=n["--persona-components-button-primary-foreground"])!=null?Le:n["--persona-text-inverse"],n["--persona-button-radius"]=(Y=(de=n["--persona-components-button-primary-borderRadius"])!=null?de:n["--persona-palette-radius-full"])!=null?Y:"9999px",n["--persona-panel-radius"]=(Ct=(Ve=n["--persona-components-panel-borderRadius"])!=null?Ve:n["--persona-radius-xl"])!=null?Ct:"0.75rem",n["--persona-panel-border"]=(Q=n["--persona-components-panel-border"])!=null?Q:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Ln=(Fe=n["--persona-components-panel-shadow"])!=null?Fe:n["--persona-palette-shadows-xl"])!=null?Ln:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-input-radius"]=(ln=(Ft=n["--persona-components-input-borderRadius"])!=null?Ft: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"]=(se=(O=n["--persona-components-message-assistant-borderRadius"])!=null?O:n["--persona-radius-lg"])!=null?se:"0.5rem",n["--persona-header-bg"]=(He=n["--persona-components-header-background"])!=null?He:n["--persona-surface"],n["--persona-header-border"]=(Xe=n["--persona-components-header-border"])!=null?Xe:n["--persona-divider"],n["--persona-header-icon-bg"]=(Oe=n["--persona-components-header-iconBackground"])!=null?Oe:n["--persona-primary"],n["--persona-header-icon-fg"]=(Ne=n["--persona-components-header-iconForeground"])!=null?Ne:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(ot=n["--persona-components-header-titleForeground"])!=null?ot:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(St=n["--persona-components-header-subtitleForeground"])!=null?St:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Nt=n["--persona-components-header-actionIconForeground"])!=null?Nt:n["--persona-muted"];let o=(jt=e.components)==null?void 0:jt.header;o!=null&&o.shadow&&(n["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom);let r=(K=e.components)==null?void 0:K.introCard;n["--persona-intro-card-bg"]=(ft=n["--persona-components-introCard-background"])!=null?ft:n["--persona-surface"],n["--persona-intro-card-radius"]=(nt=n["--persona-components-introCard-borderRadius"])!=null?nt:"1rem",n["--persona-intro-card-padding"]=($t=n["--persona-components-introCard-padding"])!=null?$t:"1.5rem",n["--persona-intro-card-shadow"]=(ve=(ae=r==null?void 0:r.shadow)!=null?ae:n["--persona-components-introCard-shadow"])!=null?ve:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(wt=n["--persona-components-input-background"])!=null?wt:n["--persona-surface"],n["--persona-input-placeholder"]=(_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"]=(vn=n["--persona-components-message-user-text"])!=null?vn:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Et=n["--persona-components-message-user-shadow"])!=null?Et:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(At=n["--persona-components-message-assistant-background"])!=null?At:n["--persona-surface"],n["--persona-message-assistant-text"]=(ht=n["--persona-components-message-assistant-text"])!=null?ht:n["--persona-text"],n["--persona-message-assistant-border"]=(yt=n["--persona-components-message-assistant-border"])!=null?yt:n["--persona-border"],n["--persona-message-assistant-shadow"]=(Ut=n["--persona-components-message-assistant-shadow"])!=null?Ut:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(Fn=(Ze=n["--persona-components-scrollToBottom-background"])!=null?Ze:n["--persona-button-primary-bg"])!=null?Fn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(xn=(Zn=n["--persona-components-scrollToBottom-foreground"])!=null?Zn:n["--persona-button-primary-fg"])!=null?xn: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"]=(ar=(Nn=(wo=n["--persona-components-scrollToBottom-borderRadius"])!=null?wo:n["--persona-button-radius"])!=null?Nn:n["--persona-radius-full"])!=null?ar:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Ir=(In=n["--persona-components-scrollToBottom-shadow"])!=null?In:n["--persona-palette-shadows-sm"])!=null?Ir:"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=(vt=n["--persona-components-scrollToBottom-fontSize"])!=null?vt: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"]=(wn=n["--persona-components-toolBubble-shadow"])!=null?wn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Rt=n["--persona-components-reasoningBubble-shadow"])!=null?Rt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(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"]=(Cn=n["--persona-components-markdown-table-headerBackground"])!=null?Cn:n["--persona-container"],n["--persona-md-table-border-color"]=(no=n["--persona-components-markdown-table-borderColor"])!=null?no:n["--persona-border"],n["--persona-md-hr-color"]=(qo=n["--persona-components-markdown-hr-color"])!=null?qo:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Ro=n["--persona-components-markdown-blockquote-borderColor"])!=null?Ro:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(jo=n["--persona-components-markdown-blockquote-background"])!=null?jo:"transparent",n["--persona-md-blockquote-text-color"]=(Co=n["--persona-components-markdown-blockquote-textColor"])!=null?Co:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(zn=n["--persona-components-collapsibleWidget-container"])!=null?zn:n["--persona-surface"],n["--cw-surface"]=(po=n["--persona-components-collapsibleWidget-surface"])!=null?po:n["--persona-surface"],n["--cw-border"]=(gt=n["--persona-components-collapsibleWidget-border"])!=null?gt:n["--persona-border"],n["--persona-message-border"]=(Kt=n["--persona-components-message-border"])!=null?Kt:n["--persona-border"];let u=e.components,p=u==null?void 0:u.iconButton;p&&(p.background&&(n["--persona-icon-btn-bg"]=p.background),p.border&&(n["--persona-icon-btn-border"]=p.border),p.color&&(n["--persona-icon-btn-color"]=p.color),p.padding&&(n["--persona-icon-btn-padding"]=p.padding),p.borderRadius&&(n["--persona-icon-btn-radius"]=p.borderRadius),p.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=p.hoverBackground),p.hoverColor&&(n["--persona-icon-btn-hover-color"]=p.hoverColor),p.activeBackground&&(n["--persona-icon-btn-active-bg"]=p.activeBackground),p.activeBorder&&(n["--persona-icon-btn-active-border"]=p.activeBorder));let g=u==null?void 0:u.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=u==null?void 0:u.toggleGroup;m&&(m.gap&&(n["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(n["--persona-toggle-group-radius"]=m.borderRadius));let w=u==null?void 0:u.artifact;if(w!=null&&w.toolbar){let T=w.toolbar;T.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=T.iconHoverColor),T.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=T.iconHoverBackground),T.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=T.iconPadding),T.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=T.iconBorderRadius),T.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=T.iconBorder),T.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=T.toggleGroupGap),T.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=T.toggleBorderRadius),T.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=T.copyBackground),T.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=T.copyBorder),T.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=T.copyColor),T.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=T.copyBorderRadius),T.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=T.copyPadding),T.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=T.copyMenuBackground,n["--persona-dropdown-bg"]=(Gt=n["--persona-dropdown-bg"])!=null?Gt:T.copyMenuBackground),T.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=T.copyMenuBorder,n["--persona-dropdown-border"]=(qn=n["--persona-dropdown-border"])!=null?qn:T.copyMenuBorder),T.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=T.copyMenuShadow,n["--persona-dropdown-shadow"]=(Ko=n["--persona-dropdown-shadow"])!=null?Ko:T.copyMenuShadow),T.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=T.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(oo=n["--persona-dropdown-radius"])!=null?oo:T.copyMenuBorderRadius),T.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=T.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(uo=n["--persona-dropdown-item-hover-bg"])!=null?uo:T.copyMenuItemHoverBackground),T.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=T.iconBackground),T.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=T.toolbarBorder)}if(w!=null&&w.tab){let T=w.tab;T.background&&(n["--persona-artifact-tab-bg"]=T.background),T.activeBackground&&(n["--persona-artifact-tab-active-bg"]=T.activeBackground),T.activeBorder&&(n["--persona-artifact-tab-active-border"]=T.activeBorder),T.borderRadius&&(n["--persona-artifact-tab-radius"]=T.borderRadius),T.textColor&&(n["--persona-artifact-tab-color"]=T.textColor),T.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=T.hoverBackground),T.listBackground&&(n["--persona-artifact-tab-list-bg"]=T.listBackground),T.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=T.listBorderColor),T.listPadding&&(n["--persona-artifact-tab-list-padding"]=T.listPadding)}if(w!=null&&w.pane){let T=w.pane;if(T.toolbarBackground){let Kn=(jn=Vr(e,T.toolbarBackground))!=null?jn:T.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Kn}}return n}var uf={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},tu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ui=()=>{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"},mf=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Ui()},ff=e=>mf(e),gf=e=>nn(e),hf=e=>{var n;let t=nn(void 0,{validate:!1});return nn({...e,palette:{...t.palette,colors:{...uf.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Ta=e=>{let t=ff(e),n=tu(e==null?void 0:e.theme),o=tu(e==null?void 0:e.darkTheme);return t==="dark"?hf(Ts(n!=null?n:{},o!=null?o:{})):gf(n)},bf=e=>eu(e),$r=(e,t)=>{var s;let n=Ta(t),o=bf(n);for(let[a,i]of Object.entries(o))e.style.setProperty(a,i);let r=(s=t==null?void 0:t.toolCall)==null?void 0:s.shadow;r!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",r.trim()===""?"none":r)},nu=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Ui())});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(Ui());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 zi(e,t){let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return o}function vr(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]:vr((i=a==null?void 0:a[r])!=null?i:{},s.join("."),n)}}var qi=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?{...kt,...n}:n!=null?n:kt,this.theme=nn(t,{validate:!1}),this.syncThemeIntoConfig(),this.pushHistorySnapshot(this.exportSnapshot(),!0)}get(t){var n;return t.startsWith("theme.")?zi(this.theme,t.replace("theme.","")):t.startsWith("darkTheme.")?zi((n=this.config.darkTheme)!=null?n:{},t.replace("darkTheme.","")):zi(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=vr(this.theme,r,n),this.syncThemeIntoConfig()}else if(t.startsWith("darkTheme.")){let r=t.replace("darkTheme.",""),s=(o=this.config.darkTheme)!=null?o:nn();this.config={...this.config,darkTheme:vr(s,r,n)}}else this.config=vr(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=vr(this.theme,d,i),n=!0}else if(a.startsWith("darkTheme.")){let d=a.replace("darkTheme.",""),l=(s=this.config.darkTheme)!=null?s:nn();this.config={...this.config,darkTheme:vr(l,d,i)},o=!0}else this.config=vr(this.config,a,i),r=!0;n&&this.syncThemeIntoConfig(),(n||o||r)&&(this.recordHistory(),this.notifyListeners())}setTheme(t){this.theme=t,this.syncThemeIntoConfig(),this.recordHistory(),this.notifyListeners()}setFullConfig(t,n){this.config={...t},n&&(this.theme=n),this.syncThemeIntoConfig(),this.recordHistory(),this.notifyListeners()}importSnapshot(t){var r,s;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Snapshot must be a JSON object");let n=t;if("config"in n||"theme"in n||n.version===2){let a=(r=n.config)!=null?r:this.config,i=nn((s=n.theme)!=null?s:this.theme,{validate:!1});this.setFullConfig(a,i);return}let o=nn(n,{validate:!1});this.setTheme(o)}resetToDefaults(){this.config={...kt},this.theme=nn(),this.syncThemeIntoConfig(),this.history=[],this.historyIndex=-1,this.pushHistorySnapshot(this.exportSnapshot()),this.notifyListeners()}canUndo(){return this.historyIndex>0}canRedo(){return this.historyIndex>=0&&this.historyIndex<this.history.length-1}getHistoryLength(){return this.history.length}getHistoryIndex(){return this.historyIndex}undo(){this.canUndo()&&(this.historyIndex-=1,this.restoreSnapshot(this.history[this.historyIndex]))}redo(){this.canRedo()&&(this.historyIndex+=1,this.restoreSnapshot(this.history[this.historyIndex]))}exportSnapshot(){return{version:2,config:{...this.config,theme:void 0},theme:this.theme}}onChange(t){return this.listeners.push(t),()=>{let n=this.listeners.indexOf(t);n>=0&&this.listeners.splice(n,1)}}syncThemeIntoConfig(){this.config={...this.config,theme:this.theme}}notifyListeners(){for(let t of this.listeners)t(this.config,this.theme)}recordHistory(){this.pushHistorySnapshot(this.exportSnapshot())}pushHistorySnapshot(t,n=!1){if(this.suppressHistory)return;let o=JSON.stringify(t),r=this.historyIndex>=0&&this.history[this.historyIndex]?JSON.stringify(this.history[this.historyIndex]):null;if(n&&this.historyIndex>=0){this.history[this.historyIndex]=t;return}o!==r&&(this.history=this.history.slice(0,this.historyIndex+1),this.history.push(t),this.historyIndex=this.history.length-1)}restoreSnapshot(t){this.suppressHistory=!0,this.config=t.config,this.theme=nn(t.theme,{validate:!1}),this.syncThemeIntoConfig(),this.suppressHistory=!1,this.notifyListeners()}};function ji(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 Ki(e,t){return t==="rem"?`${e}rem`:`${e}px`}function yf(e,t){return t==="rem"?e*16:e}function vf(e,t){return t==="rem"?e/16:e}function ks(e){if(!e)return"#000000";let t=e.trim().toLowerCase();return t==="transparent"?"transparent":t.startsWith("rgba")||t.startsWith("rgb")?t:t.startsWith("#")?t.length===4?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:t:`#${t}`}function Gi(e){return/^#[0-9A-Fa-f]{6}$/.test(e)}function Yi(e){let t=e.trim().toLowerCase().match(/^rgba?\(([^)]+)\)$/);if(!t)return null;let n=t[1].split(",").map(d=>d.trim());if(n.length<3)return null;let o=d=>{let l=d.endsWith("%"),u=parseFloat(l?d.slice(0,-1):d);return Number.isFinite(u)?Math.max(0,Math.min(255,Math.round(l?u/100*255:u))):NaN},r=o(n[0]),s=o(n[1]),a=o(n[2]);if(!Number.isFinite(r)||!Number.isFinite(s)||!Number.isFinite(a))return null;let i=d=>d.toString(16).padStart(2,"0");return`#${i(r)}${i(s)}${i(a)}`}function ka(e,t){let n=s=>{var l;let a=ks(s),i=a.startsWith("rgb")?(l=Yi(a))!=null?l:"#000000":a,d=[1,3,5].map(u=>{let p=parseInt(i.slice(u,u+2),16)/255;return p<=.03928?p/12.92:Math.pow((p+.055)/1.055,2.4)});return .2126*d[0]+.7152*d[1]+.0722*d[2]},o=n(e),r=n(t);return(Math.max(o,r)+.05)/(Math.min(o,r)+.05)}function ou(e){var g;let t=ks(e),n=t.startsWith("rgb")?(g=Yi(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,u=d>.5?l/(2-a-i):l/(a+i),p;switch(a){case o:p=((r-s)/l+(r<s?6:0))/6;break;case r:p=((s-o)/l+2)/6;break;default:p=((o-r)/l+4)/6;break}return{h:p*360,s:u,l:d}}function ru(e,t,n){let o=(e%360+360)%360,r=(1-Math.abs(2*n-1))*t,s=r*(1-Math.abs(o/60%2-1)),a=n-r/2,i,d,l;o<60?[i,d,l]=[r,s,0]:o<120?[i,d,l]=[s,r,0]:o<180?[i,d,l]=[0,r,s]:o<240?[i,d,l]=[0,s,r]:o<300?[i,d,l]=[s,0,r]:[i,d,l]=[r,0,s];let u=p=>{let g=Math.round((p+a)*255).toString(16);return g.length===1?"0"+g:g};return`#${u(i)}${u(d)}${u(l)}`}function Xi(e){let{h:t,s:n,l:o}=ou(e),r={50:.97,100:.94,200:.87,300:.77,400:.64,500:o,600:Math.max(.05,o-.1),700:Math.max(.05,o-.2),800:Math.max(.05,o-.28),900:Math.max(.05,o-.35),950:Math.max(.03,o-.42)},s={50:Math.min(1,n*.85),100:Math.min(1,n*.9),200:Math.min(1,n*.95),300:n,400:n,500:n,600:Math.min(1,n*1.05),700:Math.min(1,n*1.05),800:Math.min(1,n*1),900:Math.min(1,n*.95),950:Math.min(1,n*.9)},a={};for(let[i,d]of Object.entries(r)){let l=s[i];a[i]=ru(t,l,d)}return a}var Ur=["50","100","200","300","400","500","600","700","800","900","950"],Qi=["primary","secondary","accent","gray","success","warning","error","info"];function xf(e,t){return`palette.colors.${e}.${t}`}function su(e,t,n=0){if(n>5)return"#cbd5e1";let o=e(t);return typeof o!="string"?"#cbd5e1":o.startsWith("#")||o.startsWith("rgb")||o==="transparent"?o:o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components.")?su(e,`theme.${o}`,n+1):"#cbd5e1"}function wf(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"}],Ea=["primary","secondary","accent","gray"],Cf={primary:"Primary",secondary:"Secondary",accent:"Accent",gray:"Neutral"},Ma={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"}]},La={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"}]},Ia={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"}]},Ra={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"}]},Pa={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"}]},Wa={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"}]},Ba={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"}]},Ha={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"}]},Da={roleId:"role-borders",helper:"Borders, dividers, and separators",intensities:ko,targets:[{path:"semantic.colors.border",kind:"border"},{path:"semantic.colors.divider",kind:"border"}]},xr=[Ma,La,Ia,Ra,Pa,Wa,Ba,Ha,Da];function Fa(e,t,n){let o={},r=e==="neutral"?"gray":e;for(let s of n.targets){let a=Sf(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 Sf(e,t,n,o){let r=t==="solid";if(o==="role-header")return Af(e,r,n);if(o==="role-input")return Tf(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 Af(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 Tf(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 kf=/^palette\.colors\.(\w+)\.(\d+)$/;function Ji(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(kf);if(!r)return null;let s=r[1],a=Ea.includes(s)?s:null;if(!a)return null;for(let l of["solid","soft"]){let u=Fa(a,l,t);if(t.targets.every(g=>{var w;return String((w=e(g.path))!=null?w:"")===u[`theme.${g.path}`]}))return{family:a,intensity:l}}return null}var Ef={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"}]}]},Mf={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"}]},Lf={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"}}]},If={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)"}]}]},Rf={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"}]}]},Pf={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"}}]},Wf={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)"}]},Bf={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=[Mf,Lf,Rf,If,Ef,Pf,Wf,Bf];function au(){return{id:"brand-palette",title:"Brand Palette",description:"Define your color palette. Edit the base color (500) to auto-generate the full scale.",collapsed:!1,fields:Qi.map(t=>({id:`palette-${t}`,label:`${t.charAt(0).toUpperCase()+t.slice(1)}`,description:`${t} color palette (edit shade 500, auto-generate scale)`,type:"color-scale",path:`theme.palette.colors.${t}`,colorScale:{colorFamily:t}}))}}var iu={id:"semantic-colors",title:"Semantic Colors",description:"Map intents to palette colors.",collapsed:!0,fields:[{id:"sem-primary",label:"Primary",description:"Main brand/action color",type:"token-ref",path:"theme.semantic.colors.primary",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sem-secondary",label:"Secondary",description:"Secondary actions",type:"token-ref",path:"theme.semantic.colors.secondary",defaultValue:"palette.colors.gray.500",tokenRef:{tokenType:"color"}},{id:"sem-accent",label:"Accent",description:"Accent/highlight color",type:"token-ref",path:"theme.semantic.colors.accent",defaultValue:"palette.colors.primary.600",tokenRef:{tokenType:"color"}},{id:"sem-surface",label:"Surface",description:"Primary surface background",type:"token-ref",path:"theme.semantic.colors.surface",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-background",label:"Background",description:"Page/widget background",type:"token-ref",path:"theme.semantic.colors.background",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-container",label:"Container",description:"Container/card background",type:"token-ref",path:"theme.semantic.colors.container",defaultValue:"palette.colors.gray.100",tokenRef:{tokenType:"color"}},{id:"sem-text",label:"Text",description:"Primary text color",type:"token-ref",path:"theme.semantic.colors.text",defaultValue:"palette.colors.gray.900",tokenRef:{tokenType:"color"}},{id:"sem-text-muted",label:"Text Muted",description:"Secondary/muted text",type:"token-ref",path:"theme.semantic.colors.textMuted",defaultValue:"palette.colors.gray.500",tokenRef:{tokenType:"color"}},{id:"sem-text-inverse",label:"Text Inverse",description:"Text on dark backgrounds",type:"token-ref",path:"theme.semantic.colors.textInverse",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-border",label:"Border",description:"Default border color",type:"token-ref",path:"theme.semantic.colors.border",defaultValue:"palette.colors.gray.200",tokenRef:{tokenType:"color"}},{id:"sem-divider",label:"Divider",description:"Divider/separator color",type:"token-ref",path:"theme.semantic.colors.divider",defaultValue:"palette.colors.gray.200",tokenRef:{tokenType:"color"}},{id:"sem-interactive-default",label:"Interactive Default",type:"token-ref",path:"theme.semantic.colors.interactive.default",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sem-interactive-hover",label:"Interactive Hover",type:"token-ref",path:"theme.semantic.colors.interactive.hover",defaultValue:"palette.colors.primary.600",tokenRef:{tokenType:"color"}},{id:"sem-interactive-focus",label:"Interactive Focus",type:"token-ref",path:"theme.semantic.colors.interactive.focus",defaultValue:"palette.colors.primary.700",tokenRef:{tokenType:"color"}},{id:"sem-interactive-active",label:"Interactive Active",type:"token-ref",path:"theme.semantic.colors.interactive.active",defaultValue:"palette.colors.primary.800",tokenRef:{tokenType:"color"}},{id:"sem-interactive-disabled",label:"Interactive Disabled",type:"token-ref",path:"theme.semantic.colors.interactive.disabled",defaultValue:"palette.colors.gray.300",tokenRef:{tokenType:"color"}},{id:"sem-feedback-success",label:"Success",type:"token-ref",path:"theme.semantic.colors.feedback.success",defaultValue:"palette.colors.success.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-warning",label:"Warning",type:"token-ref",path:"theme.semantic.colors.feedback.warning",defaultValue:"palette.colors.warning.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-error",label:"Error",type:"token-ref",path:"theme.semantic.colors.feedback.error",defaultValue:"palette.colors.error.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-info",label:"Info",type:"token-ref",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}}]},Hf=au(),Df=iu,Ff=[au(),iu],Of={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:Aa},{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"}]}]},Nf={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"}]}]},_f={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"}]}]},Vf={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"}]}]},$f={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"}]}]},Uf={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"}}]},zf={id:"comp-message-colors",title:"Message Colors",collapsed:!0,fields:[{id:"msg-user-bg",label:"User Bubble Background",type:"token-ref",path:"theme.components.message.user.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"msg-user-text",label:"User Bubble Text",type:"token-ref",path:"theme.components.message.user.text",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"msg-assistant-bg",label:"Assistant Bubble Background",type:"token-ref",path:"theme.components.message.assistant.background",defaultValue:"semantic.colors.container",tokenRef:{tokenType:"color"}},{id:"msg-assistant-text",label:"Assistant Bubble Text",type:"token-ref",path:"theme.components.message.assistant.text",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},qf={id:"comp-input-colors",title:"Input Colors",collapsed:!0,fields:[{id:"input-bg",label:"Background",type:"token-ref",path:"theme.components.input.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"input-placeholder",label:"Placeholder Color",type:"token-ref",path:"theme.components.input.placeholder",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"input-focus-border",label:"Focus Border",type:"token-ref",path:"theme.components.input.focus.border",defaultValue:"semantic.colors.interactive.focus",tokenRef:{tokenType:"color"}},{id:"input-focus-ring",label:"Focus Ring",type:"token-ref",path:"theme.components.input.focus.ring",defaultValue:"semantic.colors.interactive.focus",tokenRef:{tokenType:"color"}}]},jf={id:"comp-button-colors",title:"Button Colors",collapsed:!0,fields:[{id:"btn-primary-bg",label:"Primary Background",type:"token-ref",path:"theme.components.button.primary.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"btn-primary-fg",label:"Primary Foreground",type:"token-ref",path:"theme.components.button.primary.foreground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"btn-secondary-bg",label:"Secondary Background",type:"token-ref",path:"theme.components.button.secondary.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"btn-secondary-fg",label:"Secondary Foreground",type:"token-ref",path:"theme.components.button.secondary.foreground",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}},{id:"btn-ghost-bg",label:"Ghost Background",type:"color",path:"theme.components.button.ghost.background",defaultValue:"transparent"},{id:"btn-ghost-fg",label:"Ghost Foreground",type:"token-ref",path:"theme.components.button.ghost.foreground",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},Kf={id:"scroll-to-bottom-style",title:"Scroll To Bottom",description:"Style the floating jump-to-latest affordance.",collapsed:!0,fields:[{id:"scroll-bottom-bg",label:"Background",type:"token-ref",path:"theme.components.scrollToBottom.background",defaultValue:"components.button.primary.background",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-fg",label:"Foreground",type:"token-ref",path:"theme.components.scrollToBottom.foreground",defaultValue:"components.button.primary.foreground",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-border",label:"Border",type:"token-ref",path:"theme.components.scrollToBottom.border",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-size",label:"Size",type:"text",path:"theme.components.scrollToBottom.size",defaultValue:"40px"},{id:"scroll-bottom-radius",label:"Border Radius",type:"select",path:"theme.components.scrollToBottom.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"},{value:"palette.radius.full",label:"Full"}]},{id:"scroll-bottom-shadow",label:"Shadow",type:"select",path:"theme.components.scrollToBottom.shadow",defaultValue:"palette.shadows.sm",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]},{id:"scroll-bottom-padding",label:"Padding",type:"text",path:"theme.components.scrollToBottom.padding",defaultValue:"0.5rem 0.875rem"},{id:"scroll-bottom-gap",label:"Gap",type:"text",path:"theme.components.scrollToBottom.gap",defaultValue:"0.5rem"},{id:"scroll-bottom-font-size",label:"Font Size",type:"text",path:"theme.components.scrollToBottom.fontSize",defaultValue:"0.875rem"},{id:"scroll-bottom-icon-size",label:"Icon Size",type:"text",path:"theme.components.scrollToBottom.iconSize",defaultValue:"14px"}]},lu=[Of,Nf,_f,Vf,$f],cu=[Uf,zf,qf,jf,Kf],du=[...lu,...cu],Zi=1024*1024,Gf=["What can you help me with?","Tell me about your features","How does this work?"],Es={images:["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],"images-pdf":["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf"],"images-text-pdf":["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf","text/plain","text/markdown","text/csv","application/json"],all:["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"]};function Yf(e){return Number(e)*Zi}function Xf(e){let t=Number(e);return Number.isFinite(t)?t>1024?String(Math.round(t/Zi)):String(t):"10"}function Qf(e){var t;return(t=Es[String(e)])!=null?t:Es.images}function Jf(e){let t=Array.isArray(e)?e:Es.images,n=[...new Set(t)].sort();for(let[o,r]of Object.entries(Es)){let s=[...r].sort();if(n.length===s.length&&n.every((a,i)=>a===s[i]))return o}return n.some(o=>o.startsWith("application/vnd")||o==="application/msword")?"all":n.some(o=>o==="text/plain"||o==="text/markdown"||o==="text/csv")?"images-text-pdf":n.includes("application/pdf")?"images-pdf":"images"}var Zf={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"}]},eg={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:Gf}]},tg={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:""}]},ng={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}]},og={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"}]}]},rg={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"}]}]},sg={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"}]},ag={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:""}]},ig={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"}]},lg={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"}]},cg={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"}]},dg={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"}]},pg={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:""}]},ug={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)}]},mg={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*Zi,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:Xf,parseValue:Yf},{id:"attach-types",label:"Allowed File Types",type:"select",path:"attachments.allowedTypes",defaultValue:Es.images,options:[{value:"images",label:"Images only"},{value:"images-pdf",label:"Images + PDF"},{value:"images-text-pdf",label:"Images + text + PDF"},{value:"all",label:"All supported types"}],formatValue:Jf,parseValue:Qf}]},fg={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"}]}]},gg={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}]},hg={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"}]}]},bg={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}]},yg={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}]},Oa=[{label:"Content",sections:[Zf,eg]},{label:"Layout",sections:[tg,ng,og,rg]},{label:"Widget",sections:[sg,ag,ig,lg,cg,dg]},{label:"Features",sections:[pg,ug,mg,fg,gg]},{label:"Developer",collapsedByDefault:!0,sections:[hg,bg,yg]}],pu=Oa.flatMap(e=>e.sections),uu={id:"theme-mode-v2",title:"Theme",description:"Choose how the interface adapts across light and dark mode.",collapsed:!1,fields:[{id:"color-mode",label:"Color Mode",type:"select",path:"colorScheme",defaultValue:"auto",options:[{value:"auto",label:"Auto"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}]}]},mu={id:"brand-palette-v2",title:"Brand Palette",description:"Set your brand, accent, and neutral colors. These are used to generate the interface theme.",collapsed:!1,fields:[{id:"bp-primary",label:"Primary",description:"Main brand color",type:"color",path:"theme.palette.colors.primary.500",defaultValue:"#171717"},{id:"bp-secondary",label:"Secondary",description:"Supporting brand color",type:"color",path:"theme.palette.colors.secondary.500",defaultValue:"#8b5cf6"},{id:"bp-accent",label:"Accent",description:"Highlight and decorative color",type:"color",path:"theme.palette.colors.accent.500",defaultValue:"#06b6d4"},{id:"bp-neutral",label:"Neutral",description:"Backgrounds, text, and borders",type:"color",path:"theme.palette.colors.gray.500",defaultValue:"#6b7280"}]},fu={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"}]},gu={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:Ma},{id:"role-header",label:"Header",type:"role-assignment",path:"theme.components.header.background",roleAssignment:La},{id:"role-user-messages",label:"User Messages",type:"role-assignment",path:"theme.components.message.user.background",roleAssignment:Ia},{id:"role-assistant-messages",label:"Assistant Messages",type:"role-assignment",path:"theme.components.message.assistant.background",roleAssignment:Ra},{id:"role-primary-actions",label:"Primary Actions",type:"role-assignment",path:"theme.components.button.primary.background",roleAssignment:Pa},{id:"role-scroll-to-bottom",label:"Scroll To Bottom",type:"role-assignment",path:"theme.components.scrollToBottom.background",roleAssignment:Wa},{id:"role-input",label:"Input Field",type:"role-assignment",path:"theme.components.input.background",roleAssignment:Ba},{id:"role-links-focus",label:"Links & Focus",type:"role-assignment",path:"theme.semantic.colors.accent",roleAssignment:Ha},{id:"role-borders",label:"Borders & Dividers",type:"role-assignment",path:"theme.semantic.colors.border",roleAssignment:Da}]},hu={id:"status-colors",title:"Status Colors",description:"Used for system states like success, warning, notice, and error.",collapsed:!0,fields:[{id:"sc-notice",label:"Notice",type:"token-ref",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sc-success",label:"Success",type:"token-ref",path:"theme.semantic.colors.feedback.success",defaultValue:"palette.colors.success.500",tokenRef:{tokenType:"color"}},{id:"sc-warning",label:"Warning",type:"token-ref",path:"theme.semantic.colors.feedback.warning",defaultValue:"palette.colors.warning.500",tokenRef:{tokenType:"color"}},{id:"sc-error",label:"Error",type:"token-ref",path:"theme.semantic.colors.feedback.error",defaultValue:"palette.colors.error.500",tokenRef:{tokenType:"color"}}]},bu={id:"advanced-tokens",title:"Advanced Tokens",description:"Override individual semantic and component values when you need precise control.",collapsed:!0,fields:[]},vg=[uu,mu,fu,gu,hu,bu],el=[{id:"style",label:"Style",sections:zr},{id:"design-system",label:"Design System",sections:du},{id:"configure",label:"Configure",sections:pu}];function yu(e,t){return e.startsWith("theme.")?e.replace(/^theme\./,`${t}.`):e}function xg(e,t,n){return{...e,id:`${n}-${e.id}`,path:yu(e.path,t)}}function wg(e,t){let n=e.find(o=>o.id===t);if(!n)throw new Error(`Section "${t}" not found in definitions`);return n}function Cg(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=>xg(i,t,n)),presets:(a=e.presets)==null?void 0:a.map(i=>({...i,id:`${n}-${i.id}`,values:Object.fromEntries(Object.entries(i.values).map(([d,l])=>[yu(d,t),l]))}))}}var vu=[{id:"default-light",name:"Default Light",description:"Clean monochrome light theme",theme:{components:{artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}}},preview:{primary:"#171717",surface:"#ffffff",accent:"#0f0f0f"},tags:["light"]},{id:"default-dark",name:"Default Dark",description:"Monochrome dark theme",theme:{palette:{colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},semantic:{colors:{primary:"palette.colors.primary.400",secondary:"palette.colors.gray.400",accent:"palette.colors.primary.500",surface:"palette.colors.gray.800",background:"palette.colors.gray.900",container:"palette.colors.gray.800",text:"palette.colors.gray.100",textMuted:"palette.colors.gray.400",textInverse:"palette.colors.gray.900",border:"palette.colors.gray.700",divider:"palette.colors.gray.700",interactive:{default:"palette.colors.primary.400",hover:"palette.colors.primary.300",focus:"palette.colors.primary.500",active:"palette.colors.primary.600",disabled:"palette.colors.gray.600"},feedback:{success:"palette.colors.success.400",warning:"palette.colors.warning.400",error:"palette.colors.error.400",info:"palette.colors.primary.400"}}}},preview:{primary:"#171717",surface:"#1f2937",accent:"#0f0f0f"},tags:["dark"]},{id:"high-contrast",name:"High Contrast",description:"Maximum contrast for accessibility",theme:{semantic:{colors:{primary:"palette.colors.primary.700",secondary:"palette.colors.gray.700",accent:"palette.colors.primary.800",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.200",text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.400",divider:"palette.colors.gray.400",interactive:{default:"palette.colors.primary.700",hover:"palette.colors.primary.800",focus:"palette.colors.primary.900",active:"palette.colors.primary.950",disabled:"palette.colors.gray.400"},feedback:{success:"palette.colors.success.700",warning:"palette.colors.warning.700",error:"palette.colors.error.700",info:"palette.colors.primary.700"}}}},preview:{primary:"#0a0a0a",surface:"#f9fafb",accent:"#050505"},tags:["light","high-contrast","accessibility"]}],Ms=[...vu];function tl(e){return Ms.find(t=>t.id===e)}import{Marked as Sg}from"marked";var Ag=e=>{if(e)return e},nl=e=>{var r,s;let t=e==null?void 0:e.markedOptions,n=new Sg({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=Ag(e==null?void 0:e.renderer);return o&&n.use({renderer:o}),a=>n.parse(a)},Na=e=>e?nl({markedOptions:e.options,renderer:e.renderer}):nl(),Yx=nl();var Ls=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");import Tg from"dompurify";var kg={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"]},Eg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Mg=()=>{let e=Tg(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:")&&!Eg.test(o)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,kg)},_a=e=>e===!1?null:typeof e=="function"?e:Mg();var ol="webmcp:",Va={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},$a=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 Va.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=Rg(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 m=typeof document!="undefined"&&!!document.modelContext;return vo(m?"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=Lg(t),a;try{a=await r.getTools()}catch(m){let w=m instanceof Error?m.message:String(m);return vo(`Failed to read WebMCP registry: ${w}`)}let i=a.find(m=>m.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,u=!1,p=setTimeout(()=>{u=!0,l.abort()},this.timeoutMs),g=()=>l.abort();o&&(o.aborted?l.abort():o.addEventListener("abort",g,{once:!0}));try{let m=await r.executeTool(i,Hg(n),{signal:l.signal});return Pg(m)}catch(m){if(u)return vo(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return vo("Aborted by cancel()");let w=m instanceof Error?m.message:String(m);return vo(w)}finally{clearTimeout(p),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){Va.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,Va.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:Wg;try{return await n(t)}catch(r){return Va.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=>Ig(t,o))}},Lg=e=>e.startsWith(ol)?e.slice(ol.length):e,rl=e=>e.startsWith(ol),Ig=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Rg=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Pg=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:Dg(t)}]}},vo=e=>({isError:!0,content:[{type:"text",text:e}]}),Wg=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Bg(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
1
|
+
var Yp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ts(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];Yp(s)&&Yp(r)?n[o]=Ts(s,r):n[o]=r}return n}var io="min(440px, calc(100vw - 24px))",Aa="440px",kt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:io,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Xp(e,t){if(!(!e&&!t))return e?t?Ts(e,t):e:t}function Qp(e){var t,n,o,r,s,a,i,d,l,u,p,f,g,x,C,M,W,L,H,D,B;return e?{...kt,...e,theme:Xp(kt.theme,e.theme),darkTheme:Xp(kt.darkTheme,e.darkTheme),launcher:{...kt.launcher,...e.launcher,dock:{...(t=kt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(o=kt.launcher)==null?void 0:o.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...kt.copy,...e.copy},sendButton:{...kt.sendButton,...e.sendButton},statusIndicator:{...kt.statusIndicator,...e.statusIndicator},voiceRecognition:{...kt.voiceRecognition,...e.voiceRecognition},features:(()=>{var we,We,ye,Z,Ee,X,Ae,fe;let v=(we=kt.features)==null?void 0:we.artifacts,w=(We=e.features)==null?void 0:We.artifacts,E=(ye=kt.features)==null?void 0:ye.scrollToBottom,S=(Z=e.features)==null?void 0:Z.scrollToBottom,k=(Ee=kt.features)==null?void 0:Ee.streamAnimation,F=(X=e.features)==null?void 0:X.streamAnimation,$=(Ae=kt.features)==null?void 0:Ae.askUserQuestion,q=(fe=e.features)==null?void 0:fe.askUserQuestion,me=v===void 0&&w===void 0?void 0:{...v,...w,layout:{...v==null?void 0:v.layout,...w==null?void 0:w.layout}},re=E===void 0&&S===void 0?void 0:{...E,...S},be=k===void 0&&F===void 0?void 0:{...k,...F},ie=$===void 0&&q===void 0?void 0:{...$,...q,styles:{...$==null?void 0:$.styles,...q==null?void 0:q.styles}};return{...kt.features,...e.features,...re!==void 0?{scrollToBottom:re}:{},...me!==void 0?{artifacts:me}:{},...be!==void 0?{streamAnimation:be}:{},...ie!==void 0?{askUserQuestion:ie}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:kt.suggestionChips,suggestionChipsConfig:{...kt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...kt.layout,...e.layout,header:{...(a=kt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=kt.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(p=(u=kt.layout)==null?void 0:u.messages)==null?void 0:p.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(C=(x=kt.layout)==null?void 0:x.messages)==null?void 0:C.timestamp,...(W=(M=e.layout)==null?void 0:M.messages)==null?void 0:W.timestamp}},slots:{...(L=kt.layout)==null?void 0:L.slots,...(H=e.layout)==null?void 0:H.slots}},markdown:{...kt.markdown,...e.markdown,options:{...(D=kt.markdown)==null?void 0:D.options,...(B=e.markdown)==null?void 0:B.options}},messageActions:{...kt.messageActions,...e.messageActions}}:kt}var lg={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},cg={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},dg={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:io,maxWidth:Aa,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Vr(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Vr(e,o):o}function Jp(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let i=`${r}.${s}`;if(typeof a=="string"){let d=Vr(e,a);d!==void 0&&(t[i]={path:i,value:d,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function pg(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function Zp(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=Zp(s,r):n[o]=r}return n}function ug(e,t){return t?Zp(e,t):e}function nn(e,t={}){var r,s,a,i,d,l,u,p,f,g,x,C,M;let n={palette:lg,semantic:cg,components:dg},o={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(u=e==null?void 0:e.semantic)==null?void 0:u.colors,interactive:{...n.semantic.colors.interactive,...(f=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(x=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:x.feedback}},spacing:{...n.semantic.spacing,...(C=e==null?void 0:e.semantic)==null?void 0:C.spacing},typography:{...n.semantic.typography,...(M=e==null?void 0:e.semantic)==null?void 0:M.typography}},components:ug(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let W=pg(o);if(!W.valid)throw new Error(`Theme validation failed: ${W.errors.map(L=>L.message).join(", ")}`)}if(t.plugins)for(let W of t.plugins)o=W.transform(o);return o}function eu(e){var C,M,W,L,H,D,B,v,w,E,S,k,F,$,q,me,re,be,ie,we,We,ye,Z,Ee,X,Ae,fe,le,ue,je,j,oe,Re,tt,ge,ce,_e,Le,de,Y,Ve,Ct,Q,Fe,Ln,Ft,ln,Dn,Jn,N,se,He,Xe,Oe,Ne,ot,St,Nt,jt,K,gt,nt,$t,ae,ve,wt,_t,Jt,vn,Et,At,ht,yt,Ut,Ze,Fn,Zn,xn,On,ut,wo,Nn,ar,In,Ir,$o,Lo,vt,_n,Vn,wn,Rt,eo,to,$n,Uo,Io,zo,Un,Wt,Cn,no,qo,Ro,jo,Co,zn,po,ft,Kt,Gt,qn,Ko,oo,uo,jn;let t=Jp(e),n={};for(let[T,Kn]of Object.entries(t)){let mo=T.replace(/\./g,"-");n[`--persona-${mo}`]=Kn.value}n["--persona-primary"]=(C=n["--persona-semantic-colors-primary"])!=null?C:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(M=n["--persona-semantic-colors-secondary"])!=null?M:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(W=n["--persona-semantic-colors-accent"])!=null?W: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"]=(B=n["--persona-semantic-colors-text"])!=null?B:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(v=n["--persona-semantic-colors-text-muted"])!=null?v:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(w=n["--persona-semantic-colors-text-inverse"])!=null?w:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(E=n["--persona-semantic-colors-border"])!=null?E:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(S=n["--persona-semantic-colors-divider"])!=null?S:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(k=n["--persona-components-voice-recording-indicator"])!=null?k: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"]=(q=n["--persona-components-voice-speaking-icon"])!=null?q: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"]=(re=n["--persona-components-approval-requested-border"])!=null?re:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(be=n["--persona-components-approval-requested-text"])!=null?be: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"]=(we=n["--persona-components-approval-deny-background"])!=null?we:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(We=n["--persona-components-attachment-image-background"])!=null?We:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(ye=n["--persona-components-attachment-image-border"])!=null?ye:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(Z=n["--persona-semantic-typography-fontFamily"])!=null?Z:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(Ee=n["--persona-semantic-typography-fontSize"])!=null?Ee:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(X=n["--persona-semantic-typography-fontWeight"])!=null?X:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(Ae=n["--persona-semantic-typography-lineHeight"])!=null?Ae: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"]=(fe=n["--persona-palette-radius-sm"])!=null?fe:"0.125rem",n["--persona-radius-md"]=(le=n["--persona-palette-radius-md"])!=null?le:"0.375rem",n["--persona-radius-lg"]=(ue=n["--persona-palette-radius-lg"])!=null?ue:"0.5rem",n["--persona-radius-xl"]=(je=n["--persona-palette-radius-xl"])!=null?je:"0.75rem",n["--persona-radius-full"]=(j=n["--persona-palette-radius-full"])!=null?j:"9999px",n["--persona-launcher-radius"]=(Re=(oe=n["--persona-components-launcher-borderRadius"])!=null?oe:n["--persona-palette-radius-full"])!=null?Re:"9999px",n["--persona-launcher-bg"]=(tt=n["--persona-components-launcher-background"])!=null?tt:n["--persona-primary"],n["--persona-launcher-fg"]=(ge=n["--persona-components-launcher-foreground"])!=null?ge:n["--persona-text-inverse"],n["--persona-launcher-border"]=(ce=n["--persona-components-launcher-border"])!=null?ce:n["--persona-border"],n["--persona-button-primary-bg"]=(_e=n["--persona-components-button-primary-background"])!=null?_e:n["--persona-primary"],n["--persona-button-primary-fg"]=(Le=n["--persona-components-button-primary-foreground"])!=null?Le:n["--persona-text-inverse"],n["--persona-button-radius"]=(Y=(de=n["--persona-components-button-primary-borderRadius"])!=null?de:n["--persona-palette-radius-full"])!=null?Y:"9999px",n["--persona-panel-radius"]=(Ct=(Ve=n["--persona-components-panel-borderRadius"])!=null?Ve:n["--persona-radius-xl"])!=null?Ct:"0.75rem",n["--persona-panel-border"]=(Q=n["--persona-components-panel-border"])!=null?Q:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Ln=(Fe=n["--persona-components-panel-shadow"])!=null?Fe:n["--persona-palette-shadows-xl"])!=null?Ln:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-input-radius"]=(ln=(Ft=n["--persona-components-input-borderRadius"])!=null?Ft: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"]=(se=(N=n["--persona-components-message-assistant-borderRadius"])!=null?N:n["--persona-radius-lg"])!=null?se:"0.5rem",n["--persona-header-bg"]=(He=n["--persona-components-header-background"])!=null?He:n["--persona-surface"],n["--persona-header-border"]=(Xe=n["--persona-components-header-border"])!=null?Xe:n["--persona-divider"],n["--persona-header-icon-bg"]=(Oe=n["--persona-components-header-iconBackground"])!=null?Oe:n["--persona-primary"],n["--persona-header-icon-fg"]=(Ne=n["--persona-components-header-iconForeground"])!=null?Ne:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(ot=n["--persona-components-header-titleForeground"])!=null?ot:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(St=n["--persona-components-header-subtitleForeground"])!=null?St:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Nt=n["--persona-components-header-actionIconForeground"])!=null?Nt:n["--persona-muted"];let o=(jt=e.components)==null?void 0:jt.header;o!=null&&o.shadow&&(n["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom);let r=(K=e.components)==null?void 0:K.introCard;n["--persona-intro-card-bg"]=(gt=n["--persona-components-introCard-background"])!=null?gt:n["--persona-surface"],n["--persona-intro-card-radius"]=(nt=n["--persona-components-introCard-borderRadius"])!=null?nt:"1rem",n["--persona-intro-card-padding"]=($t=n["--persona-components-introCard-padding"])!=null?$t:"1.5rem",n["--persona-intro-card-shadow"]=(ve=(ae=r==null?void 0:r.shadow)!=null?ae:n["--persona-components-introCard-shadow"])!=null?ve:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(wt=n["--persona-components-input-background"])!=null?wt:n["--persona-surface"],n["--persona-input-placeholder"]=(_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"]=(vn=n["--persona-components-message-user-text"])!=null?vn:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Et=n["--persona-components-message-user-shadow"])!=null?Et:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(At=n["--persona-components-message-assistant-background"])!=null?At:n["--persona-surface"],n["--persona-message-assistant-text"]=(ht=n["--persona-components-message-assistant-text"])!=null?ht:n["--persona-text"],n["--persona-message-assistant-border"]=(yt=n["--persona-components-message-assistant-border"])!=null?yt:n["--persona-border"],n["--persona-message-assistant-shadow"]=(Ut=n["--persona-components-message-assistant-shadow"])!=null?Ut:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(Fn=(Ze=n["--persona-components-scrollToBottom-background"])!=null?Ze:n["--persona-button-primary-bg"])!=null?Fn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(xn=(Zn=n["--persona-components-scrollToBottom-foreground"])!=null?Zn:n["--persona-button-primary-fg"])!=null?xn: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"]=(ar=(Nn=(wo=n["--persona-components-scrollToBottom-borderRadius"])!=null?wo:n["--persona-button-radius"])!=null?Nn:n["--persona-radius-full"])!=null?ar:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Ir=(In=n["--persona-components-scrollToBottom-shadow"])!=null?In:n["--persona-palette-shadows-sm"])!=null?Ir:"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=(vt=n["--persona-components-scrollToBottom-fontSize"])!=null?vt: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"]=(wn=n["--persona-components-toolBubble-shadow"])!=null?wn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Rt=n["--persona-components-reasoningBubble-shadow"])!=null?Rt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(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"]=(Cn=n["--persona-components-markdown-table-headerBackground"])!=null?Cn: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 u=e.components,p=u==null?void 0:u.iconButton;p&&(p.background&&(n["--persona-icon-btn-bg"]=p.background),p.border&&(n["--persona-icon-btn-border"]=p.border),p.color&&(n["--persona-icon-btn-color"]=p.color),p.padding&&(n["--persona-icon-btn-padding"]=p.padding),p.borderRadius&&(n["--persona-icon-btn-radius"]=p.borderRadius),p.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=p.hoverBackground),p.hoverColor&&(n["--persona-icon-btn-hover-color"]=p.hoverColor),p.activeBackground&&(n["--persona-icon-btn-active-bg"]=p.activeBackground),p.activeBorder&&(n["--persona-icon-btn-active-border"]=p.activeBorder));let f=u==null?void 0:u.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let g=u==null?void 0:u.toggleGroup;g&&(g.gap&&(n["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(n["--persona-toggle-group-radius"]=g.borderRadius));let x=u==null?void 0:u.artifact;if(x!=null&&x.toolbar){let T=x.toolbar;T.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=T.iconHoverColor),T.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=T.iconHoverBackground),T.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=T.iconPadding),T.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=T.iconBorderRadius),T.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=T.iconBorder),T.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=T.toggleGroupGap),T.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=T.toggleBorderRadius),T.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=T.copyBackground),T.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=T.copyBorder),T.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=T.copyColor),T.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=T.copyBorderRadius),T.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=T.copyPadding),T.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=T.copyMenuBackground,n["--persona-dropdown-bg"]=(Gt=n["--persona-dropdown-bg"])!=null?Gt:T.copyMenuBackground),T.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=T.copyMenuBorder,n["--persona-dropdown-border"]=(qn=n["--persona-dropdown-border"])!=null?qn:T.copyMenuBorder),T.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=T.copyMenuShadow,n["--persona-dropdown-shadow"]=(Ko=n["--persona-dropdown-shadow"])!=null?Ko:T.copyMenuShadow),T.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=T.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(oo=n["--persona-dropdown-radius"])!=null?oo:T.copyMenuBorderRadius),T.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=T.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(uo=n["--persona-dropdown-item-hover-bg"])!=null?uo:T.copyMenuItemHoverBackground),T.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=T.iconBackground),T.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=T.toolbarBorder)}if(x!=null&&x.tab){let T=x.tab;T.background&&(n["--persona-artifact-tab-bg"]=T.background),T.activeBackground&&(n["--persona-artifact-tab-active-bg"]=T.activeBackground),T.activeBorder&&(n["--persona-artifact-tab-active-border"]=T.activeBorder),T.borderRadius&&(n["--persona-artifact-tab-radius"]=T.borderRadius),T.textColor&&(n["--persona-artifact-tab-color"]=T.textColor),T.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=T.hoverBackground),T.listBackground&&(n["--persona-artifact-tab-list-bg"]=T.listBackground),T.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=T.listBorderColor),T.listPadding&&(n["--persona-artifact-tab-list-padding"]=T.listPadding)}if(x!=null&&x.pane){let T=x.pane;if(T.toolbarBackground){let Kn=(jn=Vr(e,T.toolbarBackground))!=null?jn:T.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Kn}}return n}var mg={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},tu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ui=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},gg=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Ui()},fg=e=>gg(e),hg=e=>nn(e),bg=e=>{var n;let t=nn(void 0,{validate:!1});return nn({...e,palette:{...t.palette,colors:{...mg.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Ta=e=>{let t=fg(e),n=tu(e==null?void 0:e.theme),o=tu(e==null?void 0:e.darkTheme);return t==="dark"?bg(Ts(n!=null?n:{},o!=null?o:{})):hg(n)},yg=e=>eu(e),$r=(e,t)=>{var s;let n=Ta(t),o=yg(n);for(let[a,i]of Object.entries(o))e.style.setProperty(a,i);let r=(s=t==null?void 0:t.toolCall)==null?void 0:s.shadow;r!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",r.trim()===""?"none":r)},nu=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Ui())});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(Ui());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 zi(e,t){let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return o}function vr(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]:vr((i=a==null?void 0:a[r])!=null?i:{},s.join("."),n)}}var qi=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?{...kt,...n}:n!=null?n:kt,this.theme=nn(t,{validate:!1}),this.syncThemeIntoConfig(),this.pushHistorySnapshot(this.exportSnapshot(),!0)}get(t){var n;return t.startsWith("theme.")?zi(this.theme,t.replace("theme.","")):t.startsWith("darkTheme.")?zi((n=this.config.darkTheme)!=null?n:{},t.replace("darkTheme.","")):zi(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=vr(this.theme,r,n),this.syncThemeIntoConfig()}else if(t.startsWith("darkTheme.")){let r=t.replace("darkTheme.",""),s=(o=this.config.darkTheme)!=null?o:nn();this.config={...this.config,darkTheme:vr(s,r,n)}}else this.config=vr(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=vr(this.theme,d,i),n=!0}else if(a.startsWith("darkTheme.")){let d=a.replace("darkTheme.",""),l=(s=this.config.darkTheme)!=null?s:nn();this.config={...this.config,darkTheme:vr(l,d,i)},o=!0}else this.config=vr(this.config,a,i),r=!0;n&&this.syncThemeIntoConfig(),(n||o||r)&&(this.recordHistory(),this.notifyListeners())}setTheme(t){this.theme=t,this.syncThemeIntoConfig(),this.recordHistory(),this.notifyListeners()}setFullConfig(t,n){this.config={...t},n&&(this.theme=n),this.syncThemeIntoConfig(),this.recordHistory(),this.notifyListeners()}importSnapshot(t){var r,s;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Snapshot must be a JSON object");let n=t;if("config"in n||"theme"in n||n.version===2){let a=(r=n.config)!=null?r:this.config,i=nn((s=n.theme)!=null?s:this.theme,{validate:!1});this.setFullConfig(a,i);return}let o=nn(n,{validate:!1});this.setTheme(o)}resetToDefaults(){this.config={...kt},this.theme=nn(),this.syncThemeIntoConfig(),this.history=[],this.historyIndex=-1,this.pushHistorySnapshot(this.exportSnapshot()),this.notifyListeners()}canUndo(){return this.historyIndex>0}canRedo(){return this.historyIndex>=0&&this.historyIndex<this.history.length-1}getHistoryLength(){return this.history.length}getHistoryIndex(){return this.historyIndex}undo(){this.canUndo()&&(this.historyIndex-=1,this.restoreSnapshot(this.history[this.historyIndex]))}redo(){this.canRedo()&&(this.historyIndex+=1,this.restoreSnapshot(this.history[this.historyIndex]))}exportSnapshot(){return{version:2,config:{...this.config,theme:void 0},theme:this.theme}}onChange(t){return this.listeners.push(t),()=>{let n=this.listeners.indexOf(t);n>=0&&this.listeners.splice(n,1)}}syncThemeIntoConfig(){this.config={...this.config,theme:this.theme}}notifyListeners(){for(let t of this.listeners)t(this.config,this.theme)}recordHistory(){this.pushHistorySnapshot(this.exportSnapshot())}pushHistorySnapshot(t,n=!1){if(this.suppressHistory)return;let o=JSON.stringify(t),r=this.historyIndex>=0&&this.history[this.historyIndex]?JSON.stringify(this.history[this.historyIndex]):null;if(n&&this.historyIndex>=0){this.history[this.historyIndex]=t;return}o!==r&&(this.history=this.history.slice(0,this.historyIndex+1),this.history.push(t),this.historyIndex=this.history.length-1)}restoreSnapshot(t){this.suppressHistory=!0,this.config=t.config,this.theme=nn(t.theme,{validate:!1}),this.syncThemeIntoConfig(),this.suppressHistory=!1,this.notifyListeners()}};function ji(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 Ki(e,t){return t==="rem"?`${e}rem`:`${e}px`}function vg(e,t){return t==="rem"?e*16:e}function xg(e,t){return t==="rem"?e/16:e}function ks(e){if(!e)return"#000000";let t=e.trim().toLowerCase();return t==="transparent"?"transparent":t.startsWith("rgba")||t.startsWith("rgb")?t:t.startsWith("#")?t.length===4?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:t:`#${t}`}function Gi(e){return/^#[0-9A-Fa-f]{6}$/.test(e)}function Yi(e){let t=e.trim().toLowerCase().match(/^rgba?\(([^)]+)\)$/);if(!t)return null;let n=t[1].split(",").map(d=>d.trim());if(n.length<3)return null;let o=d=>{let l=d.endsWith("%"),u=parseFloat(l?d.slice(0,-1):d);return Number.isFinite(u)?Math.max(0,Math.min(255,Math.round(l?u/100*255:u))):NaN},r=o(n[0]),s=o(n[1]),a=o(n[2]);if(!Number.isFinite(r)||!Number.isFinite(s)||!Number.isFinite(a))return null;let i=d=>d.toString(16).padStart(2,"0");return`#${i(r)}${i(s)}${i(a)}`}function ka(e,t){let n=s=>{var l;let a=ks(s),i=a.startsWith("rgb")?(l=Yi(a))!=null?l:"#000000":a,d=[1,3,5].map(u=>{let p=parseInt(i.slice(u,u+2),16)/255;return p<=.03928?p/12.92:Math.pow((p+.055)/1.055,2.4)});return .2126*d[0]+.7152*d[1]+.0722*d[2]},o=n(e),r=n(t);return(Math.max(o,r)+.05)/(Math.min(o,r)+.05)}function ou(e){var f;let t=ks(e),n=t.startsWith("rgb")?(f=Yi(t))!=null?f:"#000000":t,o=parseInt(n.slice(1,3),16)/255,r=parseInt(n.slice(3,5),16)/255,s=parseInt(n.slice(5,7),16)/255,a=Math.max(o,r,s),i=Math.min(o,r,s),d=(a+i)/2;if(a===i)return{h:0,s:0,l:d};let l=a-i,u=d>.5?l/(2-a-i):l/(a+i),p;switch(a){case o:p=((r-s)/l+(r<s?6:0))/6;break;case r:p=((s-o)/l+2)/6;break;default:p=((o-r)/l+4)/6;break}return{h:p*360,s:u,l:d}}function ru(e,t,n){let o=(e%360+360)%360,r=(1-Math.abs(2*n-1))*t,s=r*(1-Math.abs(o/60%2-1)),a=n-r/2,i,d,l;o<60?[i,d,l]=[r,s,0]:o<120?[i,d,l]=[s,r,0]:o<180?[i,d,l]=[0,r,s]:o<240?[i,d,l]=[0,s,r]:o<300?[i,d,l]=[s,0,r]:[i,d,l]=[r,0,s];let u=p=>{let f=Math.round((p+a)*255).toString(16);return f.length===1?"0"+f:f};return`#${u(i)}${u(d)}${u(l)}`}function Xi(e){let{h:t,s:n,l:o}=ou(e),r={50:.97,100:.94,200:.87,300:.77,400:.64,500:o,600:Math.max(.05,o-.1),700:Math.max(.05,o-.2),800:Math.max(.05,o-.28),900:Math.max(.05,o-.35),950:Math.max(.03,o-.42)},s={50:Math.min(1,n*.85),100:Math.min(1,n*.9),200:Math.min(1,n*.95),300:n,400:n,500:n,600:Math.min(1,n*1.05),700:Math.min(1,n*1.05),800:Math.min(1,n*1),900:Math.min(1,n*.95),950:Math.min(1,n*.9)},a={};for(let[i,d]of Object.entries(r)){let l=s[i];a[i]=ru(t,l,d)}return a}var Ur=["50","100","200","300","400","500","600","700","800","900","950"],Qi=["primary","secondary","accent","gray","success","warning","error","info"];function wg(e,t){return`palette.colors.${e}.${t}`}function su(e,t,n=0){if(n>5)return"#cbd5e1";let o=e(t);return typeof o!="string"?"#cbd5e1":o.startsWith("#")||o.startsWith("rgb")||o==="transparent"?o:o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components.")?su(e,`theme.${o}`,n+1):"#cbd5e1"}function Cg(e){if(!e.startsWith("palette.")&&!e.startsWith("semantic."))return e;let t=e.split(".");if(t[0]==="palette"&&t[1]==="colors"){let n=t[2],o=t[3];return`${n.charAt(0).toUpperCase()+n.slice(1)} ${o}`}return t[0]==="semantic"?t.slice(1).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):t[t.length-1]}var ko=[{id:"solid",label:"Solid"},{id:"soft",label:"Soft"}],Ea=["primary","secondary","accent","gray"],Sg={primary:"Primary",secondary:"Secondary",accent:"Accent",gray:"Neutral"},Ma={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"}]},La={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"}]},Ia={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"}]},Ra={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"}]},Pa={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"}]},Wa={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"}]},Ba={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"}]},Ha={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"}]},Da={roleId:"role-borders",helper:"Borders, dividers, and separators",intensities:ko,targets:[{path:"semantic.colors.border",kind:"border"},{path:"semantic.colors.divider",kind:"border"}]},xr=[Ma,La,Ia,Ra,Pa,Wa,Ba,Ha,Da];function Fa(e,t,n){let o={},r=e==="neutral"?"gray":e;for(let s of n.targets){let a=Ag(r,t,s,n.roleId);o[`theme.${s.path}`]=a,o[`darkTheme.${s.path}`]=a}if(n.roleId==="role-primary-actions"){let s=t==="solid"?`palette.colors.${r}.700`:`palette.colors.${r}.200`;o["theme.semantic.colors.interactive.hover"]=s,o["darkTheme.semantic.colors.interactive.hover"]=s}return o}function Ag(e,t,n,o){let r=t==="solid";if(o==="role-header")return Tg(e,r,n);if(o==="role-input")return kg(e,r,n);switch(n.kind){case"background":return r?`palette.colors.${e}.500`:`palette.colors.${e}.${e==="gray"?"50":"100"}`;case"foreground":return r?`palette.colors.${e==="gray"?"gray":e}.50`:`palette.colors.${e==="gray"?"gray":e}.900`;case"border":return r?`palette.colors.${e}.600`:`palette.colors.${e}.200`;case"accent":return r?`palette.colors.${e}.600`:`palette.colors.${e}.400`}}function Tg(e,t,n){let o=n.path;return o.endsWith(".background")?t?`palette.colors.${e}.500`:`palette.colors.${e}.${e==="gray"?"50":"100"}`:o.endsWith(".border")?t?`palette.colors.${e}.600`:`palette.colors.${e}.200`:o.endsWith(".iconBackground")?t?`palette.colors.${e}.${e==="gray"?"700":"600"}`:`palette.colors.${e}.500`:o.endsWith(".iconForeground")?t?`palette.colors.${e}.50`:`palette.colors.${e}.50`:o.endsWith(".titleForeground")?t?`palette.colors.${e}.50`:`palette.colors.${e}.${e==="gray"?"900":"700"}`:o.endsWith(".subtitleForeground")?t?`palette.colors.${e}.200`:`palette.colors.${e}.500`:o.endsWith(".actionIconForeground")?t?`palette.colors.${e}.200`:`palette.colors.${e}.500`:`palette.colors.${e}.500`}function kg(e,t,n){let o=n.path;return o.endsWith(".background")?t?`palette.colors.${e}.${e==="gray"?"100":"50"}`:`palette.colors.${e}.50`:o.endsWith(".placeholder")?`palette.colors.${e}.400`:o.endsWith(".border")||o.endsWith(".ring")?t?`palette.colors.${e}.500`:`palette.colors.${e}.400`:`palette.colors.${e}.500`}var Eg=/^palette\.colors\.(\w+)\.(\d+)$/;function Ji(e,t){var i,d;let n=(i=t.targets.find(l=>l.kind==="background"))!=null?i:t.targets[0];if(!n)return null;let r=String((d=e(n.path))!=null?d:"").match(Eg);if(!r)return null;let s=r[1],a=Ea.includes(s)?s:null;if(!a)return null;for(let l of["solid","soft"]){let u=Fa(a,l,t);if(t.targets.every(f=>{var x;return String((x=e(f.path))!=null?x:"")===u[`theme.${f.path}`]}))return{family:a,intensity:l}}return null}var Mg={id:"theme-mode",title:"Runtime Theme",description:"Controls how the shipped widget picks light or dark mode.",collapsed:!1,fields:[{id:"theme-mode",label:"Runtime Theme",description:"Always Light, Always Dark, or follow the visitor system preference",type:"select",path:"colorScheme",defaultValue:"auto",options:[{value:"light",label:"Light"},{value:"dark",label:"Dark"},{value:"auto",label:"Follow System"}]}]},Lg={id:"brand-colors",title:"Brand Colors",description:"Pick your brand colors. A full shade scale is generated automatically for both light and dark themes.",collapsed:!1,fields:[{id:"brand-primary",label:"Primary",description:"Main brand color for buttons, links, and accents",type:"color",path:"theme.palette.colors.primary.500",defaultValue:"#171717"},{id:"brand-secondary",label:"Secondary",description:"Supporting brand color",type:"color",path:"theme.palette.colors.secondary.500",defaultValue:"#7c3aed"},{id:"brand-accent",label:"Accent",description:"Highlight and decorative color",type:"color",path:"theme.palette.colors.accent.500",defaultValue:"#06b6d4"}]},Ig={id:"chat-colors",title:"Chat Colors",description:"Customize the main colors of the chat interface.",collapsed:!0,fields:[{id:"chat-header-bg",label:"Header Background",type:"token-ref",path:"theme.components.header.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"chat-header-icon-bg",label:"Header Icon Background",type:"token-ref",path:"theme.components.header.iconBackground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-header-icon-fg",label:"Header Icon Color",type:"token-ref",path:"theme.components.header.iconForeground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"chat-header-title-fg",label:"Header Title Color",type:"token-ref",path:"theme.components.header.titleForeground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-header-subtitle-fg",label:"Header Subtitle Color",type:"token-ref",path:"theme.components.header.subtitleForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"chat-header-action-icons-fg",label:"Header Button Icons",type:"token-ref",path:"theme.components.header.actionIconForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"chat-msg-user-bg",label:"User Message Background",type:"token-ref",path:"theme.components.message.user.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-msg-user-text",label:"User Message Text",type:"token-ref",path:"theme.components.message.user.text",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"chat-msg-assistant-bg",label:"Assistant Message Background",type:"token-ref",path:"theme.components.message.assistant.background",defaultValue:"semantic.colors.container",tokenRef:{tokenType:"color"}},{id:"chat-msg-assistant-text",label:"Assistant Message Text",type:"token-ref",path:"theme.components.message.assistant.text",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},Rg={id:"typography",title:"Typography",collapsed:!0,fields:[{id:"typo-font-family",label:"Font Family",type:"select",path:"theme.semantic.typography.fontFamily",defaultValue:"palette.typography.fontFamily.sans",options:[{value:"palette.typography.fontFamily.sans",label:"Sans Serif"},{value:"palette.typography.fontFamily.serif",label:"Serif"},{value:"palette.typography.fontFamily.mono",label:"Monospace"}]},{id:"typo-font-size",label:"Base Font Size",type:"select",path:"theme.semantic.typography.fontSize",defaultValue:"palette.typography.fontSize.base",options:[{value:"palette.typography.fontSize.xs",label:"Extra Small (0.75rem)"},{value:"palette.typography.fontSize.sm",label:"Small (0.875rem)"},{value:"palette.typography.fontSize.base",label:"Base (1rem)"},{value:"palette.typography.fontSize.lg",label:"Large (1.125rem)"},{value:"palette.typography.fontSize.xl",label:"Extra Large (1.25rem)"}]},{id:"typo-font-weight",label:"Font Weight",type:"select",path:"theme.semantic.typography.fontWeight",defaultValue:"palette.typography.fontWeight.normal",options:[{value:"palette.typography.fontWeight.normal",label:"Normal (400)"},{value:"palette.typography.fontWeight.medium",label:"Medium (500)"},{value:"palette.typography.fontWeight.semibold",label:"Semibold (600)"},{value:"palette.typography.fontWeight.bold",label:"Bold (700)"}]},{id:"typo-line-height",label:"Line Height",type:"select",path:"theme.semantic.typography.lineHeight",defaultValue:"palette.typography.lineHeight.normal",options:[{value:"palette.typography.lineHeight.tight",label:"Tight (1.25)"},{value:"palette.typography.lineHeight.normal",label:"Normal (1.5)"},{value:"palette.typography.lineHeight.relaxed",label:"Relaxed (1.625)"}]}]},Pg={id:"launcher-style",title:"Launcher",description:"Control launcher appearance.",collapsed:!0,fields:[{id:"style-launcher-size",label:"Launcher Size",type:"slider",path:"theme.components.launcher.size",defaultValue:"60px",slider:{min:32,max:80,step:2}},{id:"style-launcher-shape",label:"Launcher Shape",type:"select",path:"theme.components.launcher.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Rounded Square"},{value:"palette.radius.lg",label:"Rounded"},{value:"palette.radius.xl",label:"Very Rounded"},{value:"palette.radius.full",label:"Circle"}]},{id:"style-launcher-shadow",label:"Launcher Shadow",type:"select",path:"theme.components.launcher.shadow",defaultValue:"palette.shadows.lg",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},Wg={id:"shape",title:"Shape",description:"Control the corner roundness across the widget.",collapsed:!0,fields:[{id:"radius-sm",label:"Small",type:"slider",path:"theme.palette.radius.sm",defaultValue:"0.125rem",slider:{min:0,max:16,step:1}},{id:"radius-md",label:"Medium",type:"slider",path:"theme.palette.radius.md",defaultValue:"0.375rem",slider:{min:0,max:24,step:1}},{id:"radius-lg",label:"Large",type:"slider",path:"theme.palette.radius.lg",defaultValue:"0.5rem",slider:{min:0,max:32,step:1}},{id:"radius-xl",label:"Extra Large",type:"slider",path:"theme.palette.radius.xl",defaultValue:"0.75rem",slider:{min:0,max:48,step:1}},{id:"radius-full",label:"Full",type:"slider",path:"theme.palette.radius.full",defaultValue:"9999px",slider:{min:0,max:100,step:1,isRadiusFull:!0}}],presets:[{id:"radius-default",label:"Default",values:{"theme.palette.radius.sm":"0.125rem","theme.palette.radius.md":"0.375rem","theme.palette.radius.lg":"0.5rem","theme.palette.radius.xl":"0.75rem","theme.palette.radius.full":"9999px"}},{id:"radius-sharp",label:"Sharp",values:{"theme.palette.radius.sm":"1px","theme.palette.radius.md":"2px","theme.palette.radius.lg":"3px","theme.palette.radius.xl":"4px","theme.palette.radius.full":"4px"}},{id:"radius-rounded",label:"Rounded",values:{"theme.palette.radius.sm":"0.5rem","theme.palette.radius.md":"0.75rem","theme.palette.radius.lg":"1rem","theme.palette.radius.xl":"1.5rem","theme.palette.radius.full":"9999px"}}]},Bg={id:"shadows",title:"Shadows",collapsed:!0,fields:[{id:"shadow-sm",label:"Small",type:"text",path:"theme.palette.shadows.sm",defaultValue:"0 1px 2px 0 rgb(0 0 0 / 0.05)"},{id:"shadow-md",label:"Medium",type:"text",path:"theme.palette.shadows.md",defaultValue:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)"},{id:"shadow-lg",label:"Large",type:"text",path:"theme.palette.shadows.lg",defaultValue:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)"},{id:"shadow-xl",label:"Extra Large",type:"text",path:"theme.palette.shadows.xl",defaultValue:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)"}]},Hg={id:"widget-style",title:"Widget Surface",description:"Adjust the main panel and message bubble treatment.",collapsed:!0,fields:[{id:"style-panel-radius",label:"Panel Corner Radius",type:"select",path:"theme.components.panel.borderRadius",defaultValue:"palette.radius.xl",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"style-panel-shadow",label:"Panel Shadow",type:"select",path:"theme.components.panel.shadow",defaultValue:"palette.shadows.xl",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]},{id:"style-msg-user-radius",label:"User Message Radius",type:"select",path:"theme.components.message.user.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"style-msg-assistant-radius",label:"Assistant Message Radius",type:"select",path:"theme.components.message.assistant.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},zr=[Lg,Ig,Pg,Rg,Mg,Wg,Bg,Hg];function au(){return{id:"brand-palette",title:"Brand Palette",description:"Define your color palette. Edit the base color (500) to auto-generate the full scale.",collapsed:!1,fields:Qi.map(t=>({id:`palette-${t}`,label:`${t.charAt(0).toUpperCase()+t.slice(1)}`,description:`${t} color palette (edit shade 500, auto-generate scale)`,type:"color-scale",path:`theme.palette.colors.${t}`,colorScale:{colorFamily:t}}))}}var iu={id:"semantic-colors",title:"Semantic Colors",description:"Map intents to palette colors.",collapsed:!0,fields:[{id:"sem-primary",label:"Primary",description:"Main brand/action color",type:"token-ref",path:"theme.semantic.colors.primary",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sem-secondary",label:"Secondary",description:"Secondary actions",type:"token-ref",path:"theme.semantic.colors.secondary",defaultValue:"palette.colors.gray.500",tokenRef:{tokenType:"color"}},{id:"sem-accent",label:"Accent",description:"Accent/highlight color",type:"token-ref",path:"theme.semantic.colors.accent",defaultValue:"palette.colors.primary.600",tokenRef:{tokenType:"color"}},{id:"sem-surface",label:"Surface",description:"Primary surface background",type:"token-ref",path:"theme.semantic.colors.surface",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-background",label:"Background",description:"Page/widget background",type:"token-ref",path:"theme.semantic.colors.background",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-container",label:"Container",description:"Container/card background",type:"token-ref",path:"theme.semantic.colors.container",defaultValue:"palette.colors.gray.100",tokenRef:{tokenType:"color"}},{id:"sem-text",label:"Text",description:"Primary text color",type:"token-ref",path:"theme.semantic.colors.text",defaultValue:"palette.colors.gray.900",tokenRef:{tokenType:"color"}},{id:"sem-text-muted",label:"Text Muted",description:"Secondary/muted text",type:"token-ref",path:"theme.semantic.colors.textMuted",defaultValue:"palette.colors.gray.500",tokenRef:{tokenType:"color"}},{id:"sem-text-inverse",label:"Text Inverse",description:"Text on dark backgrounds",type:"token-ref",path:"theme.semantic.colors.textInverse",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-border",label:"Border",description:"Default border color",type:"token-ref",path:"theme.semantic.colors.border",defaultValue:"palette.colors.gray.200",tokenRef:{tokenType:"color"}},{id:"sem-divider",label:"Divider",description:"Divider/separator color",type:"token-ref",path:"theme.semantic.colors.divider",defaultValue:"palette.colors.gray.200",tokenRef:{tokenType:"color"}},{id:"sem-interactive-default",label:"Interactive Default",type:"token-ref",path:"theme.semantic.colors.interactive.default",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sem-interactive-hover",label:"Interactive Hover",type:"token-ref",path:"theme.semantic.colors.interactive.hover",defaultValue:"palette.colors.primary.600",tokenRef:{tokenType:"color"}},{id:"sem-interactive-focus",label:"Interactive Focus",type:"token-ref",path:"theme.semantic.colors.interactive.focus",defaultValue:"palette.colors.primary.700",tokenRef:{tokenType:"color"}},{id:"sem-interactive-active",label:"Interactive Active",type:"token-ref",path:"theme.semantic.colors.interactive.active",defaultValue:"palette.colors.primary.800",tokenRef:{tokenType:"color"}},{id:"sem-interactive-disabled",label:"Interactive Disabled",type:"token-ref",path:"theme.semantic.colors.interactive.disabled",defaultValue:"palette.colors.gray.300",tokenRef:{tokenType:"color"}},{id:"sem-feedback-success",label:"Success",type:"token-ref",path:"theme.semantic.colors.feedback.success",defaultValue:"palette.colors.success.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-warning",label:"Warning",type:"token-ref",path:"theme.semantic.colors.feedback.warning",defaultValue:"palette.colors.warning.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-error",label:"Error",type:"token-ref",path:"theme.semantic.colors.feedback.error",defaultValue:"palette.colors.error.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-info",label:"Info",type:"token-ref",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}}]},Dg=au(),Fg=iu,Og=[au(),iu],Ng={id:"comp-panel",title:"Panel",collapsed:!1,fields:[{id:"panel-width",label:"Width",type:"text",path:"theme.components.panel.width",defaultValue:io},{id:"panel-max-width",label:"Max Width",type:"text",path:"theme.components.panel.maxWidth",defaultValue:Aa},{id:"panel-height",label:"Height",type:"text",path:"theme.components.panel.height",defaultValue:"600px"},{id:"panel-max-height",label:"Max Height",type:"text",path:"theme.components.panel.maxHeight",defaultValue:"calc(100vh - 80px)"},{id:"panel-border-radius",label:"Border Radius",type:"select",path:"theme.components.panel.borderRadius",defaultValue:"palette.radius.xl",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"panel-shadow",label:"Shadow",type:"select",path:"theme.components.panel.shadow",defaultValue:"palette.shadows.xl",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},_g={id:"comp-launcher",title:"Launcher",collapsed:!0,fields:[{id:"launcher-size",label:"Size",type:"slider",path:"theme.components.launcher.size",defaultValue:"60px",slider:{min:32,max:80,step:2}},{id:"launcher-icon-size",label:"Icon Size",type:"slider",path:"theme.components.launcher.iconSize",defaultValue:"28px",slider:{min:16,max:48,step:2}},{id:"launcher-border-radius",label:"Border Radius",type:"select",path:"theme.components.launcher.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"},{value:"palette.radius.full",label:"Full (Circle)"}]},{id:"launcher-shadow",label:"Shadow",type:"select",path:"theme.components.launcher.shadow",defaultValue:"palette.shadows.lg",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},Vg={id:"comp-message-shape",title:"Message Shape",collapsed:!0,fields:[{id:"msg-user-radius",label:"User Bubble Radius",type:"select",path:"theme.components.message.user.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"msg-assistant-radius",label:"Assistant Bubble Radius",type:"select",path:"theme.components.message.assistant.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},$g={id:"comp-input-shape",title:"Input Shape",collapsed:!0,fields:[{id:"input-radius",label:"Border Radius",type:"select",path:"theme.components.input.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},Ug={id:"comp-button-shape",title:"Button Shape",collapsed:!0,fields:[{id:"btn-primary-radius",label:"Primary Radius",type:"select",path:"theme.components.button.primary.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.full",label:"Full"}]}]},zg={id:"comp-header-colors",title:"Header Colors",collapsed:!0,fields:[{id:"header-bg",label:"Background",type:"token-ref",path:"theme.components.header.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"header-icon-bg",label:"Icon background",type:"token-ref",path:"theme.components.header.iconBackground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"header-icon-fg",label:"Icon color",type:"token-ref",path:"theme.components.header.iconForeground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"header-title-fg",label:"Title color",type:"token-ref",path:"theme.components.header.titleForeground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"header-subtitle-fg",label:"Subtitle color",type:"token-ref",path:"theme.components.header.subtitleForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"header-action-icons-fg",label:"Clear / close icons",type:"token-ref",path:"theme.components.header.actionIconForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"header-border",label:"Border",type:"token-ref",path:"theme.components.header.border",defaultValue:"semantic.colors.border",tokenRef:{tokenType:"color"}}]},qg={id:"comp-message-colors",title:"Message Colors",collapsed:!0,fields:[{id:"msg-user-bg",label:"User Bubble Background",type:"token-ref",path:"theme.components.message.user.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"msg-user-text",label:"User Bubble Text",type:"token-ref",path:"theme.components.message.user.text",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"msg-assistant-bg",label:"Assistant Bubble Background",type:"token-ref",path:"theme.components.message.assistant.background",defaultValue:"semantic.colors.container",tokenRef:{tokenType:"color"}},{id:"msg-assistant-text",label:"Assistant Bubble Text",type:"token-ref",path:"theme.components.message.assistant.text",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},jg={id:"comp-input-colors",title:"Input Colors",collapsed:!0,fields:[{id:"input-bg",label:"Background",type:"token-ref",path:"theme.components.input.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"input-placeholder",label:"Placeholder Color",type:"token-ref",path:"theme.components.input.placeholder",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"input-focus-border",label:"Focus Border",type:"token-ref",path:"theme.components.input.focus.border",defaultValue:"semantic.colors.interactive.focus",tokenRef:{tokenType:"color"}},{id:"input-focus-ring",label:"Focus Ring",type:"token-ref",path:"theme.components.input.focus.ring",defaultValue:"semantic.colors.interactive.focus",tokenRef:{tokenType:"color"}}]},Kg={id:"comp-button-colors",title:"Button Colors",collapsed:!0,fields:[{id:"btn-primary-bg",label:"Primary Background",type:"token-ref",path:"theme.components.button.primary.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"btn-primary-fg",label:"Primary Foreground",type:"token-ref",path:"theme.components.button.primary.foreground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"btn-secondary-bg",label:"Secondary Background",type:"token-ref",path:"theme.components.button.secondary.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"btn-secondary-fg",label:"Secondary Foreground",type:"token-ref",path:"theme.components.button.secondary.foreground",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}},{id:"btn-ghost-bg",label:"Ghost Background",type:"color",path:"theme.components.button.ghost.background",defaultValue:"transparent"},{id:"btn-ghost-fg",label:"Ghost Foreground",type:"token-ref",path:"theme.components.button.ghost.foreground",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},Gg={id:"scroll-to-bottom-style",title:"Scroll To Bottom",description:"Style the floating jump-to-latest affordance.",collapsed:!0,fields:[{id:"scroll-bottom-bg",label:"Background",type:"token-ref",path:"theme.components.scrollToBottom.background",defaultValue:"components.button.primary.background",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-fg",label:"Foreground",type:"token-ref",path:"theme.components.scrollToBottom.foreground",defaultValue:"components.button.primary.foreground",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-border",label:"Border",type:"token-ref",path:"theme.components.scrollToBottom.border",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-size",label:"Size",type:"text",path:"theme.components.scrollToBottom.size",defaultValue:"40px"},{id:"scroll-bottom-radius",label:"Border Radius",type:"select",path:"theme.components.scrollToBottom.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"},{value:"palette.radius.full",label:"Full"}]},{id:"scroll-bottom-shadow",label:"Shadow",type:"select",path:"theme.components.scrollToBottom.shadow",defaultValue:"palette.shadows.sm",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]},{id:"scroll-bottom-padding",label:"Padding",type:"text",path:"theme.components.scrollToBottom.padding",defaultValue:"0.5rem 0.875rem"},{id:"scroll-bottom-gap",label:"Gap",type:"text",path:"theme.components.scrollToBottom.gap",defaultValue:"0.5rem"},{id:"scroll-bottom-font-size",label:"Font Size",type:"text",path:"theme.components.scrollToBottom.fontSize",defaultValue:"0.875rem"},{id:"scroll-bottom-icon-size",label:"Icon Size",type:"text",path:"theme.components.scrollToBottom.iconSize",defaultValue:"14px"}]},lu=[Ng,_g,Vg,$g,Ug],cu=[zg,qg,jg,Kg,Gg],du=[...lu,...cu],Zi=1024*1024,Yg=["What can you help me with?","Tell me about your features","How does this work?"],Es={images:["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],"images-pdf":["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf"],"images-text-pdf":["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf","text/plain","text/markdown","text/csv","application/json"],all:["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"]};function Xg(e){return Number(e)*Zi}function Qg(e){let t=Number(e);return Number.isFinite(t)?t>1024?String(Math.round(t/Zi)):String(t):"10"}function Jg(e){var t;return(t=Es[String(e)])!=null?t:Es.images}function Zg(e){let t=Array.isArray(e)?e:Es.images,n=[...new Set(t)].sort();for(let[o,r]of Object.entries(Es)){let s=[...r].sort();if(n.length===s.length&&n.every((a,i)=>a===s[i]))return o}return n.some(o=>o.startsWith("application/vnd")||o==="application/msword")?"all":n.some(o=>o==="text/plain"||o==="text/markdown"||o==="text/csv")?"images-text-pdf":n.includes("application/pdf")?"images-pdf":"images"}var ef={id:"copy",title:"Content & Copy",collapsed:!1,fields:[{id:"copy-show-welcome-card",label:"Show Welcome Card",type:"toggle",path:"copy.showWelcomeCard",defaultValue:!0},{id:"copy-welcome-title",label:"Welcome Title",type:"text",path:"copy.welcomeTitle",defaultValue:"Hello \u{1F44B}"},{id:"copy-welcome-subtitle",label:"Welcome Subtitle",type:"text",path:"copy.welcomeSubtitle",defaultValue:"Ask anything about your account or products."},{id:"copy-placeholder",label:"Input Placeholder",type:"text",path:"copy.inputPlaceholder",defaultValue:"Type your message\u2026"},{id:"copy-send-label",label:"Send Button Label",type:"text",path:"copy.sendButtonLabel",defaultValue:"Send"}]},tf={id:"suggestions",title:"Suggestion Chips",description:"Configure chip content and styling.",collapsed:!0,fields:[{id:"suggestions-list",label:"Suggestions",description:"Add, edit, and remove chips directly.",type:"chip-list",path:"suggestionChips",defaultValue:Yg}]},nf={id:"general-layout",title:"Layout Basics",collapsed:!0,fields:[{id:"layout-show-header",label:"Show Header",type:"toggle",path:"layout.showHeader",defaultValue:!0},{id:"layout-show-footer",label:"Show Footer",type:"toggle",path:"layout.showFooter",defaultValue:!0},{id:"layout-content-max-width",label:"Content Max Width",description:"Max width for messages + composer",type:"text",path:"layout.contentMaxWidth",defaultValue:""}]},of={id:"header-layout",title:"Header",collapsed:!0,fields:[{id:"layout-header",label:"Header Layout",type:"select",path:"layout.header.layout",defaultValue:"default",options:[{value:"default",label:"Default"},{value:"minimal",label:"Minimal"}]},{id:"layout-show-icon",label:"Show Header Icon",type:"toggle",path:"layout.header.showIcon",defaultValue:!0},{id:"layout-show-title",label:"Show Header Title",type:"toggle",path:"layout.header.showTitle",defaultValue:!0},{id:"layout-show-subtitle",label:"Show Header Subtitle",type:"toggle",path:"layout.header.showSubtitle",defaultValue:!0},{id:"layout-show-close",label:"Show Close Button",type:"toggle",path:"layout.header.showCloseButton",defaultValue:!0},{id:"layout-show-clear",label:"Show Clear Chat",type:"toggle",path:"layout.header.showClearChat",defaultValue:!0}]},rf={id:"messages-layout",title:"Messages",collapsed:!0,fields:[{id:"layout-messages",label:"Messages Layout",type:"select",path:"layout.messages.layout",defaultValue:"bubble",options:[{value:"bubble",label:"Bubble"},{value:"flat",label:"Flat"},{value:"minimal",label:"Minimal"}]},{id:"layout-group",label:"Group Consecutive",type:"toggle",path:"layout.messages.groupConsecutive",defaultValue:!1},{id:"layout-avatar-show",label:"Show Avatars",type:"toggle",path:"layout.messages.avatar.show",defaultValue:!1},{id:"layout-avatar-pos",label:"Avatar Position",type:"select",path:"layout.messages.avatar.position",defaultValue:"left",options:[{value:"left",label:"Left"},{value:"right",label:"Right"}]},{id:"layout-avatar-user",label:"User Avatar URL",type:"text",path:"layout.messages.avatar.userAvatar",defaultValue:""},{id:"layout-avatar-assistant",label:"Assistant Avatar URL",type:"text",path:"layout.messages.avatar.assistantAvatar",defaultValue:""},{id:"layout-timestamp-show",label:"Show Timestamps",type:"toggle",path:"layout.messages.timestamp.show",defaultValue:!1},{id:"layout-timestamp-pos",label:"Timestamp Position",type:"select",path:"layout.messages.timestamp.position",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"below",label:"Below"}]}]},sf={id:"message-actions",title:"Message Actions",collapsed:!0,fields:[{id:"msg-actions-enabled",label:"Enabled",type:"toggle",path:"messageActions.enabled",defaultValue:!0},{id:"msg-actions-copy",label:"Show Copy",type:"toggle",path:"messageActions.showCopy",defaultValue:!0},{id:"msg-actions-upvote",label:"Show Upvote",type:"toggle",path:"messageActions.showUpvote",defaultValue:!0},{id:"msg-actions-downvote",label:"Show Downvote",type:"toggle",path:"messageActions.showDownvote",defaultValue:!0},{id:"msg-actions-visibility",label:"Visibility",type:"select",path:"messageActions.visibility",defaultValue:"hover",options:[{value:"hover",label:"On Hover"},{value:"always",label:"Always Visible"}]},{id:"msg-actions-align",label:"Alignment",type:"select",path:"messageActions.align",defaultValue:"right",options:[{value:"left",label:"Left"},{value:"right",label:"Right"}]},{id:"msg-actions-layout",label:"Layout",type:"select",path:"messageActions.layout",defaultValue:"pill-inside",options:[{value:"pill-inside",label:"Pill"},{value:"row-inside",label:"Row"}]}]},af={id:"launcher-basics",title:"Launcher",collapsed:!0,fields:[{id:"launch-enabled",label:"Enabled",type:"toggle",path:"launcher.enabled",defaultValue:!0},{id:"launch-mount-mode",label:"Mount Mode",type:"select",path:"launcher.mountMode",defaultValue:"floating",options:[{value:"floating",label:"Floating"},{value:"docked",label:"Docked"}]},{id:"launch-position",label:"Position",type:"select",path:"launcher.position",defaultValue:"bottom-right",options:[{value:"bottom-right",label:"Bottom Right"},{value:"bottom-left",label:"Bottom Left"},{value:"top-right",label:"Top Right"},{value:"top-left",label:"Top Left"}]},{id:"launch-width",label:"Width",type:"text",path:"launcher.width",defaultValue:io},{id:"launch-auto-expand",label:"Auto Expand",type:"toggle",path:"launcher.autoExpand",defaultValue:!1},{id:"launch-title",label:"Title",type:"text",path:"launcher.title",defaultValue:"Chat Assistant"},{id:"launch-subtitle",label:"Subtitle",type:"text",path:"launcher.subtitle",defaultValue:"Here to help you get answers fast"}]},lf={id:"launcher-advanced",title:"Launcher Advanced",collapsed:!0,fields:[{id:"launch-dock-side",label:"Dock Side",type:"select",path:"launcher.dock.side",defaultValue:"right",options:[{value:"right",label:"Right"},{value:"left",label:"Left"}]},{id:"launch-dock-width",label:"Dock Width",type:"text",path:"launcher.dock.width",defaultValue:"420px"},{id:"launch-dock-animate",label:"Dock Animate",type:"toggle",path:"launcher.dock.animate",defaultValue:!0},{id:"launch-dock-reveal",label:"Dock Reveal",type:"select",path:"launcher.dock.reveal",defaultValue:"resize",options:[{value:"resize",label:"Resize"},{value:"overlay",label:"Overlay"},{value:"push",label:"Push"},{value:"emerge",label:"Emerge"}]},{id:"launch-text-hidden",label:"Hide Text",type:"toggle",path:"launcher.textHidden",defaultValue:!1},{id:"launch-icon-text",label:"Agent Icon Text",type:"text",path:"launcher.agentIconText",defaultValue:"\u{1F4AC}"},{id:"launch-icon-name",label:"Agent Icon Name (Lucide)",type:"text",path:"launcher.agentIconName",defaultValue:"bot"},{id:"launch-icon-hidden",label:"Hide Agent Icon",type:"toggle",path:"launcher.agentIconHidden",defaultValue:!1},{id:"launch-icon-size",label:"Agent Icon Size",type:"slider",path:"launcher.agentIconSize",defaultValue:"40px",slider:{min:16,max:72,step:2}},{id:"launch-icon-url",label:"Icon Image URL",description:"Custom image URL (overrides emoji/lucide)",type:"text",path:"launcher.iconUrl",defaultValue:""},{id:"launch-header-icon-name",label:"Header Icon Name (Lucide)",type:"text",path:"launcher.headerIconName",defaultValue:"bot"},{id:"launch-header-icon-size",label:"Header Icon Size",type:"slider",path:"launcher.headerIconSize",defaultValue:"48px",slider:{min:24,max:80,step:2}},{id:"launch-header-icon-hidden",label:"Hide Header Icon",type:"toggle",path:"launcher.headerIconHidden",defaultValue:!1},{id:"launch-full-height",label:"Full Height",type:"toggle",path:"launcher.fullHeight",defaultValue:!1},{id:"launch-sidebar",label:"Sidebar Mode",type:"toggle",path:"launcher.sidebarMode",defaultValue:!1},{id:"launch-sidebar-width",label:"Sidebar Width",type:"text",path:"launcher.sidebarWidth",defaultValue:"420px"},{id:"launch-mobile-fullscreen",label:"Mobile Fullscreen",description:"Fullscreen on mobile devices",type:"toggle",path:"launcher.mobileFullscreen",defaultValue:!0},{id:"launch-mobile-breakpoint",label:"Mobile Breakpoint (px)",type:"text",path:"launcher.mobileBreakpoint",defaultValue:640,formatValue:e=>String(e!=null?e:640),parseValue:e=>Number(e)},{id:"launch-height-offset",label:"Height Offset (px)",type:"text",path:"launcher.heightOffset",defaultValue:0,formatValue:e=>String(e!=null?e:0),parseValue:e=>Number(e)},{id:"launch-collapsed-max-width",label:"Collapsed Max Width",description:"Max width of launcher pill when closed",type:"text",path:"launcher.collapsedMaxWidth",defaultValue:""},{id:"launch-cta-text",label:"CTA Icon Text",type:"text",path:"launcher.callToActionIconText",defaultValue:"\u2197"},{id:"launch-cta-name",label:"CTA Icon Name",type:"text",path:"launcher.callToActionIconName",defaultValue:""},{id:"launch-cta-hidden",label:"Hide CTA Icon",type:"toggle",path:"launcher.callToActionIconHidden",defaultValue:!1},{id:"launch-cta-size",label:"CTA Icon Size",type:"slider",path:"launcher.callToActionIconSize",defaultValue:"32px",slider:{min:16,max:64,step:2}},{id:"launch-cta-padding",label:"CTA Icon Padding",type:"slider",path:"launcher.callToActionIconPadding",defaultValue:"5px",slider:{min:0,max:24,step:1}},{id:"launch-cta-bg",label:"CTA Icon Background",type:"color",path:"launcher.callToActionIconBackgroundColor",defaultValue:""}]},cf={id:"send-button",title:"Send Button",collapsed:!0,fields:[{id:"send-use-icon",label:"Use Icon",type:"toggle",path:"sendButton.useIcon",defaultValue:!1},{id:"send-icon-text",label:"Icon Text",type:"text",path:"sendButton.iconText",defaultValue:"\u2191"},{id:"send-icon-name",label:"Icon Name (Lucide)",type:"text",path:"sendButton.iconName",defaultValue:""},{id:"send-size",label:"Size",type:"slider",path:"sendButton.size",defaultValue:"40px",slider:{min:24,max:64,step:2}},{id:"send-border-width",label:"Border Width",type:"slider",path:"sendButton.borderWidth",defaultValue:"0px",slider:{min:0,max:10,step:1}},{id:"send-padding-x",label:"Padding X",type:"slider",path:"sendButton.paddingX",defaultValue:"10px",slider:{min:0,max:32,step:1}},{id:"send-padding-y",label:"Padding Y",type:"slider",path:"sendButton.paddingY",defaultValue:"6px",slider:{min:0,max:32,step:1}},{id:"send-show-tooltip",label:"Show Tooltip",type:"toggle",path:"sendButton.showTooltip",defaultValue:!1},{id:"send-tooltip-text",label:"Tooltip Text",type:"text",path:"sendButton.tooltipText",defaultValue:"Send message"}]},df={id:"close-button",title:"Close Button",collapsed:!0,fields:[{id:"close-size",label:"Size",type:"slider",path:"launcher.closeButtonSize",defaultValue:"32px",slider:{min:16,max:64,step:1}},{id:"close-placement",label:"Placement",type:"select",path:"launcher.closeButtonPlacement",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"top-right",label:"Top Right"}]},{id:"close-border-width",label:"Border Width",type:"slider",path:"launcher.closeButtonBorderWidth",defaultValue:"0px",slider:{min:0,max:8,step:1}},{id:"close-border-radius",label:"Border Radius",type:"slider",path:"launcher.closeButtonBorderRadius",defaultValue:"50%",slider:{min:0,max:100,step:1,isRadiusFull:!0}},{id:"close-icon-name",label:"Icon Name",type:"text",path:"launcher.closeButtonIconName",defaultValue:"x"},{id:"close-icon-text",label:"Icon Text",type:"text",path:"launcher.closeButtonIconText",defaultValue:"\xD7"},{id:"close-show-tooltip",label:"Show Tooltip",type:"toggle",path:"launcher.closeButtonShowTooltip",defaultValue:!0},{id:"close-tooltip-text",label:"Tooltip Text",type:"text",path:"launcher.closeButtonTooltipText",defaultValue:"Close chat"}]},pf={id:"clear-chat",title:"Clear Chat Button",collapsed:!0,fields:[{id:"clear-enabled",label:"Enabled",type:"toggle",path:"launcher.clearChat.enabled",defaultValue:!0},{id:"clear-placement",label:"Placement",type:"select",path:"launcher.clearChat.placement",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"top-right",label:"Top Right"}]},{id:"clear-icon-name",label:"Icon Name",type:"text",path:"launcher.clearChat.iconName",defaultValue:"refresh-cw"},{id:"clear-size",label:"Size",type:"slider",path:"launcher.clearChat.size",defaultValue:"32px",slider:{min:16,max:64,step:1}},{id:"clear-show-tooltip",label:"Show Tooltip",type:"toggle",path:"launcher.clearChat.showTooltip",defaultValue:!0},{id:"clear-tooltip-text",label:"Tooltip Text",type:"text",path:"launcher.clearChat.tooltipText",defaultValue:"Clear chat"}]},uf={id:"status-indicator",title:"Status Indicator",collapsed:!0,fields:[{id:"status-visible",label:"Visible",type:"toggle",path:"statusIndicator.visible",defaultValue:!0},{id:"status-align",label:"Alignment",type:"select",path:"statusIndicator.align",defaultValue:"right",options:[{value:"left",label:"Left"},{value:"center",label:"Center"},{value:"right",label:"Right"}]},{id:"status-idle-text",label:"Idle Text",type:"text",path:"statusIndicator.idleText",defaultValue:"Online"},{id:"status-connecting-text",label:"Connecting Text",type:"text",path:"statusIndicator.connectingText",defaultValue:"Connecting\u2026"},{id:"status-connected-text",label:"Connected Text",type:"text",path:"statusIndicator.connectedText",defaultValue:"Streaming\u2026"},{id:"status-error-text",label:"Error Text",type:"text",path:"statusIndicator.errorText",defaultValue:"Offline"}]},mf={id:"features",title:"Features",collapsed:!0,fields:[{id:"feat-voice",label:"Voice Recognition",description:"Enable voice input",type:"toggle",path:"voiceRecognition.enabled",defaultValue:!1},{id:"feat-auto-focus",label:"Auto Focus Input",description:"Focus input after panel opens",type:"toggle",path:"autoFocusInput",defaultValue:!1},{id:"feat-scroll-bottom-enabled",label:"Scroll To Bottom",description:"Show a jump-to-latest affordance when the user scrolls away from new content",type:"toggle",path:"features.scrollToBottom.enabled",defaultValue:!0},{id:"feat-scroll-bottom-icon",label:"Scroll To Bottom Icon",type:"text",path:"features.scrollToBottom.iconName",defaultValue:"arrow-down"},{id:"feat-scroll-bottom-label",label:"Scroll To Bottom Label",description:"Leave empty for icon-only mode",type:"text",path:"features.scrollToBottom.label",defaultValue:""}]},gf={id:"stream-animation",title:"Stream Animation",description:"Control how assistant text appears while streaming.",collapsed:!0,fields:[{id:"stream-anim-type",label:"Animation",description:"Reveal effect applied to each assistant reply as it streams.",type:"select",path:"features.streamAnimation.type",defaultValue:"none",options:[{value:"none",label:"None"},{value:"typewriter",label:"Typewriter"},{value:"word-fade",label:"Word fade"},{value:"letter-rise",label:"Letter rise"},{value:"glyph-cycle",label:"Glyph cycle"},{value:"wipe",label:"Wipe"},{value:"pop-bubble",label:"Pop bubble"}]},{id:"stream-anim-placeholder",label:"Pre-first-token Placeholder",description:"What to show before the first token arrives.",type:"select",path:"features.streamAnimation.placeholder",defaultValue:"none",options:[{value:"none",label:"Typing indicator (default)"},{value:"skeleton",label:"Skeleton shimmer"}]},{id:"stream-anim-buffer",label:"Content Buffering",description:"Trim in-progress units so only complete words/lines reveal.",type:"select",path:"features.streamAnimation.buffer",defaultValue:"none",options:[{value:"none",label:"None \u2014 stream every character"},{value:"word",label:"Word \u2014 hold until whitespace"},{value:"line",label:"Line \u2014 hold until newline"}]},{id:"stream-anim-speed",label:"Per-unit Duration (ms)",description:"Animation length for each character or word.",type:"select",path:"features.streamAnimation.speed",defaultValue:120,options:[{value:"40",label:"40ms \u2014 snappy"},{value:"80",label:"80ms"},{value:"120",label:"120ms (default)"},{value:"200",label:"200ms"},{value:"320",label:"320ms"},{value:"480",label:"480ms \u2014 slow"}],formatValue:e=>String(e!=null?e:120),parseValue:e=>Number(e)},{id:"stream-anim-duration",label:"Container Duration (ms)",description:"Length of container-level effects (pop-bubble, custom plugins).",type:"select",path:"features.streamAnimation.duration",defaultValue:1800,options:[{value:"600",label:"600ms"},{value:"1200",label:"1200ms"},{value:"1800",label:"1800ms (default)"},{value:"2400",label:"2400ms"},{value:"3600",label:"3600ms \u2014 slow"}],formatValue:e=>String(e!=null?e:1800),parseValue:e=>Number(e)}]},ff={id:"attachments-config",title:"Attachments",collapsed:!0,fields:[{id:"attach-enabled",label:"Enabled",type:"toggle",path:"attachments.enabled",defaultValue:!1},{id:"attach-max-files",label:"Max Files",type:"select",path:"attachments.maxFiles",defaultValue:4,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"4",label:"4"},{value:"6",label:"6"},{value:"8",label:"8"},{value:"10",label:"10"}],formatValue:e=>String(e!=null?e:4),parseValue:e=>Number(e)},{id:"attach-max-size",label:"Max File Size (MB)",type:"select",path:"attachments.maxFileSize",defaultValue:10*Zi,options:[{value:"1",label:"1 MB"},{value:"5",label:"5 MB"},{value:"10",label:"10 MB"},{value:"25",label:"25 MB"},{value:"50",label:"50 MB"}],formatValue:Qg,parseValue:Xg},{id:"attach-types",label:"Allowed File Types",type:"select",path:"attachments.allowedTypes",defaultValue:Es.images,options:[{value:"images",label:"Images only"},{value:"images-pdf",label:"Images + PDF"},{value:"images-text-pdf",label:"Images + text + PDF"},{value:"all",label:"All supported types"}],formatValue:Zg,parseValue:Jg}]},hf={id:"artifacts-config",title:"Artifacts",collapsed:!0,fields:[{id:"art-enabled",label:"Enabled",description:"Show artifact sidebar for documents and components",type:"toggle",path:"features.artifacts.enabled",defaultValue:!1},{id:"art-appearance",label:"Pane Appearance",type:"select",path:"features.artifacts.layout.paneAppearance",defaultValue:"panel",options:[{value:"panel",label:"Panel (bordered)"},{value:"seamless",label:"Seamless"}]}]},bf={id:"artifacts-customization",title:"Artifact Customization",collapsed:!0,fields:[{id:"art-toolbar",label:"Toolbar Preset",type:"select",path:"features.artifacts.layout.toolbarPreset",defaultValue:"default",options:[{value:"default",label:"Default"},{value:"document",label:"Document"}]},{id:"art-pane-width",label:"Pane Width",description:"CSS width (e.g. 40%, 28rem)",type:"text",path:"features.artifacts.layout.paneWidth",defaultValue:"40%"},{id:"art-pane-max-width",label:"Pane Max Width",type:"text",path:"features.artifacts.layout.paneMaxWidth",defaultValue:"28rem"},{id:"art-split-gap",label:"Split Gap",type:"text",path:"features.artifacts.layout.splitGap",defaultValue:"0.5rem"},{id:"art-pane-bg",label:"Pane Background",type:"color",path:"features.artifacts.layout.paneBackground",defaultValue:""},{id:"art-unified",label:"Unified Split Chrome",description:"Wrap chat and artifact in a single container",type:"toggle",path:"features.artifacts.layout.unifiedSplitChrome",defaultValue:!1},{id:"art-resizable",label:"Resizable",description:"Allow dragging the pane divider",type:"toggle",path:"features.artifacts.layout.resizable",defaultValue:!1},{id:"art-expand-panel",label:"Expand Panel When Open",description:"Widen the launcher panel to fit artifacts",type:"toggle",path:"features.artifacts.layout.expandLauncherPanelWhenOpen",defaultValue:!0}]},yf={id:"api-integration",title:"API & Integration",description:"Runtime and integration options.",collapsed:!0,fields:[{id:"dev-api-url",label:"API URL",type:"text",path:"apiUrl",defaultValue:""},{id:"dev-flow",label:"Flow ID",type:"text",path:"flowId",defaultValue:""},{id:"dev-parser",label:"Stream Parser",type:"select",path:"parserType",defaultValue:"plain",options:[{value:"plain",label:"Plain Text"},{value:"json",label:"JSON"},{value:"regex-json",label:"Regex JSON"},{value:"xml",label:"XML"}]}]},vf={id:"debug-inspection",title:"Debug & Inspection",collapsed:!0,fields:[{id:"dev-reasoning",label:"Show Reasoning",description:"Display AI reasoning steps",type:"toggle",path:"features.showReasoning",defaultValue:!1},{id:"dev-tool-calls",label:"Show Tool Calls",description:"Display tool call details",type:"toggle",path:"features.showToolCalls",defaultValue:!1},{id:"dev-tool-collapsed-mode",label:"Tool Call Summary",description:"Choose what collapsed tool rows show by default",type:"select",path:"features.toolCallDisplay.collapsedMode",defaultValue:"tool-call",options:[{value:"tool-call",label:"Tool Call"},{value:"tool-name",label:"Tool Name"},{value:"tool-preview",label:"Tool Preview"}]},{id:"dev-tool-active-preview",label:"Tool Preview While Active",description:"Show a lightweight preview in collapsed active tool rows",type:"toggle",path:"features.toolCallDisplay.activePreview",defaultValue:!1},{id:"dev-tool-preview-lines",label:"Tool Preview Lines",type:"select",path:"features.toolCallDisplay.previewMaxLines",defaultValue:3,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"3",label:"3"},{value:"4",label:"4"},{value:"5",label:"5"}],formatValue:e=>String(e!=null?e:3),parseValue:e=>Number(e)},{id:"dev-tool-active-min-height",label:"Tool Active Min Height",description:"CSS min-height for collapsed active tool rows (e.g. 5rem)",type:"text",path:"features.toolCallDisplay.activeMinHeight",defaultValue:""},{id:"dev-tool-expandable",label:"Tool Calls Expandable",description:"Allow expanding tool call rows to see full details",type:"toggle",path:"features.toolCallDisplay.expandable",defaultValue:!0},{id:"dev-tool-grouped",label:"Group Sequential Tool Calls",description:"Render consecutive tool rows inside a grouped container",type:"toggle",path:"features.toolCallDisplay.grouped",defaultValue:!1},{id:"dev-reasoning-expandable",label:"Reasoning Expandable",description:"Allow expanding reasoning rows to see full details",type:"toggle",path:"features.reasoningDisplay.expandable",defaultValue:!0},{id:"dev-reasoning-active-preview",label:"Reasoning Preview While Active",description:"Show a lightweight preview in collapsed active reasoning rows",type:"toggle",path:"features.reasoningDisplay.activePreview",defaultValue:!1},{id:"dev-reasoning-preview-lines",label:"Reasoning Preview Lines",type:"select",path:"features.reasoningDisplay.previewMaxLines",defaultValue:3,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"3",label:"3"},{value:"4",label:"4"},{value:"5",label:"5"}],formatValue:e=>String(e!=null?e:3),parseValue:e=>Number(e)},{id:"dev-reasoning-active-min-height",label:"Reasoning Active Min Height",description:"CSS min-height for collapsed active reasoning rows (e.g. 5rem)",type:"text",path:"features.reasoningDisplay.activeMinHeight",defaultValue:""},{id:"dev-debug",label:"Debug Mode",description:"Show debug information",type:"toggle",path:"debug",defaultValue:!1}]},xf={id:"markdown",title:"Markdown Options",collapsed:!0,fields:[{id:"md-gfm",label:"GitHub Flavored Markdown",type:"toggle",path:"markdown.options.gfm",defaultValue:!0},{id:"md-breaks",label:"Line Breaks",type:"toggle",path:"markdown.options.breaks",defaultValue:!0},{id:"md-header-ids",label:"Header IDs",type:"toggle",path:"markdown.options.headerIds",defaultValue:!1},{id:"md-pedantic",label:"Pedantic Mode",type:"toggle",path:"markdown.options.pedantic",defaultValue:!1},{id:"md-silent",label:"Silent",type:"toggle",path:"markdown.options.silent",defaultValue:!1},{id:"md-disable-styles",label:"Disable Default Styles",type:"toggle",path:"markdown.disableDefaultStyles",defaultValue:!1}]},Oa=[{label:"Content",sections:[ef,tf]},{label:"Layout",sections:[nf,of,rf,sf]},{label:"Widget",sections:[af,lf,cf,df,pf,uf]},{label:"Features",sections:[mf,gf,ff,hf,bf]},{label:"Developer",collapsedByDefault:!0,sections:[yf,vf,xf]}],pu=Oa.flatMap(e=>e.sections),uu={id:"theme-mode-v2",title:"Theme",description:"Choose how the interface adapts across light and dark mode.",collapsed:!1,fields:[{id:"color-mode",label:"Color Mode",type:"select",path:"colorScheme",defaultValue:"auto",options:[{value:"auto",label:"Auto"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}]}]},mu={id:"brand-palette-v2",title:"Brand Palette",description:"Set your brand, accent, and neutral colors. These are used to generate the interface theme.",collapsed:!1,fields:[{id:"bp-primary",label:"Primary",description:"Main brand color",type:"color",path:"theme.palette.colors.primary.500",defaultValue:"#171717"},{id:"bp-secondary",label:"Secondary",description:"Supporting brand color",type:"color",path:"theme.palette.colors.secondary.500",defaultValue:"#8b5cf6"},{id:"bp-accent",label:"Accent",description:"Highlight and decorative color",type:"color",path:"theme.palette.colors.accent.500",defaultValue:"#06b6d4"},{id:"bp-neutral",label:"Neutral",description:"Backgrounds, text, and borders",type:"color",path:"theme.palette.colors.gray.500",defaultValue:"#6b7280"}]},gu={id:"status-palette",title:"Status Palette",description:"Colors for system feedback states.",collapsed:!0,fields:[{id:"sp-success",label:"Success",type:"color",path:"theme.palette.colors.success.500",defaultValue:"#22c55e"},{id:"sp-warning",label:"Warning",type:"color",path:"theme.palette.colors.warning.500",defaultValue:"#eab308"},{id:"sp-error",label:"Error",type:"color",path:"theme.palette.colors.error.500",defaultValue:"#ef4444"},{id:"sp-notice",label:"Notice",description:"Info and notice states",type:"color",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500"}]},fu={id:"interface-roles",title:"Interface Roles",description:"Control where brand and neutral colors appear across the interface.",collapsed:!1,fields:[{id:"role-surfaces",label:"Background Surfaces",type:"role-assignment",path:"theme.semantic.colors.background",roleAssignment:Ma},{id:"role-header",label:"Header",type:"role-assignment",path:"theme.components.header.background",roleAssignment:La},{id:"role-user-messages",label:"User Messages",type:"role-assignment",path:"theme.components.message.user.background",roleAssignment:Ia},{id:"role-assistant-messages",label:"Assistant Messages",type:"role-assignment",path:"theme.components.message.assistant.background",roleAssignment:Ra},{id:"role-primary-actions",label:"Primary Actions",type:"role-assignment",path:"theme.components.button.primary.background",roleAssignment:Pa},{id:"role-scroll-to-bottom",label:"Scroll To Bottom",type:"role-assignment",path:"theme.components.scrollToBottom.background",roleAssignment:Wa},{id:"role-input",label:"Input Field",type:"role-assignment",path:"theme.components.input.background",roleAssignment:Ba},{id:"role-links-focus",label:"Links & Focus",type:"role-assignment",path:"theme.semantic.colors.accent",roleAssignment:Ha},{id:"role-borders",label:"Borders & Dividers",type:"role-assignment",path:"theme.semantic.colors.border",roleAssignment:Da}]},hu={id:"status-colors",title:"Status Colors",description:"Used for system states like success, warning, notice, and error.",collapsed:!0,fields:[{id:"sc-notice",label:"Notice",type:"token-ref",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sc-success",label:"Success",type:"token-ref",path:"theme.semantic.colors.feedback.success",defaultValue:"palette.colors.success.500",tokenRef:{tokenType:"color"}},{id:"sc-warning",label:"Warning",type:"token-ref",path:"theme.semantic.colors.feedback.warning",defaultValue:"palette.colors.warning.500",tokenRef:{tokenType:"color"}},{id:"sc-error",label:"Error",type:"token-ref",path:"theme.semantic.colors.feedback.error",defaultValue:"palette.colors.error.500",tokenRef:{tokenType:"color"}}]},bu={id:"advanced-tokens",title:"Advanced Tokens",description:"Override individual semantic and component values when you need precise control.",collapsed:!0,fields:[]},wf=[uu,mu,gu,fu,hu,bu],el=[{id:"style",label:"Style",sections:zr},{id:"design-system",label:"Design System",sections:du},{id:"configure",label:"Configure",sections:pu}];function yu(e,t){return e.startsWith("theme.")?e.replace(/^theme\./,`${t}.`):e}function Cf(e,t,n){return{...e,id:`${n}-${e.id}`,path:yu(e.path,t)}}function Sf(e,t){let n=e.find(o=>o.id===t);if(!n)throw new Error(`Section "${t}" not found in definitions`);return n}function Af(e,t,n,o=e.collapsed){var a;let r=n==="light"?"Light":"Dark",s=n==="light"?"Applies when the widget is in light mode.":"Applies when the widget is in dark mode.";return{...e,id:`${n}-${e.id}`,title:`${r} ${e.title}`,description:e.description?`${s} ${e.description}`:s,collapsed:o,fields:e.fields.map(i=>Cf(i,t,n)),presets:(a=e.presets)==null?void 0:a.map(i=>({...i,id:`${n}-${i.id}`,values:Object.fromEntries(Object.entries(i.values).map(([d,l])=>[yu(d,t),l]))}))}}var vu=[{id:"default-light",name:"Default Light",description:"Clean monochrome light theme",theme:{components:{artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}}},preview:{primary:"#171717",surface:"#ffffff",accent:"#0f0f0f"},tags:["light"]},{id:"default-dark",name:"Default Dark",description:"Monochrome dark theme",theme:{palette:{colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},semantic:{colors:{primary:"palette.colors.primary.400",secondary:"palette.colors.gray.400",accent:"palette.colors.primary.500",surface:"palette.colors.gray.800",background:"palette.colors.gray.900",container:"palette.colors.gray.800",text:"palette.colors.gray.100",textMuted:"palette.colors.gray.400",textInverse:"palette.colors.gray.900",border:"palette.colors.gray.700",divider:"palette.colors.gray.700",interactive:{default:"palette.colors.primary.400",hover:"palette.colors.primary.300",focus:"palette.colors.primary.500",active:"palette.colors.primary.600",disabled:"palette.colors.gray.600"},feedback:{success:"palette.colors.success.400",warning:"palette.colors.warning.400",error:"palette.colors.error.400",info:"palette.colors.primary.400"}}}},preview:{primary:"#171717",surface:"#1f2937",accent:"#0f0f0f"},tags:["dark"]},{id:"high-contrast",name:"High Contrast",description:"Maximum contrast for accessibility",theme:{semantic:{colors:{primary:"palette.colors.primary.700",secondary:"palette.colors.gray.700",accent:"palette.colors.primary.800",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.200",text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.400",divider:"palette.colors.gray.400",interactive:{default:"palette.colors.primary.700",hover:"palette.colors.primary.800",focus:"palette.colors.primary.900",active:"palette.colors.primary.950",disabled:"palette.colors.gray.400"},feedback:{success:"palette.colors.success.700",warning:"palette.colors.warning.700",error:"palette.colors.error.700",info:"palette.colors.primary.700"}}}},preview:{primary:"#0a0a0a",surface:"#f9fafb",accent:"#050505"},tags:["light","high-contrast","accessibility"]}],Ms=[...vu];function tl(e){return Ms.find(t=>t.id===e)}import{Marked as Tf}from"marked";var kf=e=>{if(e)return e},nl=e=>{var r,s;let t=e==null?void 0:e.markedOptions,n=new Tf({gfm:(r=t==null?void 0:t.gfm)!=null?r:!0,breaks:(s=t==null?void 0:t.breaks)!=null?s:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),o=kf(e==null?void 0:e.renderer);return o&&n.use({renderer:o}),a=>n.parse(a)},Na=e=>e?nl({markedOptions:e.options,renderer:e.renderer}):nl(),Jx=nl();var Ls=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");import Ef from"dompurify";var Mf={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},Lf=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,If=()=>{let e=Ef(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(t,n)=>{if(n.attrName==="src"||n.attrName==="href"){let o=n.attrValue;o.toLowerCase().startsWith("data:")&&!Lf.test(o)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,Mf)},_a=e=>e===!1?null:typeof e=="function"?e:If();var ol="webmcp:",Va={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function wu(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var o,r;return[n.name,(o=n.description)!=null?o:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(r=n.origin)!=null?r:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${Rf(t.join(""))}`}function xu(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function Rf(e){let t=xu(e,0).toString(36),n=xu(e,2654435761).toString(36);return`${t}.${n}`}var $a=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 Va.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",r),[]}let o=typeof location!="undefined"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=Bf(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return vo("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let g=typeof document!="undefined"&&!!document.modelContext;return vo(g?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=Pf(t),a;try{a=await r.getTools()}catch(g){let x=g instanceof Error?g.message:String(g);return vo(`Failed to read WebMCP registry: ${x}`)}let i=a.find(g=>g.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,u=!1,p=setTimeout(()=>{u=!0,l.abort()},this.timeoutMs),f=()=>l.abort();o&&(o.aborted?l.abort():o.addEventListener("abort",f,{once:!0}));try{let g=await r.executeTool(i,Of(n),{signal:l.signal});return Hf(g)}catch(g){if(u)return vo(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return vo("Aborted by cancel()");let x=g instanceof Error?g.message:String(g);return vo(x)}finally{clearTimeout(p),o&&o.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Va.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,Va.warn("document.modelContext is present but does not expose getTools()/executeTool() \u2014 WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var o;let n=(o=this.confirmHandler)!=null?o:Df;try{return await n(t)}catch(r){return Va.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,r),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>Wf(t,o))}},Pf=e=>e.startsWith(ol)?e.slice(ol.length):e,rl=e=>e.startsWith(ol),Wf=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Bf=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Hf=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:Nf(t)}]}},vo=e=>({isError:!0,content:[{type:"text",text:e}]}),Df=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Ff(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
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,"\\"),qr=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},
|
|
6
|
+
${e.description}`:"");return window.confirm(n)},Ff=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},Of=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Nf=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};import{parse as _f,STR as Vf,OBJ as $f}from"partial-json";var Cu=e=>e.replace(/\\n/g,`
|
|
7
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),qr=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Uf=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Su=e=>e.status==="complete"?Uf(e):e.status==="pending"?"Waiting":"",zf=e=>{var r,s,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((a=(s=e.startedAt)!=null?s:e.completedAt)!=null?a:Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var Au=e=>e.status==="complete"?zf(e):"Using tool...",Ua=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Rs=e=>{var n,o,r;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((r=(o=e.startedAt)!=null?o:e.completedAt)!=null?r:Date.now()));return Ua(t)},za=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 Ua(t)},sl=(e,t,n)=>{var s;if(!t)return n;let o=((s=e.name)==null?void 0:s.trim())||"tool",r=Rs(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},qa=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Is(o,n.slice(s,a.index),[]),a[1]!==void 0?Is(o,a[1],["bold"]):a[2]!==void 0?Is(o,a[2],["italic"]):a[3]!==void 0&&Is(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Is(o,n.slice(s),[]),o},Is=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},qf=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
|
|
8
8
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=o.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
|
|
9
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},wr=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Su=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Au=()=>{var t;let e=$g();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)}},Tu=()=>{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=Fg(n,Og|Ng);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?xu(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=xu(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var ku=()=>{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 ja=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 Ug="https://api.runtype.com/v1/dispatch",Ka="https://api.runtype.com";function zg(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 al=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 qg(e){switch(e){case"json":return Tu;case"regex-json":return Au;case"xml":return ku;default:return Su}}var Eu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function jg(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=Eu(n);if(!Eu(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 Ps=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;var n,o,r,s;this.apiUrl=(n=t.apiUrl)!=null?n:Ug,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:qg(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 $a(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$/,""))||Ka}/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,(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}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ka}/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.clientSession=null,(s=(r=this.config).onSessionExpired)==null||s.call(r);let m=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:m}),m}let l=await this.buildPayload(t.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([m])=>m!=="sessionId"&&m!=="session_id")):void 0,p={sessionId:d.sessionId,messages:t.messages.filter(al).map(m=>{var w,x,M;return{id:m.id,role:m.role,content:(M=(x=(w=m.contentParts)!=null?w:m.llmContent)!=null?x:m.rawContent)!=null?M:m.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context},...l.clientTools&&l.clientTools.length>0&&{clientTools:l.clientTools}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let g=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:o.signal});if(!g.ok){let m=await g.json().catch(()=>({error:"Chat request failed"}));if(g.status===401){this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a);let x=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:x}),x}if(g.status===429){let x=new Error(m.hint||"Message limit reached for this session.");throw n({type:"error",error:x}),x}let w=new Error(m.error||"Failed to send message");throw n({type:"error",error:w}),w}if(!g.body){let m=new Error("No response body received");throw n({type:"error",error:m}),m}n({type:"status",status:"connected"});try{await this.streamResponse(g.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$/,""))||Ka}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,o){var l,u;let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Ka}/resume`,a;r&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(u=o==null?void 0:o.streamResponse)!=null?u:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var s;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(al).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(al).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=u=>{let p={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return o.current=p,r(p),p},l=u=>o.current?o.current:d(u);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let u=l(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,r(u)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o){var Ft,ln,Dn,Jn;let r=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,u=O=>{let se=O.reasoning?{...O.reasoning,chunks:[...O.reasoning.chunks]}:void 0,He=O.toolCall?{...O.toolCall,chunks:O.toolCall.chunks?[...O.toolCall.chunks]:void 0}:void 0,Xe=O.tools?O.tools.map(Oe=>({...Oe,chunks:Oe.chunks?[...Oe.chunks]:void 0})):void 0;return{...O,reasoning:se,toolCall:He,tools:Xe}},p=O=>{n({type:"message",message:u(O)})},g=null,m=null,w={current:null},x={current:null},M=!1,P=new Map,W=new Map,H=new Map,_=new Map,B={lastId:null,byStep:new Map},v={lastId:null,byCall:new Map},C=(O,se,He="")=>`${O}::${se}::${He}`,E=(O,se)=>`${O}::${se}::`,S=(O,se,He,Xe)=>{let Oe=C(O,se,He),Ne=H.get(Oe);if(Ne)return Ne;let ot=He?`-${He}`:"",St={id:`nested-${O}-${se}${ot}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...He?{partId:He}:{},agentMetadata:{executionId:Xe,parentToolId:O,parentStepId:se}};return H.set(Oe,St),p(St),St},k=O=>{if(O==null)return null;try{return String(O)}catch{return null}},D=O=>{var se,He,Xe,Oe,Ne;return k((Ne=(Oe=(Xe=(He=(se=O.stepId)!=null?se:O.step_id)!=null?He:O.step)!=null?Xe:O.parentId)!=null?Oe:O.flowStepId)!=null?Ne:O.flow_step_id)},$=O=>{var se,He,Xe,Oe,Ne,ot,St;return k((St=(ot=(Ne=(Oe=(Xe=(He=(se=O.callId)!=null?se:O.call_id)!=null?He:O.requestId)!=null?Xe:O.request_id)!=null?Oe:O.toolCallId)!=null?Ne:O.tool_call_id)!=null?ot:O.stepId)!=null?St:O.step_id)},q=o,me=!1,re=()=>{if(g)return g;let O;return!me&&q?(O=q,me=!0):q&&x.current?O=`${q}_${x.current}`:O=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,g={id:O,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},p(g),g},be=(O,se)=>{B.lastId=se,O&&B.byStep.set(O,se)},ie=(O,se)=>{var Ne;let He=(Ne=O.reasoningId)!=null?Ne:O.id,Xe=D(O);if(He){let ot=String(He);return be(Xe,ot),ot}if(Xe){let ot=B.byStep.get(Xe);if(ot)return B.lastId=ot,ot}if(B.lastId&&!se)return B.lastId;if(!se)return null;let Oe=`reason-${l()}`;return be(Xe,Oe),Oe},we=O=>{let se=P.get(O);if(se)return se;let He={id:`reason-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:O,status:"streaming",chunks:[]}};return P.set(O,He),p(He),He},We=(O,se)=>{v.lastId=se,O&&v.byCall.set(O,se)},ye=new Set,Z=new Map,Ee=new Set,X=new Map,Ae=O=>{if(!O)return!1;let se=O.replace(/_+/g,"_").replace(/^_|_$/g,"");return se==="emit_artifact_markdown"||se==="emit_artifact_component"},ge=(O,se)=>{var Ne;let He=(Ne=O.toolId)!=null?Ne:O.id,Xe=$(O);if(He){let ot=String(He);return We(Xe,ot),ot}if(Xe){let ot=v.byCall.get(Xe);if(ot)return v.lastId=ot,ot}if(v.lastId&&!se)return v.lastId;if(!se)return null;let Oe=`tool-${l()}`;return We(Xe,Oe),Oe},le=O=>{let se=W.get(O);if(se)return se;let He={id:`tool-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:O,status:"pending"}};return W.set(O,He),p(He),He},ue=O=>{if(typeof O=="number"&&Number.isFinite(O))return O;if(typeof O=="string"){let se=Number(O);if(!Number.isNaN(se)&&Number.isFinite(se))return se;let He=Date.parse(O);if(!Number.isNaN(He))return He}return Date.now()},je=O=>{if(typeof O=="string")return O;if(O==null)return"";try{return JSON.stringify(O)}catch{return String(O)}},j=new Map,oe=new Map,Re=new Map,tt=new Map,fe=null,ce=(O,se,He)=>{var St;let Xe=Re.get(O);Xe||(Xe=[],Re.set(O,Xe));let Oe=0,Ne=Xe.length;for(;Oe<Ne;){let Nt=Oe+Ne>>>1;Xe[Nt].seq<se?Oe=Nt+1:Ne=Nt}((St=Xe[Oe])==null?void 0:St.seq)===se?Xe[Oe]={seq:se,text:He}:Xe.splice(Oe,0,{seq:se,text:He});let ot="";for(let Nt=0;Nt<Xe.length;Nt++)ot+=Xe[Nt].text;return ot},_e=(O,se)=>{let He=je(se),Xe=oe.get(O.id),Oe=jg(Xe,He);O.rawContent=Oe;let Ne=j.get(O.id),ot=ft=>{var $t;let nt=($t=O.content)!=null?$t:"";ft.trim()!==""&&(nt.trim().length===0||ft.startsWith(nt)||ft.trimStart().startsWith(nt.trim()))&&(O.content=ft)},St=()=>{var ft;if(Ne){let nt=(ft=Ne.close)==null?void 0:ft.call(Ne);nt instanceof Promise&&nt.catch(()=>{})}j.delete(O.id),oe.delete(O.id),O.streaming=!1,p(O)};if(!Ne){ot(He),St();return}let Nt=wr(Oe);if(Nt!==null&&Nt.trim()!==""){ot(Nt),St();return}let jt=ft=>{var ae;let nt=typeof ft=="string"?ft:(ae=ft==null?void 0:ft.text)!=null?ae:null;if(nt!==null&&nt.trim()!=="")return nt;let $t=Ne.getExtractedText();return $t!==null&&$t.trim()!==""?$t:He},K;try{K=Ne.processChunk(Oe)}catch{ot(He),St();return}if(K instanceof Promise){K.then(ft=>{ot(jt(ft)),St()}).catch(()=>{ot(He),St()});return}ot(jt(K)),St()},Le=[],de=!1,Y,Ve=()=>{de||(de=!0,queueMicrotask(()=>{de=!1,Y()}))},Ct=new ja((O,se)=>{Le.push({payloadType:O,payload:se}),Ve()}),Q=null,Fe=new Map,Ln=(Ft=this.config.iterationDisplay)!=null?Ft:"separate";for(Y=()=>{var O,se,He,Xe,Oe,Ne,ot,St,Nt,jt,K,ft,nt,$t,ae,ve,wt,_t,Jt,vn,Et,At,ht,yt,Ut,Ze,Fn,Zn,xn,On,ut,wo,Nn,ar,In,Ir,$o,Lo,vt,_n,Vn,wn,Rt,eo,to,$n,Uo,Io,zo,Un,Wt,Cn,no,qo,Ro,jo,Co,zn,po,gt,Kt,Gt,qn,Ko,oo,uo,jn,T,Kn,mo,Po,So,ss,fo,go,ho,Wo,ir,ra,as,sa,Rr,mt,is,ro,Rn,aa,ia,Pr,Bo,la,lr,ls,Ho,cs,Go,Yo,ca,da,Vi,cr,Xo,pa,ds,Qo,ua,ps,Jo,us,ma,Do,fa,Zo,Bt,Wr,Br,ms,Ao,ga,fs,gs,ha,Hr,Dr,dr,ba,ya,hs,bs,ys,vs,Sn,Gn,Fo,rt,xs,pr,bo;for(let Fr=0;Fr<Le.length;Fr++){let Ue=Le[Fr].payloadType,A=Le[Fr].payload;if(Ue==="reason_start"){let U=(O=ie(A,!0))!=null?O:`reason-${l()}`,I=we(U);I.reasoning=(se=I.reasoning)!=null?se:{id:U,status:"streaming",chunks:[]},I.reasoning.startedAt=(Xe=I.reasoning.startedAt)!=null?Xe:ue((He=A.startedAt)!=null?He:A.timestamp),I.reasoning.completedAt=void 0,I.reasoning.durationMs=void 0,I.streaming=!0,I.reasoning.status="streaming",p(I)}else if(Ue==="reason_delta"||Ue==="reason_chunk"){let U=(Ne=(Oe=ie(A,!1))!=null?Oe:ie(A,!0))!=null?Ne:`reason-${l()}`,I=we(U);I.reasoning=(ot=I.reasoning)!=null?ot:{id:U,status:"streaming",chunks:[]},I.reasoning.startedAt=(Nt=I.reasoning.startedAt)!=null?Nt:ue((St=A.startedAt)!=null?St:A.timestamp);let ee=(ft=(K=(jt=A.reasoningText)!=null?jt:A.text)!=null?K:A.delta)!=null?ft:"";if(ee&&A.hidden!==!0){let te=typeof A.sequenceIndex=="number"?A.sequenceIndex:void 0;if(te!==void 0){let G=ce(U,te,String(ee));I.reasoning.chunks=[G]}else I.reasoning.chunks.push(String(ee))}if(I.reasoning.status=A.done?"complete":"streaming",A.done){I.reasoning.completedAt=ue((nt=A.completedAt)!=null?nt:A.timestamp);let te=($t=I.reasoning.startedAt)!=null?$t:Date.now();I.reasoning.durationMs=Math.max(0,((ae=I.reasoning.completedAt)!=null?ae:Date.now())-te)}I.streaming=I.reasoning.status!=="complete",p(I)}else if(Ue==="reason_complete"){let U=(wt=(ve=ie(A,!1))!=null?ve:ie(A,!0))!=null?wt:`reason-${l()}`,I=P.get(U);if(I!=null&&I.reasoning){I.reasoning.status="complete",I.reasoning.completedAt=ue((_t=A.completedAt)!=null?_t:A.timestamp);let te=(Jt=I.reasoning.startedAt)!=null?Jt:Date.now();I.reasoning.durationMs=Math.max(0,((vn=I.reasoning.completedAt)!=null?vn:Date.now())-te),I.streaming=!1,p(I)}let ee=D(A);ee&&B.byStep.delete(ee)}else if(Ue==="tool_start"){let U=(Et=ge(A,!0))!=null?Et:`tool-${l()}`,I=(At=A.toolName)!=null?At:A.name;if(Ae(I)){ye.add(U);continue}let ee=le(U),te=(ht=ee.toolCall)!=null?ht:{id:U,status:"pending"};te.name=I!=null?I:te.name,te.status="running",A.args!==void 0?te.args=A.args:A.parameters!==void 0&&(te.args=A.parameters),te.startedAt=(Ut=te.startedAt)!=null?Ut:ue((yt=A.startedAt)!=null?yt:A.timestamp),te.completedAt=void 0,te.durationMs=void 0,ee.toolCall=te,ee.streaming=!0;let G=A.agentContext;(G||A.executionId)&&(ee.agentMetadata={executionId:(Ze=G==null?void 0:G.executionId)!=null?Ze:A.executionId,iteration:(Fn=G==null?void 0:G.iteration)!=null?Fn:A.iteration}),p(ee)}else if(Ue==="tool_chunk"||Ue==="tool_delta"){let U=(xn=(Zn=ge(A,!1))!=null?Zn:ge(A,!0))!=null?xn:`tool-${l()}`;if(ye.has(U))continue;let I=le(U),ee=(On=I.toolCall)!=null?On:{id:U,status:"running"};ee.startedAt=(wo=ee.startedAt)!=null?wo:ue((ut=A.startedAt)!=null?ut:A.timestamp);let te=(In=(ar=(Nn=A.text)!=null?Nn:A.delta)!=null?ar:A.message)!=null?In:"";te&&(ee.chunks=(Ir=ee.chunks)!=null?Ir:[],ee.chunks.push(String(te))),ee.status="running",I.toolCall=ee,I.streaming=!0;let G=A.agentContext;(G||A.executionId)&&(I.agentMetadata=(vt=I.agentMetadata)!=null?vt:{executionId:($o=G==null?void 0:G.executionId)!=null?$o:A.executionId,iteration:(Lo=G==null?void 0:G.iteration)!=null?Lo:A.iteration}),p(I)}else if(Ue==="tool_complete"){let U=(Vn=(_n=ge(A,!1))!=null?_n:ge(A,!0))!=null?Vn:`tool-${l()}`;if(ye.has(U)){ye.delete(U);continue}let I=le(U),ee=(wn=I.toolCall)!=null?wn:{id:U,status:"running"};ee.status="complete",A.result!==void 0&&(ee.result=A.result),typeof A.duration=="number"&&(ee.duration=A.duration),ee.completedAt=ue((Rt=A.completedAt)!=null?Rt:A.timestamp);let te=(eo=A.duration)!=null?eo:A.executionTime;if(typeof te=="number")ee.durationMs=te;else{let De=(to=ee.startedAt)!=null?to:Date.now();ee.durationMs=Math.max(0,(($n=ee.completedAt)!=null?$n:Date.now())-De)}I.toolCall=ee,I.streaming=!1;let G=A.agentContext;(G||A.executionId)&&(I.agentMetadata=(zo=I.agentMetadata)!=null?zo:{executionId:(Uo=G==null?void 0:G.executionId)!=null?Uo:A.executionId,iteration:(Io=G==null?void 0:G.iteration)!=null?Io:A.iteration}),p(I);let ze=$(A);ze&&v.byCall.delete(ze)}else if(Ue==="step_await"&&A.awaitReason==="local_tool_required"&&A.toolName){let U=typeof A.toolCallId=="string"&&A.toolCallId.length>0?A.toolCallId:void 0,I=(Un=U!=null?U:A.toolId)!=null?Un:`local-${l()}`,ee=le(I),te=(Wt=ee.toolCall)!=null?Wt:{id:I,status:"pending"};te.name=A.toolName,te.args=A.parameters,te.status="complete",te.chunks=(Cn=te.chunks)!=null?Cn:[],te.startedAt=(qo=te.startedAt)!=null?qo:ue((no=A.startedAt)!=null?no:A.timestamp),te.completedAt=(Ro=te.completedAt)!=null?Ro:te.startedAt,ee.toolCall=te,ee.streaming=!1,ee.agentMetadata={...ee.agentMetadata,executionId:(Co=A.executionId)!=null?Co:(jo=ee.agentMetadata)==null?void 0:jo.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},p(ee)}else if(Ue==="text_start"){if((zn=A.toolContext)!=null&&zn.toolId)continue;let U=A.partId;if(U!==void 0&&x.current!==null&&U!==x.current){let I=g;I&&(I.streaming=!1,p(I),fe=I,g=null,M=!0)}U!==void 0&&(x.current=U)}else if(Ue==="text_end"){if((po=A.toolContext)!=null&&po.toolId)continue;let U=g;U&&(U.streaming=!1,p(U),fe=U,g=null,M=!0)}else if(Ue==="step_chunk"||Ue==="step_delta"){let U=A.stepType,I=A.executionType;if(U==="tool"||I==="context")continue;let ee=A.toolContext;if(ee!=null&&ee.toolId){let De=String((Kt=(gt=A.id)!=null?gt:ee.stepId)!=null?Kt:`step-${l()}`),at=A.partId!==void 0&&A.partId!==null?String(A.partId):"",Ke=`${ee.toolId}::${De}`,Ge=_.get(Ke);if(at!==""&&Ge!==void 0&&Ge!==""&&Ge!==at){let Tt=H.get(C(ee.toolId,De,Ge));Tt&&Tt.streaming!==!1&&(Tt.streaming=!1,p(Tt))}at!==""&&_.set(Ke,at);let Qe=S(ee.toolId,De,at,ee.executionId),Yt=(oo=(Ko=(qn=(Gt=A.text)!=null?Gt:A.delta)!=null?qn:A.content)!=null?Ko:A.chunk)!=null?oo:"";Yt&&(Qe.content+=String(Yt),Qe.streaming=!0,p(Qe)),A.isComplete&&(Qe.streaming=!1,p(Qe));continue}let te=A.partId;if(te!==void 0&&x.current!==null&&te!==x.current){let De=g;De&&(De.streaming=!1,p(De),fe=De,g=null,M=!0)}te!==void 0&&(x.current=te);let G=te!==void 0&&(uo=tt.get(te))!=null?uo:re();te!==void 0&&(G.partId||(G.partId=te),tt.set(te,G));let ze=(mo=(Kn=(T=(jn=A.text)!=null?jn:A.delta)!=null?T:A.content)!=null?Kn:A.chunk)!=null?mo:"";if(ze){let De=typeof A.seq=="number"?A.seq:void 0,at=te!=null?te:G.id,Ke=De!==void 0?ce(at,De,String(ze)):((Po=oe.get(G.id))!=null?Po:"")+ze;G.rawContent=Ke,j.has(G.id)||j.set(G.id,this.createStreamParser());let Ge=j.get(G.id),Qe=Ke.trim().startsWith("{")||Ke.trim().startsWith("[");if(Qe&&oe.set(G.id,Ke),Ge.__isPlainTextParser===!0){G.content=De!==void 0?Ke:G.content+ze,oe.delete(G.id),j.delete(G.id),G.rawContent=void 0,p(G);continue}let Tt=Ge.processChunk(Ke);if(Tt instanceof Promise)Tt.then(Lt=>{var mn;let on=typeof Lt=="string"?Lt:(mn=Lt==null?void 0:Lt.text)!=null?mn:null;if(on!==null&&on.trim()!=="")G.content=on,p(G);else if(!Qe&&!Ke.trim().startsWith("<")){let cn=g,Zt=cn&&cn.id===G.id?cn:G;Zt.id===G.id&&(Zt.content=De!==void 0?Ke:Zt.content+ze,oe.delete(Zt.id),j.delete(Zt.id),Zt.rawContent=void 0,p(Zt))}}).catch(()=>{G.content=De!==void 0?Ke:G.content+ze,oe.delete(G.id),j.delete(G.id),G.rawContent=void 0,p(G)});else{let Lt=typeof Tt=="string"?Tt:(So=Tt==null?void 0:Tt.text)!=null?So:null;Lt!==null&&Lt.trim()!==""?(G.content=Lt,p(G)):!Qe&&!Ke.trim().startsWith("<")&&(G.content=De!==void 0?Ke:G.content+ze,oe.delete(G.id),j.delete(G.id),G.rawContent=void 0,p(G))}}if(A.isComplete){let De=(fo=(ss=A.result)==null?void 0:ss.response)!=null?fo:G.content;if(De){let at=oe.get(G.id),Ke=at!=null?at:je(De);G.rawContent=Ke;let Ge=j.get(G.id),Qe=null,Yt=!1;if(Ge&&(Qe=Ge.getExtractedText(),Qe===null&&(Qe=wr(Ke)),Qe===null)){let Tt=Ge.processChunk(Ke);Tt instanceof Promise?(Yt=!0,Tt.then(Lt=>{var mn;let on=typeof Lt=="string"?Lt:(mn=Lt==null?void 0:Lt.text)!=null?mn:null;if(on!==null){let cn=g;cn&&cn.id===G.id&&(cn.content=on,cn.streaming=!1,j.delete(cn.id),oe.delete(cn.id),p(cn))}})):Qe=typeof Tt=="string"?Tt:(go=Tt==null?void 0:Tt.text)!=null?go:null}if(!Yt){Qe!==null&&Qe.trim()!==""?G.content=Qe:oe.has(G.id)||(G.content=je(De));let Tt=j.get(G.id);if(Tt){let Lt=(ho=Tt.close)==null?void 0:ho.call(Tt);Lt instanceof Promise&&Lt.catch(()=>{}),j.delete(G.id)}oe.delete(G.id),G.streaming=!1,p(G)}}}}else if(Ue==="step_complete"){let U=A.stepType,I=A.executionType;if(U==="tool"||I==="context")continue;let ee=A.toolContext;if(ee!=null&&ee.toolId){let De=String((ir=(Wo=A.id)!=null?Wo:ee.stepId)!=null?ir:"");if(De){let at=E(ee.toolId,De);for(let[Ke,Ge]of H)Ke.startsWith(at)&&Ge.streaming!==!1&&(Ge.streaming=!1,p(Ge));_.delete(`${ee.toolId}::${De}`)}continue}let te=A.stopReason;if(M){if(g!==null){let Ke=g;te&&(Ke.stopReason=te),j.delete(Ke.id),oe.delete(Ke.id),Ke.streaming!==!1&&(Ke.streaming=!1,p(Ke))}let De=(ra=A.result)==null?void 0:ra.response,at=fe;at&&(te&&(at.stopReason=te),De!=null?_e(at,De):(j.delete(at.id),oe.delete(at.id))),fe=null;continue}let G=(as=A.result)==null?void 0:as.response,ze=re();if(te&&(ze.stopReason=te),G!=null){let De=j.get(ze.id),at=!1,Ke=!1;if(De){let Ge=De.getExtractedText(),Qe=oe.get(ze.id),Yt=Qe!=null?Qe:je(G);if(ze.rawContent=Yt,Ge!==null&&Ge.trim()!=="")ze.content=Ge,at=!0;else{let Tt=wr(Yt);if(Tt!==null)ze.content=Tt,at=!0;else{let Lt=De.processChunk(Yt);if(Lt instanceof Promise)Ke=!0,Lt.then(on=>{var cn;let mn=typeof on=="string"?on:(cn=on==null?void 0:on.text)!=null?cn:null;if(mn!==null&&mn.trim()!==""){let Zt=g;Zt&&Zt.id===ze.id&&(Zt.content=mn,Zt.streaming=!1,j.delete(Zt.id),oe.delete(Zt.id),p(Zt))}else{let Zt=De.getExtractedText(),so=g;so&&so.id===ze.id&&(Zt!==null&&Zt.trim()!==""?so.content=Zt:oe.has(so.id)||(so.content=je(G)),so.streaming=!1,j.delete(so.id),oe.delete(so.id),p(so))}});else{let on=typeof Lt=="string"?Lt:(sa=Lt==null?void 0:Lt.text)!=null?sa:null;if(on!==null&&on.trim()!=="")ze.content=on,at=!0;else{let mn=De.getExtractedText();mn!==null&&mn.trim()!==""&&(ze.content=mn,at=!0)}}}}}if(!Ke){if(!ze.rawContent){let Ge=oe.get(ze.id);ze.rawContent=Ge!=null?Ge:je(G)}if(!at&&!oe.has(ze.id)&&(ze.content=je(G)),De){let Ge=(Rr=De.close)==null?void 0:Rr.call(De);Ge instanceof Promise&&Ge.catch(()=>{})}j.delete(ze.id),oe.delete(ze.id),ze.streaming=!1,p(ze)}}else j.delete(ze.id),oe.delete(ze.id),ze.streaming=!1,p(ze)}else if(Ue==="flow_complete"){let U=(mt=A.result)==null?void 0:mt.response;if(M){if(g!==null){let I=g;j.delete(I.id),oe.delete(I.id),I.streaming!==!1&&(I.streaming=!1,p(I))}}else if(U!=null){let I=re(),ee=oe.get(I.id),te=ee!=null?ee:je(U);I.rawContent=te;let G=je(U),ze=j.get(I.id);if(ze){let Ke=wr(te);if(Ke!==null)G=Ke;else{let Ge=ze.processChunk(te);Ge instanceof Promise&&Ge.then(Yt=>{var Lt;let Tt=typeof Yt=="string"?Yt:(Lt=Yt==null?void 0:Yt.text)!=null?Lt:null;Tt!==null&&(I.content=Tt,I.streaming=!1,p(I))});let Qe=ze.getExtractedText();Qe!==null&&(G=Qe)}}j.delete(I.id),oe.delete(I.id);let De=G!==I.content,at=I.streaming!==!1;De&&(I.content=G),I.streaming=!1,(De||at)&&p(I)}else if(g!==null){let I=g;j.delete(I.id),oe.delete(I.id),I.streaming!==!1&&(I.streaming=!1,p(I))}n({type:"status",status:"idle"})}else if(Ue==="agent_start")Q={executionId:A.executionId,agentId:(is=A.agentId)!=null?is:"virtual",agentName:(ro=A.agentName)!=null?ro:"",status:"running",currentIteration:0,maxTurns:(Rn=A.maxTurns)!=null?Rn:1,startedAt:ue(A.startedAt)};else if(Ue==="agent_iteration_start"){if(Q&&(Q.currentIteration=A.iteration),Ln==="separate"&&A.iteration>1){let U=g;U&&(U.streaming=!1,p(U),Fe.set(A.iteration-1,U),g=null)}}else if(Ue==="agent_turn_start")m=null;else if(Ue==="agent_turn_delta"){if(A.contentType==="text"){let U=re();U.content+=(aa=A.delta)!=null?aa:"",U.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId,agentName:Q==null?void 0:Q.agentName},m=U,p(U)}else if(A.contentType==="thinking"){let U=(ia=A.turnId)!=null?ia:`agent-think-${A.iteration}`,I=we(U);I.reasoning=(Pr=I.reasoning)!=null?Pr:{id:U,status:"streaming",chunks:[]},I.reasoning.chunks.push((Bo=A.delta)!=null?Bo:""),I.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId},p(I)}else if(A.contentType==="tool_input"){let U=(la=A.toolCallId)!=null?la:v.lastId;if(U){let I=W.get(U);I!=null&&I.toolCall&&(I.toolCall.chunks=(lr=I.toolCall.chunks)!=null?lr:[],I.toolCall.chunks.push((ls=A.delta)!=null?ls:""),p(I))}}}else if(Ue==="agent_turn_complete"){let U=A.turnId;if(U){let te=P.get(U);if(te!=null&&te.reasoning){te.reasoning.status="complete",te.reasoning.completedAt=ue(A.completedAt);let G=(Ho=te.reasoning.startedAt)!=null?Ho:Date.now();te.reasoning.durationMs=Math.max(0,((cs=te.reasoning.completedAt)!=null?cs:Date.now())-G),te.streaming=!1,p(te)}}let I=A.stopReason,ee=g!=null?g:m;if(I&&ee!==null){let te=A.turnId;(!te||((Go=ee.agentMetadata)==null?void 0:Go.turnId)===te)&&(ee.stopReason=I,p(ee))}}else if(Ue==="agent_tool_start"){g&&(g.streaming=!1,p(g),g=null);let U=(Yo=A.toolCallId)!=null?Yo:`agent-tool-${l()}`;We($(A),U);let I=le(U),ee=(ca=I.toolCall)!=null?ca:{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};ee.name=(Vi=(da=A.toolName)!=null?da:A.name)!=null?Vi:ee.name,ee.status="running",A.parameters!==void 0&&(ee.args=A.parameters),ee.startedAt=ue((cr=A.startedAt)!=null?cr:A.timestamp),I.toolCall=ee,I.streaming=!0,I.agentMetadata={executionId:A.executionId,iteration:A.iteration},p(I)}else if(Ue==="agent_tool_delta"){let U=(Xo=A.toolCallId)!=null?Xo:v.lastId;if(U){let I=(pa=W.get(U))!=null?pa:le(U);I.toolCall&&(I.toolCall.chunks=(ds=I.toolCall.chunks)!=null?ds:[],I.toolCall.chunks.push((Qo=A.delta)!=null?Qo:""),I.toolCall.status="running",I.streaming=!0,p(I))}}else if(Ue==="agent_tool_complete"){let U=(ua=A.toolCallId)!=null?ua:v.lastId;if(U){let I=(ps=W.get(U))!=null?ps:le(U);if(I.toolCall){I.toolCall.status="complete",A.result!==void 0&&(I.toolCall.result=A.result),typeof A.executionTime=="number"&&(I.toolCall.durationMs=A.executionTime),I.toolCall.completedAt=ue((Jo=A.completedAt)!=null?Jo:A.timestamp),I.streaming=!1,p(I);let ee=$(A);ee&&v.byCall.delete(ee)}}}else if(Ue==="agent_media"){let U=Array.isArray(A.media)?A.media:[],I=[];for(let ee of U){if(!ee||typeof ee!="object")continue;let te=ee,G=typeof te.type=="string"?te.type:void 0,ze=typeof te.mediaType=="string"?te.mediaType.toLowerCase():"",De=null,at="";if(G==="media"){let Ke=typeof te.data=="string"?te.data:void 0;if(!Ke)continue;at=ze.length>0?ze:"application/octet-stream",De=`data:${at};base64,${Ke}`}else if(G==="image-url"){let Ke=typeof te.url=="string"?te.url:void 0;if(!Ke)continue;at=ze,De=Ke}else if(G==="file-url"){let Ke=typeof te.url=="string"?te.url:void 0;if(!Ke)continue;at=ze,De=Ke}else continue;if(De)if(G==="image-url"||at.startsWith("image/"))I.push({type:"image",image:De,...at?{mimeType:at}:{}});else if(at.startsWith("audio/"))I.push({type:"audio",audio:De,mimeType:at});else if(at.startsWith("video/"))I.push({type:"video",video:De,mimeType:at});else{let Ke=at||"application/octet-stream";I.push({type:"file",data:De,mimeType:Ke,filename:zg(Ke)})}}if(I.length>0){let ee=l(),te=A.toolCallId,ze={id:`agent-media-${typeof te=="string"&&te.length>0?`${te}-${ee}`:String(ee)}`,role:"assistant",content:"",contentParts:I,createdAt:new Date().toISOString(),streaming:!1,sequence:ee,agentMetadata:{executionId:A.executionId,iteration:A.iteration}};p(ze);let De=g;De&&(De.streaming=!1,p(De)),g=null,w.current=null}}else if(Ue!=="agent_iteration_complete"){if(Ue==="agent_reflection"||Ue==="agent_reflect"){let U=`agent-reflection-${A.executionId}-${A.iteration}`,I={id:U,role:"assistant",content:(us=A.reflection)!=null?us:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:U,status:"complete",chunks:[(ma=A.reflection)!=null?ma:""]},agentMetadata:{executionId:A.executionId,iteration:A.iteration}};p(I)}else if(Ue==="agent_complete"){Q&&(Q.status=A.success?"complete":"error",Q.completedAt=ue(A.completedAt),Q.stopReason=A.stopReason);let U=g;U&&(U.streaming=!1,p(U)),n({type:"status",status:"idle"})}else if(Ue==="agent_error"){let U=typeof A.error=="string"?A.error:(fa=(Do=A.error)==null?void 0:Do.message)!=null?fa:"Agent execution error";A.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",U):n({type:"error",error:new Error(U)})}else if(Ue!=="agent_ping"){if(Ue==="agent_approval_start"){let U=(Zo=A.approvalId)!=null?Zo:`approval-${l()}`,I={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(Bt=Q==null?void 0:Q.agentId)!=null?Bt:"virtual",executionId:(Br=(Wr=A.executionId)!=null?Wr:Q==null?void 0:Q.executionId)!=null?Br:"",toolName:(ms=A.toolName)!=null?ms:"",toolType:A.toolType,description:(ga=A.description)!=null?ga:`Execute ${(Ao=A.toolName)!=null?Ao:"tool"}`,parameters:A.parameters}};p(I)}else if(Ue==="step_await"&&A.awaitReason==="approval_required"){let U=(fs=A.approvalId)!=null?fs:`approval-${l()}`,I={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(gs=Q==null?void 0:Q.agentId)!=null?gs:"virtual",executionId:(Hr=(ha=A.executionId)!=null?ha:Q==null?void 0:Q.executionId)!=null?Hr:"",toolName:(Dr=A.toolName)!=null?Dr:"",toolType:A.toolType,description:(ba=A.description)!=null?ba:`Execute ${(dr=A.toolName)!=null?dr:"tool"}`,parameters:A.parameters}};p(I)}else if(Ue==="agent_approval_complete"){let U=A.approvalId;if(U){let ee={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:(ya=A.decision)!=null?ya:"approved",agentId:(hs=Q==null?void 0:Q.agentId)!=null?hs:"virtual",executionId:(ys=(bs=A.executionId)!=null?bs:Q==null?void 0:Q.executionId)!=null?ys:"",toolName:(vs=A.toolName)!=null?vs:"",description:(Sn=A.description)!=null?Sn:"",resolvedAt:Date.now()}};p(ee)}}else if(Ue==="artifact_start"||Ue==="artifact_delta"||Ue==="artifact_update"||Ue==="artifact_complete"){if(Ue==="artifact_start"){let U=A.artifactType,I=String(A.id),ee=typeof A.title=="string"?A.title:void 0;if(n({type:"artifact_start",id:I,artifactType:U,title:ee,component:typeof A.component=="string"?A.component:void 0}),X.set(I,{markdown:"",title:ee}),!Ee.has(I)){Ee.add(I);let te={id:`artifact-ref-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:I,title:ee,artifactType:U,status:"streaming"}})};Z.set(I,te),p(te)}}else if(Ue==="artifact_delta"){let U=String(A.id),I=typeof A.delta=="string"?A.delta:String((Gn=A.delta)!=null?Gn:"");n({type:"artifact_delta",id:U,artDelta:I});let ee=X.get(U);ee&&(ee.markdown+=I)}else if(Ue==="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(Ue==="artifact_complete"){let U=String(A.id);n({type:"artifact_complete",id:U});let I=Z.get(U);if(I){I.streaming=!1;try{let ee=JSON.parse((Fo=I.rawContent)!=null?Fo:"{}");if(ee.props){ee.props.status="complete";let te=X.get(U);te!=null&&te.markdown&&(ee.props.markdown=te.markdown)}I.rawContent=JSON.stringify(ee)}catch{}X.delete(U),p(I),Z.delete(U)}}}else if(Ue==="transcript_insert"){let U=A.message;if(!U||typeof U!="object")continue;let I=String((rt=U.id)!=null?rt:`msg-${l()}`),ee=U.role,G={id:I,role:ee==="user"?"user":ee==="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(p(G),G.rawContent)try{let ze=JSON.parse(G.rawContent),De=(xs=ze==null?void 0:ze.props)==null?void 0:xs.artifactId;typeof De=="string"&&Ee.add(De)}catch{}g=null,w.current=null,j.delete(I),oe.delete(I)}else if(Ue==="error"||Ue==="step_error"||Ue==="dispatch_error"||Ue==="flow_error"){let U=null;if(A.error instanceof Error)U=A.error;else if(Ue==="dispatch_error"){let I=(pr=A.message)!=null?pr:A.error;I!=null&&I!==""&&(U=new Error(String(I)))}else if(Ue==="step_error"||Ue==="flow_error"){let I=A.error;typeof I=="string"&&I!==""?U=new Error(I):I!=null&&typeof I=="object"&&"message"in I&&(U=new Error(String((bo=I.message)!=null?bo:I)))}else Ue==="error"&&A.error!=null&&A.error!==""&&(U=new Error(String(A.error)));if(U){n({type:"error",error:U});let I=g;I&&I.streaming&&(I.streaming=!1,p(I)),n({type:"status",status:"idle"})}}}}}Le.length=0};;){let{done:O,value:se}=await r.read();if(O)break;a+=s.decode(se,{stream:!0});let He=a.split(`
|
|
9
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},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},Tu=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ku=()=>{var t;let e=qf();return{processChunk:async n=>{let o=n.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},Eu=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=_f(n,Vf|$f);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Cu(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Cu(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var Mu=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var ja=class{constructor(t,n=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=n}push(t,n){var s,a,i;let o=(i=(s=n==null?void 0:n.seq)!=null?s:n==null?void 0:n.sequenceIndex)!=null?i:(a=n==null?void 0:n.agentContext)==null?void 0:a.seq;if(o==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,n);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),o===this.nextExpectedSeq){this.emitter(t,n),this.nextExpectedSeq=o+1,this.drainConsecutive();return}if(o<this.nextExpectedSeq){this.emitter(t,n);return}let r=this.buffer.get(o);r!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${o} (${r.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(r.payloadType,r.payload)),this.buffer.set(o,{payloadType:t,payload:n,seq:o}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((n,o)=>n[0]-o[0]);for(let[n,o]of t)this.buffer.delete(n),this.emitter(o.payloadType,o.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var jf="https://api.runtype.com/v1/dispatch",Ka="https://api.runtype.com";function Kf(e){var s,a;let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let i=(a=(s=t.slice(r+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var al=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Gf(e){switch(e){case"json":return Eu;case"regex-json":return ku;case"xml":return Mu;default:return Tu}}var Lu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Yf(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=Lu(n);if(!Lu(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=wr(e);return wr(t)!==null&&a===null?t:e}var Ps=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,o,r,s;this.apiUrl=(n=t.apiUrl)!=null?n:jf,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:Gf(t.parserType),this.contextProviders=(r=t.contextProviders)!=null?r:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new $a(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$/,""))||Ka}/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$/,""))||Ka}/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),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([D])=>D!=="sessionId"&&D!=="session_id")):void 0,p={sessionId:d.sessionId,messages:t.messages.filter(al).map(D=>{var B,v,w;return{id:D.id,role:D.role,content:(w=(v=(B=D.contentParts)!=null?B:D.llmContent)!=null?v:D.rawContent)!=null?w:D.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},f=l.clientTools,g=!!(f&&f.length>0),x=g?wu(f):void 0,C=this.clientToolsFingerprintSessionId===d.sessionId,M=g&&C&&this.lastSentClientToolsFingerprint===x,W=!1,L=null,H;for(let D=0;;D++){let v={...p,...g&&(W||!M)&&f?{clientTools:f}:{},...x?{clientToolsFingerprint:x}:{}};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&&g){let w=await H.json().catch(()=>null);if((w==null?void 0:w.error)==="client_tools_resend_required"){W=!0,this.lastSentClientToolsFingerprint=null;continue}L=w!=null?w:{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 B=new Error(D.error||"Failed to send message");throw n({type:"error",error:B}),B}if(!H.body){let D=new Error("No response body received");throw n({type:"error",error:D}),D}this.lastSentClientToolsFingerprint=x!=null?x: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$/,""))||Ka}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,o){var l,u;let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Ka}/resume`,a;r&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(u=o==null?void 0:o.streamResponse)!=null?u:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var s;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(al).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(al).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=u=>{let p={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return o.current=p,r(p),p},l=u=>o.current?o.current:d(u);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let u=l(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,r(u)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o){var Ft,ln,Dn,Jn;let r=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,u=N=>{let se=N.reasoning?{...N.reasoning,chunks:[...N.reasoning.chunks]}:void 0,He=N.toolCall?{...N.toolCall,chunks:N.toolCall.chunks?[...N.toolCall.chunks]:void 0}:void 0,Xe=N.tools?N.tools.map(Oe=>({...Oe,chunks:Oe.chunks?[...Oe.chunks]:void 0})):void 0;return{...N,reasoning:se,toolCall:He,tools:Xe}},p=N=>{n({type:"message",message:u(N)})},f=null,g=null,x={current:null},C={current:null},M=!1,W=new Map,L=new Map,H=new Map,D=new Map,B={lastId:null,byStep:new Map},v={lastId:null,byCall:new Map},w=(N,se,He="")=>`${N}::${se}::${He}`,E=(N,se)=>`${N}::${se}::`,S=(N,se,He,Xe)=>{let Oe=w(N,se,He),Ne=H.get(Oe);if(Ne)return Ne;let ot=He?`-${He}`:"",St={id:`nested-${N}-${se}${ot}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...He?{partId:He}:{},agentMetadata:{executionId:Xe,parentToolId:N,parentStepId:se}};return H.set(Oe,St),p(St),St},k=N=>{if(N==null)return null;try{return String(N)}catch{return null}},F=N=>{var se,He,Xe,Oe,Ne;return k((Ne=(Oe=(Xe=(He=(se=N.stepId)!=null?se:N.step_id)!=null?He:N.step)!=null?Xe:N.parentId)!=null?Oe:N.flowStepId)!=null?Ne:N.flow_step_id)},$=N=>{var se,He,Xe,Oe,Ne,ot,St;return k((St=(ot=(Ne=(Oe=(Xe=(He=(se=N.callId)!=null?se:N.call_id)!=null?He:N.requestId)!=null?Xe:N.request_id)!=null?Oe:N.toolCallId)!=null?Ne:N.tool_call_id)!=null?ot:N.stepId)!=null?St:N.step_id)},q=o,me=!1,re=()=>{if(f)return f;let N;return!me&&q?(N=q,me=!0):q&&C.current?N=`${q}_${C.current}`:N=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:N,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},p(f),f},be=(N,se)=>{B.lastId=se,N&&B.byStep.set(N,se)},ie=(N,se)=>{var Ne;let He=(Ne=N.reasoningId)!=null?Ne:N.id,Xe=F(N);if(He){let ot=String(He);return be(Xe,ot),ot}if(Xe){let ot=B.byStep.get(Xe);if(ot)return B.lastId=ot,ot}if(B.lastId&&!se)return B.lastId;if(!se)return null;let Oe=`reason-${l()}`;return be(Xe,Oe),Oe},we=N=>{let se=W.get(N);if(se)return se;let He={id:`reason-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:N,status:"streaming",chunks:[]}};return W.set(N,He),p(He),He},We=(N,se)=>{v.lastId=se,N&&v.byCall.set(N,se)},ye=new Set,Z=new Map,Ee=new Set,X=new Map,Ae=N=>{if(!N)return!1;let se=N.replace(/_+/g,"_").replace(/^_|_$/g,"");return se==="emit_artifact_markdown"||se==="emit_artifact_component"},fe=(N,se)=>{var Ne;let He=(Ne=N.toolId)!=null?Ne:N.id,Xe=$(N);if(He){let ot=String(He);return We(Xe,ot),ot}if(Xe){let ot=v.byCall.get(Xe);if(ot)return v.lastId=ot,ot}if(v.lastId&&!se)return v.lastId;if(!se)return null;let Oe=`tool-${l()}`;return We(Xe,Oe),Oe},le=N=>{let se=L.get(N);if(se)return se;let He={id:`tool-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:N,status:"pending"}};return L.set(N,He),p(He),He},ue=N=>{if(typeof N=="number"&&Number.isFinite(N))return N;if(typeof N=="string"){let se=Number(N);if(!Number.isNaN(se)&&Number.isFinite(se))return se;let He=Date.parse(N);if(!Number.isNaN(He))return He}return Date.now()},je=N=>{if(typeof N=="string")return N;if(N==null)return"";try{return JSON.stringify(N)}catch{return String(N)}},j=new Map,oe=new Map,Re=new Map,tt=new Map,ge=null,ce=(N,se,He)=>{var St;let Xe=Re.get(N);Xe||(Xe=[],Re.set(N,Xe));let Oe=0,Ne=Xe.length;for(;Oe<Ne;){let Nt=Oe+Ne>>>1;Xe[Nt].seq<se?Oe=Nt+1:Ne=Nt}((St=Xe[Oe])==null?void 0:St.seq)===se?Xe[Oe]={seq:se,text:He}:Xe.splice(Oe,0,{seq:se,text:He});let ot="";for(let Nt=0;Nt<Xe.length;Nt++)ot+=Xe[Nt].text;return ot},_e=(N,se)=>{let He=je(se),Xe=oe.get(N.id),Oe=Yf(Xe,He);N.rawContent=Oe;let Ne=j.get(N.id),ot=gt=>{var $t;let nt=($t=N.content)!=null?$t:"";gt.trim()!==""&&(nt.trim().length===0||gt.startsWith(nt)||gt.trimStart().startsWith(nt.trim()))&&(N.content=gt)},St=()=>{var gt;if(Ne){let nt=(gt=Ne.close)==null?void 0:gt.call(Ne);nt instanceof Promise&&nt.catch(()=>{})}j.delete(N.id),oe.delete(N.id),N.streaming=!1,p(N)};if(!Ne){ot(He),St();return}let Nt=wr(Oe);if(Nt!==null&&Nt.trim()!==""){ot(Nt),St();return}let jt=gt=>{var ae;let nt=typeof gt=="string"?gt:(ae=gt==null?void 0:gt.text)!=null?ae:null;if(nt!==null&&nt.trim()!=="")return nt;let $t=Ne.getExtractedText();return $t!==null&&$t.trim()!==""?$t:He},K;try{K=Ne.processChunk(Oe)}catch{ot(He),St();return}if(K instanceof Promise){K.then(gt=>{ot(jt(gt)),St()}).catch(()=>{ot(He),St()});return}ot(jt(K)),St()},Le=[],de=!1,Y,Ve=()=>{de||(de=!0,queueMicrotask(()=>{de=!1,Y()}))},Ct=new ja((N,se)=>{Le.push({payloadType:N,payload:se}),Ve()}),Q=null,Fe=new Map,Ln=(Ft=this.config.iterationDisplay)!=null?Ft:"separate";for(Y=()=>{var N,se,He,Xe,Oe,Ne,ot,St,Nt,jt,K,gt,nt,$t,ae,ve,wt,_t,Jt,vn,Et,At,ht,yt,Ut,Ze,Fn,Zn,xn,On,ut,wo,Nn,ar,In,Ir,$o,Lo,vt,_n,Vn,wn,Rt,eo,to,$n,Uo,Io,zo,Un,Wt,Cn,no,qo,Ro,jo,Co,zn,po,ft,Kt,Gt,qn,Ko,oo,uo,jn,T,Kn,mo,Po,So,ss,go,fo,ho,Wo,ir,ra,as,sa,Rr,mt,is,ro,Rn,aa,ia,Pr,Bo,la,lr,ls,Ho,cs,Go,Yo,ca,da,Vi,cr,Xo,pa,ds,Qo,ua,ps,Jo,us,ma,Do,ga,Zo,Bt,Wr,Br,ms,Ao,fa,gs,fs,ha,Hr,Dr,dr,ba,ya,hs,bs,ys,vs,Sn,Gn,Fo,rt,xs,pr,bo;for(let Fr=0;Fr<Le.length;Fr++){let Ue=Le[Fr].payloadType,A=Le[Fr].payload;if(Ue==="reason_start"){let U=(N=ie(A,!0))!=null?N:`reason-${l()}`,R=we(U);R.reasoning=(se=R.reasoning)!=null?se:{id:U,status:"streaming",chunks:[]},R.reasoning.startedAt=(Xe=R.reasoning.startedAt)!=null?Xe:ue((He=A.startedAt)!=null?He:A.timestamp),R.reasoning.completedAt=void 0,R.reasoning.durationMs=void 0,R.streaming=!0,R.reasoning.status="streaming",p(R)}else if(Ue==="reason_delta"||Ue==="reason_chunk"){let U=(Ne=(Oe=ie(A,!1))!=null?Oe:ie(A,!0))!=null?Ne:`reason-${l()}`,R=we(U);R.reasoning=(ot=R.reasoning)!=null?ot:{id:U,status:"streaming",chunks:[]},R.reasoning.startedAt=(Nt=R.reasoning.startedAt)!=null?Nt:ue((St=A.startedAt)!=null?St:A.timestamp);let ee=(gt=(K=(jt=A.reasoningText)!=null?jt:A.text)!=null?K:A.delta)!=null?gt:"";if(ee&&A.hidden!==!0){let te=typeof A.sequenceIndex=="number"?A.sequenceIndex:void 0;if(te!==void 0){let G=ce(U,te,String(ee));R.reasoning.chunks=[G]}else R.reasoning.chunks.push(String(ee))}if(R.reasoning.status=A.done?"complete":"streaming",A.done){R.reasoning.completedAt=ue((nt=A.completedAt)!=null?nt:A.timestamp);let te=($t=R.reasoning.startedAt)!=null?$t:Date.now();R.reasoning.durationMs=Math.max(0,((ae=R.reasoning.completedAt)!=null?ae:Date.now())-te)}R.streaming=R.reasoning.status!=="complete",p(R)}else if(Ue==="reason_complete"){let U=(wt=(ve=ie(A,!1))!=null?ve:ie(A,!0))!=null?wt:`reason-${l()}`,R=W.get(U);if(R!=null&&R.reasoning){R.reasoning.status="complete",R.reasoning.completedAt=ue((_t=A.completedAt)!=null?_t:A.timestamp);let te=(Jt=R.reasoning.startedAt)!=null?Jt:Date.now();R.reasoning.durationMs=Math.max(0,((vn=R.reasoning.completedAt)!=null?vn:Date.now())-te),R.streaming=!1,p(R)}let ee=F(A);ee&&B.byStep.delete(ee)}else if(Ue==="tool_start"){let U=(Et=fe(A,!0))!=null?Et:`tool-${l()}`,R=(At=A.toolName)!=null?At:A.name;if(Ae(R)){ye.add(U);continue}let ee=le(U),te=(ht=ee.toolCall)!=null?ht:{id:U,status:"pending"};te.name=R!=null?R:te.name,te.status="running",A.args!==void 0?te.args=A.args:A.parameters!==void 0&&(te.args=A.parameters),te.startedAt=(Ut=te.startedAt)!=null?Ut:ue((yt=A.startedAt)!=null?yt:A.timestamp),te.completedAt=void 0,te.durationMs=void 0,ee.toolCall=te,ee.streaming=!0;let G=A.agentContext;(G||A.executionId)&&(ee.agentMetadata={executionId:(Ze=G==null?void 0:G.executionId)!=null?Ze:A.executionId,iteration:(Fn=G==null?void 0:G.iteration)!=null?Fn:A.iteration}),p(ee)}else if(Ue==="tool_chunk"||Ue==="tool_delta"){let U=(xn=(Zn=fe(A,!1))!=null?Zn:fe(A,!0))!=null?xn:`tool-${l()}`;if(ye.has(U))continue;let R=le(U),ee=(On=R.toolCall)!=null?On:{id:U,status:"running"};ee.startedAt=(wo=ee.startedAt)!=null?wo:ue((ut=A.startedAt)!=null?ut:A.timestamp);let te=(In=(ar=(Nn=A.text)!=null?Nn:A.delta)!=null?ar:A.message)!=null?In:"";te&&(ee.chunks=(Ir=ee.chunks)!=null?Ir:[],ee.chunks.push(String(te))),ee.status="running",R.toolCall=ee,R.streaming=!0;let G=A.agentContext;(G||A.executionId)&&(R.agentMetadata=(vt=R.agentMetadata)!=null?vt:{executionId:($o=G==null?void 0:G.executionId)!=null?$o:A.executionId,iteration:(Lo=G==null?void 0:G.iteration)!=null?Lo:A.iteration}),p(R)}else if(Ue==="tool_complete"){let U=(Vn=(_n=fe(A,!1))!=null?_n:fe(A,!0))!=null?Vn:`tool-${l()}`;if(ye.has(U)){ye.delete(U);continue}let R=le(U),ee=(wn=R.toolCall)!=null?wn:{id:U,status:"running"};ee.status="complete",A.result!==void 0&&(ee.result=A.result),typeof A.duration=="number"&&(ee.duration=A.duration),ee.completedAt=ue((Rt=A.completedAt)!=null?Rt:A.timestamp);let te=(eo=A.duration)!=null?eo:A.executionTime;if(typeof te=="number")ee.durationMs=te;else{let De=(to=ee.startedAt)!=null?to:Date.now();ee.durationMs=Math.max(0,(($n=ee.completedAt)!=null?$n:Date.now())-De)}R.toolCall=ee,R.streaming=!1;let G=A.agentContext;(G||A.executionId)&&(R.agentMetadata=(zo=R.agentMetadata)!=null?zo:{executionId:(Uo=G==null?void 0:G.executionId)!=null?Uo:A.executionId,iteration:(Io=G==null?void 0:G.iteration)!=null?Io:A.iteration}),p(R);let ze=$(A);ze&&v.byCall.delete(ze)}else if(Ue==="step_await"&&A.awaitReason==="local_tool_required"&&A.toolName){let U=typeof A.toolCallId=="string"&&A.toolCallId.length>0?A.toolCallId:void 0,R=(Un=U!=null?U:A.toolId)!=null?Un:`local-${l()}`,ee=le(R),te=(Wt=ee.toolCall)!=null?Wt:{id:R,status:"pending"};te.name=A.toolName,te.args=A.parameters,te.status="complete",te.chunks=(Cn=te.chunks)!=null?Cn:[],te.startedAt=(qo=te.startedAt)!=null?qo:ue((no=A.startedAt)!=null?no:A.timestamp),te.completedAt=(Ro=te.completedAt)!=null?Ro:te.startedAt,ee.toolCall=te,ee.streaming=!1,ee.agentMetadata={...ee.agentMetadata,executionId:(Co=A.executionId)!=null?Co:(jo=ee.agentMetadata)==null?void 0:jo.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},p(ee)}else if(Ue==="text_start"){if((zn=A.toolContext)!=null&&zn.toolId)continue;let U=A.partId;if(U!==void 0&&C.current!==null&&U!==C.current){let R=f;R&&(R.streaming=!1,p(R),ge=R,f=null,M=!0)}U!==void 0&&(C.current=U)}else if(Ue==="text_end"){if((po=A.toolContext)!=null&&po.toolId)continue;let U=f;U&&(U.streaming=!1,p(U),ge=U,f=null,M=!0)}else if(Ue==="step_chunk"||Ue==="step_delta"){let U=A.stepType,R=A.executionType;if(U==="tool"||R==="context")continue;let ee=A.toolContext;if(ee!=null&&ee.toolId){let De=String((Kt=(ft=A.id)!=null?ft:ee.stepId)!=null?Kt:`step-${l()}`),at=A.partId!==void 0&&A.partId!==null?String(A.partId):"",Ke=`${ee.toolId}::${De}`,Ge=D.get(Ke);if(at!==""&&Ge!==void 0&&Ge!==""&&Ge!==at){let Tt=H.get(w(ee.toolId,De,Ge));Tt&&Tt.streaming!==!1&&(Tt.streaming=!1,p(Tt))}at!==""&&D.set(Ke,at);let Qe=S(ee.toolId,De,at,ee.executionId),Yt=(oo=(Ko=(qn=(Gt=A.text)!=null?Gt:A.delta)!=null?qn:A.content)!=null?Ko:A.chunk)!=null?oo:"";Yt&&(Qe.content+=String(Yt),Qe.streaming=!0,p(Qe)),A.isComplete&&(Qe.streaming=!1,p(Qe));continue}let te=A.partId;if(te!==void 0&&C.current!==null&&te!==C.current){let De=f;De&&(De.streaming=!1,p(De),ge=De,f=null,M=!0)}te!==void 0&&(C.current=te);let G=te!==void 0&&(uo=tt.get(te))!=null?uo:re();te!==void 0&&(G.partId||(G.partId=te),tt.set(te,G));let ze=(mo=(Kn=(T=(jn=A.text)!=null?jn:A.delta)!=null?T:A.content)!=null?Kn:A.chunk)!=null?mo:"";if(ze){let De=typeof A.seq=="number"?A.seq:void 0,at=te!=null?te:G.id,Ke=De!==void 0?ce(at,De,String(ze)):((Po=oe.get(G.id))!=null?Po:"")+ze;G.rawContent=Ke,j.has(G.id)||j.set(G.id,this.createStreamParser());let Ge=j.get(G.id),Qe=Ke.trim().startsWith("{")||Ke.trim().startsWith("[");if(Qe&&oe.set(G.id,Ke),Ge.__isPlainTextParser===!0){G.content=De!==void 0?Ke:G.content+ze,oe.delete(G.id),j.delete(G.id),G.rawContent=void 0,p(G);continue}let Tt=Ge.processChunk(Ke);if(Tt instanceof Promise)Tt.then(Lt=>{var mn;let on=typeof Lt=="string"?Lt:(mn=Lt==null?void 0:Lt.text)!=null?mn:null;if(on!==null&&on.trim()!=="")G.content=on,p(G);else if(!Qe&&!Ke.trim().startsWith("<")){let cn=f,Zt=cn&&cn.id===G.id?cn:G;Zt.id===G.id&&(Zt.content=De!==void 0?Ke:Zt.content+ze,oe.delete(Zt.id),j.delete(Zt.id),Zt.rawContent=void 0,p(Zt))}}).catch(()=>{G.content=De!==void 0?Ke:G.content+ze,oe.delete(G.id),j.delete(G.id),G.rawContent=void 0,p(G)});else{let Lt=typeof Tt=="string"?Tt:(So=Tt==null?void 0:Tt.text)!=null?So:null;Lt!==null&&Lt.trim()!==""?(G.content=Lt,p(G)):!Qe&&!Ke.trim().startsWith("<")&&(G.content=De!==void 0?Ke:G.content+ze,oe.delete(G.id),j.delete(G.id),G.rawContent=void 0,p(G))}}if(A.isComplete){let De=(go=(ss=A.result)==null?void 0:ss.response)!=null?go:G.content;if(De){let at=oe.get(G.id),Ke=at!=null?at:je(De);G.rawContent=Ke;let Ge=j.get(G.id),Qe=null,Yt=!1;if(Ge&&(Qe=Ge.getExtractedText(),Qe===null&&(Qe=wr(Ke)),Qe===null)){let Tt=Ge.processChunk(Ke);Tt instanceof Promise?(Yt=!0,Tt.then(Lt=>{var mn;let on=typeof Lt=="string"?Lt:(mn=Lt==null?void 0:Lt.text)!=null?mn:null;if(on!==null){let cn=f;cn&&cn.id===G.id&&(cn.content=on,cn.streaming=!1,j.delete(cn.id),oe.delete(cn.id),p(cn))}})):Qe=typeof Tt=="string"?Tt:(fo=Tt==null?void 0:Tt.text)!=null?fo:null}if(!Yt){Qe!==null&&Qe.trim()!==""?G.content=Qe:oe.has(G.id)||(G.content=je(De));let Tt=j.get(G.id);if(Tt){let Lt=(ho=Tt.close)==null?void 0:ho.call(Tt);Lt instanceof Promise&&Lt.catch(()=>{}),j.delete(G.id)}oe.delete(G.id),G.streaming=!1,p(G)}}}}else if(Ue==="step_complete"){let U=A.stepType,R=A.executionType;if(U==="tool"||R==="context")continue;let ee=A.toolContext;if(ee!=null&&ee.toolId){let De=String((ir=(Wo=A.id)!=null?Wo:ee.stepId)!=null?ir:"");if(De){let at=E(ee.toolId,De);for(let[Ke,Ge]of H)Ke.startsWith(at)&&Ge.streaming!==!1&&(Ge.streaming=!1,p(Ge));D.delete(`${ee.toolId}::${De}`)}continue}let te=A.stopReason;if(M){if(f!==null){let Ke=f;te&&(Ke.stopReason=te),j.delete(Ke.id),oe.delete(Ke.id),Ke.streaming!==!1&&(Ke.streaming=!1,p(Ke))}let De=(ra=A.result)==null?void 0:ra.response,at=ge;at&&(te&&(at.stopReason=te),De!=null?_e(at,De):(j.delete(at.id),oe.delete(at.id))),ge=null;continue}let G=(as=A.result)==null?void 0:as.response,ze=re();if(te&&(ze.stopReason=te),G!=null){let De=j.get(ze.id),at=!1,Ke=!1;if(De){let Ge=De.getExtractedText(),Qe=oe.get(ze.id),Yt=Qe!=null?Qe:je(G);if(ze.rawContent=Yt,Ge!==null&&Ge.trim()!=="")ze.content=Ge,at=!0;else{let Tt=wr(Yt);if(Tt!==null)ze.content=Tt,at=!0;else{let Lt=De.processChunk(Yt);if(Lt instanceof Promise)Ke=!0,Lt.then(on=>{var cn;let mn=typeof on=="string"?on:(cn=on==null?void 0:on.text)!=null?cn:null;if(mn!==null&&mn.trim()!==""){let Zt=f;Zt&&Zt.id===ze.id&&(Zt.content=mn,Zt.streaming=!1,j.delete(Zt.id),oe.delete(Zt.id),p(Zt))}else{let Zt=De.getExtractedText(),so=f;so&&so.id===ze.id&&(Zt!==null&&Zt.trim()!==""?so.content=Zt:oe.has(so.id)||(so.content=je(G)),so.streaming=!1,j.delete(so.id),oe.delete(so.id),p(so))}});else{let on=typeof Lt=="string"?Lt:(sa=Lt==null?void 0:Lt.text)!=null?sa:null;if(on!==null&&on.trim()!=="")ze.content=on,at=!0;else{let mn=De.getExtractedText();mn!==null&&mn.trim()!==""&&(ze.content=mn,at=!0)}}}}}if(!Ke){if(!ze.rawContent){let Ge=oe.get(ze.id);ze.rawContent=Ge!=null?Ge:je(G)}if(!at&&!oe.has(ze.id)&&(ze.content=je(G)),De){let Ge=(Rr=De.close)==null?void 0:Rr.call(De);Ge instanceof Promise&&Ge.catch(()=>{})}j.delete(ze.id),oe.delete(ze.id),ze.streaming=!1,p(ze)}}else j.delete(ze.id),oe.delete(ze.id),ze.streaming=!1,p(ze)}else if(Ue==="flow_complete"){let U=(mt=A.result)==null?void 0:mt.response;if(M){if(f!==null){let R=f;j.delete(R.id),oe.delete(R.id),R.streaming!==!1&&(R.streaming=!1,p(R))}}else if(U!=null){let R=re(),ee=oe.get(R.id),te=ee!=null?ee:je(U);R.rawContent=te;let G=je(U),ze=j.get(R.id);if(ze){let Ke=wr(te);if(Ke!==null)G=Ke;else{let Ge=ze.processChunk(te);Ge instanceof Promise&&Ge.then(Yt=>{var Lt;let Tt=typeof Yt=="string"?Yt:(Lt=Yt==null?void 0:Yt.text)!=null?Lt:null;Tt!==null&&(R.content=Tt,R.streaming=!1,p(R))});let Qe=ze.getExtractedText();Qe!==null&&(G=Qe)}}j.delete(R.id),oe.delete(R.id);let De=G!==R.content,at=R.streaming!==!1;De&&(R.content=G),R.streaming=!1,(De||at)&&p(R)}else if(f!==null){let R=f;j.delete(R.id),oe.delete(R.id),R.streaming!==!1&&(R.streaming=!1,p(R))}n({type:"status",status:"idle"})}else if(Ue==="agent_start")Q={executionId:A.executionId,agentId:(is=A.agentId)!=null?is:"virtual",agentName:(ro=A.agentName)!=null?ro:"",status:"running",currentIteration:0,maxTurns:(Rn=A.maxTurns)!=null?Rn:1,startedAt:ue(A.startedAt)};else if(Ue==="agent_iteration_start"){if(Q&&(Q.currentIteration=A.iteration),Ln==="separate"&&A.iteration>1){let U=f;U&&(U.streaming=!1,p(U),Fe.set(A.iteration-1,U),f=null)}}else if(Ue==="agent_turn_start")g=null;else if(Ue==="agent_turn_delta"){if(A.contentType==="text"){let U=re();U.content+=(aa=A.delta)!=null?aa:"",U.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId,agentName:Q==null?void 0:Q.agentName},g=U,p(U)}else if(A.contentType==="thinking"){let U=(ia=A.turnId)!=null?ia:`agent-think-${A.iteration}`,R=we(U);R.reasoning=(Pr=R.reasoning)!=null?Pr:{id:U,status:"streaming",chunks:[]},R.reasoning.chunks.push((Bo=A.delta)!=null?Bo:""),R.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId},p(R)}else if(A.contentType==="tool_input"){let U=(la=A.toolCallId)!=null?la:v.lastId;if(U){let R=L.get(U);R!=null&&R.toolCall&&(R.toolCall.chunks=(lr=R.toolCall.chunks)!=null?lr:[],R.toolCall.chunks.push((ls=A.delta)!=null?ls:""),p(R))}}}else if(Ue==="agent_turn_complete"){let U=A.turnId;if(U){let te=W.get(U);if(te!=null&&te.reasoning){te.reasoning.status="complete",te.reasoning.completedAt=ue(A.completedAt);let G=(Ho=te.reasoning.startedAt)!=null?Ho:Date.now();te.reasoning.durationMs=Math.max(0,((cs=te.reasoning.completedAt)!=null?cs:Date.now())-G),te.streaming=!1,p(te)}}let R=A.stopReason,ee=f!=null?f:g;if(R&&ee!==null){let te=A.turnId;(!te||((Go=ee.agentMetadata)==null?void 0:Go.turnId)===te)&&(ee.stopReason=R,p(ee))}}else if(Ue==="agent_tool_start"){f&&(f.streaming=!1,p(f),f=null);let U=(Yo=A.toolCallId)!=null?Yo:`agent-tool-${l()}`;We($(A),U);let R=le(U),ee=(ca=R.toolCall)!=null?ca:{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};ee.name=(Vi=(da=A.toolName)!=null?da:A.name)!=null?Vi:ee.name,ee.status="running",A.parameters!==void 0&&(ee.args=A.parameters),ee.startedAt=ue((cr=A.startedAt)!=null?cr:A.timestamp),R.toolCall=ee,R.streaming=!0,R.agentMetadata={executionId:A.executionId,iteration:A.iteration},p(R)}else if(Ue==="agent_tool_delta"){let U=(Xo=A.toolCallId)!=null?Xo:v.lastId;if(U){let R=(pa=L.get(U))!=null?pa:le(U);R.toolCall&&(R.toolCall.chunks=(ds=R.toolCall.chunks)!=null?ds:[],R.toolCall.chunks.push((Qo=A.delta)!=null?Qo:""),R.toolCall.status="running",R.streaming=!0,p(R))}}else if(Ue==="agent_tool_complete"){let U=(ua=A.toolCallId)!=null?ua:v.lastId;if(U){let R=(ps=L.get(U))!=null?ps:le(U);if(R.toolCall){R.toolCall.status="complete",A.result!==void 0&&(R.toolCall.result=A.result),typeof A.executionTime=="number"&&(R.toolCall.durationMs=A.executionTime),R.toolCall.completedAt=ue((Jo=A.completedAt)!=null?Jo:A.timestamp),R.streaming=!1,p(R);let ee=$(A);ee&&v.byCall.delete(ee)}}}else if(Ue==="agent_media"){let U=Array.isArray(A.media)?A.media:[],R=[];for(let ee of U){if(!ee||typeof ee!="object")continue;let te=ee,G=typeof te.type=="string"?te.type:void 0,ze=typeof te.mediaType=="string"?te.mediaType.toLowerCase():"",De=null,at="";if(G==="media"){let Ke=typeof te.data=="string"?te.data:void 0;if(!Ke)continue;at=ze.length>0?ze:"application/octet-stream",De=`data:${at};base64,${Ke}`}else if(G==="image-url"){let Ke=typeof te.url=="string"?te.url:void 0;if(!Ke)continue;at=ze,De=Ke}else if(G==="file-url"){let Ke=typeof te.url=="string"?te.url:void 0;if(!Ke)continue;at=ze,De=Ke}else continue;if(De)if(G==="image-url"||at.startsWith("image/"))R.push({type:"image",image:De,...at?{mimeType:at}:{}});else if(at.startsWith("audio/"))R.push({type:"audio",audio:De,mimeType:at});else if(at.startsWith("video/"))R.push({type:"video",video:De,mimeType:at});else{let Ke=at||"application/octet-stream";R.push({type:"file",data:De,mimeType:Ke,filename:Kf(Ke)})}}if(R.length>0){let ee=l(),te=A.toolCallId,ze={id:`agent-media-${typeof te=="string"&&te.length>0?`${te}-${ee}`:String(ee)}`,role:"assistant",content:"",contentParts:R,createdAt:new Date().toISOString(),streaming:!1,sequence:ee,agentMetadata:{executionId:A.executionId,iteration:A.iteration}};p(ze);let De=f;De&&(De.streaming=!1,p(De)),f=null,x.current=null}}else if(Ue!=="agent_iteration_complete"){if(Ue==="agent_reflection"||Ue==="agent_reflect"){let U=`agent-reflection-${A.executionId}-${A.iteration}`,R={id:U,role:"assistant",content:(us=A.reflection)!=null?us:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:U,status:"complete",chunks:[(ma=A.reflection)!=null?ma:""]},agentMetadata:{executionId:A.executionId,iteration:A.iteration}};p(R)}else if(Ue==="agent_complete"){Q&&(Q.status=A.success?"complete":"error",Q.completedAt=ue(A.completedAt),Q.stopReason=A.stopReason);let U=f;U&&(U.streaming=!1,p(U)),n({type:"status",status:"idle"})}else if(Ue==="agent_error"){let U=typeof A.error=="string"?A.error:(ga=(Do=A.error)==null?void 0:Do.message)!=null?ga:"Agent execution error";A.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",U):n({type:"error",error:new Error(U)})}else if(Ue!=="agent_ping"){if(Ue==="agent_approval_start"){let U=(Zo=A.approvalId)!=null?Zo:`approval-${l()}`,R={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(Bt=Q==null?void 0:Q.agentId)!=null?Bt:"virtual",executionId:(Br=(Wr=A.executionId)!=null?Wr:Q==null?void 0:Q.executionId)!=null?Br:"",toolName:(ms=A.toolName)!=null?ms:"",toolType:A.toolType,description:(fa=A.description)!=null?fa:`Execute ${(Ao=A.toolName)!=null?Ao:"tool"}`,parameters:A.parameters}};p(R)}else if(Ue==="step_await"&&A.awaitReason==="approval_required"){let U=(gs=A.approvalId)!=null?gs:`approval-${l()}`,R={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(fs=Q==null?void 0:Q.agentId)!=null?fs:"virtual",executionId:(Hr=(ha=A.executionId)!=null?ha:Q==null?void 0:Q.executionId)!=null?Hr:"",toolName:(Dr=A.toolName)!=null?Dr:"",toolType:A.toolType,description:(ba=A.description)!=null?ba:`Execute ${(dr=A.toolName)!=null?dr:"tool"}`,parameters:A.parameters}};p(R)}else if(Ue==="agent_approval_complete"){let U=A.approvalId;if(U){let ee={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:(ya=A.decision)!=null?ya:"approved",agentId:(hs=Q==null?void 0:Q.agentId)!=null?hs:"virtual",executionId:(ys=(bs=A.executionId)!=null?bs:Q==null?void 0:Q.executionId)!=null?ys:"",toolName:(vs=A.toolName)!=null?vs:"",description:(Sn=A.description)!=null?Sn:"",resolvedAt:Date.now()}};p(ee)}}else if(Ue==="artifact_start"||Ue==="artifact_delta"||Ue==="artifact_update"||Ue==="artifact_complete"){if(Ue==="artifact_start"){let U=A.artifactType,R=String(A.id),ee=typeof A.title=="string"?A.title:void 0;if(n({type:"artifact_start",id:R,artifactType:U,title:ee,component:typeof A.component=="string"?A.component:void 0}),X.set(R,{markdown:"",title:ee}),!Ee.has(R)){Ee.add(R);let te={id:`artifact-ref-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:R,title:ee,artifactType:U,status:"streaming"}})};Z.set(R,te),p(te)}}else if(Ue==="artifact_delta"){let U=String(A.id),R=typeof A.delta=="string"?A.delta:String((Gn=A.delta)!=null?Gn:"");n({type:"artifact_delta",id:U,artDelta:R});let ee=X.get(U);ee&&(ee.markdown+=R)}else if(Ue==="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(Ue==="artifact_complete"){let U=String(A.id);n({type:"artifact_complete",id:U});let R=Z.get(U);if(R){R.streaming=!1;try{let ee=JSON.parse((Fo=R.rawContent)!=null?Fo:"{}");if(ee.props){ee.props.status="complete";let te=X.get(U);te!=null&&te.markdown&&(ee.props.markdown=te.markdown)}R.rawContent=JSON.stringify(ee)}catch{}X.delete(U),p(R),Z.delete(U)}}}else if(Ue==="transcript_insert"){let U=A.message;if(!U||typeof U!="object")continue;let R=String((rt=U.id)!=null?rt:`msg-${l()}`),ee=U.role,G={id:R,role:ee==="user"?"user":ee==="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(p(G),G.rawContent)try{let ze=JSON.parse(G.rawContent),De=(xs=ze==null?void 0:ze.props)==null?void 0:xs.artifactId;typeof De=="string"&&Ee.add(De)}catch{}f=null,x.current=null,j.delete(R),oe.delete(R)}else if(Ue==="error"||Ue==="step_error"||Ue==="dispatch_error"||Ue==="flow_error"){let U=null;if(A.error instanceof Error)U=A.error;else if(Ue==="dispatch_error"){let R=(pr=A.message)!=null?pr:A.error;R!=null&&R!==""&&(U=new Error(String(R)))}else if(Ue==="step_error"||Ue==="flow_error"){let R=A.error;typeof R=="string"&&R!==""?U=new Error(R):R!=null&&typeof R=="object"&&"message"in R&&(U=new Error(String((bo=R.message)!=null?bo:R)))}else Ue==="error"&&A.error!=null&&A.error!==""&&(U=new Error(String(A.error)));if(U){n({type:"error",error:U});let R=f;R&&R.streaming&&(R.streaming=!1,p(R)),n({type:"status",status:"idle"})}}}}}Le.length=0};;){let{done:N,value:se}=await r.read();if(N)break;a+=s.decode(se,{stream:!0});let He=a.split(`
|
|
10
10
|
|
|
11
11
|
`);a=(ln=He.pop())!=null?ln:"";for(let Xe of He){let Oe=Xe.split(`
|
|
12
|
-
`),Ne="message",ot="";for(let jt of Oe)jt.startsWith("event:")?Ne=jt.replace("event:","").trim():jt.startsWith("data:")&&(ot+=jt.replace("data:","").trim());if(!ot)continue;let St;try{St=JSON.parse(ot)}catch(jt){n({type:"error",error:jt instanceof Error?jt:new Error("Failed to parse chat stream payload")});continue}let Nt=Ne!=="message"?Ne:(Dn=St.type)!=null?Dn:"message";if((Jn=this.onSSEEvent)==null||Jn.call(this,Nt,St),this.parseSSEEvent){w.current=g;let jt=await this.handleCustomSSEEvent(St,n,w,p,l,x);if(w.current&&w.current!==g&&(g=w.current),jt)continue}Ct.push(Nt,St),Y()}}Ct.flushPending(),Y(),Ct.destroy()}};function Ga(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Ws(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ya="[Image]";function il(e){return{type:"text",text:e}}var Mu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Kg=["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=[...Mu,...Kg];function Gg(e){return Mu.includes(e)||e.startsWith("image/")}function Xa(e){return Gg(e.type)}async function Lu(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Xa(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 Iu(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 Yg(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Ru(e,t){let n=Yg(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 Qa=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 Ja=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,o,r,s){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(n),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let u=0;u<a.length;u++)i+=a[u]*a[u];let d=Math.sqrt(i/a.length);(o==="silence"?d<r.threshold:d>=r.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=r.duration&&(this.fired=!0,s()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Bs=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new Ja;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,n,o;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let r=this.w;if(!r||!r.location)throw new Error("Window object or location not available");let s=r.location.protocol==="https:"?"wss:":"ws:",a=(t=this.config)==null?void 0:t.host,i=(n=this.config)==null?void 0:n.agentId,d=(o=this.config)==null?void 0:o.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let u=`${s}//${a}/ws/agents/${i}/voice?token=...`,p=" 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 w=!1,x=P=>{w||(w=!0,clearTimeout(M),m(new Error(P)))},M=setTimeout(()=>x("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{w||(w=!0,clearTimeout(M),g())},{once:!0}),this.ws.addEventListener("error",()=>{x("WebSocket connection failed to "+u+"."+p)},{once:!0}),this.ws.addEventListener("close",P=>{if(!P.wasClean&&!w){let W=P.code!==1006?` (code ${P.code})`:"";x("WebSocket connection failed"+W+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(r){throw this.ws=null,this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(n=>n(new Error("WebSocket error"))),this.statusCallbacks.forEach(n=>n("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let n=JSON.parse(t.data);this.handleWebSocketMessage(n)}catch{this.errorCallbacks.forEach(o=>o(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var n,o;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(r=>r({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),(n=t.response.audio)!=null&&n.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(r=>r("speaking")),this.playAudio(t.response.audio).catch(r=>this.errorCallbacks.forEach(s=>s(r instanceof Error?r:new Error(String(r)))))):(o=t.response.audio)!=null&&o.base64;break;case"audio_end":if(t.requestId&&t.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(r=>r("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(r=>r(new Error(t.error))),this.statusCallbacks.forEach(r=>r("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Qa(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 u=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:u});await this.sendAudio(p),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var s,a;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let n=this.audioContext,o=(a=(s=this.config)==null?void 0:s.silenceThreshold)!=null?a:.01;this.vad.start(n,this.mediaStream,"speech",{threshold:o,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(n=>n(t instanceof Error?t:new Error(String(t))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(t){var n;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(o=>o(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(o=>o("error"));return}try{let o=await this.blobToBase64(t),r=this.getFormatFromMimeType(t.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:o,format:r,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:s}))}catch(o){this.errorCallbacks.forEach(r=>r(o)),this.statusCallbacks.forEach(r=>r("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,o)=>{let r=new FileReader;r.onload=()=>{let a=r.result.split(",")[1];n(a)},r.onerror=o,r.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let n=atob(t.base64),o=new Uint8Array(n.length);for(let l=0;l<n.length;l++)o[l]=n.charCodeAt(l);let r=t.format||"mp3",s=r==="mp3"?"audio/mpeg":`audio/${r}`,a=new Blob([o],{type:s}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Cr=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let o=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!o)throw new Error("Browser speech recognition not supported");this.recognition=new o,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=r=>{var i;let s=Array.from(r.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=r.results[r.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=r=>{this.errorCallbacks.forEach(s=>s(new Error(r.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(r=>r("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(r=>r("idle"))},this.recognition.start()}catch(o){throw this.errorCallbacks.forEach(r=>r(o)),this.statusCallbacks.forEach(r=>r("error")),o}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Hs(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Bs(e.runtype);case"browser":if(!Cr.isSupported())throw new Error("Browser speech recognition not supported");return new Cr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Pu(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Hs({type:"runtype",runtype:e.runtype});if(Cr.isSupported())return Hs({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function ll(e){try{return Pu(e),!0}catch{return!1}}function Wu(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}
|
|
12
|
+
`),Ne="message",ot="";for(let jt of Oe)jt.startsWith("event:")?Ne=jt.replace("event:","").trim():jt.startsWith("data:")&&(ot+=jt.replace("data:","").trim());if(!ot)continue;let St;try{St=JSON.parse(ot)}catch(jt){n({type:"error",error:jt instanceof Error?jt:new Error("Failed to parse chat stream payload")});continue}let Nt=Ne!=="message"?Ne:(Dn=St.type)!=null?Dn:"message";if((Jn=this.onSSEEvent)==null||Jn.call(this,Nt,St),this.parseSSEEvent){x.current=f;let jt=await this.handleCustomSSEEvent(St,n,x,p,l,C);if(x.current&&x.current!==f&&(f=x.current),jt)continue}Ct.push(Nt,St),Y()}}Ct.flushPending(),Y(),Ct.destroy()}};function Ga(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Ws(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ya="[Image]";function il(e){return{type:"text",text:e}}var Iu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Xf=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],_o=[...Iu,...Xf];function Qf(e){return Iu.includes(e)||e.startsWith("image/")}function Xa(e){return Qf(e.type)}async function Ru(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Xa(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function Pu(e,t=_o,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Jf(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Wu(e,t){let n=Jf(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var Qa=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 Ja=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,o,r,s){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(n),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let u=0;u<a.length;u++)i+=a[u]*a[u];let d=Math.sqrt(i/a.length);(o==="silence"?d<r.threshold:d>=r.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=r.duration&&(this.fired=!0,s()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Bs=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new Ja;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,n,o;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let r=this.w;if(!r||!r.location)throw new Error("Window object or location not available");let s=r.location.protocol==="https:"?"wss:":"ws:",a=(t=this.config)==null?void 0:t.host,i=(n=this.config)==null?void 0:n.agentId,d=(o=this.config)==null?void 0:o.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let u=`${s}//${a}/ws/agents/${i}/voice?token=...`,p=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,g)=>{if(!this.ws)return g(new Error("WebSocket not created"));let x=!1,C=W=>{x||(x=!0,clearTimeout(M),g(new Error(W)))},M=setTimeout(()=>C("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{x||(x=!0,clearTimeout(M),f())},{once:!0}),this.ws.addEventListener("error",()=>{C("WebSocket connection failed to "+u+"."+p)},{once:!0}),this.ws.addEventListener("close",W=>{if(!W.wasClean&&!x){let L=W.code!==1006?` (code ${W.code})`:"";C("WebSocket connection failed"+L+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(r){throw this.ws=null,this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(n=>n(new Error("WebSocket error"))),this.statusCallbacks.forEach(n=>n("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let n=JSON.parse(t.data);this.handleWebSocketMessage(n)}catch{this.errorCallbacks.forEach(o=>o(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var n,o;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(r=>r({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),(n=t.response.audio)!=null&&n.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(r=>r("speaking")),this.playAudio(t.response.audio).catch(r=>this.errorCallbacks.forEach(s=>s(r instanceof Error?r:new Error(String(r)))))):(o=t.response.audio)!=null&&o.base64;break;case"audio_end":if(t.requestId&&t.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(r=>r("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(r=>r(new Error(t.error))),this.statusCallbacks.forEach(r=>r("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Qa(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,n,o,r;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(r=(o=this.config)==null?void 0:o.silenceThreshold)!=null?r:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let u=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:u});await this.sendAudio(p),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var s,a;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let n=this.audioContext,o=(a=(s=this.config)==null?void 0:s.silenceThreshold)!=null?a:.01;this.vad.start(n,this.mediaStream,"speech",{threshold:o,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(n=>n(t instanceof Error?t:new Error(String(t))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(t){var n;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(o=>o(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(o=>o("error"));return}try{let o=await this.blobToBase64(t),r=this.getFormatFromMimeType(t.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:o,format:r,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:s}))}catch(o){this.errorCallbacks.forEach(r=>r(o)),this.statusCallbacks.forEach(r=>r("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,o)=>{let r=new FileReader;r.onload=()=>{let a=r.result.split(",")[1];n(a)},r.onerror=o,r.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let n=atob(t.base64),o=new Uint8Array(n.length);for(let l=0;l<n.length;l++)o[l]=n.charCodeAt(l);let r=t.format||"mp3",s=r==="mp3"?"audio/mpeg":`audio/${r}`,a=new Blob([o],{type:s}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Cr=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let o=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!o)throw new Error("Browser speech recognition not supported");this.recognition=new o,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=r=>{var i;let s=Array.from(r.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=r.results[r.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=r=>{this.errorCallbacks.forEach(s=>s(new Error(r.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(r=>r("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(r=>r("idle"))},this.recognition.start()}catch(o){throw this.errorCallbacks.forEach(r=>r(o)),this.statusCallbacks.forEach(r=>r("error")),o}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Hs(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Bs(e.runtype);case"browser":if(!Cr.isSupported())throw new Error("Browser speech recognition not supported");return new Cr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Bu(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Hs({type:"runtype",runtype:e.runtype});if(Cr.isSupported())return Hs({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function ll(e){try{return Bu(e),!0}catch{return!1}}function Hu(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let o="Sorry \u2014 I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
|
|
13
13
|
|
|
14
|
-
_Details: ${n.message}_`:o}var Za=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 u=t.message.toolCall;((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&(u!=null&&u.name)&&rl(u.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 u=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":u||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var o,r;this.messages=[...(o=t.initialMessages)!=null?o:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Ps(t),this.wireDefaultWebMcpConfirm();for(let s of(r=t.initialArtifacts)!=null?r:[])this.artifacts.set(s.id,{...s,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return ll((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,o;return(o=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?o:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(t){var n,o,r;try{let s=t||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=Hs(s);let a=(n=this.config.voiceRecognition)!=null?n:{},i=(o=a.processingText)!=null?o:"\u{1F3A4} Processing voice...",d=(r=a.processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var u,p,g,m,w,x;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((u=l.transcript)!=null&&u.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=l.transcript)!=null&&p.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((g=l.text)!=null&&g.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=l.text)!=null&&m.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let M=(x=this.pendingVoiceAssistantMessageId)!=null?x:(w=[...this.messages].reverse().find(P=>P.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 u,p;this.voiceStatus=l,this.voiceActive=l==="listening",(p=(u=this.callbacks).onVoiceStatusChanged)==null||p.call(u,l)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,o,r,s,a,i,d,l,u;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((o=t.runtype)==null?void 0:o.agentId)||"",clientToken:((r=t.runtype)==null?void 0:r.clientToken)||"",host:(s=t.runtype)==null?void 0:s.host,voiceId:(a=t.runtype)==null?void 0:a.voiceId,pauseDuration:(i=t.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=t.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=t.browser)==null?void 0:l.language)||"en-US",continuous:(u=t.browser)==null?void 0:u.continuous}};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let o=await this.client.initSession();return this.setClientSession(o),o}catch(o){return(n=(t=this.callbacks).onError)==null||n.call(t,o instanceof Error?o:new Error(String(o))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let n=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new Ps(this.config),this.wireDefaultWebMcpConfirm(),n&&this.client.setSSEEventCallback(n)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:u,rawContent:p}=t,m={id:a!=null?a:n==="user"?Ga():n==="assistant"?Ws():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...p!==void 0&&{rawContent:p}};return this.upsertMessage(m),m}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:u,streaming:p=!1,voiceProcessing:g,rawContent:m}=o,x={id:d!=null?d:r==="user"?Ga():r==="assistant"?Ws():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:p,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...m!==void 0&&{rawContent:m}};n.push(x)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:i,sequence:d}=t,l={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(l),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var l,u,p,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=Ga(),s=Ws(),a={id:r,role:"user",content:o||Ya,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 x=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));if(!x){let M=Wu(w,this.config.errorMessage);if(M){let P={id:s,role:"assistant",createdAt:new Date().toISOString(),content:M,sequence:this.nextSequence()};this.appendMessage(P)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(w instanceof Error?(p=(u=this.callbacks).onError)==null||p.call(u,w):(m=(g=this.callbacks).onError)==null||m.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=Ws();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(l){let u=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!u){let p=Wu(l,this.config.errorMessage);if(p){let g={id:t,role:"assistant",createdAt:new Date().toISOString(),content:p,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var r,s,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(r=this.abortController)==null||r.abort();let o=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var r,s,a;try{if(((s=(r=this.config.webmcp)==null?void 0:r.autoApprove)==null?void 0:s.call(r,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(o,i)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r!=null&&r.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n){var d,l,u,p;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 m=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}`)}m=g.body}else g instanceof ReadableStream&&(m=g);m?await this.connectStream(m,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(g){let m=g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||(p=(u=this.callbacks).onError)==null||p.call(u,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 u,p,g,m,w,x,M,P,W,H,_,B;let o=this.messages.find(v=>v.id===t.id);if(((u=o==null?void 0:o.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let r=(p=t.agentMetadata)==null?void 0:p.executionId,s=(g=t.toolCall)==null?void 0:g.name;if(!r||!s){(w=(m=this.callbacks).onError)==null||w.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 v=(x=t.toolCall)==null?void 0:x.args,C=Array.isArray(v==null?void 0:v.questions)?v.questions:[];if(C.length===1){let E=typeof((M=C[0])==null?void 0:M.question)=="string"?C[0].question:"";E&&(a={[E]:n})}}this.markAskUserQuestionResolved(t,a),(P=this.abortController)==null||P.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(W=t.toolCall)==null?void 0:W.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(([C,E])=>`${C}: ${Array.isArray(E)?E.join(", "):E}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:v,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let v=a!=null?a:{};l.forEach((C,E)=>{let S=typeof(C==null?void 0:C.question)=="string"?C.question:"";if(!S)return;let k=v[S],D=Array.isArray(k)?k.join(", "):typeof k=="string"?k:"";this.appendMessage({id:`ask-user-q-${i}-${E}`,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${E}`,role:"user",content:D||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let v=await this.client.resumeFlow(r,{[s]:n});if(!v.ok){let C=await v.json().catch(()=>null);throw new Error((H=C==null?void 0:C.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 C=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,C||(B=(_=this.callbacks).onError)==null||B.call(_,v instanceof Error?v:new Error(String(v)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,o=(a=t.toolCall)==null?void 0:a.id;if(!n||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}async resolveWebMcpToolCallBatch(t,n){var i,d,l;let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async u=>{var W,H,_,B,v,C,E;let p=(W=u.toolCall)==null?void 0:W.name,g=(H=u.toolCall)==null?void 0:H.id;if(!p||!g)return null;let m=`${t}:${g}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m))return null;this.webMcpInflightKeys.add(m),o.push(m),this.upsertMessage({...u,agentMetadata:{...u.agentMetadata,awaitingLocalTool:!1}});let w=new AbortController;this.webMcpResolveControllers.add(w),r.push(w);let x=(B=(_=u.agentMetadata)==null?void 0:_.webMcpToolCallId)!=null?B:p,M=this.client.executeWebMcpToolCall(p,(v=u.toolCall)==null?void 0:v.args,w.signal),P;if(!M)P={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{P=await M}catch(S){return S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"))||(E=(C=this.callbacks).onError)==null||E.call(C,S instanceof Error?S:new Error(String(S))),this.webMcpInflightKeys.delete(m),null}return w.signal.aborted?(this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:x,output:P}}));try{let u=a.filter(m=>m!==null);if(u.length===0)return;let p={};for(let m of u)p[m.resumeKey]=m.output;let g=await this.client.resumeFlow(t,p,{signal:s.signal});if(!g.ok){let m=await g.json().catch(()=>null);throw new Error((i=m==null?void 0:m.error)!=null?i:`Resume failed: ${g.status}`)}for(let m of u)this.webMcpResolvedKeys.add(m.dedupeKey);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(u){u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))||(l=(d=this.callbacks).onError)==null||l.call(d,u instanceof Error?u:new Error(String(u)))}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 u,p,g,m,w,x,M,P,W,H,_,B;let n=(u=t.agentMetadata)==null?void 0:u.executionId,o=(p=t.toolCall)==null?void 0:p.name,r=(g=t.toolCall)==null?void 0:g.id;if(!n){(w=(m=this.callbacks).onError)==null||w.call(m,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!o)return;if(!r){let v=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v))return;this.webMcpInflightKeys.add(v);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(v)}catch(C){(M=(x=this.callbacks).onError)==null||M.call(x,C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(v)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s))return;this.webMcpInflightKeys.add(s),this.upsertMessage({...t,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1}});let a=new AbortController;this.webMcpResolveControllers.add(a);let{signal:i}=a;this.setStreaming(!0);let d=(P=t.toolCall)==null?void 0:P.args,l=this.client.executeWebMcpToolCall(o,d,i);try{let v;if(l?v=await l:v={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},i.aborted)return;let C=(H=(W=t.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?H:o;await this.resumeWithToolOutput(n,C,v,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s)},signal:i})}catch(v){v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"))||(B=(_=this.callbacks).onError)==null||B.call(_,v instanceof Error?v:new Error(String(v)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){var a,i;let s=await this.client.resumeFlow(t,{[n]:o},{signal:r==null?void 0:r.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=r==null?void 0:r.onHttpOk)==null||i.call(r),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var r;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let o={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(r=t.props)!=null?r:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),o}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,o;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let r=this.artifacts.get(t.id);(r==null?void 0:r.artifactType)==="markdown"&&(r.markdown=((o=r.markdown)!=null?o:"")+t.artDelta);break}case"artifact_update":{let r=this.artifacts.get(t.id);(r==null?void 0:r.artifactType)==="component"&&(r.props={...r.props,...t.props},t.component&&(r.component=t.component));break}case"artifact_complete":{let r=this.artifacts.get(t.id);r&&(r.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>{var r;return{...o,streaming:!1,sequence:(r=o.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=o.content;r.trim()&&this.speak(r,t)}speak(t,n){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t),s=o.getVoices();if(n.voice){let a=s.find(i=>i.name===n.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=n.pickVoice?n.pickVoice(s):e.pickBestVoice(s));n.rate!==void 0&&(r.rate=n.rate),n.pitch!==void 0&&(r.pitch=n.pitch),setTimeout(()=>o.speak(r),50)}static pickBestVoice(t){var o;let n=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of n){let s=t.find(a=>a.name===r);if(s)return s}return(o=t.find(r=>r.lang.startsWith("en")))!=null?o:t[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{var u,p,g,m,w,x;if(s!==o)return r;let a={...r,...n};((u=r.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(p=n.toolCall)==null?void 0:p.name,d=(g=n.agentMetadata)==null?void 0:g.executionId,l=(m=n.toolCall)==null?void 0:m.id;if(i&&rl(i)&&d&&l&&((w=n.agentMetadata)==null?void 0:w.awaitingLocalTool)===!0){let M=`${d}:${l}`;(this.webMcpInflightKeys.has(M)||this.webMcpResolvedKeys.has(M))&&(a.agentMetadata={...(x=a.agentMetadata)!=null?x:{},awaitingLocalTool:!1})}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{var d,l;let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=(d=n.sequence)!=null?d:0,i=(l=o.sequence)!=null?l:0;return a!==i?a-i:n.id.localeCompare(o.id)})}};var b=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Eo=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o};import{Activity as Xg,ArrowDown as Qg,ArrowUp as Jg,ArrowUpRight as Zg,Bot as eh,ChevronDown as th,ChevronUp as nh,ChevronRight as oh,ChevronLeft as rh,Check as sh,Clipboard as ah,ClipboardCopy as ih,Copy as lh,File as ch,FileCode as dh,FileSpreadsheet as ph,FileText as uh,ImagePlus as mh,Loader as fh,LoaderCircle as gh,Mic as hh,Paperclip as bh,RefreshCw as yh,Search as vh,Send as xh,ShieldAlert as wh,ShieldCheck as Ch,ShieldX as Sh,Square as Ah,ThumbsDown as Th,ThumbsUp as kh,Upload as Eh,Volume2 as Mh,X as Lh,User as Ih,Mail as Rh,Phone as Ph,Calendar as Wh,Clock as Bh,Building as Hh,MapPin as Dh,Lock as Fh,Key as Oh,CreditCard as Nh,AtSign as _h,Hash as Vh,Globe as $h,Link as Uh,CircleCheck as zh,CircleX as qh,TriangleAlert as jh,Info as Kh,Ban as Gh,Shield as Yh,ArrowLeft as Xh,ArrowRight as Qh,ExternalLink as Jh,Ellipsis as Zh,EllipsisVertical as eb,Menu as tb,House as nb,Plus as ob,Minus as rb,Pencil as sb,Trash as ab,Trash2 as ib,Save as lb,Download as cb,Share as db,Funnel as pb,Settings as ub,RotateCw as mb,Maximize as fb,Minimize as gb,ShoppingCart as hb,ShoppingBag as bb,Package as yb,Truck as vb,Tag as xb,Gift as wb,Receipt as Cb,Wallet as Sb,Store as Ab,DollarSign as Tb,Percent as kb,Play as Eb,Pause as Mb,VolumeX as Lb,Camera as Ib,Image as Rb,Film as Pb,Headphones as Wb,MessageCircle as Bb,MessageSquare as Hb,Bell as Db,Heart as Fb,Star as Ob,Eye as Nb,EyeOff as _b,Bookmark as Vb,CalendarDays as $b,History as Ub,Timer as zb,Folder as qb,FolderOpen as jb,Files as Kb,Sparkles as Gb,Zap as Yb,Sun as Xb,Moon as Qb,Flag as Jb,Monitor as Zb,Smartphone as ey}from"lucide";var ty={activity:Xg,"arrow-down":Qg,"arrow-up":Jg,"arrow-up-right":Zg,bot:eh,"chevron-down":th,"chevron-up":nh,"chevron-right":oh,"chevron-left":rh,check:sh,clipboard:ah,"clipboard-copy":ih,copy:lh,file:ch,"file-code":dh,"file-spreadsheet":ph,"file-text":uh,"image-plus":mh,loader:fh,"loader-circle":gh,mic:hh,paperclip:bh,"refresh-cw":yh,search:vh,send:xh,"shield-alert":wh,"shield-check":Ch,"shield-x":Sh,square:Ah,"thumbs-down":Th,"thumbs-up":kh,upload:Eh,"volume-2":Mh,x:Lh,user:Ih,mail:Rh,phone:Ph,calendar:Wh,clock:Bh,building:Hh,"map-pin":Dh,lock:Fh,key:Oh,"credit-card":Nh,"at-sign":_h,hash:Vh,globe:$h,link:Uh,"circle-check":zh,"circle-x":qh,"triangle-alert":jh,info:Kh,ban:Gh,shield:Yh,"arrow-left":Xh,"arrow-right":Qh,"external-link":Jh,ellipsis:Zh,"ellipsis-vertical":eb,menu:tb,house:nb,plus:ob,minus:rb,pencil:sb,trash:ab,"trash-2":ib,save:lb,download:cb,share:db,funnel:pb,settings:ub,"rotate-cw":mb,maximize:fb,minimize:gb,"shopping-cart":hb,"shopping-bag":bb,package:yb,truck:vb,tag:xb,gift:wb,receipt:Cb,wallet:Sb,store:Ab,"dollar-sign":Tb,percent:kb,play:Eb,pause:Mb,"volume-x":Lb,camera:Ib,image:Rb,film:Pb,headphones:Wb,"message-circle":Bb,"message-square":Hb,bell:Db,heart:Fb,star:Ob,eye:Nb,"eye-off":_b,bookmark:Vb,"calendar-days":$b,history:Ub,timer:zb,folder:qb,"folder-open":jb,files:Kb,sparkles:Gb,zap:Yb,sun:Xb,moon:Qb,flag:Jb,monitor:Zb,smartphone:ey},Se=(e,t=24,n="currentColor",o=2)=>{let r=ty[e];return r?ny(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 ny(e,t,n,o){if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,u])=>{l!=="stroke"&&d.setAttribute(l,String(u))}),r.appendChild(d)}),r}var ei={allowedTypes:_o,maxFileSize:10*1024*1024,maxFiles:4};function oy(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function ry(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var Ds=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,o,r;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:ei.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:ei.maxFileSize,maxFiles:(r=t.maxFiles)!=null?r:ei.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:ei.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,o,r,s,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(o=(n=this.config).onFileRejected)==null||o.call(n,l,"count");continue}let u=Iu(l,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let p=(r=u.error)!=null&&r.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,p);continue}try{let p=await Lu(l),g=Xa(l)?URL.createObjectURL(l):null,m={id:oy(),file:l,previewUrl:g,contentPart:p};this.attachments.push(m),this.renderPreview(m)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let o of this.attachments)o.previewUrl&&URL.revokeObjectURL(o.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Xa(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=ry(t.file.type),d=Se(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=b("span");l.textContent=Ru(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=Se("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};import{Idiomorph as sy}from"idiomorph";var ti=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;sy.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){var a,i;if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=r.textContent)!=null?a:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var ni={index:-1,draft:""};function Bu(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:{...ni}}}function Hu(e,t){var n,o,r,s,a,i,d,l,u,p,g,m,w,x,M,P,W,H,_,B,v,C,E,S,k,D,$,q,me,re,be,ie,we,We,ye,Z,Ee,X;return[e.id,e.role,(o=(n=e.content)==null?void 0:n.length)!=null?o:0,(s=(r=e.content)==null?void 0:r.slice(-32))!=null?s:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(u=(l=e.llmContent)==null?void 0:l.length)!=null?u:0,(g=(p=e.approval)==null?void 0:p.status)!=null?g:"",(w=(m=e.toolCall)==null?void 0:m.status)!=null?w:"",(M=(x=e.toolCall)==null?void 0:x.name)!=null?M:"",(H=(W=(P=e.toolCall)==null?void 0:P.chunks)==null?void 0:W.length)!=null?H:0,(C=(v=(B=(_=e.toolCall)==null?void 0:_.chunks)==null?void 0:B[e.toolCall.chunks.length-1])==null?void 0:v.slice(-32))!=null?C:"",typeof((E=e.toolCall)==null?void 0:E.args)=="string"?e.toolCall.args.length:(S=e.toolCall)!=null&&S.args?JSON.stringify(e.toolCall.args).length:0,($=(D=(k=e.reasoning)==null?void 0:k.chunks)==null?void 0:D.length)!=null?$:0,(be=(re=(me=(q=e.reasoning)==null?void 0:q.chunks)==null?void 0:me[e.reasoning.chunks.length-1])==null?void 0:re.length)!=null?be:0,(ye=(We=(we=(ie=e.reasoning)==null?void 0:ie.chunks)==null?void 0:we[e.reasoning.chunks.length-1])==null?void 0:We.slice(-32))!=null?ye:"",(Ee=(Z=e.contentParts)==null?void 0:Z.length)!=null?Ee:0,(X=e.stopReason)!=null?X:"",t].join("\0")}function Du(){return new Map}function Fu(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function Ou(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Nu(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function oi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Fs(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Os(e,t){return Fs(e)-e.scrollTop<=t}function ri(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,u=n-o;return a||Math.abs(u)<s?{action:"none",delta:u,nextLastScrollTop:n}:!t&&r&&(!l||u>0)?{action:"resume",delta:u,nextLastScrollTop:n}:t&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:n}:t&&d&&!r?{action:"pause",delta:u,nextLastScrollTop:n}:{action:"none",delta:u,nextLastScrollTop:n}}function si(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}var hn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},bn=1e5,nr=bn+1;var Ns={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},ay=["pre","code","a","script","style"],ai=e=>{var t,n,o,r,s;return{type:(t=e==null?void 0:e.type)!=null?t:Ns.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:Ns.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:Ns.speed,duration:(r=e==null?void 0:e.duration)!=null?r:Ns.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:Ns.buffer}},iy=[{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"}],Vu=new Map;for(let e of iy)Vu.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=Vu.get(e))!=null?o:null},ii=(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 Za=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 u=t.message.toolCall;((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&(u!=null&&u.name)&&rl(u.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 u=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":u||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var o,r;this.messages=[...(o=t.initialMessages)!=null?o:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Ps(t),this.wireDefaultWebMcpConfirm();for(let s of(r=t.initialArtifacts)!=null?r:[])this.artifacts.set(s.id,{...s,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return ll((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,o;return(o=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?o:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(t){var n,o,r;try{let s=t||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=Hs(s);let a=(n=this.config.voiceRecognition)!=null?n:{},i=(o=a.processingText)!=null?o:"\u{1F3A4} Processing voice...",d=(r=a.processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var u,p,f,g,x,C;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((u=l.transcript)!=null&&u.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=l.transcript)!=null&&p.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=l.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(g=l.text)!=null&&g.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let M=(C=this.pendingVoiceAssistantMessageId)!=null?C:(x=[...this.messages].reverse().find(W=>W.role==="assistant"))==null?void 0:x.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 u,p;this.voiceStatus=l,this.voiceActive=l==="listening",(p=(u=this.callbacks).onVoiceStatusChanged)==null||p.call(u,l)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,o,r,s,a,i,d,l,u;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((o=t.runtype)==null?void 0:o.agentId)||"",clientToken:((r=t.runtype)==null?void 0:r.clientToken)||"",host:(s=t.runtype)==null?void 0:s.host,voiceId:(a=t.runtype)==null?void 0:a.voiceId,pauseDuration:(i=t.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=t.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=t.browser)==null?void 0:l.language)||"en-US",continuous:(u=t.browser)==null?void 0:u.continuous}};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let o=await this.client.initSession();return this.setClientSession(o),o}catch(o){return(n=(t=this.callbacks).onError)==null||n.call(t,o instanceof Error?o:new Error(String(o))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let n=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new Ps(this.config),this.wireDefaultWebMcpConfirm(),n&&this.client.setSSEEventCallback(n)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:u,rawContent:p}=t,g={id:a!=null?a:n==="user"?Ga():n==="assistant"?Ws():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...p!==void 0&&{rawContent:p}};return this.upsertMessage(g),g}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:u,streaming:p=!1,voiceProcessing:f,rawContent:g}=o,C={id:d!=null?d:r==="user"?Ga():r==="assistant"?Ws():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:p,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...g!==void 0&&{rawContent:g}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:i,sequence:d}=t,l={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(l),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var l,u,p,f,g;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=Ga(),s=Ws(),a={id:r,role:"user",content:o||Ya,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(x){let C=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!C){let M=Hu(x,this.config.errorMessage);if(M){let W={id:s,role:"assistant",createdAt:new Date().toISOString(),content:M,sequence:this.nextSequence()};this.appendMessage(W)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,C||(x instanceof Error?(p=(u=this.callbacks).onError)==null||p.call(u,x):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(x))))}}async continueConversation(){var r,s,a,i,d;if(this.streaming)return;(r=this.abortController)==null||r.abort();let t=Ws();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(l){let u=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!u){let p=Hu(l,this.config.errorMessage);if(p){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:p,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var r,s,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(r=this.abortController)==null||r.abort();let o=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var r,s,a;try{if(((s=(r=this.config.webmcp)==null?void 0:r.autoApprove)==null?void 0:s.call(r,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(o,i)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r!=null&&r.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n){var d,l,u,p;let o=`approval-${t.id}`,r={...t,status:n,resolvedAt:Date.now()},s={id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:r};this.upsertMessage(s),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let f;if(i?f=await i({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n):f=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),f){let g=null;if(f instanceof Response){if(!f.ok){let x=await f.json().catch(()=>null);throw new Error((l=x==null?void 0:x.error)!=null?l:`Approval request failed: ${f.status}`)}g=f.body}else f instanceof ReadableStream&&(g=f);g?await this.connectStream(g,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(f){let g=f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"));this.setStreaming(!1),this.abortController=null,g||(p=(u=this.callbacks).onError)==null||p.call(u,f instanceof Error?f:new Error(String(f)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var u,p,f,g,x,C,M,W,L,H,D,B;let o=this.messages.find(v=>v.id===t.id);if(((u=o==null?void 0:o.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let r=(p=t.agentMetadata)==null?void 0:p.executionId,s=(f=t.toolCall)==null?void 0:f.name;if(!r||!s){(x=(g=this.callbacks).onError)==null||x.call(g,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let v=(C=t.toolCall)==null?void 0:C.args,w=Array.isArray(v==null?void 0:v.questions)?v.questions:[];if(w.length===1){let E=typeof((M=w[0])==null?void 0:M.question)=="string"?w[0].question:"";E&&(a={[E]:n})}}this.markAskUserQuestionResolved(t,a),(W=this.abortController)==null||W.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(([w,E])=>`${w}: ${Array.isArray(E)?E.join(", "):E}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:v,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let v=a!=null?a:{};l.forEach((w,E)=>{let S=typeof(w==null?void 0:w.question)=="string"?w.question:"";if(!S)return;let k=v[S],F=Array.isArray(k)?k.join(", "):typeof k=="string"?k:"";this.appendMessage({id:`ask-user-q-${i}-${E}`,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${E}`,role:"user",content: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 w=await v.json().catch(()=>null);throw new Error((H=w==null?void 0:w.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 w=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,w||(B=(D=this.callbacks).onError)==null||B.call(D,v instanceof Error?v:new Error(String(v)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,o=(a=t.toolCall)==null?void 0:a.id;if(!n||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}async resolveWebMcpToolCallBatch(t,n){var i,d,l;let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async u=>{var L,H,D,B,v,w,E;let p=(L=u.toolCall)==null?void 0:L.name,f=(H=u.toolCall)==null?void 0:H.id;if(!p||!f)return null;let g=`${t}:${f}`;if(this.webMcpInflightKeys.has(g)||this.webMcpResolvedKeys.has(g))return null;this.webMcpInflightKeys.add(g),o.push(g),this.upsertMessage({...u,agentMetadata:{...u.agentMetadata,awaitingLocalTool:!1}});let x=new AbortController;this.webMcpResolveControllers.add(x),r.push(x);let C=(B=(D=u.agentMetadata)==null?void 0:D.webMcpToolCallId)!=null?B:p,M=this.client.executeWebMcpToolCall(p,(v=u.toolCall)==null?void 0:v.args,x.signal),W;if(!M)W={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{W=await M}catch(S){return S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"))||(E=(w=this.callbacks).onError)==null||E.call(w,S instanceof Error?S:new Error(String(S))),this.webMcpInflightKeys.delete(g),null}return x.signal.aborted?(this.webMcpInflightKeys.delete(g),null):{dedupeKey:g,resumeKey:C,output:W}}));try{let u=a.filter(g=>g!==null);if(u.length===0)return;let p={};for(let g of u)p[g.resumeKey]=g.output;let f=await this.client.resumeFlow(t,p,{signal:s.signal});if(!f.ok){let g=await f.json().catch(()=>null);throw new Error((i=g==null?void 0:g.error)!=null?i:`Resume failed: ${f.status}`)}for(let g of u)this.webMcpResolvedKeys.add(g.dedupeKey);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(u){u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))||(l=(d=this.callbacks).onError)==null||l.call(d,u instanceof Error?u:new Error(String(u)))}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 u,p,f,g,x,C,M,W,L,H,D,B;let n=(u=t.agentMetadata)==null?void 0:u.executionId,o=(p=t.toolCall)==null?void 0:p.name,r=(f=t.toolCall)==null?void 0:f.id;if(!n){(x=(g=this.callbacks).onError)==null||x.call(g,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!o)return;if(!r){let v=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v))return;this.webMcpInflightKeys.add(v);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(v)}catch(w){(M=(C=this.callbacks).onError)==null||M.call(C,w instanceof Error?w:new Error(String(w)))}finally{this.webMcpInflightKeys.delete(v)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s))return;this.webMcpInflightKeys.add(s),this.upsertMessage({...t,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1}});let a=new AbortController;this.webMcpResolveControllers.add(a);let{signal:i}=a;this.setStreaming(!0);let d=(W=t.toolCall)==null?void 0:W.args,l=this.client.executeWebMcpToolCall(o,d,i);try{let v;if(l?v=await l:v={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},i.aborted)return;let w=(H=(L=t.agentMetadata)==null?void 0:L.webMcpToolCallId)!=null?H:o;await this.resumeWithToolOutput(n,w,v,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s)},signal:i})}catch(v){v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"))||(B=(D=this.callbacks).onError)==null||B.call(D,v instanceof Error?v:new Error(String(v)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){var a,i;let s=await this.client.resumeFlow(t,{[n]:o},{signal:r==null?void 0:r.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=r==null?void 0:r.onHttpOk)==null||i.call(r),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var r;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let o={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(r=t.props)!=null?r:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),o}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,o;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let r=this.artifacts.get(t.id);(r==null?void 0:r.artifactType)==="markdown"&&(r.markdown=((o=r.markdown)!=null?o:"")+t.artDelta);break}case"artifact_update":{let r=this.artifacts.get(t.id);(r==null?void 0:r.artifactType)==="component"&&(r.props={...r.props,...t.props},t.component&&(r.component=t.component));break}case"artifact_complete":{let r=this.artifacts.get(t.id);r&&(r.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>{var r;return{...o,streaming:!1,sequence:(r=o.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=o.content;r.trim()&&this.speak(r,t)}speak(t,n){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t),s=o.getVoices();if(n.voice){let a=s.find(i=>i.name===n.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=n.pickVoice?n.pickVoice(s):e.pickBestVoice(s));n.rate!==void 0&&(r.rate=n.rate),n.pitch!==void 0&&(r.pitch=n.pitch),setTimeout(()=>o.speak(r),50)}static pickBestVoice(t){var o;let n=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of n){let s=t.find(a=>a.name===r);if(s)return s}return(o=t.find(r=>r.lang.startsWith("en")))!=null?o:t[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{var u,p,f,g,x,C;if(s!==o)return r;let a={...r,...n};((u=r.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(p=n.toolCall)==null?void 0:p.name,d=(f=n.agentMetadata)==null?void 0:f.executionId,l=(g=n.toolCall)==null?void 0:g.id;if(i&&rl(i)&&d&&l&&((x=n.agentMetadata)==null?void 0:x.awaitingLocalTool)===!0){let M=`${d}:${l}`;(this.webMcpInflightKeys.has(M)||this.webMcpResolvedKeys.has(M))&&(a.agentMetadata={...(C=a.agentMetadata)!=null?C:{},awaitingLocalTool:!1})}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{var d,l;let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=(d=n.sequence)!=null?d:0,i=(l=o.sequence)!=null?l:0;return a!==i?a-i:n.id.localeCompare(o.id)})}};var b=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Eo=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o};import{Activity as Zf,ArrowDown as eh,ArrowUp as th,ArrowUpRight as nh,Bot as oh,ChevronDown as rh,ChevronUp as sh,ChevronRight as ah,ChevronLeft as ih,Check as lh,Clipboard as ch,ClipboardCopy as dh,Copy as ph,File as uh,FileCode as mh,FileSpreadsheet as gh,FileText as fh,ImagePlus as hh,Loader as bh,LoaderCircle as yh,Mic as vh,Paperclip as xh,RefreshCw as wh,Search as Ch,Send as Sh,ShieldAlert as Ah,ShieldCheck as Th,ShieldX as kh,Square as Eh,ThumbsDown as Mh,ThumbsUp as Lh,Upload as Ih,Volume2 as Rh,X as Ph,User as Wh,Mail as Bh,Phone as Hh,Calendar as Dh,Clock as Fh,Building as Oh,MapPin as Nh,Lock as _h,Key as Vh,CreditCard as $h,AtSign as Uh,Hash as zh,Globe as qh,Link as jh,CircleCheck as Kh,CircleX as Gh,TriangleAlert as Yh,Info as Xh,Ban as Qh,Shield as Jh,ArrowLeft as Zh,ArrowRight as eb,ExternalLink as tb,Ellipsis as nb,EllipsisVertical as ob,Menu as rb,House as sb,Plus as ab,Minus as ib,Pencil as lb,Trash as cb,Trash2 as db,Save as pb,Download as ub,Share as mb,Funnel as gb,Settings as fb,RotateCw as hb,Maximize as bb,Minimize as yb,ShoppingCart as vb,ShoppingBag as xb,Package as wb,Truck as Cb,Tag as Sb,Gift as Ab,Receipt as Tb,Wallet as kb,Store as Eb,DollarSign as Mb,Percent as Lb,Play as Ib,Pause as Rb,VolumeX as Pb,Camera as Wb,Image as Bb,Film as Hb,Headphones as Db,MessageCircle as Fb,MessageSquare as Ob,Bell as Nb,Heart as _b,Star as Vb,Eye as $b,EyeOff as Ub,Bookmark as zb,CalendarDays as qb,History as jb,Timer as Kb,Folder as Gb,FolderOpen as Yb,Files as Xb,Sparkles as Qb,Zap as Jb,Sun as Zb,Moon as ey,Flag as ty,Monitor as ny,Smartphone as oy}from"lucide";var ry={activity:Zf,"arrow-down":eh,"arrow-up":th,"arrow-up-right":nh,bot:oh,"chevron-down":rh,"chevron-up":sh,"chevron-right":ah,"chevron-left":ih,check:lh,clipboard:ch,"clipboard-copy":dh,copy:ph,file:uh,"file-code":mh,"file-spreadsheet":gh,"file-text":fh,"image-plus":hh,loader:bh,"loader-circle":yh,mic:vh,paperclip:xh,"refresh-cw":wh,search:Ch,send:Sh,"shield-alert":Ah,"shield-check":Th,"shield-x":kh,square:Eh,"thumbs-down":Mh,"thumbs-up":Lh,upload:Ih,"volume-2":Rh,x:Ph,user:Wh,mail:Bh,phone:Hh,calendar:Dh,clock:Fh,building:Oh,"map-pin":Nh,lock:_h,key:Vh,"credit-card":$h,"at-sign":Uh,hash:zh,globe:qh,link:jh,"circle-check":Kh,"circle-x":Gh,"triangle-alert":Yh,info:Xh,ban:Qh,shield:Jh,"arrow-left":Zh,"arrow-right":eb,"external-link":tb,ellipsis:nb,"ellipsis-vertical":ob,menu:rb,house:sb,plus:ab,minus:ib,pencil:lb,trash:cb,"trash-2":db,save:pb,download:ub,share:mb,funnel:gb,settings:fb,"rotate-cw":hb,maximize:bb,minimize:yb,"shopping-cart":vb,"shopping-bag":xb,package:wb,truck:Cb,tag:Sb,gift:Ab,receipt:Tb,wallet:kb,store:Eb,"dollar-sign":Mb,percent:Lb,play:Ib,pause:Rb,"volume-x":Pb,camera:Wb,image:Bb,film:Hb,headphones:Db,"message-circle":Fb,"message-square":Ob,bell:Nb,heart:_b,star:Vb,eye:$b,"eye-off":Ub,bookmark:zb,"calendar-days":qb,history:jb,timer:Kb,folder:Gb,"folder-open":Yb,files:Xb,sparkles:Qb,zap:Jb,sun:Zb,moon:ey,flag:ty,monitor:ny,smartphone:oy},Se=(e,t=24,n="currentColor",o=2)=>{let r=ry[e];return r?sy(r,t,n,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function sy(e,t,n,o){if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,u])=>{l!=="stroke"&&d.setAttribute(l,String(u))}),r.appendChild(d)}),r}var ei={allowedTypes:_o,maxFileSize:10*1024*1024,maxFiles:4};function ay(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function iy(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var Ds=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,o,r;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:ei.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:ei.maxFileSize,maxFiles:(r=t.maxFiles)!=null?r:ei.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:ei.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,o,r,s,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(o=(n=this.config).onFileRejected)==null||o.call(n,l,"count");continue}let u=Pu(l,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let p=(r=u.error)!=null&&r.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,p);continue}try{let p=await Ru(l),f=Xa(l)?URL.createObjectURL(l):null,g={id:ay(),file:l,previewUrl:f,contentPart:p};this.attachments.push(g),this.renderPreview(g)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let o of this.attachments)o.previewUrl&&URL.revokeObjectURL(o.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Xa(t.file),o=b("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let a=b("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=b("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=iy(t.file.type),d=Se(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=b("span");l.textContent=Wu(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),o.appendChild(a)}let r=b("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=Se("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};import{Idiomorph as ly}from"idiomorph";var ti=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;ly.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){var a,i;if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=r.textContent)!=null?a:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var ni={index:-1,draft:""};function Du(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:o}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...ni}}}function Fu(e,t){var n,o,r,s,a,i,d,l,u,p,f,g,x,C,M,W,L,H,D,B,v,w,E,S,k,F,$,q,me,re,be,ie,we,We,ye,Z,Ee,X;return[e.id,e.role,(o=(n=e.content)==null?void 0:n.length)!=null?o:0,(s=(r=e.content)==null?void 0:r.slice(-32))!=null?s:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(u=(l=e.llmContent)==null?void 0:l.length)!=null?u:0,(f=(p=e.approval)==null?void 0:p.status)!=null?f:"",(x=(g=e.toolCall)==null?void 0:g.status)!=null?x:"",(M=(C=e.toolCall)==null?void 0:C.name)!=null?M:"",(H=(L=(W=e.toolCall)==null?void 0:W.chunks)==null?void 0:L.length)!=null?H:0,(w=(v=(B=(D=e.toolCall)==null?void 0:D.chunks)==null?void 0:B[e.toolCall.chunks.length-1])==null?void 0:v.slice(-32))!=null?w:"",typeof((E=e.toolCall)==null?void 0:E.args)=="string"?e.toolCall.args.length:(S=e.toolCall)!=null&&S.args?JSON.stringify(e.toolCall.args).length:0,($=(F=(k=e.reasoning)==null?void 0:k.chunks)==null?void 0:F.length)!=null?$:0,(be=(re=(me=(q=e.reasoning)==null?void 0:q.chunks)==null?void 0:me[e.reasoning.chunks.length-1])==null?void 0:re.length)!=null?be:0,(ye=(We=(we=(ie=e.reasoning)==null?void 0:ie.chunks)==null?void 0:we[e.reasoning.chunks.length-1])==null?void 0:We.slice(-32))!=null?ye:"",(Ee=(Z=e.contentParts)==null?void 0:Z.length)!=null?Ee:0,(X=e.stopReason)!=null?X:"",t].join("\0")}function Ou(){return new Map}function Nu(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function _u(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Vu(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function oi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Fs(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Os(e,t){return Fs(e)-e.scrollTop<=t}function ri(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,u=n-o;return a||Math.abs(u)<s?{action:"none",delta:u,nextLastScrollTop:n}:!t&&r&&(!l||u>0)?{action:"resume",delta:u,nextLastScrollTop:n}:t&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:n}:t&&d&&!r?{action:"pause",delta:u,nextLastScrollTop:n}:{action:"none",delta:u,nextLastScrollTop:n}}function si(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}var hn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},bn=1e5,nr=bn+1;var Ns={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},cy=["pre","code","a","script","style"],ai=e=>{var t,n,o,r,s;return{type:(t=e==null?void 0:e.type)!=null?t:Ns.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:Ns.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:Ns.speed,duration:(r=e==null?void 0:e.duration)!=null?r:Ns.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:Ns.buffer}},dy=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],Uu=new Map;for(let e of dy)Uu.set(e.name,e);var _s=(e,t)=>{var n,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(o=Uu.get(e))!=null?o:null},ii=(e,t,n,o,r)=>{if(!r)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
|
|
15
|
+
`);return s<0?"":e.slice(0,s)}return e},py=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},uy=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},cl=/\s/,my=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},gy=(e,t,n)=>{var d;let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=o.createDocumentFragment(),i=0;for(;i<s.length;)if(cl.test(s[i])){let l=i;for(;l<s.length&&cl.test(s[l]);)l+=1;a.appendChild(o.createTextNode(s.slice(i,l))),i=l}else{let l=o.createElement("span");l.className="persona-stream-word-group";let u=i;for(;u<s.length&&!cl.test(s[u]);)l.appendChild(py(o,s[u],t,n.value)),n.value+=1,u+=1;a.appendChild(l),i=u}r.replaceChild(a,e)},fy=(e,t,n)=>{var d;let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=o.createDocumentFragment(),i=s.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(o.createTextNode(l)):(a.appendChild(uy(o,l,t,n.value)),n.value+=1));r.replaceChild(a,e)},Vs=(e,t,n,o)=>{var p,f;if(!e||typeof document=="undefined")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set(((p=o==null?void 0:o.skipTags)!=null?p:cy).map(g=>g.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)my(d,s)||i.push(d),d=a.nextNode();let l={value:(f=o==null?void 0:o.startIndex)!=null?f:0},u=t==="char"?gy:fy;for(let g of i)u(g,n,l);return r.innerHTML},li=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},$s=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},$u=new WeakMap,hy=(e,t)=>{var s;if(!e.styles)return;let n=$u.get(t);if(n||(n=new Set,$u.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},dl=new WeakMap,by=(e,t)=>{if(!e.onAttach)return;let n=dl.get(t);if(n||(n=new Map,dl.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},zu=e=>{let t=dl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},pl=(e,t)=>{hy(e,t),by(e,t)};function ul(e,t=bn){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var Us=0,or=null;function ml(e=document){var n;if(Us++,Us===1){let o=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;or={originalOverflow:o.style.overflow,originalPosition:o.style.position,originalTop:o.style.top,originalWidth:o.style.width,scrollY:s},o.style.overflow="hidden",o.style.position="fixed",o.style.top=`-${s}px`,o.style.width="100%"}let t=!1;return()=>{var o;if(!t&&(t=!0,Us=Math.max(0,Us-1),Us===0&&or)){let r=e.body,s=(o=e.defaultView)!=null?o:window;r.style.overflow=or.originalOverflow,r.style.position=or.originalPosition,r.style.top=or.originalTop,r.style.width=or.originalWidth,s.scrollTo(0,or.scrollY),or=null}}}var ci={side:"right",width:"420px",animate:!0,reveal:"resize"},un=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},zs=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},Mo=e=>{var n,o,r,s,a;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(o=t==null?void 0:t.side)!=null?o: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 xo={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var qs=(e,t)=>{let n=b("button");n.type="button",n.innerHTML=`
|
|
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 Za=class e{constructor(t={},n){this.config=t;this
|
|
|
20
20
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
21
21
|
</span>
|
|
22
22
|
<span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
23
|
-
`,n.addEventListener("click",t);let o=s=>{var H,_,B,v,C,E,S,k,D,$,q,me,re,be;let a=(H=s.launcher)!=null?H:{},i=un(s),d=n.querySelector("[data-role='launcher-title']");if(d){let ie=(_=a.title)!=null?_:"Chat Assistant";d.textContent=ie,d.setAttribute("title",ie)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let ie=(B=a.subtitle)!=null?B:"Get answers fast";l.textContent=ie,l.setAttribute("title",ie)}let u=n.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let p=n.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let ie=(v=a.agentIconSize)!=null?v:"40px";if(p.style.height=ie,p.style.width=ie,p.innerHTML="",a.agentIconName){let we=parseFloat(ie)||24,We=Se(a.agentIconName,we*.6,"var(--persona-text-inverse, #ffffff)",2);We?(p.appendChild(We),p.style.display=""):(p.textContent=(C=a.agentIconText)!=null?C:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(E=a.agentIconText)!=null?E:"\u{1F4AC}",p.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let ie=(S=a.agentIconSize)!=null?S:"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 m=n.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let ie=(k=a.callToActionIconSize)!=null?k:"32px";m.style.height=ie,m.style.width=ie,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 we=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,we=(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 We=parseFloat(ie)||24,ye=Math.max(We-we,8),Z=Se(a.callToActionIconName,ye,"currentColor",2);Z?m.appendChild(Z):m.textContent=(D=a.callToActionIconText)!=null?D:"\u2197"}else m.textContent=($=a.callToActionIconText)!=null?$:"\u2197"}let w=a.position&&xo[a.position]?xo[a.position]:xo["bottom-right"],x="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:`${x} ${w}`,i||(n.style.zIndex=String((q=a.zIndex)!=null?q:bn));let P="1px solid var(--persona-border, #e5e7eb)",W="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:P,n.style.boxShadow=(re=a.shadow)!=null?re:W,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=(be=a.collapsedMaxWidth)!=null?be:"",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 gy="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",di=(e,t={})=>{var x,M,P,W,H,_;let{showClose:n=!0,wrapperClassName:o=gy,buttonSize:r,iconSize:s="28px"}=t,a=(x=e==null?void 0:e.launcher)!=null?x:{},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 u=(P=a.closeButtonTooltipText)!=null?P:"Close chat",p=(W=a.closeButtonShowTooltip)!=null?W:!0;l.setAttribute("aria-label",u),l.style.display=n?"":"none";let g=(H=a.closeButtonIconName)!=null?H:"x",m=(_=a.closeButtonIconText)!=null?_:"\xD7";l.style.color=a.closeButtonColor||Mn.actionIconColor;let w=Se(g,s,"currentColor",1);if(w?(w.style.display="block",l.appendChild(w)):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 B=a.closeButtonBorderWidth||"0px",v=a.closeButtonBorderColor||"transparent";l.style.border=`${B} solid ${v}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),p&&u){let B=null,v=()=>{if(B)return;let E=l.ownerDocument,S=E.body;if(!S)return;B=Eo(E,"div","persona-clear-chat-tooltip"),B.textContent=u;let k=Eo(E,"div");k.className="persona-clear-chat-tooltip-arrow",B.appendChild(k);let D=l.getBoundingClientRect();B.style.position="fixed",B.style.zIndex=String(nr),B.style.left=`${D.left+D.width/2}px`,B.style.top=`${D.top-8}px`,B.style.transform="translate(-50%, -100%)",S.appendChild(B)},C=()=>{B&&B.parentNode&&(B.parentNode.removeChild(B),B=null)};d.addEventListener("mouseenter",v),d.addEventListener("mouseleave",C),l.addEventListener("focus",v),l.addEventListener("blur",C),d._cleanupTooltip=()=>{C(),d.removeEventListener("mouseenter",v),d.removeEventListener("mouseleave",C),l.removeEventListener("focus",v),l.removeEventListener("blur",C)}}return{button:l,wrapper:d}},hy="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",pi=(e,t={})=>{var B,v,C,E,S,k,D,$,q,me,re,be,ie;let{wrapperClassName:n=hy,buttonSize:o,iconSize:r="20px"}=t,a=(v=((B=e==null?void 0:e.launcher)!=null?B:{}).clearChat)!=null?v:{},i=(C=o!=null?o:a.size)!=null?C:"32px",d=(E=a.iconName)!=null?E:"refresh-cw",l=(S=a.iconColor)!=null?S:"",u=(k=a.backgroundColor)!=null?k:"",p=(D=a.borderWidth)!=null?D:"",g=($=a.borderColor)!=null?$:"",m=(q=a.borderRadius)!=null?q:"",w=(me=a.paddingX)!=null?me:"",x=(re=a.paddingY)!=null?re:"",M=(be=a.tooltipText)!=null?be:"Clear chat",P=(ie=a.showTooltip)!=null?ie:!0,W=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 _=Se(d,r,"currentColor",1);if(_&&(_.style.display="block",H.appendChild(_)),u&&(H.style.backgroundColor=u,H.classList.remove("hover:persona-bg-gray-100")),p||g){let we=p||"0px",We=g||"transparent";H.style.border=`${we} solid ${We}`,H.classList.remove("persona-border-none")}if(m&&(H.style.borderRadius=m,H.classList.remove("persona-rounded-full")),w&&(H.style.paddingLeft=w,H.style.paddingRight=w),x&&(H.style.paddingTop=x,H.style.paddingBottom=x),W.appendChild(H),P&&M){let we=null,We=()=>{if(we)return;let Z=H.ownerDocument,Ee=Z.body;if(!Ee)return;we=Eo(Z,"div","persona-clear-chat-tooltip"),we.textContent=M;let X=Eo(Z,"div");X.className="persona-clear-chat-tooltip-arrow",we.appendChild(X);let Ae=H.getBoundingClientRect();we.style.position="fixed",we.style.zIndex=String(nr),we.style.left=`${Ae.left+Ae.width/2}px`,we.style.top=`${Ae.top-8}px`,we.style.transform="translate(-50%, -100%)",Ee.appendChild(we)},ye=()=>{we&&we.parentNode&&(we.parentNode.removeChild(we),we=null)};W.addEventListener("mouseenter",We),W.addEventListener("mouseleave",ye),H.addEventListener("focus",We),H.addEventListener("blur",ye),W._cleanupTooltip=()=>{ye(),W.removeEventListener("mouseenter",We),W.removeEventListener("mouseleave",ye),H.removeEventListener("focus",We),H.removeEventListener("blur",ye)}}return{button:H,wrapper:W}};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))"},Sr=e=>{var B,v,C,E,S,k,D,$,q,me,re,be,ie,we,We,ye;let{config:t,showClose:n=!0}=e,o=b("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");o.setAttribute("data-persona-theme-zone","header"),o.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",o.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",o.style.boxShadow="var(--persona-header-shadow, none)",o.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let r=(B=t==null?void 0:t.launcher)!=null?B:{},s=(v=r.headerIconSize)!=null?v:"48px",a=(C=r.closeButtonPlacement)!=null?C:"inline",i=(E=r.headerIconHidden)!=null?E:!1,d=r.headerIconName,l=b("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let Z=parseFloat(s)||24,Ee=Se(d,Z*.6,"currentColor",1);Ee?l.replaceChildren(Ee):l.textContent=(k=(S=t==null?void 0:t.launcher)==null?void 0:S.agentIconText)!=null?k:"\u{1F4AC}"}else if((D=t==null?void 0:t.launcher)!=null&&D.iconUrl){let Z=b("img");Z.src=t.launcher.iconUrl,Z.alt="",Z.className="persona-rounded-xl persona-object-cover",Z.style.height=s,Z.style.width=s,l.replaceChildren(Z)}else l.textContent=(q=($=t==null?void 0:t.launcher)==null?void 0:$.agentIconText)!=null?q:"\u{1F4AC}";let u=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),p=b("span","persona-text-base persona-font-semibold");p.style.color=Mn.titleColor,p.textContent=(re=(me=t==null?void 0:t.launcher)==null?void 0:me.title)!=null?re:"Chat Assistant";let g=b("span","persona-text-xs");g.style.color=Mn.subtitleColor,g.textContent=(ie=(be=t==null?void 0:t.launcher)==null?void 0:be.subtitle)!=null?ie:"Here to help you get answers fast",u.append(p,g),i?o.append(u):o.append(l,u);let m=(we=r.clearChat)!=null?we:{},w=(We=m.enabled)!=null?We:!0,x=(ye=m.placement)!=null?ye:"inline",M=null,P=null;if(w){let Ee=pi(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=Ee.button,P=Ee.wrapper,x==="top-right"&&(P.style.right="48px"),x==="inline"&&o.appendChild(P)}let W=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":w&&x==="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:_}=di(t,{showClose:n,wrapperClassName:W});return a!=="top-right"&&o.appendChild(_),{header:o,iconHolder:l,headerTitle:p,headerSubtitle:g,closeButton:H,closeButtonWrapper:_,clearChatButton:M,clearChatButtonWrapper:P}},js=(e,t,n)=>{var a,i,d,l;let o=(a=n==null?void 0:n.launcher)!=null?a:{},r=(i=o.closeButtonPlacement)!=null?i:"inline",s=(l=(d=o.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function jr(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=e,a=b("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(nr)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of t){if(m.dividerBefore){let M=document.createElement("hr");a.appendChild(M)}let w=document.createElement("button");if(w.type="button",w.setAttribute("role","menuitem"),w.setAttribute("data-dropdown-item-id",m.id),m.destructive&&w.setAttribute("data-destructive",""),m.icon){let M=Se(m.icon,16,"currentColor",1.5);M&&w.appendChild(M)}let x=document.createElement("span");x.textContent=m.label,w.appendChild(x),w.addEventListener("click",M=>{M.stopPropagation(),u(),n(m.id)}),a.appendChild(w)}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=w=>{!a.contains(w.target)&&!o.contains(w.target)&&u()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function p(){a.classList.contains("persona-hidden")?l():u()}function g(){u(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:u,toggle:p,destroy:g}}function yn(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:i}=e,d=b("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=Se(t,o!=null?o:16,"currentColor",r!=null?r:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[u,p]of Object.entries(i))d.setAttribute(u,p);return d}function fl(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";o!=="default"&&(l+=" persona-label-btn--"+o),l+=" persona-label-btn--"+r,a&&(l+=" "+a);let u=b("button",l);if(u.type="button",u.setAttribute("aria-label",n),t){let g=Se(t,s!=null?s:14,"currentColor",2);g&&u.appendChild(g)}let p=b("span");if(p.textContent=n,u.appendChild(p),i&&u.addEventListener("click",i),d)for(let[g,m]of Object.entries(d))u.setAttribute(g,m);return u}function Uu(e){var m,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 u=b("span","persona-combo-btn-label");u.textContent=t,l.appendChild(u);let p=Se(n,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",l.appendChild(p)),d&&(l.style.borderRadius=(m=d.borderRadius)!=null?m:"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 x,M;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(M=d.border)!=null?M:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let g=jr({items:o,onSelect:x=>{l.setAttribute("aria-expanded","false"),r(x)},anchor:l,position:s,portal:a});return a||l.appendChild(g.element),l.addEventListener("click",x=>{x.stopPropagation();let M=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",M?"false":"true"),g.toggle()}),l.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l.click())}),{element:l,setLabel:x=>{u.textContent=x,l.setAttribute("aria-label",x)},open:()=>{l.setAttribute("aria-expanded","true"),g.show()},close:()=>{l.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let x=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",x?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),l.remove()}}}var by=e=>{var o;let t=Sr({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 yy(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=Se(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=b("div","persona-relative");d.appendChild(i);let l=jr({items:a.menuItems,onSelect:u=>n==null?void 0:n(u),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",u=>{u.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var vy=e=>{var W,H,_,B,v,C,E,S,k;let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=(W=t==null?void 0:t.launcher)!=null?W:{},i=b("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=r==null?void 0:r.titleMenu,l,u;if(d)l=Uu({label:(H=a.title)!=null?H:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Mn.titleColor,u=(_=l.querySelector(".persona-combo-btn-label"))!=null?_:l;else{if(l=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=b("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=Mn.titleColor,u.textContent=(B=a.title)!=null?B:"Chat Assistant",l.appendChild(u),yy(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",q=>{q.target.closest("button")||$()}),l.addEventListener("keydown",q=>{(q.key==="Enter"||q.key===" ")&&(q.preventDefault(),$())})}let D=r==null?void 0:r.titleRowHover;D&&(l.style.borderRadius=(C=D.borderRadius)!=null?C:"10px",l.style.padding=(E=D.padding)!=null?E:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var $,q;l.style.backgroundColor=($=D.background)!=null?$:"",l.style.borderColor=(q=D.border)!=null?q:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let p=(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=p,m.style.width=p,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=n?"":"none",m.style.color=a.closeButtonColor||Mn.actionIconColor;let w=(k=a.closeButtonIconName)!=null?k:"x",x=Se(w,"28px","currentColor",1);x?m.appendChild(x):m.textContent="\xD7",o&&m.addEventListener("click",o),g.appendChild(m),i.appendChild(g);let M=b("div");M.style.display="none";let P=b("span");return P.style.display="none",{header:i,iconHolder:M,headerTitle:u,headerSubtitle:P,closeButton:m,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},zu={default:by,minimal:vy},xy=e=>{var t;return(t=zu[e])!=null?t:zu.default},ui=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),u=b("div");u.style.display="none";let p=b("span"),g=b("span"),m=b("button");m.style.display="none";let w=b("div");return w.style.display="none",{header:l,iconHolder:u,headerTitle:p,headerSubtitle:g,closeButton:m,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}}let o=(a=t==null?void 0:t.layout)!=null?a:"default",s=xy(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 mi=e=>{var a,i;let t=b("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;t.style.maxHeight=`${n*o}px`,t.style.overflowY="auto";let r=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*o},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,r());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},fi=e=>{var B,v,C,E,S,k,D,$,q,me,re,be;let t=(B=e==null?void 0:e.sendButton)!=null?B:{},n=(v=t.useIcon)!=null?v:!1,o=(C=t.iconText)!=null?C:"\u2191",r=t.iconName,s=(E=t.stopIconName)!=null?E:"square",a=(S=t.tooltipText)!=null?S:"Send message",i=(k=t.stopTooltipText)!=null?k:"Stop generating",d=($=(D=e==null?void 0:e.copy)==null?void 0:D.sendButtonLabel)!=null?$:"Send",l=(me=(q=e==null?void 0:e.copy)==null?void 0:q.stopButtonLabel)!=null?me:"Stop",u=(re=t.showTooltip)!=null?re:!1,p=(be=t.size)!=null?be:"40px",g=t.backgroundColor,m=t.textColor,w=b("div","persona-send-button-wrapper"),x=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");x.type="submit",x.setAttribute("data-persona-composer-submit","");let M=null,P=null;if(n){x.style.width=p,x.style.height=p,x.style.minWidth=p,x.style.minHeight=p,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",m?x.style.color=m:x.style.color="var(--persona-button-primary-fg, #ffffff)";let ie=parseFloat(p)||24,we=(m==null?void 0:m.trim())||"currentColor";r?(M=Se(r,ie,we,2),M?x.appendChild(M):x.textContent=o):x.textContent=o,P=Se(s,ie,we,2),g?x.style.backgroundColor=g:x.classList.add("persona-bg-persona-primary")}else x.textContent=d,m?x.style.color=m:x.classList.add("persona-text-white");t.borderWidth&&(x.style.borderWidth=t.borderWidth,x.style.borderStyle="solid"),t.borderColor&&(x.style.borderColor=t.borderColor),t.paddingX?(x.style.paddingLeft=t.paddingX,x.style.paddingRight=t.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),t.paddingY?(x.style.paddingTop=t.paddingY,x.style.paddingBottom=t.paddingY):(x.style.paddingTop="",x.style.paddingBottom="");let W=null;u&&a&&(W=b("div","persona-send-button-tooltip"),W.textContent=a,w.appendChild(W)),x.setAttribute("aria-label",a),w.appendChild(x);let H="send";return{button:x,wrapper:w,setMode:ie=>{if(ie===H)return;H=ie;let we=ie==="stop"?i:a;if(x.setAttribute("aria-label",we),W&&(W.textContent=we),n){if(M&&P){let We=ie==="stop"?P:M;x.replaceChildren(We)}}else x.textContent=ie==="stop"?l:d}}},gi=e=>{var W,H,_,B,v,C,E,S,k,D,$,q;let t=(W=e==null?void 0:e.voiceRecognition)!=null?W:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),r=((H=t.provider)==null?void 0:H.type)==="runtype";if(!(o||r))return null;let a=(B=(_=e==null?void 0:e.sendButton)==null?void 0:_.size)!=null?B:"40px",i=b("div","persona-send-button-wrapper"),d=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(v=t.iconName)!=null?v:"mic",u=(C=t.iconSize)!=null?C:a,p=parseFloat(u)||24,g=(S=t.backgroundColor)!=null?S:(E=e==null?void 0:e.sendButton)==null?void 0:E.backgroundColor,m=(D=t.iconColor)!=null?D:(k=e==null?void 0:e.sendButton)==null?void 0:k.textColor;d.style.width=u,d.style.height=u,d.style.minWidth=u,d.style.minHeight=u,d.style.fontSize="18px",d.style.lineHeight="1",m?d.style.color=m:d.style.color="var(--persona-text, #111827)";let x=Se(l,p,m||"currentColor",1.5);x?d.appendChild(x):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(((q=t.showTooltip)!=null?q:!1)&&M){let me=b("div","persona-send-button-tooltip");me.textContent=M,i.appendChild(me)}return{button:d,wrapper:i}},hi=e=>{var w,x,M,P,W,H,_,B;let t=(w=e==null?void 0:e.attachments)!=null?w:{};if(t.enabled!==!0)return null;let n=(M=(x=e==null?void 0:e.sendButton)==null?void 0:x.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=((P=t.allowedTypes)!=null?P:_o).join(","),r.multiple=((W=t.maxFiles)!=null?W: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=(_=t.buttonIconName)!=null?_:"paperclip",d=n,l=parseFloat(d)||40,u=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let p=Se(i,u,"currentColor",1.5);p?a.appendChild(p):a.textContent="\u{1F4CE}",a.addEventListener("click",v=>{v.preventDefault(),r.click()}),s.appendChild(a);let g=(B=t.buttonTooltipText)!=null?B:"Attach file",m=b("div","persona-send-button-tooltip");return m.textContent=g,s.appendChild(m),{button:a,wrapper:s,input:r,previewsContainer:o}},bi=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},yi=()=>b("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var vi=e=>{var w,x,M,P,W,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=yi(),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}=mi(t);a();let i=fi(t),d=gi(t),l=hi(t),u=bi(t);l&&(l.previewsContainer.style.gap="8px",r.append(l.previewsContainer,l.input)),r.append(s);let p=b("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),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),p.append(g,m),r.append(p),r.addEventListener("click",_=>{_.target!==i.button&&_.target!==i.wrapper&&_.target!==(d==null?void 0:d.button)&&_.target!==(d==null?void 0:d.wrapper)&&_.target!==(l==null?void 0:l.button)&&_.target!==(l==null?void 0:l.wrapper)&&s.focus()}),n.append(o,r,u),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(w=d==null?void 0:d.button)!=null?w:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:u,attachmentButton:(M=l==null?void 0:l.button)!=null?M:null,attachmentButtonWrapper:(P=l==null?void 0:l.wrapper)!=null?P:null,attachmentInput:(W=l==null?void 0:l.input)!=null?W:null,attachmentPreviewsContainer:(H=l==null?void 0:l.previewsContainer)!=null?H:null,actionsRow:p,leftActions:g,rightActions:m,setSendButtonMode:i.setMode}};var qu=()=>{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=Se("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=Se("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},ju=e=>{var w,x,M,P,W,H;let{config:t}=e,n=b("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let o=yi();o.style.display="none";let r=bi(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=mi(t);s.style.maxHeight="100px",a();let i=fi(t),d=gi(t),l=hi(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let u=b("form","persona-widget-composer persona-pill-composer");u.setAttribute("data-persona-composer-form",""),u.style.outline="none";let p=b("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&p.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),u.addEventListener("click",_=>{_.target!==i.button&&_.target!==i.wrapper&&_.target!==(d==null?void 0:d.button)&&_.target!==(d==null?void 0:d.wrapper)&&_.target!==(l==null?void 0:l.button)&&_.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&u.append(l.input),u.append(p,s,g),l&&n.append(l.previewsContainer),n.append(u,o,r);let m=u;return{footer:n,suggestions:o,composerForm:u,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(w=d==null?void 0:d.button)!=null?w:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:r,attachmentButton:(M=l==null?void 0:l.button)!=null?M:null,attachmentButtonWrapper:(P=l==null?void 0:l.wrapper)!=null?P:null,attachmentInput:(W=l==null?void 0:l.input)!=null?W:null,attachmentPreviewsContainer:(H=l==null?void 0:l.previewsContainer)!=null?H:null,actionsRow:m,leftActions:p,rightActions:g,setSendButtonMode:i.setMode}};var Ku=e=>{var u,p,g,m,w,x,M,P,W,H,_,B,v,C,E,S,k;let t=(p=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?p:!0,n=un(e);if(zs(e)){let D=(m=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?m:{},$=b("div","persona-widget-wrapper persona-fixed persona-transition");$.setAttribute("data-persona-composer-bar",""),$.dataset.state="collapsed",$.dataset.expandedSize=(w=D.expandedSize)!=null?w:"anchored",$.style.zIndex=String((M=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?M:bn);let q=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");q.style.width="100%",$.appendChild(q);let me=b("div","persona-widget-pill-root");return me.setAttribute("data-persona-composer-bar",""),me.dataset.state="collapsed",me.dataset.expandedSize=(P=D.expandedSize)!=null?P:"anchored",me.style.zIndex=String((H=(W=e==null?void 0:e.launcher)==null?void 0:W.zIndex)!=null?H:bn),{wrapper:$,panel:q,pillRoot:me}}if(n){let D=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 D.appendChild($),{wrapper:D,panel:$}}if(!t){let D=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"),q=(B=(_=e==null?void 0:e.launcher)==null?void 0:_.width)!=null?B:"100%";return D.style.width=q,$.style.width="100%",D.appendChild($),{wrapper:D,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((E=(C=e==null?void 0:e.launcher)==null?void 0:C.zIndex)!=null?E:bn);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(k=(S=e==null?void 0:e.launcher)==null?void 0:S.width)!=null?k:e==null?void 0:e.launcherWidth,l=d!=null?d:io;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},wy=(e,t)=>{var _,B,v,C,E,S,k,D,$;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}=di(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=(v=(B=(_=e==null?void 0:e.launcher)==null?void 0:_.clearChat)==null?void 0:B.enabled)!=null?v:!0,a=null,i=null;if(s){let q=pi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=q.button,i=q.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 u=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");u.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",u.setAttribute("data-persona-intro-card","");let p=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");p.textContent=(E=(C=e==null?void 0:e.copy)==null?void 0:C.welcomeTitle)!=null?E:"Hello \u{1F44B}";let g=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");g.textContent=(k=(S=e==null?void 0:e.copy)==null?void 0:S.welcomeSubtitle)!=null?k:"Ask anything about your account or products.",u.append(p,g);let m=b("div","persona-flex persona-flex-col persona-gap-3"),w=(D=e==null?void 0:e.layout)==null?void 0:D.contentMaxWidth;w&&(m.style.maxWidth=w,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),(($=e==null?void 0:e.copy)==null?void 0:$.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,m);let M=b("div","persona-composer-overlay persona-pointer-events-none");M.setAttribute("data-persona-composer-overlay",""),M.style.position="absolute",M.style.left="0",M.style.right="0",M.style.bottom="0",M.style.zIndex="20";let P=ju({config:e}),{root:W,textNode:H}=qu();return n.append(d,r,l,M),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:m,composerOverlay:M,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:p,introSubtitle:g,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:d,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,peekBanner:W,peekTextNode:H}},Gu=(e,t=!0)=>{var M,P,W,H,_,B,v,C,E;if(zs(e))return wy(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=((P=e==null?void 0:e.layout)==null?void 0:P.showHeader)!==!1,s=o?ui(e,o,{showClose:t}):Sr({config:e,showClose:t}),a=b("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=un(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(H=(W=e==null?void 0:e.copy)==null?void 0:W.welcomeTitle)!=null?H:"Hello \u{1F44B}";let l=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(B=(_=e==null?void 0:e.copy)==null?void 0:_.welcomeSubtitle)!=null?B:"Ask anything about your account or products.",i.append(d,l);let u=b("div","persona-flex persona-flex-col persona-gap-3"),p=(v=e==null?void 0:e.layout)==null?void 0:v.contentMaxWidth;p&&(u.style.maxWidth=p,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((C=e==null?void 0:e.copy)==null?void 0:C.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,u);let m=vi({config:e}),w=((E=e==null?void 0:e.layout)==null?void 0:E.showFooter)!==!1;r?js(n,s,e):(s.header.style.display="none",js(n,s,e)),n.append(a);let x=b("div","persona-composer-overlay persona-pointer-events-none");return x.setAttribute("data-persona-composer-overlay",""),x.style.position="absolute",x.style.left="0",x.style.right="0",x.style.bottom="0",x.style.zIndex="20",w||(m.footer.style.display="none"),n.append(m.footer),n.append(x),{container:n,body:a,messagesWrapper:u,composerOverlay:x,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 Cy=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}},Sy=(e,t)=>{if(!e)return null;let n=Cy(e);if(n===null)return null;let o=t==null?void 0:t[e],r=o!==void 0?o:n;return r||null},Ay=(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},Ty=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},gl=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},hl=320,Xu=320,ky=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Ey=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),My=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Ly=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Iy=(e,t,n)=>{if(e.length===0)return null;try{let o=b("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n==null||n())};return e.forEach((i,d)=>{var p;let l=b("img");l.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${hl}px`,l.style.maxHeight=`${Xu}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;r+=1,l.addEventListener("error",()=>{u||(u=!0,r=Math.max(0,r-1),l.remove(),r===0&&a())}),l.addEventListener("load",()=>{u=!0}),Ty(i.image)?(l.src=i.image,o.appendChild(l)):(u=!0,r=Math.max(0,r-1),l.remove())}),r===0?(a(),null):o}catch{return n==null||n(),null}},Ry=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!gl(o.audio))return;let r=b("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${hl}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Py=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!gl(o.video))return;let r=b("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${hl}px`,r.style.maxHeight=`${Xu}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}},Wy=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!gl(o.data))return;let r=b("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Ks=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},By=(e,t,n)=>{let o={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Ks};if(t){let r=t(o);if(r!==null)return r}return Ks()},Hy=(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},Yu=(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},Dy=(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},Fy=(e,t,n)=>{var m,w,x,M,P,W;let o=(m=t.showCopy)!=null?m:!0,r=(w=t.showUpvote)!=null?w:!0,s=(x=t.showDownvote)!=null?x:!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=(P=t.align)!=null?P:"right",d=(W=t.layout)!=null?W:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${u} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let g=(H,_,B)=>{let v=yn({icon:H,label:_,size:14,className:"persona-message-action-btn"});return v.setAttribute("data-action",B),v};return o&&p.appendChild(g("copy","Copy message","copy")),r&&p.appendChild(g("thumbs-up","Upvote","upvote")),s&&p.appendChild(g("thumbs-down","Downvote","downvote")),p},bl=(e,t,n,o,r,s)=>{var Z,Ee,X,Ae,ge,le,ue,je,j,oe,Re,tt,fe,ce,_e,Le,de;let a=n!=null?n:{},i=(Z=a.layout)!=null?Z:"bubble",d=a.avatar,l=a.timestamp,u=(Ee=d==null?void 0:d.show)!=null?Ee:!1,p=(X=l==null?void 0:l.show)!=null?X:!1,g=(Ae=d==null?void 0:d.position)!=null?Ae:"left",m=(ge=l==null?void 0:l.position)!=null?ge:"below",w=Dy(e.role,i),x=b("div",w.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let M=ky(e),P=(ue=(le=e.content)==null?void 0:le.trim())!=null?ue:"",H=M.length>0&&P===Ya,_=ai((j=(je=s==null?void 0:s.widgetConfig)==null?void 0:je.features)==null?void 0:j.streamAnimation),B=(tt=(Re=(oe=s==null?void 0:s.widgetConfig)==null?void 0:oe.features)==null?void 0:Re.streamAnimation)==null?void 0:tt.plugins,v=e.role==="assistant"&&_.type!=="none"?_s(_.type,B):null,C=e.role==="assistant"&&((fe=v==null?void 0:v.isAnimating)==null?void 0:fe.call(v,e))===!0,E=e.role==="assistant"&&v!==null&&(!!e.streaming||C);E&&(v!=null&&v.bubbleClass)&&x.classList.add(v.bubbleClass);let S=document.createElement("div");S.classList.add("persona-message-content"),E&&v&&(v.containerClass&&S.classList.add(v.containerClass),S.style.setProperty("--persona-stream-step",`${_.speed}ms`),S.style.setProperty("--persona-stream-duration",`${_.duration}ms`));let k=E?ii((ce=e.content)!=null?ce:"",_.buffer,v,e,!!e.streaming):(_e=e.content)!=null?_e:"",D=t({text:k,message:e,streaming:!!e.streaming,raw:e.rawContent}),$=D;E&&(v==null?void 0:v.wrap)==="char"?$=Vs(D,"char",e.id,{skipTags:v.skipTags}):E&&(v==null?void 0:v.wrap)==="word"&&($=Vs(D,"word",e.id,{skipTags:v.skipTags}));let q=null;if(H?(q=document.createElement("div"),q.innerHTML=$,q.style.display="none",S.appendChild(q)):S.innerHTML=$,E&&(v!=null&&v.useCaret)&&!H&&P){let Y=li(),Ve=S.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ct=Ve[Ve.length-1];if(Ct!=null&&Ct.parentNode)Ct.parentNode.insertBefore(Y,Ct.nextSibling);else{let Q=S.lastElementChild;Q?Q.appendChild(Y):S.appendChild(Y)}}if(p&&m==="inline"&&e.createdAt){let Y=Yu(e,l);Y.classList.add("persona-ml-2","persona-inline"),S.appendChild(Y)}if(M.length>0){let Y=Iy(M,!H&&!!P,()=>{H&&q&&(q.style.display="")});Y?x.appendChild(Y):H&&q&&(q.style.display="")}let me=Ey(e);if(me.length>0){let Y=Ry(me);Y&&x.appendChild(Y)}let re=My(e);if(re.length>0){let Y=Py(re);Y&&x.appendChild(Y)}let be=Ly(e);if(be.length>0){let Y=Wy(be);Y&&x.appendChild(Y)}if(x.appendChild(S),p&&m==="below"&&e.createdAt){let Y=Yu(e,l);Y.classList.add("persona-mt-1"),x.appendChild(Y)}let ie=e.role==="assistant"?Sy(e.stopReason,(de=(Le=s==null?void 0:s.widgetConfig)==null?void 0:Le.copy)==null?void 0:de.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Y=!!(k&&k.trim()),Ve=_.placeholder==="skeleton",Ct=Ve&&_.buffer==="line"&&Y;if(Y)Ct&&x.appendChild($s());else if(Ve)x.appendChild($s());else{let Q=By("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Q&&x.appendChild(Q)}}if(ie&&e.stopReason&&!e.streaming&&(P||(S.style.display="none"),x.appendChild(Ay(e.stopReason,ie))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let Y=Fy(e,o,r);x.appendChild(Y)}if(!u||e.role==="system")return x;let We=b("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ye=Hy(d,e.role);return g==="right"||g==="left"&&e.role==="user"?We.append(x,ye):We.append(ye,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),We};var Kr=new Set,Oy=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Ny=(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
|
-
`):""},
|
|
23
|
+
`,n.addEventListener("click",t);let o=s=>{var H,D,B,v,w,E,S,k,F,$,q,me,re,be;let a=(H=s.launcher)!=null?H:{},i=un(s),d=n.querySelector("[data-role='launcher-title']");if(d){let ie=(D=a.title)!=null?D:"Chat Assistant";d.textContent=ie,d.setAttribute("title",ie)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let ie=(B=a.subtitle)!=null?B:"Get answers fast";l.textContent=ie,l.setAttribute("title",ie)}let u=n.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let p=n.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let ie=(v=a.agentIconSize)!=null?v:"40px";if(p.style.height=ie,p.style.width=ie,p.innerHTML="",a.agentIconName){let we=parseFloat(ie)||24,We=Se(a.agentIconName,we*.6,"var(--persona-text-inverse, #ffffff)",2);We?(p.appendChild(We),p.style.display=""):(p.textContent=(w=a.agentIconText)!=null?w:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(E=a.agentIconText)!=null?E:"\u{1F4AC}",p.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let ie=(S=a.agentIconSize)!=null?S:"40px";f.style.height=ie,f.style.width=ie,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let g=n.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let ie=(k=a.callToActionIconSize)!=null?k:"32px";g.style.height=ie,g.style.width=ie,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let we=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,we=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=i?"none":"",g.innerHTML="",a.callToActionIconName){let We=parseFloat(ie)||24,ye=Math.max(We-we,8),Z=Se(a.callToActionIconName,ye,"currentColor",2);Z?g.appendChild(Z):g.textContent=(F=a.callToActionIconText)!=null?F:"\u2197"}else g.textContent=($=a.callToActionIconText)!=null?$:"\u2197"}let x=a.position&&xo[a.position]?xo[a.position]:xo["bottom-right"],C="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",M="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?M:`${C} ${x}`,i||(n.style.zIndex=String((q=a.zIndex)!=null?q:bn));let W="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:W,n.style.boxShadow=(re=a.shadow)!=null?re: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=(be=a.collapsedMaxWidth)!=null?be:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}};var yy="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",di=(e,t={})=>{var C,M,W,L,H,D;let{showClose:n=!0,wrapperClassName:o=yy,buttonSize:r,iconSize:s="28px"}=t,a=(C=e==null?void 0:e.launcher)!=null?C:{},i=(M=r!=null?r:a.closeButtonSize)!=null?M:"32px",d=b("div",o),l=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let u=(W=a.closeButtonTooltipText)!=null?W:"Close chat",p=(L=a.closeButtonShowTooltip)!=null?L:!0;l.setAttribute("aria-label",u),l.style.display=n?"":"none";let f=(H=a.closeButtonIconName)!=null?H:"x",g=(D=a.closeButtonIconText)!=null?D:"\xD7";l.style.color=a.closeButtonColor||Mn.actionIconColor;let x=Se(f,s,"currentColor",1);if(x?(x.style.display="block",l.appendChild(x)):l.textContent=g,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let B=a.closeButtonBorderWidth||"0px",v=a.closeButtonBorderColor||"transparent";l.style.border=`${B} solid ${v}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),p&&u){let B=null,v=()=>{if(B)return;let E=l.ownerDocument,S=E.body;if(!S)return;B=Eo(E,"div","persona-clear-chat-tooltip"),B.textContent=u;let k=Eo(E,"div");k.className="persona-clear-chat-tooltip-arrow",B.appendChild(k);let F=l.getBoundingClientRect();B.style.position="fixed",B.style.zIndex=String(nr),B.style.left=`${F.left+F.width/2}px`,B.style.top=`${F.top-8}px`,B.style.transform="translate(-50%, -100%)",S.appendChild(B)},w=()=>{B&&B.parentNode&&(B.parentNode.removeChild(B),B=null)};d.addEventListener("mouseenter",v),d.addEventListener("mouseleave",w),l.addEventListener("focus",v),l.addEventListener("blur",w),d._cleanupTooltip=()=>{w(),d.removeEventListener("mouseenter",v),d.removeEventListener("mouseleave",w),l.removeEventListener("focus",v),l.removeEventListener("blur",w)}}return{button:l,wrapper:d}},vy="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",pi=(e,t={})=>{var B,v,w,E,S,k,F,$,q,me,re,be,ie;let{wrapperClassName:n=vy,buttonSize:o,iconSize:r="20px"}=t,a=(v=((B=e==null?void 0:e.launcher)!=null?B:{}).clearChat)!=null?v:{},i=(w=o!=null?o:a.size)!=null?w:"32px",d=(E=a.iconName)!=null?E:"refresh-cw",l=(S=a.iconColor)!=null?S:"",u=(k=a.backgroundColor)!=null?k:"",p=(F=a.borderWidth)!=null?F:"",f=($=a.borderColor)!=null?$:"",g=(q=a.borderRadius)!=null?q:"",x=(me=a.paddingX)!=null?me:"",C=(re=a.paddingY)!=null?re:"",M=(be=a.tooltipText)!=null?be:"Clear chat",W=(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=Se(d,r,"currentColor",1);if(D&&(D.style.display="block",H.appendChild(D)),u&&(H.style.backgroundColor=u,H.classList.remove("hover:persona-bg-gray-100")),p||f){let we=p||"0px",We=f||"transparent";H.style.border=`${we} solid ${We}`,H.classList.remove("persona-border-none")}if(g&&(H.style.borderRadius=g,H.classList.remove("persona-rounded-full")),x&&(H.style.paddingLeft=x,H.style.paddingRight=x),C&&(H.style.paddingTop=C,H.style.paddingBottom=C),L.appendChild(H),W&&M){let we=null,We=()=>{if(we)return;let Z=H.ownerDocument,Ee=Z.body;if(!Ee)return;we=Eo(Z,"div","persona-clear-chat-tooltip"),we.textContent=M;let X=Eo(Z,"div");X.className="persona-clear-chat-tooltip-arrow",we.appendChild(X);let Ae=H.getBoundingClientRect();we.style.position="fixed",we.style.zIndex=String(nr),we.style.left=`${Ae.left+Ae.width/2}px`,we.style.top=`${Ae.top-8}px`,we.style.transform="translate(-50%, -100%)",Ee.appendChild(we)},ye=()=>{we&&we.parentNode&&(we.parentNode.removeChild(we),we=null)};L.addEventListener("mouseenter",We),L.addEventListener("mouseleave",ye),H.addEventListener("focus",We),H.addEventListener("blur",ye),L._cleanupTooltip=()=>{ye(),L.removeEventListener("mouseenter",We),L.removeEventListener("mouseleave",ye),H.removeEventListener("focus",We),H.removeEventListener("blur",ye)}}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))"},Sr=e=>{var B,v,w,E,S,k,F,$,q,me,re,be,ie,we,We,ye;let{config:t,showClose:n=!0}=e,o=b("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");o.setAttribute("data-persona-theme-zone","header"),o.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",o.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",o.style.boxShadow="var(--persona-header-shadow, none)",o.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let r=(B=t==null?void 0:t.launcher)!=null?B:{},s=(v=r.headerIconSize)!=null?v:"48px",a=(w=r.closeButtonPlacement)!=null?w:"inline",i=(E=r.headerIconHidden)!=null?E:!1,d=r.headerIconName,l=b("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let Z=parseFloat(s)||24,Ee=Se(d,Z*.6,"currentColor",1);Ee?l.replaceChildren(Ee):l.textContent=(k=(S=t==null?void 0:t.launcher)==null?void 0:S.agentIconText)!=null?k:"\u{1F4AC}"}else if((F=t==null?void 0:t.launcher)!=null&&F.iconUrl){let Z=b("img");Z.src=t.launcher.iconUrl,Z.alt="",Z.className="persona-rounded-xl persona-object-cover",Z.style.height=s,Z.style.width=s,l.replaceChildren(Z)}else l.textContent=(q=($=t==null?void 0:t.launcher)==null?void 0:$.agentIconText)!=null?q:"\u{1F4AC}";let u=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),p=b("span","persona-text-base persona-font-semibold");p.style.color=Mn.titleColor,p.textContent=(re=(me=t==null?void 0:t.launcher)==null?void 0:me.title)!=null?re:"Chat Assistant";let f=b("span","persona-text-xs");f.style.color=Mn.subtitleColor,f.textContent=(ie=(be=t==null?void 0:t.launcher)==null?void 0:be.subtitle)!=null?ie:"Here to help you get answers fast",u.append(p,f),i?o.append(u):o.append(l,u);let g=(we=r.clearChat)!=null?we:{},x=(We=g.enabled)!=null?We:!0,C=(ye=g.placement)!=null?ye:"inline",M=null,W=null;if(x){let Ee=pi(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=Ee.button,W=Ee.wrapper,C==="top-right"&&(W.style.right="48px"),C==="inline"&&o.appendChild(W)}let L=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:H,wrapper:D}=di(t,{showClose:n,wrapperClassName:L});return a!=="top-right"&&o.appendChild(D),{header:o,iconHolder:l,headerTitle:p,headerSubtitle:f,closeButton:H,closeButtonWrapper:D,clearChatButton:M,clearChatButtonWrapper:W}},js=(e,t,n)=>{var a,i,d,l;let o=(a=n==null?void 0:n.launcher)!=null?a:{},r=(i=o.closeButtonPlacement)!=null?i:"inline",s=(l=(d=o.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function jr(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=e,a=b("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(nr)):(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 g of t){if(g.dividerBefore){let M=document.createElement("hr");a.appendChild(M)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",g.id),g.destructive&&x.setAttribute("data-destructive",""),g.icon){let M=Se(g.icon,16,"currentColor",1.5);M&&x.appendChild(M)}let C=document.createElement("span");C.textContent=g.label,x.appendChild(C),x.addEventListener("click",M=>{M.stopPropagation(),u(),n(g.id)}),a.appendChild(x)}let i=null;function d(){if(!s)return;let g=o.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=x=>{!a.contains(x.target)&&!o.contains(x.target)&&u()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function p(){a.classList.contains("persona-hidden")?l():u()}function f(){u(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:u,toggle:p,destroy:f}}function yn(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:i}=e,d=b("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=Se(t,o!=null?o:16,"currentColor",r!=null?r:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[u,p]of Object.entries(i))d.setAttribute(u,p);return d}function gl(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";o!=="default"&&(l+=" persona-label-btn--"+o),l+=" persona-label-btn--"+r,a&&(l+=" "+a);let u=b("button",l);if(u.type="button",u.setAttribute("aria-label",n),t){let f=Se(t,s!=null?s:14,"currentColor",2);f&&u.appendChild(f)}let p=b("span");if(p.textContent=n,u.appendChild(p),i&&u.addEventListener("click",i),d)for(let[f,g]of Object.entries(d))u.setAttribute(f,g);return u}function qu(e){var g,x;let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:i,hover:d}=e,l=b("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let u=b("span","persona-combo-btn-label");u.textContent=t,l.appendChild(u);let p=Se(n,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",l.appendChild(p)),d&&(l.style.borderRadius=(g=d.borderRadius)!=null?g:"10px",l.style.padding=(x=d.padding)!=null?x:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var C,M;l.style.backgroundColor=(C=d.background)!=null?C:"",l.style.borderColor=(M=d.border)!=null?M:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=jr({items:o,onSelect:C=>{l.setAttribute("aria-expanded","false"),r(C)},anchor:l,position:s,portal:a});return a||l.appendChild(f.element),l.addEventListener("click",C=>{C.stopPropagation();let M=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",M?"false":"true"),f.toggle()}),l.addEventListener("keydown",C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),l.click())}),{element:l,setLabel:C=>{u.textContent=C,l.setAttribute("aria-label",C)},open:()=>{l.setAttribute("aria-expanded","true"),f.show()},close:()=>{l.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let C=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",C?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}var xy=e=>{var o;let t=Sr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(o=e.layoutHeaderConfig)==null?void 0:o.onTitleClick;if(n){let r=t.headerTitle.parentElement;r&&(r.style.cursor="pointer",r.setAttribute("role","button"),r.setAttribute("tabindex","0"),r.addEventListener("click",()=>n()),r.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function wy(e,t,n){var o,r,s;if(t!=null&&t.length)for(let a of t){let i=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(r=(o=a.ariaLabel)!=null?o:a.label)!=null?r:a.id),a.icon){let d=Se(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=b("div","persona-relative");d.appendChild(i);let l=jr({items:a.menuItems,onSelect:u=>n==null?void 0:n(u),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",u=>{u.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var Cy=e=>{var L,H,D,B,v,w,E,S,k;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,u;if(d)l=qu({label:(H=a.title)!=null?H:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Mn.titleColor,u=(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"),u=b("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=Mn.titleColor,u.textContent=(B=a.title)!=null?B:"Chat Assistant",l.appendChild(u),wy(l,r==null?void 0:r.trailingActions,(v=r==null?void 0:r.onAction)!=null?v:s),r!=null&&r.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let $=r.onTitleClick;l.addEventListener("click",q=>{q.target.closest("button")||$()}),l.addEventListener("keydown",q=>{(q.key==="Enter"||q.key===" ")&&(q.preventDefault(),$())})}let F=r==null?void 0:r.titleRowHover;F&&(l.style.borderRadius=(w=F.borderRadius)!=null?w:"10px",l.style.padding=(E=F.padding)!=null?E:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var $,q;l.style.backgroundColor=($=F.background)!=null?$:"",l.style.borderColor=(q=F.border)!=null?q:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let p=(S=a.closeButtonSize)!=null?S:"32px",f=b("div",""),g=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");g.style.height=p,g.style.width=p,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=n?"":"none",g.style.color=a.closeButtonColor||Mn.actionIconColor;let x=(k=a.closeButtonIconName)!=null?k:"x",C=Se(x,"28px","currentColor",1);C?g.appendChild(C):g.textContent="\xD7",o&&g.addEventListener("click",o),f.appendChild(g),i.appendChild(f);let M=b("div");M.style.display="none";let W=b("span");return W.style.display="none",{header:i,iconHolder:M,headerTitle:u,headerSubtitle:W,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},ju={default:xy,minimal:Cy},Sy=e=>{var t;return(t=ju[e])!=null?t:ju.default},ui=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),u=b("div");u.style.display="none";let p=b("span"),f=b("span"),g=b("button");g.style.display="none";let x=b("div");return x.style.display="none",{header:l,iconHolder:u,headerTitle:p,headerSubtitle:f,closeButton:g,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let o=(a=t==null?void 0:t.layout)!=null?a:"default",s=Sy(o)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var mi=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}},gi=e=>{var B,v,w,E,S,k,F,$,q,me,re,be;let t=(B=e==null?void 0:e.sendButton)!=null?B:{},n=(v=t.useIcon)!=null?v:!1,o=(w=t.iconText)!=null?w:"\u2191",r=t.iconName,s=(E=t.stopIconName)!=null?E:"square",a=(S=t.tooltipText)!=null?S:"Send message",i=(k=t.stopTooltipText)!=null?k:"Stop generating",d=($=(F=e==null?void 0:e.copy)==null?void 0:F.sendButtonLabel)!=null?$:"Send",l=(me=(q=e==null?void 0:e.copy)==null?void 0:q.stopButtonLabel)!=null?me:"Stop",u=(re=t.showTooltip)!=null?re:!1,p=(be=t.size)!=null?be:"40px",f=t.backgroundColor,g=t.textColor,x=b("div","persona-send-button-wrapper"),C=b("button",n?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");C.type="submit",C.setAttribute("data-persona-composer-submit","");let M=null,W=null;if(n){C.style.width=p,C.style.height=p,C.style.minWidth=p,C.style.minHeight=p,C.style.fontSize="18px",C.style.lineHeight="1",C.innerHTML="",g?C.style.color=g:C.style.color="var(--persona-button-primary-fg, #ffffff)";let ie=parseFloat(p)||24,we=(g==null?void 0:g.trim())||"currentColor";r?(M=Se(r,ie,we,2),M?C.appendChild(M):C.textContent=o):C.textContent=o,W=Se(s,ie,we,2),f?C.style.backgroundColor=f:C.classList.add("persona-bg-persona-primary")}else C.textContent=d,g?C.style.color=g:C.classList.add("persona-text-white");t.borderWidth&&(C.style.borderWidth=t.borderWidth,C.style.borderStyle="solid"),t.borderColor&&(C.style.borderColor=t.borderColor),t.paddingX?(C.style.paddingLeft=t.paddingX,C.style.paddingRight=t.paddingX):(C.style.paddingLeft="",C.style.paddingRight=""),t.paddingY?(C.style.paddingTop=t.paddingY,C.style.paddingBottom=t.paddingY):(C.style.paddingTop="",C.style.paddingBottom="");let L=null;u&&a&&(L=b("div","persona-send-button-tooltip"),L.textContent=a,x.appendChild(L)),C.setAttribute("aria-label",a),x.appendChild(C);let H="send";return{button:C,wrapper:x,setMode:ie=>{if(ie===H)return;H=ie;let we=ie==="stop"?i:a;if(C.setAttribute("aria-label",we),L&&(L.textContent=we),n){if(M&&W){let We=ie==="stop"?W:M;C.replaceChildren(We)}}else C.textContent=ie==="stop"?l:d}}},fi=e=>{var L,H,D,B,v,w,E,S,k,F,$,q;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=(B=(D=e==null?void 0:e.sendButton)==null?void 0:D.size)!=null?B:"40px",i=b("div","persona-send-button-wrapper"),d=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(v=t.iconName)!=null?v:"mic",u=(w=t.iconSize)!=null?w:a,p=parseFloat(u)||24,f=(S=t.backgroundColor)!=null?S:(E=e==null?void 0:e.sendButton)==null?void 0:E.backgroundColor,g=(F=t.iconColor)!=null?F:(k=e==null?void 0:e.sendButton)==null?void 0:k.textColor;d.style.width=u,d.style.height=u,d.style.minWidth=u,d.style.minHeight=u,d.style.fontSize="18px",d.style.lineHeight="1",g?d.style.color=g:d.style.color="var(--persona-text, #111827)";let C=Se(l,p,g||"currentColor",1.5);C?d.appendChild(C):d.textContent="\u{1F3A4}",f&&(d.style.backgroundColor=f),t.borderWidth&&(d.style.borderWidth=t.borderWidth,d.style.borderStyle="solid"),t.borderColor&&(d.style.borderColor=t.borderColor),t.paddingX&&(d.style.paddingLeft=t.paddingX,d.style.paddingRight=t.paddingX),t.paddingY&&(d.style.paddingTop=t.paddingY,d.style.paddingBottom=t.paddingY),i.appendChild(d);let M=($=t.tooltipText)!=null?$:"Start voice recognition";if(((q=t.showTooltip)!=null?q:!1)&&M){let me=b("div","persona-send-button-tooltip");me.textContent=M,i.appendChild(me)}return{button:d,wrapper:i}},hi=e=>{var x,C,M,W,L,H,D,B;let t=(x=e==null?void 0:e.attachments)!=null?x:{};if(t.enabled!==!0)return null;let n=(M=(C=e==null?void 0:e.sendButton)==null?void 0:C.size)!=null?M:"40px",o=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.style.display="none";let r=b("input");r.type="file",r.accept=((W=t.allowedTypes)!=null?W:_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,u=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let p=Se(i,u,"currentColor",1.5);p?a.appendChild(p):a.textContent="\u{1F4CE}",a.addEventListener("click",v=>{v.preventDefault(),r.click()}),s.appendChild(a);let f=(B=t.buttonTooltipText)!=null?B:"Attach file",g=b("div","persona-send-button-tooltip");return g.textContent=f,s.appendChild(g),{button:a,wrapper:s,input:r,previewsContainer:o}},bi=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},yi=()=>b("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var vi=e=>{var x,C,M,W,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=yi(),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}=mi(t);a();let i=gi(t),d=fi(t),l=hi(t),u=bi(t);l&&(l.previewsContainer.style.gap="8px",r.append(l.previewsContainer,l.input)),r.append(s);let p=b("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),f=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&f.append(l.wrapper),d&&g.append(d.wrapper),g.append(i.wrapper),p.append(f,g),r.append(p),r.addEventListener("click",D=>{D.target!==i.button&&D.target!==i.wrapper&&D.target!==(d==null?void 0:d.button)&&D.target!==(d==null?void 0:d.wrapper)&&D.target!==(l==null?void 0:l.button)&&D.target!==(l==null?void 0:l.wrapper)&&s.focus()}),n.append(o,r,u),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(C=d==null?void 0:d.wrapper)!=null?C:null,statusText:u,attachmentButton:(M=l==null?void 0:l.button)!=null?M:null,attachmentButtonWrapper:(W=l==null?void 0:l.wrapper)!=null?W: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:f,rightActions:g,setSendButtonMode:i.setMode}};var Ku=()=>{let e=b("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let t=b("span","persona-pill-peek__icon"),n=Se("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=Se("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},Gu=e=>{var x,C,M,W,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=yi();o.style.display="none";let r=bi(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=mi(t);s.style.maxHeight="100px",a();let i=gi(t),d=fi(t),l=hi(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let u=b("form","persona-widget-composer persona-pill-composer");u.setAttribute("data-persona-composer-form",""),u.style.outline="none";let p=b("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&p.append(l.wrapper);let f=b("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),u.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&&u.append(l.input),u.append(p,s,f),l&&n.append(l.previewsContainer),n.append(u,o,r);let g=u;return{footer:n,suggestions:o,composerForm:u,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(C=d==null?void 0:d.wrapper)!=null?C:null,statusText:r,attachmentButton:(M=l==null?void 0:l.button)!=null?M:null,attachmentButtonWrapper:(W=l==null?void 0:l.wrapper)!=null?W:null,attachmentInput:(L=l==null?void 0:l.input)!=null?L:null,attachmentPreviewsContainer:(H=l==null?void 0:l.previewsContainer)!=null?H:null,actionsRow:g,leftActions:p,rightActions:f,setSendButtonMode:i.setMode}};var Yu=e=>{var u,p,f,g,x,C,M,W,L,H,D,B,v,w,E,S,k;let t=(p=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?p:!0,n=un(e);if(zs(e)){let F=(g=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?g:{},$=b("div","persona-widget-wrapper persona-fixed persona-transition");$.setAttribute("data-persona-composer-bar",""),$.dataset.state="collapsed",$.dataset.expandedSize=(x=F.expandedSize)!=null?x:"anchored",$.style.zIndex=String((M=(C=e==null?void 0:e.launcher)==null?void 0:C.zIndex)!=null?M:bn);let q=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");q.style.width="100%",$.appendChild(q);let me=b("div","persona-widget-pill-root");return me.setAttribute("data-persona-composer-bar",""),me.dataset.state="collapsed",me.dataset.expandedSize=(W=F.expandedSize)!=null?W:"anchored",me.style.zIndex=String((H=(L=e==null?void 0:e.launcher)==null?void 0:L.zIndex)!=null?H:bn),{wrapper:$,panel:q,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"),q=(B=(D=e==null?void 0:e.launcher)==null?void 0:D.width)!=null?B:"100%";return F.style.width=q,$.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((E=(w=e==null?void 0:e.launcher)==null?void 0:w.zIndex)!=null?E:bn);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(k=(S=e==null?void 0:e.launcher)==null?void 0:S.width)!=null?k:e==null?void 0:e.launcherWidth,l=d!=null?d:io;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Ay=(e,t)=>{var D,B,v,w,E,S,k,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}=di(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=(v=(B=(D=e==null?void 0:e.launcher)==null?void 0:D.clearChat)==null?void 0:B.enabled)!=null?v:!0,a=null,i=null;if(s){let q=pi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=q.button,i=q.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 u=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");u.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",u.setAttribute("data-persona-intro-card","");let p=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");p.textContent=(E=(w=e==null?void 0:e.copy)==null?void 0:w.welcomeTitle)!=null?E:"Hello \u{1F44B}";let f=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(k=(S=e==null?void 0:e.copy)==null?void 0:S.welcomeSubtitle)!=null?k:"Ask anything about your account or products.",u.append(p,f);let g=b("div","persona-flex persona-flex-col persona-gap-3"),x=(F=e==null?void 0:e.layout)==null?void 0:F.contentMaxWidth;x&&(g.style.maxWidth=x,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),(($=e==null?void 0:e.copy)==null?void 0:$.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,g);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 W=Gu({config:e}),{root:L,textNode:H}=Ku();return n.append(d,r,l,M),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:g,composerOverlay:M,suggestions:W.suggestions,textarea:W.textarea,sendButton:W.sendButton,sendButtonWrapper:W.sendButtonWrapper,micButton:W.micButton,micButtonWrapper:W.micButtonWrapper,composerForm:W.composerForm,statusText:W.statusText,introTitle:p,introSubtitle:f,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:d,footer:W.footer,attachmentButton:W.attachmentButton,attachmentButtonWrapper:W.attachmentButtonWrapper,attachmentInput:W.attachmentInput,attachmentPreviewsContainer:W.attachmentPreviewsContainer,actionsRow:W.actionsRow,leftActions:W.leftActions,rightActions:W.rightActions,setSendButtonMode:W.setSendButtonMode,peekBanner:L,peekTextNode:H}},Xu=(e,t=!0)=>{var M,W,L,H,D,B,v,w,E;if(zs(e))return Ay(e,t);let n=b("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");n.setAttribute("data-persona-theme-zone","container");let o=(M=e==null?void 0:e.layout)==null?void 0:M.header,r=((W=e==null?void 0:e.layout)==null?void 0:W.showHeader)!==!1,s=o?ui(e,o,{showClose:t}):Sr({config:e,showClose:t}),a=b("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=un(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(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=(B=(D=e==null?void 0:e.copy)==null?void 0:D.welcomeSubtitle)!=null?B:"Ask anything about your account or products.",i.append(d,l);let u=b("div","persona-flex persona-flex-col persona-gap-3"),p=(v=e==null?void 0:e.layout)==null?void 0:v.contentMaxWidth;p&&(u.style.maxWidth=p,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((w=e==null?void 0:e.copy)==null?void 0:w.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,u);let g=vi({config:e}),x=((E=e==null?void 0:e.layout)==null?void 0:E.showFooter)!==!1;r?js(n,s,e):(s.header.style.display="none",js(n,s,e)),n.append(a);let C=b("div","persona-composer-overlay persona-pointer-events-none");return C.setAttribute("data-persona-composer-overlay",""),C.style.position="absolute",C.style.left="0",C.style.right="0",C.style.bottom="0",C.style.zIndex="20",x||(g.footer.style.display="none"),n.append(g.footer),n.append(C),{container:n,body:a,messagesWrapper:u,composerOverlay:C,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.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:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};var Ty=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},ky=(e,t)=>{if(!e)return null;let n=Ty(e);if(n===null)return null;let o=t==null?void 0:t[e],r=o!==void 0?o:n;return r||null},Ey=(e,t)=>{let n=b("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},My=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},fl=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,Ju=320,Ly=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Iy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Ry=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Py=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Wy=(e,t,n)=>{if(e.length===0)return null;try{let o=b("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n==null||n())};return e.forEach((i,d)=>{var p;let l=b("img");l.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${hl}px`,l.style.maxHeight=`${Ju}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;r+=1,l.addEventListener("error",()=>{u||(u=!0,r=Math.max(0,r-1),l.remove(),r===0&&a())}),l.addEventListener("load",()=>{u=!0}),My(i.image)?(l.src=i.image,o.appendChild(l)):(u=!0,r=Math.max(0,r-1),l.remove())}),r===0?(a(),null):o}catch{return n==null||n(),null}},By=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!fl(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}},Hy=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!fl(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=`${Ju}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Dy=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!fl(o.data))return;let r=b("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Ks=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},Fy=(e,t,n)=>{let o={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Ks};if(t){let r=t(o);if(r!==null)return r}return Ks()},Oy=(e,t)=>{let n=b("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=b("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Qu=(e,t)=>{let n=b("div","persona-text-xs persona-text-persona-muted"),o=new Date(e.createdAt);return t.format?n.textContent=t.format(o):n.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},Ny=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},_y=(e,t,n)=>{var g,x,C,M,W,L;let o=(g=t.showCopy)!=null?g:!0,r=(x=t.showUpvote)!=null?x:!0,s=(C=t.showDownvote)!=null?C:!0;if(!o&&!r&&!s){let H=b("div");return H.style.display="none",H.id=`actions-${e.id}`,H.setAttribute("data-actions-for",e.id),H}let a=(M=t.visibility)!=null?M:"hover",i=(W=t.align)!=null?W:"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],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${u} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let f=(H,D,B)=>{let v=yn({icon:H,label:D,size:14,className:"persona-message-action-btn"});return v.setAttribute("data-action",B),v};return o&&p.appendChild(f("copy","Copy message","copy")),r&&p.appendChild(f("thumbs-up","Upvote","upvote")),s&&p.appendChild(f("thumbs-down","Downvote","downvote")),p},bl=(e,t,n,o,r,s)=>{var Z,Ee,X,Ae,fe,le,ue,je,j,oe,Re,tt,ge,ce,_e,Le,de;let a=n!=null?n:{},i=(Z=a.layout)!=null?Z:"bubble",d=a.avatar,l=a.timestamp,u=(Ee=d==null?void 0:d.show)!=null?Ee:!1,p=(X=l==null?void 0:l.show)!=null?X:!1,f=(Ae=d==null?void 0:d.position)!=null?Ae:"left",g=(fe=l==null?void 0:l.position)!=null?fe:"below",x=Ny(e.role,i),C=b("div",x.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let M=Ly(e),W=(ue=(le=e.content)==null?void 0:le.trim())!=null?ue:"",H=M.length>0&&W===Ya,D=ai((j=(je=s==null?void 0:s.widgetConfig)==null?void 0:je.features)==null?void 0:j.streamAnimation),B=(tt=(Re=(oe=s==null?void 0:s.widgetConfig)==null?void 0:oe.features)==null?void 0:Re.streamAnimation)==null?void 0:tt.plugins,v=e.role==="assistant"&&D.type!=="none"?_s(D.type,B):null,w=e.role==="assistant"&&((ge=v==null?void 0:v.isAnimating)==null?void 0:ge.call(v,e))===!0,E=e.role==="assistant"&&v!==null&&(!!e.streaming||w);E&&(v!=null&&v.bubbleClass)&&C.classList.add(v.bubbleClass);let S=document.createElement("div");S.classList.add("persona-message-content"),E&&v&&(v.containerClass&&S.classList.add(v.containerClass),S.style.setProperty("--persona-stream-step",`${D.speed}ms`),S.style.setProperty("--persona-stream-duration",`${D.duration}ms`));let k=E?ii((ce=e.content)!=null?ce:"",D.buffer,v,e,!!e.streaming):(_e=e.content)!=null?_e:"",F=t({text:k,message:e,streaming:!!e.streaming,raw:e.rawContent}),$=F;E&&(v==null?void 0:v.wrap)==="char"?$=Vs(F,"char",e.id,{skipTags:v.skipTags}):E&&(v==null?void 0:v.wrap)==="word"&&($=Vs(F,"word",e.id,{skipTags:v.skipTags}));let q=null;if(H?(q=document.createElement("div"),q.innerHTML=$,q.style.display="none",S.appendChild(q)):S.innerHTML=$,E&&(v!=null&&v.useCaret)&&!H&&W){let Y=li(),Ve=S.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ct=Ve[Ve.length-1];if(Ct!=null&&Ct.parentNode)Ct.parentNode.insertBefore(Y,Ct.nextSibling);else{let Q=S.lastElementChild;Q?Q.appendChild(Y):S.appendChild(Y)}}if(p&&g==="inline"&&e.createdAt){let Y=Qu(e,l);Y.classList.add("persona-ml-2","persona-inline"),S.appendChild(Y)}if(M.length>0){let Y=Wy(M,!H&&!!W,()=>{H&&q&&(q.style.display="")});Y?C.appendChild(Y):H&&q&&(q.style.display="")}let me=Iy(e);if(me.length>0){let Y=By(me);Y&&C.appendChild(Y)}let re=Ry(e);if(re.length>0){let Y=Hy(re);Y&&C.appendChild(Y)}let be=Py(e);if(be.length>0){let Y=Dy(be);Y&&C.appendChild(Y)}if(C.appendChild(S),p&&g==="below"&&e.createdAt){let Y=Qu(e,l);Y.classList.add("persona-mt-1"),C.appendChild(Y)}let ie=e.role==="assistant"?ky(e.stopReason,(de=(Le=s==null?void 0:s.widgetConfig)==null?void 0:Le.copy)==null?void 0:de.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Y=!!(k&&k.trim()),Ve=D.placeholder==="skeleton",Ct=Ve&&D.buffer==="line"&&Y;if(Y)Ct&&C.appendChild($s());else if(Ve)C.appendChild($s());else{let Q=Fy("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Q&&C.appendChild(Q)}}if(ie&&e.stopReason&&!e.streaming&&(W||(S.style.display="none"),C.appendChild(Ey(e.stopReason,ie))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let Y=_y(e,o,r);C.appendChild(Y)}if(!u||e.role==="system")return C;let We=b("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ye=Oy(d,e.role);return f==="right"||f==="left"&&e.role==="user"?We.append(C,ye):We.append(ye,C),C.classList.remove("persona-max-w-[85%]"),C.classList.add("persona-max-w-[calc(85%-2.5rem)]"),We};var Kr=new Set,Vy=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),$y=(e,t)=>{var o,r;let n=(r=(o=e.reasoning)==null?void 0:o.chunks.join("").trim())!=null?r:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
|
|
24
|
+
`):""},Zu=(e,t)=>{let n=Kr.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let a=o.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=Se(n?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},yl=(e,t)=>{var re,be,ie,we,We,ye,Z,Ee,X,Ae,fe;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=(be=(re=t==null?void 0:t.features)==null?void 0:re.reasoningDisplay)!=null?be:{},s=r.expandable!==!1,a=s&&Kr.has(e.id),i=n.status!=="complete",d=$y(e,(ie=r.previewMaxLines)!=null?ie:3),l=b("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",s&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let u=b("div","persona-flex persona-flex-col persona-text-left"),p=b("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",g=(we=t==null?void 0:t.reasoning)!=null?we:{},x=String((We=n.startedAt)!=null?We:Date.now()),C=()=>{let le=b("span","");return le.setAttribute("data-tool-elapsed",x),le.textContent=za(n),le},M=(ye=g.renderCollapsedSummary)==null?void 0:ye.call(g,{message:e,reasoning:n,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:za(n),createElapsedElement:C});typeof M=="string"&&M.trim()?(p.textContent=M,u.appendChild(p)):M instanceof HTMLElement?u.appendChild(M):(p.textContent=f,u.appendChild(p));let W=b("span","persona-text-xs persona-text-persona-primary");W.textContent=Su(n),u.appendChild(W);let L=(Z=r.loadingAnimation)!=null?Z:"none",H=g.activeTextTemplate,D=g.completeTextTemplate,B=i?H:D,v=M instanceof HTMLElement,w=(le,ue,je)=>{let j=je;for(let oe of ue){let Re=b("span","persona-tool-char");Re.style.setProperty("--char-index",String(j)),Re.textContent=oe===" "?"\xA0":oe,le.appendChild(Re),j++}return j},E=(le,ue)=>{p.textContent="";let je=qa(le,""),j=0;for(let oe of je){let Re=oe.styles.length>0?(()=>{let tt=b("span",oe.styles.map(ge=>`persona-tool-text-${ge}`).join(" "));return p.appendChild(tt),tt})():p;if(oe.isDuration&&i)Re.appendChild(C());else{let tt=oe.isDuration?za(n):oe.text;ue?j=w(Re,tt,j):Re.appendChild(document.createTextNode(tt))}}};if(!v&&B)if(W.style.display="none",p.style.display="",i&&L!=="none"){let le=(Ee=g.loadingAnimationDuration)!=null?Ee:2e3;p.setAttribute("data-preserve-animation","true"),L==="pulse"?(p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${le}ms`),E(B,!1)):(p.classList.add(`persona-tool-loading-${L}`),p.style.setProperty("--persona-tool-anim-duration",`${le}ms`),L==="shimmer-color"&&(g.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),E(B,!0))}else E(B,!1);else if(!v&&i&&L!=="none"){p.style.display="";let le=(X=g.loadingAnimationDuration)!=null?X:2e3;if(p.setAttribute("data-preserve-animation","true"),L==="pulse")p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${le}ms`);else{p.classList.add(`persona-tool-loading-${L}`),p.style.setProperty("--persona-tool-anim-duration",`${le}ms`),L==="shimmer-color"&&(g.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let ue=p.textContent||f;p.textContent="",w(p,ue,0)}n.status==="complete"&&(p.style.display="none")}else v||(n.status==="complete"?p.style.display="none":p.style.display="");let S=null;if(s){S=b("div","persona-flex persona-items-center");let ue=Se(a?"chevron-up":"chevron-down",16,"currentColor",2);ue?S.appendChild(ue):S.textContent=a?"Hide":"Show";let je=b("div","persona-flex persona-items-center persona-ml-auto");je.append(S),l.append(u,je)}else l.append(u);let k=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(k.setAttribute("data-persona-collapsed-preview","reasoning"),k.style.display="none",k.style.whiteSpace="pre-wrap",!a&&i&&r.activePreview&&d){let le=(fe=(Ae=t==null?void 0:t.reasoning)==null?void 0:Ae.renderCollapsedPreview)==null?void 0:fe.call(Ae,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});Vy(k,le)||(k.textContent=d),k.style.display=""}if(!a&&i&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(l,k),o;let F=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");F.style.display=a?"":"none";let $=n.chunks.join(""),q=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return q.textContent=$||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),F.appendChild(q),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),S){S.innerHTML="";let ue=Se(a?"chevron-up":"chevron-down",16,"currentColor",2);ue?S.appendChild(ue):S.textContent=a?"Hide":"Show"}F.style.display=a?"":"none",k.style.display=a?"none":k.textContent||k.childNodes.length?"":"none"})(),o.append(l,k,F),o};var Gr=new Set,Uy=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),zy=(e,t)=>{var s;let n=e.toolCall;if(!n)return"";let o=((s=n.chunks)!=null?s:[]).join("").trim();if(o)return o.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
|
|
25
25
|
`);let r=qr(n.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
|
|
26
|
-
`):""},$y=(e,t)=>{var u,p,g,m,w;let n=e.toolCall,o=(u=t==null?void 0:t.features)==null?void 0:u.toolCallDisplay,r=(p=o==null?void 0:o.collapsedMode)!=null?p:"tool-call",s=Vy(e,(g=o==null?void 0:o.previewMaxLines)!=null?g:3),a=n?Cu(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=((w=n.name)==null?void 0:w.trim())||a:r==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=sl(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=sl(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},Ju=(e,t,n)=>{var u;let o=Gr.has(e),r=(u=n==null?void 0:n.toolCall)!=null?u:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let p=r.toggleTextColor||r.headerTextColor||"currentColor",g=Se(o?"chevron-up":"chevron-down",16,p,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")},vl=(e,t)=>{var $,q,me,re,be,ie,we,We,ye;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=(q=t==null?void 0:t.features)==null?void 0:q.toolCallDisplay)!=null?me:{},a=s.expandable!==!1,i=a&&Gr.has(e.id),{summary:d,previewText:l,isActive:u}=$y(e,t),p=b("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");p.type="button",a&&(p.setAttribute("aria-expanded",i?"true":"false"),p.setAttribute("data-expand-header","true")),p.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(p.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(p.style.paddingLeft=o.headerPaddingX,p.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(p.style.paddingTop=o.headerPaddingY,p.style.paddingBottom=o.headerPaddingY);let 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 w=String((re=n.startedAt)!=null?re:Date.now()),x=()=>{let Z=b("span","");return Z.setAttribute("data-tool-elapsed",w),Z.textContent=Rs(n),Z},M=(ie=o.renderCollapsedSummary)==null?void 0:ie.call(o,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(be=s.collapsedMode)!=null?be:"tool-call",isActive:u,config:t!=null?t:{},elapsed:Rs(n),createElapsedElement:x});typeof M=="string"&&M.trim()?(m.textContent=M,g.appendChild(m)):M instanceof HTMLElement?g.appendChild(M):(m.textContent=d,g.appendChild(m));let P=(we=s.loadingAnimation)!=null?we:"none",W=o.activeTextTemplate,H=o.completeTextTemplate,_=u?W:H,B=M instanceof HTMLElement,v=(Z,Ee,X)=>{let Ae=X;for(let ge of Ee){let le=b("span","persona-tool-char");le.style.setProperty("--char-index",String(Ae)),le.textContent=ge===" "?"\xA0":ge,Z.appendChild(le),Ae++}return Ae},C=(Z,Ee)=>{var le;m.textContent="";let X=((le=n.name)==null?void 0:le.trim())||"tool",Ae=qa(Z,X),ge=0;for(let ue of Ae){let je=ue.styles.length>0?(()=>{let j=b("span",ue.styles.map(oe=>`persona-tool-text-${oe}`).join(" "));return m.appendChild(j),j})():m;if(ue.isDuration&&u)je.appendChild(x());else{let j=ue.isDuration?Rs(n):ue.text;Ee?ge=v(je,j,ge):je.appendChild(document.createTextNode(j))}}};if(!B)if(u&&P!=="none"){let Z=(We=o.loadingAnimationDuration)!=null?We:2e3;if(m.setAttribute("data-preserve-animation","true"),P==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${Z}ms`),_&&C(_,!1);else if(m.classList.add(`persona-tool-loading-${P}`),m.style.setProperty("--persona-tool-anim-duration",`${Z}ms`),P==="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)),_)C(_,!0);else{let Ee=m.textContent||d;m.textContent="",v(m,Ee,0)}}else _&&C(_,!1);let E=null;if(a){E=b("div","persona-flex persona-items-center");let Z=o.toggleTextColor||o.headerTextColor||"currentColor",Ee=Se(i?"chevron-up":"chevron-down",16,Z,2);Ee?E.appendChild(Ee):E.textContent=i?"Hide":"Show";let X=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");X.append(E),p.append(g,X)}else p.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&&u&&s.activePreview&&l){let Z=(ye=o.renderCollapsedPreview)==null?void 0:ye.call(o,{message:e,toolCall:n,defaultPreview:l,isActive:u,config:t!=null?t:{}});_y(S,Z)||(S.textContent=l),S.style.display=""}if(!i&&u&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(p,S),r;let k=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(k.style.display=i?"":"none",o.contentBackgroundColor&&(k.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(k.style.color=o.contentTextColor),o.contentPaddingX&&(k.style.paddingLeft=o.contentPaddingX,k.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(k.style.paddingTop=o.contentPaddingY,k.style.paddingBottom=o.contentPaddingY),n.name){let Z=b("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?Z.style.color=o.contentTextColor:o.headerTextColor&&(Z.style.color=o.headerTextColor),Z.textContent=n.name,k.appendChild(Z)}if(n.args!==void 0){let Z=b("div","persona-space-y-1"),Ee=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Ee.style.color=o.labelTextColor),Ee.textContent="Arguments";let X=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(X.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(X.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(X.style.color=o.codeBlockTextColor),X.textContent=qr(n.args),Z.append(Ee,X),k.appendChild(Z)}if(n.chunks&&n.chunks.length){let Z=b("div","persona-space-y-1"),Ee=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Ee.style.color=o.labelTextColor),Ee.textContent="Activity";let X=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(X.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(X.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(X.style.color=o.codeBlockTextColor),X.textContent=n.chunks.join(""),Z.append(Ee,X),k.appendChild(Z)}if(n.status==="complete"&&n.result!==void 0){let Z=b("div","persona-space-y-1"),Ee=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Ee.style.color=o.labelTextColor),Ee.textContent="Result";let X=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(X.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(X.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(X.style.color=o.codeBlockTextColor),X.textContent=qr(n.result),Z.append(Ee,X),k.appendChild(Z)}if(n.status==="complete"&&typeof n.duration=="number"){let Z=b("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(Z.style.color=o.contentTextColor),Z.textContent=`Duration: ${n.duration}ms`,k.appendChild(Z)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),E){E.innerHTML="";let Z=o.toggleTextColor||o.headerTextColor||"currentColor",Ee=Se(i?"chevron-up":"chevron-down",16,Z,2);Ee?E.appendChild(Ee):E.textContent=i?"Hide":"Show"}k.style.display=i?"":"none",S.style.display=i?"none":S.textContent||S.childNodes.length?"":"none"})(),r.append(p,S,k),r};import{parse as Uy,ARR as zy,OBJ as qy,STR as jy}from"partial-json";var Ky="ask_user_question",xl=8,Yr="data-persona-ask-sheet-for",Gy="Other",Yy="Other\u2026",em="Type your own answer here",tm="Send",Xy="Next",Qy="Back",Jy="Submit all",Zy="Skip",ev=3,wl="data-ask-current-index",Cl="data-ask-question-count",nm="data-ask-answers",Sl="data-ask-grouped",om="data-ask-layout",tv=e=>e.layout==="pills"?"pills":"rows",nv=e=>e.getAttribute(om)==="pills"?"pills":"rows",Zu=!1,rm=e=>e.replace(/["\\]/g,"\\$&"),Ar=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Ky,Al=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},Xr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=Uy(r,jy|qy|zy);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Gs=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>xl&&!Zu&&(Zu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${xl}.`)),t.slice(0,xl)},ov=e=>{var t;return(t=Gs(e)[0])!=null?t:null},rv=(e,t)=>{var n;return(n=Gs(e)[t])!=null?n:null},sv=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},sm=(e,t,n)=>{if(e!=="rows")return null;let o=b("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=b("span","persona-ask-row-check");o.appendChild(r)}else{let r=b("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},av=(e,t,n,o)=>{let s=b("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=b("span","persona-ask-row-content"),i=b("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=b("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}s.appendChild(a);let d=sm(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},iv=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},lv=(e,t,n,o)=>{var u,p,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<ev;m++)s.appendChild(iv(o));return s}if(d.forEach((m,w)=>{s.appendChild(av(m,w,o,a))}),(e==null?void 0:e.allowFreeText)!==!1){let m=o==="rows"?Gy:Yy;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 x=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=(u=t.freeTextPlaceholder)!=null?u:em,M.setAttribute("data-ask-free-text-input","true"),M.setAttribute("aria-label",(p=t.freeTextLabel)!=null?p:m),x.appendChild(M),w.appendChild(x);let P=sm(o,a,d.length);P&&w.appendChild(P),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:m,s.appendChild(w)}}return s},am=(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:em,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:tm,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},cv=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:tm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},dv=(e,t,n)=>{var l,u,p,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:Qy,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(u=n.skipLabel)!=null?u:Zy,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=b("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(p=n.submitAllLabel)!=null?p:Jy:(g=n.nextLabel)!=null?g:Xy,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},Tr=e=>{let t=e.getAttribute(nm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},im=(e,t)=>{e.setAttribute(nm,JSON.stringify(t))},lo=e=>{var n;let t=Number((n=e.getAttribute(wl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},pv=(e,t)=>{e.setAttribute(wl,String(Math.max(0,Math.floor(t))))},Qr=e=>{var n;let t=Number((n=e.getAttribute(Cl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},rr=e=>e.getAttribute(Sl)==="true",uv=(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},mv=(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)))},xi=(e,t)=>{let{payload:n}=Xr(t),o=Gs(n),r=Tr(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},lm=e=>{let t=Tr(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 p;let l=(p=d.getAttribute("data-option-label"))!=null?p:"",u=r.has(l);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!a.has(o)){i.value=o;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},cm=e=>{if(!rr(e))return;let t=Tr(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}},Tl=(e,t,n)=>{let o=Al(n),r=nv(e),{payload:s,complete:a}=Xr(t),i=rr(e),d=lo(e),l=Qr(e),u=i?rv(s,d):ov(s),p=!!(u!=null&&u.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 w=e.querySelector('[data-ask-question="true"]');if(w){let W=typeof(u==null?void 0:u.question)=="string"?u.question:"";w.textContent=W,w.classList.toggle("persona-ask-question-skeleton",!W&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let W=lv(u,o,a,r);x.replaceWith(W)}if(r!=="rows"){let W=e.querySelector('[data-ask-free-text-row="true"]');W&&W.replaceWith(am(o,r))}let M=e.querySelector('[data-ask-multi-actions="true"]');!i&&p&&!M?e.appendChild(cv(o)):(!p||i)&&M&&M.remove(),e.setAttribute("data-multi-select",p?"true":"false");let P=e.querySelector('[data-ask-nav-row="true"]');if(i){let W=dv(d,l,o);P?P.replaceWith(W):e.appendChild(W)}else P&&P.remove();lm(e),cm(e)},fv=(e,t,n)=>{let o=Al(t),r=tv(o),s=e.toolCall.id,a=Gs(n),i=Math.max(1,a.length),d=i>1,l=uv(e,a),u=d?mv(e,i):0,p=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(Yr,s),p.setAttribute("data-tool-call-id",s),p.setAttribute("data-message-id",e.id),p.setAttribute(Cl,String(i)),p.setAttribute(wl,String(u)),p.setAttribute(Sl,d?"true":"false"),p.setAttribute(om,r),im(p,l),p.setAttribute("role","group"),p.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&p.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),sv(p,o);let 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 w=b("span","persona-ask-sheet-step-inline");w.setAttribute("data-ask-step-inline","true"),w.textContent="",g.appendChild(w),p.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"),p.appendChild(M),r!=="rows"&&p.appendChild(am(o,r)),Tl(p,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p},gv=(e,t,n)=>{let{payload:o}=Xr(t),r=Math.max(1,Gs(o).length);r>Qr(e)&&(e.setAttribute(Cl,String(r)),r>1&&!rr(e)&&e.setAttribute(Sl,"true")),Tl(e,t,n)};var wi=(e,t,n)=>{if(!n||!Ar(e)||Al(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Yr}]`).forEach(l=>{l.getAttribute(Yr)!==r&&l.remove()});let a=n.querySelector(`[${Yr}="${rm(r)}"]`);if(a){gv(a,e,t);return}let{payload:i}=Xr(e),d=fv(e,t,i);n.appendChild(d)},Jr=(e,t)=>{if(!e)return;let n=t?`[${Yr}="${rm(t)}"]`:`[${Yr}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},kl=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),sr=(e,t)=>{let n=Tr(e),o=lo(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,im(e,n),lm(e),cm(e)},Ci=(e,t,n,o)=>{let r=Qr(e),s=Math.max(0,Math.min(r-1,o));pv(e,s),Tl(e,t,n)};var El=(e,t)=>{var x,M,P,W,H,_,B,v,C,E,S,k;let n=e.approval,o=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,r=(n==null?void 0:n.status)==="pending",s=b("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(x=o==null?void 0:o.backgroundColor)!=null?x:"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)":(P=o==null?void 0:o.titleColor)!=null?P:"currentColor",u=Se(d,20,l,2);u&&i.appendChild(u);let p=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=(W=o==null?void 0:o.title)!=null?W:"Approval Required",g.appendChild(m),!r){let D=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");D.setAttribute("data-approval-status",n.status),n.status==="approved"?(D.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",D.style.color="var(--persona-palette-colors-success-700, #15803d)",D.textContent="Approved"):n.status==="denied"?(D.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",D.style.color="var(--persona-palette-colors-error-700, #b91c1c)",D.textContent="Denied"):n.status==="timeout"&&(D.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",D.style.color="var(--persona-palette-colors-warning-700, #b45309)",D.textContent="Timeout"),g.appendChild(D)}p.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,p.appendChild(w),n.parameters){let D=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&&(D.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(D.style.color=o.parameterTextColor),D.style.fontSize="0.75rem",D.style.lineHeight="1rem",D.textContent=qr(n.parameters),p.appendChild(D)}if(r){let D=b("div","persona-flex persona-gap-2 persona-mt-2");D.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=(_=o==null?void 0:o.approveButtonTextColor)!=null?_:"#ffffff",$.setAttribute("data-approval-action","approve");let q=Se("shield-check",14,(B=o==null?void 0:o.approveButtonTextColor)!=null?B:"#ffffff",2);q&&(q.style.marginRight="4px",$.appendChild(q));let me=document.createTextNode((v=o==null?void 0:o.approveLabel)!=null?v:"Approve");$.appendChild(me);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-cursor-pointer");re.type="button",re.style.backgroundColor=(C=o==null?void 0:o.denyButtonColor)!=null?C:"transparent",re.style.color=(E=o==null?void 0:o.denyButtonTextColor)!=null?E:"var(--persona-feedback-error, #dc2626)",re.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,re.setAttribute("data-approval-action","deny");let be=Se("shield-x",14,(S=o==null?void 0:o.denyButtonTextColor)!=null?S:"var(--persona-feedback-error, #dc2626)",2);be&&(be.style.marginRight="4px",re.appendChild(be));let ie=document.createTextNode((k=o==null?void 0:o.denyLabel)!=null?k:"Deny");re.appendChild(ie),D.append($,re),p.appendChild(D)}return a.append(i,p),s.appendChild(a),s};var dm=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 u=document.createDocumentFragment(),p=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 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=m,w.disabled=p,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(m))}),u.appendChild(w),t.push(w)}),e.appendChild(u)}}};var Ys=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Xs=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}};var hv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),bv=new Set(["step_start","execution_start"]),yv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),vv=new Set(["step_complete","agent_turn_complete"]),xv=new Set(["flow_complete","agent_complete"]),pm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),mm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,kr=(e,t)=>{let n=e[t];return mm(n)?n:void 0};function Ml(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Si(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function wv(e,t){return typeof t.type=="string"?t.type:e}function Cv(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 Sv(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 um(e){var o,r,s,a,i;let t=kr(e,"result"),n=[kr(e,"tokens"),kr(e,"totalTokens"),t?kr(t,"tokens"):void 0,kr(e,"usage"),t?kr(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 Av(e){var n,o,r,s,a;let t=kr(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 Tv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Qs=class{constructor(t=Tv){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:Si(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(!mm(n)){pm.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=wv(t,n),r=this.now();if(hv.has(o)){this.startRun(r);return}if(bv.has(o)){this.run||this.startRun(r);return}if(yv.has(o)){if(!Sv(o,n))return;let a=Cv(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+Ml(i.visibleCharCount),l=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Si(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(vv.has(o)){if(!this.run)return;let a=this.run,i=um(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Ml(a.visibleCharCount),u=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:Si(l,u),outputTokens:l,durationMs:u,source:d?"usage":"estimate"};return}if(xv.has(o)){if(!this.run)return;let a=this.run,i=um(n),d=i!=null?i:a.exactOutputTokens+Ml(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:Si(d,u),outputTokens:d,durationMs:u,source:l},this.run=null;return}if(pm.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=Av(n);return s!=null?s:o-t.startedAt}};function Zr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var kv={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)"}},Ev={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Mv=["flowName","stepName","reasoningText","text","name","tool","toolName"],Lv=100;function Iv(e,t){let n={...kv,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Ev}function Rv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Pv(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 Wv(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 Bv(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 Hv(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 Dv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Fv(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 Ov(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 Ll(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");Zr(l,(g=o.classNames)==null?void 0:g.eventRow);let u=a.find(m=>m.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let m=u.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(m)return l.appendChild(m),l}return l.appendChild(p()),l;function p(){var $,q;let m=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 x=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=Se(d?"chevron-down":"chevron-right","14px","currentColor",2);M&&x.appendChild(M);let P=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),W=($=o.timestampFormat)!=null?$:"relative";P.textContent=W==="relative"?Rv(e.timestamp,n):Pv(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 _=Iv(e.type,o.badgeColors),B=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");B.style.backgroundColor=_.bg,B.style.color=_.text,B.style.borderColor=_.text+"50",B.textContent=e.type;let v=(q=o.descriptionFields)!=null?q:Mv,C=Wv(e.payload,v),E=null;C&&(E=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),E.textContent=C);let S=b("div","persona-flex-1 persona-min-w-0"),k=b("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),D=Se("clipboard","12px","currentColor",1.5);return D&&k.appendChild(D),k.addEventListener("click",async me=>{me.stopPropagation(),await Bv(Hv(e)),k.innerHTML="";let re=Se("check","12px","currentColor",1.5);re&&k.appendChild(re),setTimeout(()=>{k.innerHTML="";let be=Se("clipboard","12px","currentColor",1.5);be&&k.appendChild(be)},1500)}),w.appendChild(x),w.appendChild(P),H&&w.appendChild(H),w.appendChild(B),E&&w.appendChild(E),w.appendChild(S),w.appendChild(k),m.appendChild(w),d&&m.appendChild(Ov(e,a,i)),m}}function fm(e){var w,x,M,P,W;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=(x=i==null?void 0:i.iconName)!=null?x:"arrow-down",u=(M=i==null?void 0:i.label)!=null?M:"",p=(W=(P=r==null?void 0:r.features)==null?void 0:P.eventStream)!=null?W:{},g=s.find(H=>H.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&r){let H=g.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>m().element,onClose:o});if(H)return{element:H,update:()=>{},destroy:()=>{}}}return m();function m(){let H=p.classNames,_=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Zr(_,H==null?void 0:H.panel);let B=[],v="",C="",E=null,S=[],k={},D=0,$=oi(),q=0,me=0,re=!1,be=null,ie=!1,we=0,We=new Set,ye=new Map,Z="",Ee="",X=null,Ae,ge,le,ue,je,j=null,oe=null,Re=null;function tt(){let ae=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ve=b("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");Zr(ve,H==null?void 0:H.headerBar);let wt=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(wt.textContent="Events",Ae=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"),Ae.textContent="0",a){oe=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),oe.style.cursor="help";let Fn=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Fn.textContent="Throughput",j=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"),j.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=oe,xn=Re,On=()=>{if(!xn.textContent)return;let wo=Zn.getBoundingClientRect(),Nn=ae.getBoundingClientRect();xn.style.left=`${wo.left-Nn.left}px`,xn.style.top=`${wo.bottom-Nn.top+4}px`,xn.style.display="block"},ut=()=>{xn.style.display="none"};oe.addEventListener("mouseenter",On),oe.addEventListener("mouseleave",ut),oe.appendChild(Fn),oe.appendChild(j)}let _t=b("div","persona-flex-1");ge=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",ge.appendChild(Jt),le=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"),le.type="button",le.title="Copy All";let Et=Se("clipboard-copy","12px","currentColor",1.5);Et&&le.appendChild(Et);let At=b("span","persona-text-xs");At.textContent="Copy All",le.appendChild(At),ve.appendChild(wt),ve.appendChild(Ae),oe&&ve.appendChild(oe),ve.appendChild(_t),ve.appendChild(ge),ve.appendChild(le);let ht=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Zr(ht,H==null?void 0:H.searchBar);let yt=Se("search","14px","var(--persona-muted, #9ca3af)",1.5),Ut=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");yt&&Ut.appendChild(yt),ue=b("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Zr(ue,H==null?void 0:H.searchInput),ue.type="text",ue.placeholder="Search event payloads...",je=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"),je.type="button",je.style.display="none";let Ze=Se("x","12px","currentColor",2);return Ze&&je.appendChild(Ze),ht.appendChild(Ut),ht.appendChild(ue),ht.appendChild(je),ae.appendChild(ve),ae.appendChild(ht),Re&&ae.appendChild(Re),ae}let fe,ce=s.find(ae=>ae.renderEventStreamToolbar);if(ce!=null&&ce.renderEventStreamToolbar&&r){let ae=ce.renderEventStreamToolbar({config:r,defaultRenderer:()=>tt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:ve=>{v=ve,Dn(),se()},onSearchChange:ve=>{C=ve,Dn(),se()}});fe=ae!=null?ae:tt()}else fe=tt();let _e=b("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");_e.style.display="none";function Le(){if(!a||!j||!oe)return;let ae=a();j.textContent=Dv(ae);let ve=Fv(ae);Re&&(Re.textContent=ve,ve||(Re.style.display="none")),ve?oe.setAttribute("aria-label",ve):oe.removeAttribute("aria-label")}let de=b("div","persona-flex-1 persona-min-h-0 persona-relative"),Y=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Y.style.height="100%";let 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");Zr(Ve,H==null?void 0:H.scrollIndicator),Ve.style.display="none",Ve.setAttribute("data-persona-scroll-to-bottom-has-label",u?"true":"false");let Ct=Se(l,"14px","currentColor",2);Ct&&Ve.appendChild(Ct);let Q=b("span","");Q.textContent=u,Ve.appendChild(Q);let Fe=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Fe.style.display="none",de.appendChild(Y),de.appendChild(Fe),de.appendChild(Ve),_.setAttribute("tabindex","0"),_.appendChild(fe),_.appendChild(_e),_.appendChild(de);function Ln(){let ae=t.getAll(),ve={};for(let At of ae)ve[At.type]=(ve[At.type]||0)+1;let wt=Object.keys(ve).sort(),_t=wt.length!==S.length||!wt.every((At,ht)=>At===S[ht]),Jt=!_t&&wt.some(At=>ve[At]!==k[At]),vn=ae.length!==Object.values(k).reduce((At,ht)=>At+ht,0);if(!_t&&!Jt&&!vn||(S=wt,k=ve,!ge))return;let Et=ge.value;if(ge.options[0].textContent="All events",_t){for(;ge.options.length>1;)ge.remove(1);for(let At of wt){let ht=b("option","");ht.value=At,ht.textContent=`${At} (${ve[At]||0})`,ge.appendChild(ht)}Et&&wt.includes(Et)?ge.value=Et:Et&&(ge.value="",v="")}else for(let At=1;At<ge.options.length;At++){let ht=ge.options[At];ht.textContent=`${ht.value} (${ve[ht.value]||0})`}}function Ft(){let ae=t.getAll();if(v&&(ae=ae.filter(ve=>ve.type===v)),C){let ve=C.toLowerCase();ae=ae.filter(wt=>wt.type.toLowerCase().includes(ve)||wt.payload.toLowerCase().includes(ve))}return ae}function ln(){return v!==""||C!==""}function Dn(){D=0,q=0,$.resume(),Ve.style.display="none"}function Jn(ae){We.has(ae)?We.delete(ae):We.add(ae),X=ae;let ve=Y.scrollTop,wt=$.isFollowing();ie=!0,$.pause(),se(),Y.scrollTop=ve,wt&&$.resume(),ie=!1}function O(){return Os(Y,50)}function se(){me=Date.now(),re=!1,Le(),Ln();let ae=t.getEvictedCount();ae>0?(_e.textContent=`${ae.toLocaleString()} older events truncated`,_e.style.display=""):_e.style.display="none",B=Ft();let ve=B.length,wt=t.getSize()>0;Ae&&(Ae.textContent=String(t.getSize())),ve===0&&wt&&ln()?(Fe.textContent=C?`No events matching '${C}'`:"No events matching filter",Fe.style.display="",Y.style.display="none"):(Fe.style.display="none",Y.style.display=""),le&&(le.title=ln()?`Copy Filtered (${ve})`:"Copy All"),d&&!$.isFollowing()&&ve>D&&(q+=ve-D,Q.textContent=u?`${u}${q>0?` (${q})`:""}`:"",Ve.style.display=""),D=ve;let _t=t.getAll(),Jt=_t.length>0?_t[0].timestamp:0,vn=new Set(B.map(ht=>ht.id));for(let ht of We)vn.has(ht)||We.delete(ht);let Et=v!==Z||C!==Ee,At=ye.size===0&&B.length>0;if(Et||At||B.length===0){Y.innerHTML="",ye.clear();let ht=document.createDocumentFragment();for(let yt=0;yt<B.length;yt++){let Ut=Ll(B[yt],yt,Jt,p,We,Jn,s,r);ye.set(B[yt].id,Ut),ht.appendChild(Ut)}Y.appendChild(ht),Z=v,Ee=C,X=null}else{if(X!==null){let yt=ye.get(X);if(yt&&yt.parentNode===Y){let Ut=B.findIndex(Ze=>Ze.id===X);if(Ut>=0){let Ze=Ll(B[Ut],Ut,Jt,p,We,Jn,s,r);Y.insertBefore(Ze,yt),yt.remove(),ye.set(X,Ze)}}X=null}let ht=new Set(B.map(yt=>yt.id));for(let[yt,Ut]of ye)ht.has(yt)||(Ut.remove(),ye.delete(yt));for(let yt=0;yt<B.length;yt++){let Ut=B[yt];if(!ye.has(Ut.id)){let Ze=Ll(Ut,yt,Jt,p,We,Jn,s,r);ye.set(Ut.id,Ze),Y.appendChild(Ze)}}}$.isFollowing()&&(Y.scrollTop=Y.scrollHeight)}function He(){if(Date.now()-me>=Lv){be!==null&&(cancelAnimationFrame(be),be=null),se();return}re||(re=!0,be=requestAnimationFrame(()=>{be=null,se()}))}let Xe=(ae,ve)=>{if(!le)return;le.innerHTML="";let wt=Se(ae,"12px","currentColor",1.5);wt&&le.appendChild(wt);let _t=b("span","persona-text-xs");_t.textContent="Copy All",le.appendChild(_t),setTimeout(()=>{le.innerHTML="";let Jt=Se("clipboard-copy","12px","currentColor",1.5);Jt&&le.appendChild(Jt);let vn=b("span","persona-text-xs");vn.textContent="Copy All",le.appendChild(vn),le.disabled=!1},ve)},Oe=async()=>{if(le){le.disabled=!0;try{let ae;ln()?ae=B:n?(ae=await n(),ae.length===0&&(ae=t.getAll())):ae=t.getAll();let ve=ae.map(wt=>{try{return JSON.parse(wt.payload)}catch{return wt.payload}});await navigator.clipboard.writeText(JSON.stringify(ve,null,2)),Xe("check",1500)}catch{Xe("x",1500)}}},Ne=()=>{ge&&(v=ge.value,Dn(),se())},ot=()=>{!ue||!je||(je.style.display=ue.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{C=ue.value,Dn(),se()},150))},St=()=>{!ue||!je||(ue.value="",C="",je.style.display="none",E&&clearTimeout(E),Dn(),se())},Nt=()=>{if(ie)return;let ae=Y.scrollTop,{action:ve,nextLastScrollTop:wt}=ri({following:$.isFollowing(),currentScrollTop:ae,lastScrollTop:we,nearBottom:O(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});we=wt,ve==="resume"?($.resume(),q=0,Ve.style.display="none"):ve==="pause"&&($.pause(),d&&(Q.textContent=u,Ve.style.display=""))},jt=ae=>{let ve=si({following:$.isFollowing(),deltaY:ae.deltaY,nearBottom:O(),resumeWhenNearBottom:!0});ve==="pause"?($.pause(),d&&(Q.textContent=u,Ve.style.display="")):ve==="resume"&&($.resume(),q=0,Ve.style.display="none")},K=()=>{d&&(Y.scrollTop=Y.scrollHeight,$.resume(),q=0,Ve.style.display="none")},ft=ae=>{let ve=ae.target;if(!ve||ve.closest("button"))return;let wt=ve.closest("[data-event-id]");if(!wt)return;let _t=wt.getAttribute("data-event-id");_t&&Jn(_t)},nt=ae=>{if((ae.metaKey||ae.ctrlKey)&&ae.key==="f"){ae.preventDefault(),ue==null||ue.focus(),ue==null||ue.select();return}ae.key==="Escape"&&(ue&&document.activeElement===ue?(St(),ue.blur(),_.focus()):o&&o())};le&&le.addEventListener("click",Oe),ge&&ge.addEventListener("change",Ne),ue&&ue.addEventListener("input",ot),je&&je.addEventListener("click",St),Y.addEventListener("scroll",Nt),Y.addEventListener("wheel",jt,{passive:!0}),Y.addEventListener("click",ft),Ve.addEventListener("click",K),_.addEventListener("keydown",nt);function $t(){E&&clearTimeout(E),be!==null&&(cancelAnimationFrame(be),be=null),re=!1,ye.clear(),le&&le.removeEventListener("click",Oe),ge&&ge.removeEventListener("change",Ne),ue&&ue.removeEventListener("input",ot),je&&je.removeEventListener("click",St),Y.removeEventListener("scroll",Nt),Y.removeEventListener("wheel",jt),Y.removeEventListener("click",ft),Ve.removeEventListener("click",K),_.removeEventListener("keydown",nt)}return{element:_,update:He,destroy:$t}}}function gm(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",o=typeof e.artifactId=="string"?e.artifactId:"",r=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),o&&i.setAttribute("data-open-artifact",o);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=n;let p=document.createElement("div");if(p.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",p.style.color="var(--persona-muted, #9ca3af)",r==="streaming"){let 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",p.appendChild(g);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,p.appendChild(m)}else p.textContent=a;if(l.append(u,p),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 hm=(e,t)=>{var o,r,s;let n=(s=(r=(o=t==null?void 0:t.config)==null?void 0:o.features)==null?void 0:r.artifacts)==null?void 0:s.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",u=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>gm(e,t)});if(u)return u}return gm(e,t)};var Il=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)})}},Er=new Il;Er.register("PersonaArtifactCard",hm);function Nv(e){var r;let t=b("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=b("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify((r=e.props)!=null?r:{},null,2),t.appendChild(n),t.appendChild(o),t}function bm(e,t){var ge,le,ue,je;let n=(le=(ge=e.features)==null?void 0:ge.artifacts)==null?void 0:le.layout,r=((ue=n==null?void 0:n.toolbarPreset)!=null?ue:"default")==="document",s=(je=n==null?void 0:n.panePadding)==null?void 0:je.trim(),a=e.markdown?Na(e.markdown):null,i=_a(e.sanitize),d=j=>{let oe=a?a(j):Ls(j);return i?i(oe):oe},l=typeof document!="undefined"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{l==null||l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"),D==null||D.hide()};l&&l.addEventListener("click",()=>{var j;u(),(j=t.onDismiss)==null||j.call(t)});let p=b("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");p.setAttribute("data-persona-theme-zone","artifact-pane"),r&&p.classList.add("persona-artifact-pane-document");let 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 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 j;u(),(j=t.onDismiss)==null||j.call(t)});let x="rendered",M=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),P=r?yn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):yn({icon:"eye",label:"Rendered view"}),W=r?yn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):yn({icon:"code-2",label:"Source"}),H=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),_=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,B=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,v=n==null?void 0:n.documentToolbarCopyMenuItems,C=!!(B&&v&&v.length>0),E=null,S,k=null,D=null;if(r&&(_||B)&&!C){if(S=_?fl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):yn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),B){let j=Se("chevron-down",14,"currentColor",2);j&&S.appendChild(j)}}else r&&C?(E=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),S=_?fl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):yn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),k=yn({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),E.append(S,k)):r?S=yn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):S=yn({icon:"copy",label:"Copy"});let $=r?yn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):yn({icon:"refresh-cw",label:"Refresh"}),q=r?yn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):yn({icon:"x",label:"Close"}),me=()=>{var fe,ce,_e;let j=(fe=ye.find(Le=>Le.id===Z))!=null?fe:ye[ye.length-1],oe=(ce=j==null?void 0:j.id)!=null?ce:null,Re=(j==null?void 0:j.artifactType)==="markdown"&&(_e=j.markdown)!=null?_e:"",tt=j?JSON.stringify({component:j.component,props:j.props},null,2):"";return{markdown:Re,jsonPayload:tt,id:oe}},re=async()=>{var fe;let{markdown:j,jsonPayload:oe}=me(),Re=(fe=ye.find(ce=>ce.id===Z))!=null?fe:ye[ye.length-1],tt=(Re==null?void 0:Re.artifactType)==="markdown"?j:Re?oe:"";try{await navigator.clipboard.writeText(tt)}catch{}};if(S.addEventListener("click",async()=>{let j=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(j&&C){let{markdown:oe,jsonPayload:Re,id:tt}=me();try{await j({actionId:"primary",artifactId:tt,markdown:oe,jsonPayload:Re})}catch{}return}await re()}),k&&(v!=null&&v.length)){let j=()=>{var Re;return(Re=p.closest("[data-persona-root]"))!=null?Re:document.body},oe=()=>{D=jr({items:v.map(Re=>({id:Re.id,label:Re.label})),onSelect:async Re=>{let{markdown:tt,jsonPayload:fe,id:ce}=me(),_e=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{_e?await _e({actionId:Re,artifactId:ce,markdown:tt,jsonPayload:fe}):Re==="markdown"||Re==="md"?await navigator.clipboard.writeText(tt):Re==="json"||Re==="source"?await navigator.clipboard.writeText(fe):await navigator.clipboard.writeText(tt||fe)}catch{}},anchor:E!=null?E:k,position:"bottom-right",portal:j()})};p.isConnected?oe():requestAnimationFrame(oe),k.addEventListener("click",Re=>{Re.stopPropagation(),D==null||D.toggle()})}$.addEventListener("click",async()=>{var j;try{await((j=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:j.call(n))}catch{}X()}),q.addEventListener("click",()=>{var j;u(),(j=t.onDismiss)==null||j.call(t)});let be=()=>{r&&(P.setAttribute("aria-pressed",x==="rendered"?"true":"false"),W.setAttribute("aria-pressed",x==="source"?"true":"false"))};P.addEventListener("click",()=>{x="rendered",be(),X()}),W.addEventListener("click",()=>{x="source",be(),X()});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(P,W),E?H.append(E,$,q):H.append(S,$,q),g.append(M,ie,H),be()):(g.appendChild(m),g.appendChild(w)),s&&(g.style.paddingLeft=s,g.style.paddingRight=s);let we=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"),We=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(we.style.paddingLeft=s,we.style.paddingRight=s,We.style.padding=s),p.appendChild(g),p.appendChild(we),p.appendChild(We);let ye=[],Z=null,Ee=!1,X=()=>{var tt,fe,ce,_e;let j=r&&ye.length<=1;we.classList.toggle("persona-hidden",j),we.replaceChildren();for(let Le of ye){let de=b("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");de.type="button",de.textContent=Le.title||Le.id.slice(0,8),Le.id===Z&&de.classList.add("persona-bg-persona-container","persona-border-persona-border"),de.addEventListener("click",()=>t.onSelect(Le.id)),we.appendChild(de)}We.replaceChildren();let oe=Z&&ye.find(Le=>Le.id===Z)||ye[ye.length-1];if(!oe)return;if(r){let Le=oe.artifactType==="markdown"?"MD":(tt=oe.component)!=null?tt:"Component",Y=(oe.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ie.textContent=`${Y} \xB7 ${Le}`}else m.textContent="Artifacts";if(oe.artifactType==="markdown"){if(r&&x==="source"){let de=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");de.textContent=(fe=oe.markdown)!=null?fe:"",We.appendChild(de);return}let Le=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Le.innerHTML=d((ce=oe.markdown)!=null?ce:""),We.appendChild(Le);return}let Re=oe.component?Er.get(oe.component):void 0;if(Re){let de={message:{id:oe.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Y=Re((_e=oe.props)!=null?_e:{},de);if(Y){We.appendChild(Y);return}}catch{}}We.appendChild(Nv(oe))},Ae=()=>{var oe;let j=ye.length>0;if(p.classList.toggle("persona-hidden",!j),l){let Re=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,fe=((oe=Re==null?void 0:Re.classList.contains("persona-artifact-narrow-host"))!=null?oe:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;j&&fe&&Ee?(l.classList.remove("persona-hidden"),p.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"))}};return{element:p,backdrop:l,update(j){var oe,Re,tt;ye=j.artifacts,Z=(tt=(Re=j.selectedId)!=null?Re:(oe=j.artifacts[j.artifacts.length-1])==null?void 0:oe.id)!=null?tt:null,ye.length>0&&(Ee=!0),X(),Ae()},setMobileOpen(j){Ee=j,!j&&l?(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):Ae()}}}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 ym(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 _v(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 Ai(e,t){var d,l,u,p,g,m,w,x,M,P;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"),_v(e),ym(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(u=n==null?void 0:n.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=n==null?void 0:n.paneWidth)!=null?p:"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=(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=(x=n==null?void 0:n.documentToolbarIconColor)==null?void 0:x.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=(P=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:P.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),ym(e,t)}var vm=["panel","seamless"];function Ti(e,t){var i,d,l,u,p,g;for(let m of vm)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"),!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=vm.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${r}`);let s=(u=n==null?void 0:n.paneBorderRadius)==null?void 0:u.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(p=n==null?void 0:n.paneShadow)==null?void 0:p.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((g=n.unifiedSplitOuterRadius)==null?void 0:g.trim())||s;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function xm(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 Vv(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 $v(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 Uv(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function zv(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function wm(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 Cm(e,t,n,o,r,s){let a=Vv(r,200),i=zv(t,n,o,200);i=Math.max(a,i);let d=$v(s);return d!==null&&(i=Math.min(i,d)),Uv(e,a,i)}var Sm={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"}},Rl=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var w,x,M;if(s.dataset.enhanced==="true")return;let a=(w=s.dataset.tvForm)!=null?w:"init";s.dataset.enhanced="true";let i=(x=Sm[a])!=null?x:Sm.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 P=b("p","persona-text-sm persona-text-persona-muted");P.textContent=i.description,d.appendChild(P)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(P=>{var v,C;let W=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");W.htmlFor=`${t.id}-${a}-${P.name}`;let H=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");H.textContent=P.label,W.appendChild(H);let _=(v=P.type)!=null?v:"text",B;_==="textarea"?(B=document.createElement("textarea"),B.rows=3):(B=document.createElement("input"),B.type=_),B.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",B.id=`${t.id}-${a}-${P.name}`,B.name=P.name,B.placeholder=(C=P.placeholder)!=null?C:"",P.required&&(B.required=!0),W.appendChild(B),u.appendChild(W)});let p=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=b("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(M=i.submitLabel)!=null?M:"Submit",p.appendChild(g),p.appendChild(m),u.appendChild(p),s.replaceChildren(d,u),u.addEventListener("submit",async P=>{var B,v;P.preventDefault();let W=(B=n.formEndpoint)!=null?B:"/form",H=new FormData(u),_={};H.forEach((C,E)=>{_[E]=C}),_.type=a,m.disabled=!0,g.textContent="Submitting\u2026";try{let C=await fetch(W,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(_)});if(!C.ok)throw new Error(`Form submission failed (${C.status})`);let E=await C.json();g.textContent=(v=E.message)!=null?v:"Thanks! We'll be in touch soon.",E.success&&E.nextPrompt&&await o.sendMessage(String(E.nextPrompt))}catch(C){g.textContent=C instanceof Error?C.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var Pl=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()}},Wl=new Pl;var Am=()=>{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 qv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},jv=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},Hl=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=qv(e),n=jv(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}},Bl=e=>typeof e=="string"?e:e==null?"":String(e),Js={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Bl(e.payload.text)},messageAndClick:(e,t)=>{var r;if(e.type!=="message_and_click")return;let n=e.payload,o=Bl(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:Bl(n.text)}}},Tm=e=>Array.isArray(e)?e.map(t=>String(t)):[],Dl=e=>{let t=new Set(Tm(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Tm(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,u)=>l||(u==null?void 0:u({text:a,message:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),o();let d={action:i,message:s.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let u=()=>{e.emit("action:resubmit",d)},p=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!p)continue;if(p.handled){let g=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:g,resubmit:p.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:n}};var Kv=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}},Gv=e=>e.map(t=>({...t,streaming:!1})),Yv=e=>e.map(t=>({...t,status:"complete"})),km=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Kv(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?Gv(n.messages):void 0,artifacts:n.artifacts?Yv(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 U0,STR as z0,OBJ as q0}from"partial-json";function Em(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Er.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 Mm(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 Lm(e){let t=Mm(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 Im(e){let t=Mm(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 Xv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Rm(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=Xv}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let p=null,g=document.createElement("div");g.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let w=document.createElement("h3");w.className="persona-feedback-title",w.textContent=o,m.appendChild(w);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=r,m.appendChild(x),g.appendChild(m);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let P=[];for(let v=1;v<=5;v++){let C=document.createElement("button");C.type="button",C.className="persona-feedback-rating-btn persona-feedback-star-btn",C.setAttribute("role","radio"),C.setAttribute("aria-checked","false"),C.setAttribute("aria-label",`${v} star${v>1?"s":""}: ${l[v-1]}`),C.title=l[v-1],C.dataset.rating=String(v),C.innerHTML=`
|
|
26
|
+
`):""},qy=(e,t)=>{var u,p,f,g,x;let n=e.toolCall,o=(u=t==null?void 0:t.features)==null?void 0:u.toolCallDisplay,r=(p=o==null?void 0:o.collapsedMode)!=null?p:"tool-call",s=zy(e,(f=o==null?void 0:o.previewMaxLines)!=null?f:3),a=n?Au(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(g=t==null?void 0:t.toolCall)!=null?g:{},l=a;return r==="tool-name"?l=((x=n.name)==null?void 0:x.trim())||a:r==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=sl(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=sl(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},em=(e,t,n)=>{var u;let o=Gr.has(e),r=(u=n==null?void 0:n.toolCall)!=null?u:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let p=r.toggleTextColor||r.headerTextColor||"currentColor",f=Se(o?"chevron-up":"chevron-down",16,p,2);f?l.appendChild(f):l.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},vl=(e,t)=>{var $,q,me,re,be,ie,we,We,ye;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=(q=t==null?void 0:t.features)==null?void 0:q.toolCallDisplay)!=null?me:{},a=s.expandable!==!1,i=a&&Gr.has(e.id),{summary:d,previewText:l,isActive:u}=qy(e,t),p=b("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");p.type="button",a&&(p.setAttribute("aria-expanded",i?"true":"false"),p.setAttribute("data-expand-header","true")),p.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(p.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(p.style.paddingLeft=o.headerPaddingX,p.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(p.style.paddingTop=o.headerPaddingY,p.style.paddingBottom=o.headerPaddingY);let f=b("div","persona-flex persona-flex-col persona-text-left"),g=b("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(g.style.color=o.headerTextColor);let x=String((re=n.startedAt)!=null?re:Date.now()),C=()=>{let Z=b("span","");return Z.setAttribute("data-tool-elapsed",x),Z.textContent=Rs(n),Z},M=(ie=o.renderCollapsedSummary)==null?void 0:ie.call(o,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(be=s.collapsedMode)!=null?be:"tool-call",isActive:u,config:t!=null?t:{},elapsed:Rs(n),createElapsedElement:C});typeof M=="string"&&M.trim()?(g.textContent=M,f.appendChild(g)):M instanceof HTMLElement?f.appendChild(M):(g.textContent=d,f.appendChild(g));let W=(we=s.loadingAnimation)!=null?we:"none",L=o.activeTextTemplate,H=o.completeTextTemplate,D=u?L:H,B=M instanceof HTMLElement,v=(Z,Ee,X)=>{let Ae=X;for(let fe of Ee){let le=b("span","persona-tool-char");le.style.setProperty("--char-index",String(Ae)),le.textContent=fe===" "?"\xA0":fe,Z.appendChild(le),Ae++}return Ae},w=(Z,Ee)=>{var le;g.textContent="";let X=((le=n.name)==null?void 0:le.trim())||"tool",Ae=qa(Z,X),fe=0;for(let ue of Ae){let je=ue.styles.length>0?(()=>{let j=b("span",ue.styles.map(oe=>`persona-tool-text-${oe}`).join(" "));return g.appendChild(j),j})():g;if(ue.isDuration&&u)je.appendChild(C());else{let j=ue.isDuration?Rs(n):ue.text;Ee?fe=v(je,j,fe):je.appendChild(document.createTextNode(j))}}};if(!B)if(u&&W!=="none"){let Z=(We=o.loadingAnimationDuration)!=null?We:2e3;if(g.setAttribute("data-preserve-animation","true"),W==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${Z}ms`),D&&w(D,!1);else if(g.classList.add(`persona-tool-loading-${W}`),g.style.setProperty("--persona-tool-anim-duration",`${Z}ms`),W==="shimmer-color"&&(o.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),D)w(D,!0);else{let Ee=g.textContent||d;g.textContent="",v(g,Ee,0)}}else D&&w(D,!1);let E=null;if(a){E=b("div","persona-flex persona-items-center");let Z=o.toggleTextColor||o.headerTextColor||"currentColor",Ee=Se(i?"chevron-up":"chevron-down",16,Z,2);Ee?E.appendChild(Ee):E.textContent=i?"Hide":"Show";let X=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");X.append(E),p.append(f,X)}else p.append(f);let S=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(S.setAttribute("data-persona-collapsed-preview","tool"),S.style.display="none",S.style.whiteSpace="pre-wrap",!i&&u&&s.activePreview&&l){let Z=(ye=o.renderCollapsedPreview)==null?void 0:ye.call(o,{message:e,toolCall:n,defaultPreview:l,isActive:u,config:t!=null?t:{}});Uy(S,Z)||(S.textContent=l),S.style.display=""}if(!i&&u&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(p,S),r;let k=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(k.style.display=i?"":"none",o.contentBackgroundColor&&(k.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(k.style.color=o.contentTextColor),o.contentPaddingX&&(k.style.paddingLeft=o.contentPaddingX,k.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(k.style.paddingTop=o.contentPaddingY,k.style.paddingBottom=o.contentPaddingY),n.name){let Z=b("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?Z.style.color=o.contentTextColor:o.headerTextColor&&(Z.style.color=o.headerTextColor),Z.textContent=n.name,k.appendChild(Z)}if(n.args!==void 0){let Z=b("div","persona-space-y-1"),Ee=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Ee.style.color=o.labelTextColor),Ee.textContent="Arguments";let X=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(X.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(X.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(X.style.color=o.codeBlockTextColor),X.textContent=qr(n.args),Z.append(Ee,X),k.appendChild(Z)}if(n.chunks&&n.chunks.length){let Z=b("div","persona-space-y-1"),Ee=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Ee.style.color=o.labelTextColor),Ee.textContent="Activity";let X=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(X.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(X.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(X.style.color=o.codeBlockTextColor),X.textContent=n.chunks.join(""),Z.append(Ee,X),k.appendChild(Z)}if(n.status==="complete"&&n.result!==void 0){let Z=b("div","persona-space-y-1"),Ee=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Ee.style.color=o.labelTextColor),Ee.textContent="Result";let X=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(X.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(X.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(X.style.color=o.codeBlockTextColor),X.textContent=qr(n.result),Z.append(Ee,X),k.appendChild(Z)}if(n.status==="complete"&&typeof n.duration=="number"){let Z=b("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(Z.style.color=o.contentTextColor),Z.textContent=`Duration: ${n.duration}ms`,k.appendChild(Z)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),E){E.innerHTML="";let Z=o.toggleTextColor||o.headerTextColor||"currentColor",Ee=Se(i?"chevron-up":"chevron-down",16,Z,2);Ee?E.appendChild(Ee):E.textContent=i?"Hide":"Show"}k.style.display=i?"":"none",S.style.display=i?"none":S.textContent||S.childNodes.length?"":"none"})(),r.append(p,S,k),r};import{parse as jy,ARR as Ky,OBJ as Gy,STR as Yy}from"partial-json";var Xy="ask_user_question",xl=8,Yr="data-persona-ask-sheet-for",Qy="Other",Jy="Other\u2026",nm="Type your own answer here",om="Send",Zy="Next",ev="Back",tv="Submit all",nv="Skip",ov=3,wl="data-ask-current-index",Cl="data-ask-question-count",rm="data-ask-answers",Sl="data-ask-grouped",sm="data-ask-layout",rv=e=>e.layout==="pills"?"pills":"rows",sv=e=>e.getAttribute(sm)==="pills"?"pills":"rows",tm=!1,am=e=>e.replace(/["\\]/g,"\\$&"),Ar=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Xy,Al=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},Xr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=jy(r,Yy|Gy|Ky);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Gs=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>xl&&!tm&&(tm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${xl}.`)),t.slice(0,xl)},av=e=>{var t;return(t=Gs(e)[0])!=null?t:null},iv=(e,t)=>{var n;return(n=Gs(e)[t])!=null?n:null},lv=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},im=(e,t,n)=>{if(e!=="rows")return null;let o=b("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=b("span","persona-ask-row-check");o.appendChild(r)}else{let r=b("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},cv=(e,t,n,o)=>{let s=b("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=b("span","persona-ask-row-content"),i=b("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=b("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}s.appendChild(a);let d=im(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},dv=e=>{let n=b("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},pv=(e,t,n,o)=>{var u,p,f;let s=b("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(g=>g&&typeof g.label=="string"&&g.label.length>0);if(d.length===0&&!n){for(let g=0;g<ov;g++)s.appendChild(dv(o));return s}if(d.forEach((g,x)=>{s.appendChild(cv(g,x,o,a))}),(e==null?void 0:e.allowFreeText)!==!1){let g=o==="rows"?Qy:Jy;if(o==="rows"){let x=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");x.setAttribute("data-ask-user-action","focus-free-text"),x.setAttribute("data-option-index",String(d.length)),x.setAttribute("data-ask-other-row","true");let C=b("span","persona-ask-row-content"),M=document.createElement("input");M.type="text",M.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",M.placeholder=(u=t.freeTextPlaceholder)!=null?u:nm,M.setAttribute("data-ask-free-text-input","true"),M.setAttribute("aria-label",(p=t.freeTextLabel)!=null?p:g),C.appendChild(M),x.appendChild(C);let W=im(o,a,d.length);W&&x.appendChild(W),s.appendChild(x)}else{let x=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");x.type="button",x.setAttribute("data-ask-user-action","open-free-text"),x.textContent=(f=t.freeTextLabel)!=null?f:g,s.appendChild(x)}}return s},lm=(e,t)=>{var s,a;let o=b("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=(s=e.freeTextPlaceholder)!=null?s:nm,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let i=b("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:om,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},uv=e=>{var o;let t=b("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=b("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(o=e.submitLabel)!=null?o:om,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},mv=(e,t,n)=>{var l,u,p,f;let o=b("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=b("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=(l=n.backLabel)!=null?l:ev,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(u=n.skipLabel)!=null?u:nv,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=b("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(p=n.submitAllLabel)!=null?p:tv:(f=n.nextLabel)!=null?f:Zy,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},Tr=e=>{let t=e.getAttribute(rm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},cm=(e,t)=>{e.setAttribute(rm,JSON.stringify(t))},lo=e=>{var n;let t=Number((n=e.getAttribute(wl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},gv=(e,t)=>{e.setAttribute(wl,String(Math.max(0,Math.floor(t))))},Qr=e=>{var n;let t=Number((n=e.getAttribute(Cl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},rr=e=>e.getAttribute(Sl)==="true",fv=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(o[a]=d)}}),o},hv=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},xi=(e,t)=>{let{payload:n}=Xr(t),o=Gs(n),r=Tr(e),s={},a=new Set;return o.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(r,d)&&(s[l]=r[d]))}),s},dm=e=>{let t=Tr(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 p;let l=(p=d.getAttribute("data-option-label"))!=null?p:"",u=r.has(l);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!a.has(o)){i.value=o;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},pm=e=>{if(!rr(e))return;let t=Tr(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}},Tl=(e,t,n)=>{let o=Al(n),r=sv(e),{payload:s,complete:a}=Xr(t),i=rr(e),d=lo(e),l=Qr(e),u=i?iv(s,d):av(s),p=!!(u!=null&&u.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let L=typeof(u==null?void 0:u.question)=="string"?u.question:"";x.textContent=L,x.classList.toggle("persona-ask-question-skeleton",!L&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let L=pv(u,o,a,r);C.replaceWith(L)}if(r!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(lm(o,r))}let M=e.querySelector('[data-ask-multi-actions="true"]');!i&&p&&!M?e.appendChild(uv(o)):(!p||i)&&M&&M.remove(),e.setAttribute("data-multi-select",p?"true":"false");let W=e.querySelector('[data-ask-nav-row="true"]');if(i){let L=mv(d,l,o);W?W.replaceWith(L):e.appendChild(L)}else W&&W.remove();dm(e),pm(e)},bv=(e,t,n)=>{let o=Al(t),r=rv(o),s=e.toolCall.id,a=Gs(n),i=Math.max(1,a.length),d=i>1,l=fv(e,a),u=d?hv(e,i):0,p=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(Yr,s),p.setAttribute("data-tool-call-id",s),p.setAttribute("data-message-id",e.id),p.setAttribute(Cl,String(i)),p.setAttribute(wl,String(u)),p.setAttribute(Sl,d?"true":"false"),p.setAttribute(sm,r),cm(p,l),p.setAttribute("role","group"),p.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&p.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),lv(p,o);let f=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=b("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",f.appendChild(g);let x=b("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",f.appendChild(x),p.appendChild(f);let M=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),p.appendChild(M),r!=="rows"&&p.appendChild(lm(o,r)),Tl(p,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p},yv=(e,t,n)=>{let{payload:o}=Xr(t),r=Math.max(1,Gs(o).length);r>Qr(e)&&(e.setAttribute(Cl,String(r)),r>1&&!rr(e)&&e.setAttribute(Sl,"true")),Tl(e,t,n)};var wi=(e,t,n)=>{if(!n||!Ar(e)||Al(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Yr}]`).forEach(l=>{l.getAttribute(Yr)!==r&&l.remove()});let a=n.querySelector(`[${Yr}="${am(r)}"]`);if(a){yv(a,e,t);return}let{payload:i}=Xr(e),d=bv(e,t,i);n.appendChild(d)},Jr=(e,t)=>{if(!e)return;let n=t?`[${Yr}="${am(t)}"]`:`[${Yr}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},kl=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),sr=(e,t)=>{let n=Tr(e),o=lo(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,cm(e,n),dm(e),pm(e)},Ci=(e,t,n,o)=>{let r=Qr(e),s=Math.max(0,Math.min(r-1,o));gv(e,s),Tl(e,t,n)};var El=(e,t)=>{var C,M,W,L,H,D,B,v,w,E,S,k;let n=e.approval,o=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,r=(n==null?void 0:n.status)==="pending",s=b("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(C=o==null?void 0:o.backgroundColor)!=null?C:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(M=o==null?void 0:o.borderColor)!=null?M:"var(--persona-approval-border, #fef08a)",!n)return s;let a=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=b("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",l=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(W=o==null?void 0:o.titleColor)!=null?W:"currentColor",u=Se(d,20,l,2);u&&i.appendChild(u);let p=b("div","persona-flex-1 persona-min-w-0"),f=b("div","persona-flex persona-items-center persona-gap-2"),g=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o!=null&&o.titleColor&&(g.style.color=o.titleColor),g.textContent=(L=o==null?void 0:o.title)!=null?L:"Approval Required",f.appendChild(g),!r){let F=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");F.setAttribute("data-approval-status",n.status),n.status==="approved"?(F.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",F.style.color="var(--persona-palette-colors-success-700, #15803d)",F.textContent="Approved"):n.status==="denied"?(F.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",F.style.color="var(--persona-palette-colors-error-700, #b91c1c)",F.textContent="Denied"):n.status==="timeout"&&(F.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",F.style.color="var(--persona-palette-colors-warning-700, #b45309)",F.textContent="Timeout"),f.appendChild(F)}p.appendChild(f);let x=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(o!=null&&o.descriptionColor&&(x.style.color=o.descriptionColor),x.textContent=n.description,p.appendChild(x),n.parameters){let F=b("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o!=null&&o.parameterBackgroundColor&&(F.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(F.style.color=o.parameterTextColor),F.style.fontSize="0.75rem",F.style.lineHeight="1rem",F.textContent=qr(n.parameters),p.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 q=Se("shield-check",14,(B=o==null?void 0:o.approveButtonTextColor)!=null?B:"#ffffff",2);q&&(q.style.marginRight="4px",$.appendChild(q));let me=document.createTextNode((v=o==null?void 0:o.approveLabel)!=null?v:"Approve");$.appendChild(me);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-cursor-pointer");re.type="button",re.style.backgroundColor=(w=o==null?void 0:o.denyButtonColor)!=null?w:"transparent",re.style.color=(E=o==null?void 0:o.denyButtonTextColor)!=null?E:"var(--persona-feedback-error, #dc2626)",re.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,re.setAttribute("data-approval-action","deny");let be=Se("shield-x",14,(S=o==null?void 0:o.denyButtonTextColor)!=null?S:"var(--persona-feedback-error, #dc2626)",2);be&&(be.style.marginRight="4px",re.appendChild(be));let ie=document.createTextNode((k=o==null?void 0:o.denyLabel)!=null?k:"Deny");re.appendChild(ie),F.append($,re),p.appendChild(F)}return a.append(i,p),s.appendChild(a),s};var um=e=>{let t=[];return{buttons:t,render:(o,r,s,a,i)=>{if(e.innerHTML="",t.length=0,!o||!o.length||(a!=null?a:r?r.getMessages():[]).some(g=>g.role==="user"))return;let u=document.createDocumentFragment(),p=r?r.isStreaming():!1,f=g=>{switch(g){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(g=>{let x=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");x.type="button",x.textContent=g,x.disabled=p,i!=null&&i.fontFamily&&(x.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(x.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(x.style.paddingLeft=i.paddingX,x.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(x.style.paddingTop=i.paddingY,x.style.paddingBottom=i.paddingY),x.addEventListener("click",()=>{!r||r.isStreaming()||(s.value="",r.sendMessage(g))}),u.appendChild(x),t.push(x)}),e.appendChild(u)}}};var Ys=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Xs=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}};var vv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),xv=new Set(["step_start","execution_start"]),wv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Cv=new Set(["step_complete","agent_turn_complete"]),Sv=new Set(["flow_complete","agent_complete"]),mm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),fm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,kr=(e,t)=>{let n=e[t];return fm(n)?n:void 0};function Ml(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Si(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Av(e,t){return typeof t.type=="string"?t.type:e}function Tv(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function kv(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function gm(e){var o,r,s,a,i;let t=kr(e,"result"),n=[kr(e,"tokens"),kr(e,"totalTokens"),t?kr(t,"tokens"):void 0,kr(e,"usage"),t?kr(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(r=(o=Qn(d.output))!=null?o:Qn(d.outputTokens))!=null?r:Qn(d.completionTokens);if(l!==void 0)return l}return(i=(s=Qn(e.outputTokens))!=null?s:Qn(e.completionTokens))!=null?i:t?(a=Qn(t.outputTokens))!=null?a:Qn(t.completionTokens):void 0}function Ev(e){var n,o,r,s,a;let t=kr(e,"result");return(a=(r=(o=(n=Qn(e.executionTime))!=null?n:Qn(e.executionTimeMs))!=null?o:Qn(e.execution_time))!=null?r:Qn(e.duration))!=null?a:t?(s=Qn(t.executionTime))!=null?s:Qn(t.executionTimeMs):void 0}function Mv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Qs=class{constructor(t=Mv){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:Si(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var s;if(!fm(n)){mm.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Av(t,n),r=this.now();if(vv.has(o)){this.startRun(r);return}if(xv.has(o)){this.run||this.startRun(r);return}if(wv.has(o)){if(!kv(o,n))return;let a=Tv(n);if(!a)return;this.run||this.startRun(r);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=r),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Ml(i.visibleCharCount),l=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Si(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Cv.has(o)){if(!this.run)return;let a=this.run,i=gm(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Ml(a.visibleCharCount),u=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:Si(l,u),outputTokens:l,durationMs:u,source:d?"usage":"estimate"};return}if(Sv.has(o)){if(!this.run)return;let a=this.run,i=gm(n),d=i!=null?i:a.exactOutputTokens+Ml(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:Si(d,u),outputTokens:d,durationMs:u,source:l},this.run=null;return}if(mm.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;if(r!==void 0&&r>=250)return r;let s=Ev(n);return s!=null?s:o-t.startedAt}};function Zr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Lv={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},Iv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Rv=["flowName","stepName","reasoningText","text","name","tool","toolName"],Pv=100;function Wv(e,t){let n={...Lv,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Iv}function Bv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Hv(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function Dv(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Fv(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let o=document.createElement("textarea");o.value=e,o.style.position="fixed",o.style.opacity="0",document.body.appendChild(o),o.select(),document.execCommand("copy"),document.body.removeChild(o),n()})}function Ov(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function Nv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function _v(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function Vv(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(i)return i}return a();function a(){let i=b("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=b("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=o,i.appendChild(d),i}}function Ll(e,t,n,o,r,s,a,i){var f;let d=r.has(e.id),l=b("div","persona-border-b persona-border-persona-divider persona-text-xs");Zr(l,(f=o.classNames)==null?void 0:f.eventRow);let u=a.find(g=>g.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let g=u.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(g)return l.appendChild(g),l}return l.appendChild(p()),l;function p(){var $,q;let g=b("div",""),x=b("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");x.setAttribute("data-event-id",e.id);let C=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),M=Se(d?"chevron-down":"chevron-right","14px","currentColor",2);M&&C.appendChild(M);let W=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";W.textContent=L==="relative"?Bv(e.timestamp,n):Hv(e.timestamp);let H=null;o.showSequenceNumbers!==!1&&(H=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),H.textContent=String(t+1));let D=Wv(e.type,o.badgeColors),B=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");B.style.backgroundColor=D.bg,B.style.color=D.text,B.style.borderColor=D.text+"50",B.textContent=e.type;let v=(q=o.descriptionFields)!=null?q:Rv,w=Dv(e.payload,v),E=null;w&&(E=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),E.textContent=w);let S=b("div","persona-flex-1 persona-min-w-0"),k=b("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),F=Se("clipboard","12px","currentColor",1.5);return F&&k.appendChild(F),k.addEventListener("click",async me=>{me.stopPropagation(),await Fv(Ov(e)),k.innerHTML="";let re=Se("check","12px","currentColor",1.5);re&&k.appendChild(re),setTimeout(()=>{k.innerHTML="";let be=Se("clipboard","12px","currentColor",1.5);be&&k.appendChild(be)},1500)}),x.appendChild(C),x.appendChild(W),H&&x.appendChild(H),x.appendChild(B),E&&x.appendChild(E),x.appendChild(S),x.appendChild(k),g.appendChild(x),d&&g.appendChild(Vv(e,a,i)),g}}function hm(e){var x,C,M,W,L;let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,i=(x=r==null?void 0:r.features)==null?void 0:x.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(C=i==null?void 0:i.iconName)!=null?C:"arrow-down",u=(M=i==null?void 0:i.label)!=null?M:"",p=(L=(W=r==null?void 0:r.features)==null?void 0:W.eventStream)!=null?L:{},f=s.find(H=>H.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&r){let H=f.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>g().element,onClose:o});if(H)return{element:H,update:()=>{},destroy:()=>{}}}return g();function g(){let H=p.classNames,D=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Zr(D,H==null?void 0:H.panel);let B=[],v="",w="",E=null,S=[],k={},F=0,$=oi(),q=0,me=0,re=!1,be=null,ie=!1,we=0,We=new Set,ye=new Map,Z="",Ee="",X=null,Ae,fe,le,ue,je,j=null,oe=null,Re=null;function tt(){let ae=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ve=b("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");Zr(ve,H==null?void 0:H.headerBar);let wt=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(wt.textContent="Events",Ae=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"),Ae.textContent="0",a){oe=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),oe.style.cursor="help";let Fn=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Fn.textContent="Throughput",j=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"),j.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=oe,xn=Re,On=()=>{if(!xn.textContent)return;let wo=Zn.getBoundingClientRect(),Nn=ae.getBoundingClientRect();xn.style.left=`${wo.left-Nn.left}px`,xn.style.top=`${wo.bottom-Nn.top+4}px`,xn.style.display="block"},ut=()=>{xn.style.display="none"};oe.addEventListener("mouseenter",On),oe.addEventListener("mouseleave",ut),oe.appendChild(Fn),oe.appendChild(j)}let _t=b("div","persona-flex-1");fe=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",fe.appendChild(Jt),le=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"),le.type="button",le.title="Copy All";let Et=Se("clipboard-copy","12px","currentColor",1.5);Et&&le.appendChild(Et);let At=b("span","persona-text-xs");At.textContent="Copy All",le.appendChild(At),ve.appendChild(wt),ve.appendChild(Ae),oe&&ve.appendChild(oe),ve.appendChild(_t),ve.appendChild(fe),ve.appendChild(le);let ht=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Zr(ht,H==null?void 0:H.searchBar);let yt=Se("search","14px","var(--persona-muted, #9ca3af)",1.5),Ut=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");yt&&Ut.appendChild(yt),ue=b("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Zr(ue,H==null?void 0:H.searchInput),ue.type="text",ue.placeholder="Search event payloads...",je=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"),je.type="button",je.style.display="none";let Ze=Se("x","12px","currentColor",2);return Ze&&je.appendChild(Ze),ht.appendChild(Ut),ht.appendChild(ue),ht.appendChild(je),ae.appendChild(ve),ae.appendChild(ht),Re&&ae.appendChild(Re),ae}let ge,ce=s.find(ae=>ae.renderEventStreamToolbar);if(ce!=null&&ce.renderEventStreamToolbar&&r){let ae=ce.renderEventStreamToolbar({config:r,defaultRenderer:()=>tt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:ve=>{v=ve,Dn(),se()},onSearchChange:ve=>{w=ve,Dn(),se()}});ge=ae!=null?ae:tt()}else ge=tt();let _e=b("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");_e.style.display="none";function Le(){if(!a||!j||!oe)return;let ae=a();j.textContent=Nv(ae);let ve=_v(ae);Re&&(Re.textContent=ve,ve||(Re.style.display="none")),ve?oe.setAttribute("aria-label",ve):oe.removeAttribute("aria-label")}let de=b("div","persona-flex-1 persona-min-h-0 persona-relative"),Y=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Y.style.height="100%";let 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");Zr(Ve,H==null?void 0:H.scrollIndicator),Ve.style.display="none",Ve.setAttribute("data-persona-scroll-to-bottom-has-label",u?"true":"false");let Ct=Se(l,"14px","currentColor",2);Ct&&Ve.appendChild(Ct);let Q=b("span","");Q.textContent=u,Ve.appendChild(Q);let Fe=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Fe.style.display="none",de.appendChild(Y),de.appendChild(Fe),de.appendChild(Ve),D.setAttribute("tabindex","0"),D.appendChild(ge),D.appendChild(_e),D.appendChild(de);function Ln(){let ae=t.getAll(),ve={};for(let At of ae)ve[At.type]=(ve[At.type]||0)+1;let wt=Object.keys(ve).sort(),_t=wt.length!==S.length||!wt.every((At,ht)=>At===S[ht]),Jt=!_t&&wt.some(At=>ve[At]!==k[At]),vn=ae.length!==Object.values(k).reduce((At,ht)=>At+ht,0);if(!_t&&!Jt&&!vn||(S=wt,k=ve,!fe))return;let Et=fe.value;if(fe.options[0].textContent="All events",_t){for(;fe.options.length>1;)fe.remove(1);for(let At of wt){let ht=b("option","");ht.value=At,ht.textContent=`${At} (${ve[At]||0})`,fe.appendChild(ht)}Et&&wt.includes(Et)?fe.value=Et:Et&&(fe.value="",v="")}else for(let At=1;At<fe.options.length;At++){let ht=fe.options[At];ht.textContent=`${ht.value} (${ve[ht.value]||0})`}}function Ft(){let ae=t.getAll();if(v&&(ae=ae.filter(ve=>ve.type===v)),w){let ve=w.toLowerCase();ae=ae.filter(wt=>wt.type.toLowerCase().includes(ve)||wt.payload.toLowerCase().includes(ve))}return ae}function ln(){return v!==""||w!==""}function Dn(){F=0,q=0,$.resume(),Ve.style.display="none"}function Jn(ae){We.has(ae)?We.delete(ae):We.add(ae),X=ae;let ve=Y.scrollTop,wt=$.isFollowing();ie=!0,$.pause(),se(),Y.scrollTop=ve,wt&&$.resume(),ie=!1}function N(){return Os(Y,50)}function se(){me=Date.now(),re=!1,Le(),Ln();let ae=t.getEvictedCount();ae>0?(_e.textContent=`${ae.toLocaleString()} older events truncated`,_e.style.display=""):_e.style.display="none",B=Ft();let ve=B.length,wt=t.getSize()>0;Ae&&(Ae.textContent=String(t.getSize())),ve===0&&wt&&ln()?(Fe.textContent=w?`No events matching '${w}'`:"No events matching filter",Fe.style.display="",Y.style.display="none"):(Fe.style.display="none",Y.style.display=""),le&&(le.title=ln()?`Copy Filtered (${ve})`:"Copy All"),d&&!$.isFollowing()&&ve>F&&(q+=ve-F,Q.textContent=u?`${u}${q>0?` (${q})`:""}`:"",Ve.style.display=""),F=ve;let _t=t.getAll(),Jt=_t.length>0?_t[0].timestamp:0,vn=new Set(B.map(ht=>ht.id));for(let ht of We)vn.has(ht)||We.delete(ht);let Et=v!==Z||w!==Ee,At=ye.size===0&&B.length>0;if(Et||At||B.length===0){Y.innerHTML="",ye.clear();let ht=document.createDocumentFragment();for(let yt=0;yt<B.length;yt++){let Ut=Ll(B[yt],yt,Jt,p,We,Jn,s,r);ye.set(B[yt].id,Ut),ht.appendChild(Ut)}Y.appendChild(ht),Z=v,Ee=w,X=null}else{if(X!==null){let yt=ye.get(X);if(yt&&yt.parentNode===Y){let Ut=B.findIndex(Ze=>Ze.id===X);if(Ut>=0){let Ze=Ll(B[Ut],Ut,Jt,p,We,Jn,s,r);Y.insertBefore(Ze,yt),yt.remove(),ye.set(X,Ze)}}X=null}let ht=new Set(B.map(yt=>yt.id));for(let[yt,Ut]of ye)ht.has(yt)||(Ut.remove(),ye.delete(yt));for(let yt=0;yt<B.length;yt++){let Ut=B[yt];if(!ye.has(Ut.id)){let Ze=Ll(Ut,yt,Jt,p,We,Jn,s,r);ye.set(Ut.id,Ze),Y.appendChild(Ze)}}}$.isFollowing()&&(Y.scrollTop=Y.scrollHeight)}function He(){if(Date.now()-me>=Pv){be!==null&&(cancelAnimationFrame(be),be=null),se();return}re||(re=!0,be=requestAnimationFrame(()=>{be=null,se()}))}let Xe=(ae,ve)=>{if(!le)return;le.innerHTML="";let wt=Se(ae,"12px","currentColor",1.5);wt&&le.appendChild(wt);let _t=b("span","persona-text-xs");_t.textContent="Copy All",le.appendChild(_t),setTimeout(()=>{le.innerHTML="";let Jt=Se("clipboard-copy","12px","currentColor",1.5);Jt&&le.appendChild(Jt);let vn=b("span","persona-text-xs");vn.textContent="Copy All",le.appendChild(vn),le.disabled=!1},ve)},Oe=async()=>{if(le){le.disabled=!0;try{let ae;ln()?ae=B:n?(ae=await n(),ae.length===0&&(ae=t.getAll())):ae=t.getAll();let ve=ae.map(wt=>{try{return JSON.parse(wt.payload)}catch{return wt.payload}});await navigator.clipboard.writeText(JSON.stringify(ve,null,2)),Xe("check",1500)}catch{Xe("x",1500)}}},Ne=()=>{fe&&(v=fe.value,Dn(),se())},ot=()=>{!ue||!je||(je.style.display=ue.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{w=ue.value,Dn(),se()},150))},St=()=>{!ue||!je||(ue.value="",w="",je.style.display="none",E&&clearTimeout(E),Dn(),se())},Nt=()=>{if(ie)return;let ae=Y.scrollTop,{action:ve,nextLastScrollTop:wt}=ri({following:$.isFollowing(),currentScrollTop:ae,lastScrollTop:we,nearBottom:N(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});we=wt,ve==="resume"?($.resume(),q=0,Ve.style.display="none"):ve==="pause"&&($.pause(),d&&(Q.textContent=u,Ve.style.display=""))},jt=ae=>{let ve=si({following:$.isFollowing(),deltaY:ae.deltaY,nearBottom:N(),resumeWhenNearBottom:!0});ve==="pause"?($.pause(),d&&(Q.textContent=u,Ve.style.display="")):ve==="resume"&&($.resume(),q=0,Ve.style.display="none")},K=()=>{d&&(Y.scrollTop=Y.scrollHeight,$.resume(),q=0,Ve.style.display="none")},gt=ae=>{let ve=ae.target;if(!ve||ve.closest("button"))return;let wt=ve.closest("[data-event-id]");if(!wt)return;let _t=wt.getAttribute("data-event-id");_t&&Jn(_t)},nt=ae=>{if((ae.metaKey||ae.ctrlKey)&&ae.key==="f"){ae.preventDefault(),ue==null||ue.focus(),ue==null||ue.select();return}ae.key==="Escape"&&(ue&&document.activeElement===ue?(St(),ue.blur(),D.focus()):o&&o())};le&&le.addEventListener("click",Oe),fe&&fe.addEventListener("change",Ne),ue&&ue.addEventListener("input",ot),je&&je.addEventListener("click",St),Y.addEventListener("scroll",Nt),Y.addEventListener("wheel",jt,{passive:!0}),Y.addEventListener("click",gt),Ve.addEventListener("click",K),D.addEventListener("keydown",nt);function $t(){E&&clearTimeout(E),be!==null&&(cancelAnimationFrame(be),be=null),re=!1,ye.clear(),le&&le.removeEventListener("click",Oe),fe&&fe.removeEventListener("change",Ne),ue&&ue.removeEventListener("input",ot),je&&je.removeEventListener("click",St),Y.removeEventListener("scroll",Nt),Y.removeEventListener("wheel",jt),Y.removeEventListener("click",gt),Ve.removeEventListener("click",K),D.removeEventListener("keydown",nt)}return{element:D,update:He,destroy:$t}}}function bm(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",o=typeof e.artifactId=="string"?e.artifactId:"",r=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),o&&i.setAttribute("data-open-artifact",o);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=n;let p=document.createElement("div");if(p.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",p.style.color="var(--persona-muted, #9ca3af)",r==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",p.appendChild(f);let g=document.createElement("span");g.textContent=`Generating ${a.toLowerCase()}...`,p.appendChild(g)}else p.textContent=a;if(l.append(u,p),i.append(d,l),r==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${n}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",o),i.append(f)}return i}var ym=(e,t)=>{var o,r,s;let n=(s=(r=(o=t==null?void 0:t.config)==null?void 0:o.features)==null?void 0:r.artifacts)==null?void 0:s.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",u=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>bm(e,t)});if(u)return u}return bm(e,t)};var Il=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)})}},Er=new Il;Er.register("PersonaArtifactCard",ym);function $v(e){var r;let t=b("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=b("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify((r=e.props)!=null?r:{},null,2),t.appendChild(n),t.appendChild(o),t}function vm(e,t){var fe,le,ue,je;let n=(le=(fe=e.features)==null?void 0:fe.artifacts)==null?void 0:le.layout,r=((ue=n==null?void 0:n.toolbarPreset)!=null?ue:"default")==="document",s=(je=n==null?void 0:n.panePadding)==null?void 0:je.trim(),a=e.markdown?Na(e.markdown):null,i=_a(e.sanitize),d=j=>{let oe=a?a(j):Ls(j);return i?i(oe):oe},l=typeof document!="undefined"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{l==null||l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"),F==null||F.hide()};l&&l.addEventListener("click",()=>{var j;u(),(j=t.onDismiss)==null||j.call(t)});let p=b("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");p.setAttribute("data-persona-theme-zone","artifact-pane"),r&&p.classList.add("persona-artifact-pane-document");let f=b("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&f.classList.add("persona-artifact-toolbar-document");let g=b("span","persona-text-xs persona-font-medium persona-truncate");g.textContent="Artifacts";let x=b("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");x.type="button",x.textContent="Close",x.setAttribute("aria-label","Close artifacts panel"),x.addEventListener("click",()=>{var j;u(),(j=t.onDismiss)==null||j.call(t)});let C="rendered",M=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),W=r?yn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):yn({icon:"eye",label:"Rendered view"}),L=r?yn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):yn({icon:"code-2",label:"Source"}),H=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),D=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,B=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,v=n==null?void 0:n.documentToolbarCopyMenuItems,w=!!(B&&v&&v.length>0),E=null,S,k=null,F=null;if(r&&(D||B)&&!w){if(S=D?gl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):yn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),B){let j=Se("chevron-down",14,"currentColor",2);j&&S.appendChild(j)}}else r&&w?(E=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),S=D?gl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):yn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),k=yn({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),E.append(S,k)):r?S=yn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):S=yn({icon:"copy",label:"Copy"});let $=r?yn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):yn({icon:"refresh-cw",label:"Refresh"}),q=r?yn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):yn({icon:"x",label:"Close"}),me=()=>{var ge,ce,_e;let j=(ge=ye.find(Le=>Le.id===Z))!=null?ge:ye[ye.length-1],oe=(ce=j==null?void 0:j.id)!=null?ce:null,Re=(j==null?void 0:j.artifactType)==="markdown"&&(_e=j.markdown)!=null?_e:"",tt=j?JSON.stringify({component:j.component,props:j.props},null,2):"";return{markdown:Re,jsonPayload:tt,id:oe}},re=async()=>{var ge;let{markdown:j,jsonPayload:oe}=me(),Re=(ge=ye.find(ce=>ce.id===Z))!=null?ge:ye[ye.length-1],tt=(Re==null?void 0:Re.artifactType)==="markdown"?j:Re?oe:"";try{await navigator.clipboard.writeText(tt)}catch{}};if(S.addEventListener("click",async()=>{let j=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(j&&w){let{markdown:oe,jsonPayload:Re,id:tt}=me();try{await j({actionId:"primary",artifactId:tt,markdown:oe,jsonPayload:Re})}catch{}return}await re()}),k&&(v!=null&&v.length)){let j=()=>{var Re;return(Re=p.closest("[data-persona-root]"))!=null?Re:document.body},oe=()=>{F=jr({items:v.map(Re=>({id:Re.id,label:Re.label})),onSelect:async Re=>{let{markdown:tt,jsonPayload:ge,id:ce}=me(),_e=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{_e?await _e({actionId:Re,artifactId:ce,markdown:tt,jsonPayload:ge}):Re==="markdown"||Re==="md"?await navigator.clipboard.writeText(tt):Re==="json"||Re==="source"?await navigator.clipboard.writeText(ge):await navigator.clipboard.writeText(tt||ge)}catch{}},anchor:E!=null?E:k,position:"bottom-right",portal:j()})};p.isConnected?oe():requestAnimationFrame(oe),k.addEventListener("click",Re=>{Re.stopPropagation(),F==null||F.toggle()})}$.addEventListener("click",async()=>{var j;try{await((j=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:j.call(n))}catch{}X()}),q.addEventListener("click",()=>{var j;u(),(j=t.onDismiss)==null||j.call(t)});let be=()=>{r&&(W.setAttribute("aria-pressed",C==="rendered"?"true":"false"),L.setAttribute("aria-pressed",C==="source"?"true":"false"))};W.addEventListener("click",()=>{C="rendered",be(),X()}),L.addEventListener("click",()=>{C="source",be(),X()});let ie=b("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");r?(f.replaceChildren(),M.append(W,L),E?H.append(E,$,q):H.append(S,$,q),f.append(M,ie,H),be()):(f.appendChild(g),f.appendChild(x)),s&&(f.style.paddingLeft=s,f.style.paddingRight=s);let we=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"),We=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(we.style.paddingLeft=s,we.style.paddingRight=s,We.style.padding=s),p.appendChild(f),p.appendChild(we),p.appendChild(We);let ye=[],Z=null,Ee=!1,X=()=>{var tt,ge,ce,_e;let j=r&&ye.length<=1;we.classList.toggle("persona-hidden",j),we.replaceChildren();for(let Le of ye){let de=b("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");de.type="button",de.textContent=Le.title||Le.id.slice(0,8),Le.id===Z&&de.classList.add("persona-bg-persona-container","persona-border-persona-border"),de.addEventListener("click",()=>t.onSelect(Le.id)),we.appendChild(de)}We.replaceChildren();let oe=Z&&ye.find(Le=>Le.id===Z)||ye[ye.length-1];if(!oe)return;if(r){let Le=oe.artifactType==="markdown"?"MD":(tt=oe.component)!=null?tt:"Component",Y=(oe.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ie.textContent=`${Y} \xB7 ${Le}`}else g.textContent="Artifacts";if(oe.artifactType==="markdown"){if(r&&C==="source"){let de=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");de.textContent=(ge=oe.markdown)!=null?ge:"",We.appendChild(de);return}let Le=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Le.innerHTML=d((ce=oe.markdown)!=null?ce:""),We.appendChild(Le);return}let Re=oe.component?Er.get(oe.component):void 0;if(Re){let de={message:{id:oe.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Y=Re((_e=oe.props)!=null?_e:{},de);if(Y){We.appendChild(Y);return}}catch{}}We.appendChild($v(oe))},Ae=()=>{var oe;let j=ye.length>0;if(p.classList.toggle("persona-hidden",!j),l){let Re=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,ge=((oe=Re==null?void 0:Re.classList.contains("persona-artifact-narrow-host"))!=null?oe:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;j&&ge&&Ee?(l.classList.remove("persona-hidden"),p.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"))}};return{element:p,backdrop:l,update(j){var oe,Re,tt;ye=j.artifacts,Z=(tt=(Re=j.selectedId)!=null?Re:(oe=j.artifacts[j.artifacts.length-1])==null?void 0:oe.id)!=null?tt:null,ye.length>0&&(Ee=!0),X(),Ae()},setMobileOpen(j){Ee=j,!j&&l?(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):Ae()}}}function co(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function xm(e,t){var s,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!co(t))return;let n=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,o=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),r=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function Uv(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function Ai(e,t){var d,l,u,p,f,g,x,C,M,W;if(!co(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),Uv(e),xm(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(u=n==null?void 0:n.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=n==null?void 0:n.paneWidth)!=null?p:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=n==null?void 0:n.paneMaxWidth)!=null?f:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=(g=n==null?void 0:n.paneBackground)==null?void 0:g.trim();o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let r=(x=n==null?void 0:n.panePadding)==null?void 0:x.trim();r?e.style.setProperty("--persona-artifact-pane-padding",r):e.style.removeProperty("--persona-artifact-pane-padding");let s=(C=n==null?void 0:n.documentToolbarIconColor)==null?void 0:C.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(M=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:M.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(W=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:W.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),xm(e,t)}var wm=["panel","seamless"];function Ti(e,t){var i,d,l,u,p,f;for(let g of wm)e.classList.remove(`persona-artifact-appearance-${g}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!co(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,o=(l=n==null?void 0:n.paneAppearance)!=null?l:"panel",r=wm.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${r}`);let s=(u=n==null?void 0:n.paneBorderRadius)==null?void 0:u.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(p=n==null?void 0:n.paneShadow)==null?void 0:p.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let g=((f=n.unifiedSplitOuterRadius)==null?void 0:f.trim())||s;g&&e.style.setProperty("--persona-artifact-unified-outer-radius",g)}}function Cm(e,t){var n,o,r;return!t||!co(e)?!1:((r=(o=(n=e.features)==null?void 0:n.artifacts)==null?void 0:o.layout)==null?void 0:r.expandLauncherPanelWhenOpen)!==!1}function zv(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function qv(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function jv(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Kv(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Sm(e,t){var a;let o=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function Am(e,t,n,o,r,s){let a=zv(r,200),i=Kv(t,n,o,200);i=Math.max(a,i);let d=qv(s);return d!==null&&(i=Math.min(i,d)),jv(e,a,i)}var Tm={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Rl=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var x,C,M;if(s.dataset.enhanced==="true")return;let a=(x=s.dataset.tvForm)!=null?x:"init";s.dataset.enhanced="true";let i=(C=Tm[a])!=null?C:Tm.init;s.classList.add("persona-form-card","persona-space-y-4");let d=b("div","persona-space-y-1"),l=b("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let W=b("p","persona-text-sm persona-text-persona-muted");W.textContent=i.description,d.appendChild(W)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(W=>{var v,w;let L=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");L.htmlFor=`${t.id}-${a}-${W.name}`;let H=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");H.textContent=W.label,L.appendChild(H);let D=(v=W.type)!=null?v:"text",B;D==="textarea"?(B=document.createElement("textarea"),B.rows=3):(B=document.createElement("input"),B.type=D),B.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",B.id=`${t.id}-${a}-${W.name}`,B.name=W.name,B.placeholder=(w=W.placeholder)!=null?w:"",W.required&&(B.required=!0),L.appendChild(B),u.appendChild(L)});let p=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=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");g.type="submit",g.textContent=(M=i.submitLabel)!=null?M:"Submit",p.appendChild(f),p.appendChild(g),u.appendChild(p),s.replaceChildren(d,u),u.addEventListener("submit",async W=>{var B,v;W.preventDefault();let L=(B=n.formEndpoint)!=null?B:"/form",H=new FormData(u),D={};H.forEach((w,E)=>{D[E]=w}),D.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let w=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D)});if(!w.ok)throw new Error(`Form submission failed (${w.status})`);let E=await w.json();f.textContent=(v=E.message)!=null?v:"Thanks! We'll be in touch soon.",E.success&&E.nextPrompt&&await o.sendMessage(String(E.nextPrompt))}catch(w){f.textContent=w instanceof Error?w.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var Pl=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()}},Wl=new Pl;var km=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{var a;(a=e.get(r))==null||a.delete(s)};return{on:t,off:n,emit:(r,s)=>{var a;(a=e.get(r))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Gv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Yv=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},Hl=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Gv(e),n=Yv(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},Bl=e=>typeof e=="string"?e:e==null?"":String(e),Js={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Bl(e.payload.text)},messageAndClick:(e,t)=>{var r;if(e.type!=="message_and_click")return;let n=e.payload,o=Bl(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:Bl(n.text)}}},Em=e=>Array.isArray(e)?e.map(t=>String(t)):[],Dl=e=>{let t=new Set(Em(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Em(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,u)=>l||(u==null?void 0:u({text:a,message:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),o();let d={action:i,message:s.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let u=()=>{e.emit("action:resubmit",d)},p=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!p)continue;if(p.handled){let f=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:f,resubmit:p.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:n}};var Xv=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Qv=e=>e.map(t=>({...t,streaming:!1})),Jv=e=>e.map(t=>({...t,status:"complete"})),Mm=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Xv(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?Qv(n.messages):void 0,artifacts:n.artifacts?Jv(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};import{parse as j0,STR as K0,OBJ as G0}from"partial-json";function Lm(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Er.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:i=>{r&&r(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Im(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function Rm(e){let t=Im(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Pm(e){let t=Im(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var Zv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Wm(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=Zv}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let p=null,f=document.createElement("div");f.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=o,g.appendChild(x);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,g.appendChild(C),f.appendChild(g);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 W=[];for(let v=1;v<=5;v++){let w=document.createElement("button");w.type="button",w.className="persona-feedback-rating-btn persona-feedback-star-btn",w.setAttribute("role","radio"),w.setAttribute("aria-checked","false"),w.setAttribute("aria-label",`${v} star${v>1?"s":""}: ${l[v-1]}`),w.title=l[v-1],w.dataset.rating=String(v),w.innerHTML=`
|
|
27
27
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
28
28
|
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
|
|
29
29
|
</svg>
|
|
30
|
-
`,C.addEventListener("click",()=>{p=v,P.forEach((E,S)=>{let k=S<v;E.classList.toggle("selected",k),E.setAttribute("aria-checked",S===v-1?"true":"false")})}),P.push(C),M.appendChild(C)}g.appendChild(M);let W=null;if(d){let v=document.createElement("div");v.className="persona-feedback-comment-container",W=document.createElement("textarea"),W.className="persona-feedback-comment",W.placeholder=s,W.rows=3,W.setAttribute("aria-label","Additional comments"),v.appendChild(W),g.appendChild(v)}let H=document.createElement("div");H.className="persona-feedback-actions";let _=document.createElement("button");_.type="button",_.className="persona-feedback-btn persona-feedback-btn-skip",_.textContent=i,_.addEventListener("click",()=>{n==null||n(),u.remove()});let B=document.createElement("button");return B.type="button",B.className="persona-feedback-btn persona-feedback-btn-submit",B.textContent=a,B.addEventListener("click",async()=>{if(p===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}B.disabled=!0,B.textContent="Submitting...";try{let v=(W==null?void 0:W.value.trim())||void 0;await t(p,v),u.remove()}catch(v){B.disabled=!1,B.textContent=a,console.error("[CSAT Feedback] Failed to submit:",v)}}),H.appendChild(_),H.appendChild(B),g.appendChild(H),u.appendChild(g),u}function Pm(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:u="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let g=null,m=document.createElement("div");m.className="persona-feedback-content";let w=document.createElement("div");w.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=o,w.appendChild(x);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=r,w.appendChild(M),m.appendChild(w);let P=document.createElement("div");P.className="persona-feedback-rating persona-feedback-rating-nps",P.setAttribute("role","radiogroup"),P.setAttribute("aria-label","Likelihood rating from 0 to 10");let W=document.createElement("div");W.className="persona-feedback-labels";let H=document.createElement("span");H.className="persona-feedback-label-low",H.textContent=l;let _=document.createElement("span");_.className="persona-feedback-label-high",_.textContent=u,W.appendChild(H),W.appendChild(_);let B=document.createElement("div");B.className="persona-feedback-numbers";let v=[];for(let D=0;D<=10;D++){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 ${D} out of 10`),$.textContent=String(D),$.dataset.rating=String(D),D<=6?$.classList.add("persona-feedback-detractor"):D<=8?$.classList.add("persona-feedback-passive"):$.classList.add("persona-feedback-promoter"),$.addEventListener("click",()=>{g=D,v.forEach((q,me)=>{q.classList.toggle("selected",me===D),q.setAttribute("aria-checked",me===D?"true":"false")})}),v.push($),B.appendChild($)}P.appendChild(W),P.appendChild(B),m.appendChild(P);let C=null;if(d){let D=document.createElement("div");D.className="persona-feedback-comment-container",C=document.createElement("textarea"),C.className="persona-feedback-comment",C.placeholder=s,C.rows=3,C.setAttribute("aria-label","Additional comments"),D.appendChild(C),m.appendChild(D)}let E=document.createElement("div");E.className="persona-feedback-actions";let S=document.createElement("button");S.type="button",S.className="persona-feedback-btn persona-feedback-btn-skip",S.textContent=i,S.addEventListener("click",()=>{n==null||n(),p.remove()});let k=document.createElement("button");return k.type="button",k.className="persona-feedback-btn persona-feedback-btn-submit",k.textContent=a,k.addEventListener("click",async()=>{if(g===null){B.classList.add("persona-feedback-shake"),setTimeout(()=>B.classList.remove("persona-feedback-shake"),500);return}k.disabled=!0,k.textContent="Submitting...";try{let D=(C==null?void 0:C.value.trim())||void 0;await t(g,D),p.remove()}catch(D){k.disabled=!1,k.textContent=a,console.error("[NPS Feedback] Failed to submit:",D)}}),E.appendChild(S),E.appendChild(k),m.appendChild(E),p.appendChild(m),p}var es="persona-chat-history",Qv=30*1e3,Jv={"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 Zv(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=Jv[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 ki(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 ex(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 tx(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Fl=e=>!e||typeof e!="object"?{}:{...e},Wm=e=>e.map(t=>({...t,streaming:!1})),Bm=(e,t,n)=>{let o=e!=null&&e.markdown?Na(e.markdown):null,r=_a(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&r&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var l,u,p;let a=(l=s.text)!=null?l:"",i=(u=s.message.rawContent)!=null?u: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:(p=i!=null?i:s.text)!=null?p:""}):o?d=o(a):d=Ls(a),r?r(d):d}};function Hm(e){var i,d,l,u;let t=b("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",o=(d=e==null?void 0:e.iconSize)!=null?d:"48px",r=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(u=e==null?void 0:e.iconStrokeWidth)!=null?u:.5,a=Se(n,o,r,s);if(a&&t.appendChild(a),e!=null&&e.label){let p=b("span","persona-drop-overlay-label");p.textContent=e.label,t.appendChild(p)}return t}var Dm=(e,t,n)=>{var sc,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;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=Qp(t),r=Wl.getForInstance(o.plugins);o.components&&Er.registerAll(o.components);let s=Am(),i=o.persistState===!1?null:(sc=o.storageAdapter)!=null?sc:km(),d={},l=null,u=!1,p=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&&(u=!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 p(h)});else{let f=c!=null?c:{messages:[],metadata:{}},h=p(f);h.metadata&&(d=Fl(h.metadata)),(ac=h.messages)!=null&&ac.length&&(o={...o,initialMessages:h.messages}),(ic=h.artifacts)!=null&&ic.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(lc=h.selectedArtifactId)!=null?lc:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(o.onStateLoaded)try{let c=p({messages:[],metadata:{}});(cc=c.messages)!=null&&cc.length&&(o={...o,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let g=()=>d,m=c=>{var h;d=(h=c({...d}))!=null?h:{},Pr()},w=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Hl],x=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Js.message,Js.messageAndClick],M=Dl({parsers:w,handlers:x,getSessionMetadata:g,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let P=(pc=(dc=o.launcher)==null?void 0:dc.enabled)!=null?pc:!0,W=(mc=(uc=o.launcher)==null?void 0:uc.autoExpand)!=null?mc:!1,H=(fc=o.autoFocusInput)!=null?fc:!1,_=W,B=P,v=(hc=(gc=o.layout)==null?void 0:gc.header)==null?void 0:hc.layout,C=!1,E=()=>zs(o),S=()=>P||E(),k=E()?!1:P?W:!0,D=!1,$=null,q=()=>{D=!0,$&&clearTimeout($),$=setTimeout(()=>{D&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),D=!1)},1e4)},me=Bm(o,M,q),re=(yc=(bc=o.features)==null?void 0:bc.showReasoning)!=null?yc:!0,be=(xc=(vc=o.features)==null?void 0:vc.showToolCalls)!=null?xc:!0,ie=(Cc=(wc=o.features)==null?void 0:wc.showEventStreamToggle)!=null?Cc:!1,we=(Ac=(Sc=o.features)==null?void 0:Sc.scrollToBottom)!=null?Ac:{},ye=`${(kc=typeof o.persistState=="object"?(Tc=o.persistState)==null?void 0:Tc.keyPrefix:void 0)!=null?kc:"persona-"}event-stream`,Z=ie?new Xs(ye):null,Ee=(Lc=(Mc=(Ec=o.features)==null?void 0:Ec.eventStream)==null?void 0:Mc.maxEvents)!=null?Lc:2e3,X=ie?new Ys(Ee,Z):null,Ae=ie?new Qs:null,ge=null,le=!1,ue=null,je=0;Z==null||Z.open().then(()=>X==null?void 0:X.restore()).catch(c=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let j={onCopy:c=>{var f,h;s.emit("message:copy",c),T!=null&&T.isClientTokenMode()&&T.submitMessageFeedback(c.id,"copy").catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",y)}),(h=(f=o.messageActions)==null?void 0:f.onCopy)==null||h.call(f,c)},onFeedback:c=>{var f,h;s.emit("message:feedback",c),T!=null&&T.isClientTokenMode()&&T.submitMessageFeedback(c.messageId,c.type).catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",y)}),(h=(f=o.messageActions)==null?void 0:f.onFeedback)==null||h.call(f,c)}},oe=(Ic=o.statusIndicator)!=null?Ic:{},Re=c=>{var f,h,y,R;return c==="idle"?(f=oe.idleText)!=null?f:hn.idle:c==="connecting"?(h=oe.connectingText)!=null?h:hn.connecting:c==="connected"?(y=oe.connectedText)!=null?y:hn.connected:c==="error"?(R=oe.errorText)!=null?R:hn.error:hn[c]};function tt(c,f,h,y){if(y==="idle"&&h.idleLink){c.textContent="";let R=document.createElement("a");R.href=h.idleLink,R.target="_blank",R.rel="noopener noreferrer",R.textContent=f,R.style.color="inherit",R.style.textDecoration="none",c.appendChild(R)}else c.textContent=f}let{wrapper:fe,panel:ce,pillRoot:_e}=Ku(o),Le=Gu(o,S()),{container:de,body:Y,messagesWrapper:Ve,suggestions:Ct,textarea:Q,sendButton:Fe,sendButtonWrapper:Ln,composerForm:Ft,statusText:ln,introTitle:Dn,introSubtitle:Jn,closeButton:O,iconHolder:se,headerTitle:He,headerSubtitle:Xe,header:Oe,footer:Ne,actionsRow:ot,leftActions:St,rightActions:Nt}=Le,jt=Le.setSendButtonMode,K=Le.micButton,ft=Le.micButtonWrapper,nt=Le.attachmentButton,$t=Le.attachmentButtonWrapper,ae=Le.attachmentInput,ve=Le.attachmentPreviewsContainer;de.classList.add("persona-relative"),Y.classList.add("persona-relative");let wt=12,_t=()=>{var c;return(c=we.label)!=null?c:""},Jt=()=>{var c;return(c=we.iconName)!=null?c:"arrow-down"},vn=()=>we.enabled!==!1,Et=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");Et.type="button",Et.style.display="none",Et.setAttribute("data-persona-scroll-to-bottom","true");let At=b("span","persona-flex persona-items-center"),ht=b("span","");Et.append(At,ht),de.appendChild(Et);let yt=()=>{let f=Ne.style.display==="none"?0:Ne.offsetHeight;Et.style.bottom=`${f+wt}px`};yt();let Ut=()=>{let c=!!_t();Et.setAttribute("aria-label",_t()||"Jump to latest"),Et.title=_t(),Et.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),At.innerHTML="";let f=Se(Jt(),"14px","currentColor",2);f?(At.appendChild(f),At.style.display=""):At.style.display="none",ht.textContent=_t(),ht.style.display=c?"":"none"};Ut();let Ze=null,Fn=null,Zn=r.find(c=>c.renderHeader);if(Zn!=null&&Zn.renderHeader){let c=Zn.renderHeader({config:o,defaultRenderer:()=>{let f=Sr({config:o,showClose:S()});return js(de,f,o),f.header},onClose:()=>Bt(!1,"user")});if(c){let f=de.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(c),Oe=c)}}let xn=()=>{var f,h,y,R;if(!X)return;if(le=!0,!ge&&X&&(ge=fm({buffer:X,getFullHistory:()=>X.getAllFromStore(),onClose:()=>On(),config:o,plugins:r,getThroughput:()=>{var N;return(N=Ae==null?void 0:Ae.getMetric())!=null?N:{status:"idle"}}})),ge&&(Y.style.display="none",(f=Ne.parentNode)==null||f.insertBefore(ge.element,Ne),ge.update()),ut){ut.style.boxShadow=`inset 0 0 0 1.5px ${Mn.actionIconColor}`;let N=(R=(y=(h=o.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:R.toggleButtonActive;N&&N.split(/\s+/).forEach(V=>V&&ut.classList.add(V))}let c=()=>{if(!le)return;let N=Date.now();N-je>=200&&(ge==null||ge.update(),je=N),ue=requestAnimationFrame(c)};je=0,ue=requestAnimationFrame(c),Ho(),s.emit("eventStream:opened",{timestamp:Date.now()})},On=()=>{var c,f,h;if(le){if(le=!1,ge&&ge.element.remove(),Y.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(R=>R&&ut.classList.remove(R))}ue!==null&&(cancelAnimationFrame(ue),ue=null),Ho(),s.emit("eventStream:closed",{timestamp:Date.now()})}},ut=null;if(ie){let c=(Pc=(Rc=o.features)==null?void 0:Rc.eventStream)==null?void 0:Pc.classNames,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=Se("activity","18px","currentColor",1.5);h&&ut.appendChild(h);let y=Le.clearChatButtonWrapper,R=Le.closeButtonWrapper,N=y||R;N&&N.parentNode===Oe?Oe.insertBefore(ut,N):Oe.appendChild(ut),ut.addEventListener("click",()=>{le?On():xn()})}let wo=c=>{var y,R,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=((R=f.maxFiles)!=null?R: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:()=>vi({config:o}).footer,onSubmit:h=>{var V;if(!T||T.isStreaming())return;let y=h.trim(),R=(V=Ze==null?void 0:Ze.hasAttachments())!=null?V:!1;if(!y&&!R)return;fs();let N;R&&(N=[],N.push(...Ze.getContentParts()),y&&N.push(il(y))),T.sendMessage(y,{contentParts:N}),R&&Ze.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{ae==null||ae.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:((Wc=o.voiceRecognition)==null?void 0:Wc.enabled)===!0?()=>{Fn==null||Fn()}:void 0});f&&(Ne.replaceWith(f),Ne=f)}let ar=c=>{let f=c.querySelector("[data-persona-composer-form]"),h=c.querySelector("[data-persona-composer-input]"),y=c.querySelector("[data-persona-composer-submit]"),R=c.querySelector("[data-persona-composer-mic]"),N=c.querySelector("[data-persona-composer-status]");f&&(Ft=f),h&&(Q=h),y&&(Fe=y),R&&(K=R,ft=R.parentElement),N&&(ln=N);let V=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");V&&(Ct=V);let z=c.querySelector(".persona-attachment-button");z&&(nt=z,$t=z.parentElement),ae=c.querySelector('input[type="file"]'),ve=c.querySelector(".persona-attachment-previews");let F=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");F&&(ot=F)};wo(Ne),ar(Ne);let In=(Oc=(Bc=o.layout)==null?void 0:Bc.contentMaxWidth)!=null?Oc:E()?(Fc=(Dc=(Hc=o.launcher)==null?void 0:Hc.composerBar)==null?void 0:Dc.contentMaxWidth)!=null?Fc:"720px":void 0;if(In&&(Ve.style.maxWidth=In,Ve.style.marginLeft="auto",Ve.style.marginRight="auto",Ve.style.width="100%"),In&&Ft&&!E()&&(Ft.style.maxWidth=In,Ft.style.marginLeft="auto",Ft.style.marginRight="auto"),In&&Ct&&!E()&&(Ct.style.maxWidth=In,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),In&&ve&&!E()&&(ve.style.maxWidth=In,ve.style.marginLeft="auto",ve.style.marginRight="auto"),(Nc=o.attachments)!=null&&Nc.enabled&&ae&&ve){Ze=Ds.fromConfig(o.attachments),Ze.setPreviewsContainer(ve),ae.addEventListener("change",h=>{let y=h.target;Ze==null||Ze.handleFileSelect(y.files),y.value=""});let c=o.attachments.dropOverlay,f=Hm(c);de.appendChild(f)}(()=>{var y,R;let c=(R=(y=o.layout)==null?void 0:y.slots)!=null?R:{},f=N=>{switch(N){case"body-top":return de.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ve;case"footer-top":return Ct;case"composer":return Ft;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")Oe.insertBefore(V,Oe.firstChild);else if(N==="header-right")Oe.appendChild(V);else{let F=Oe.querySelector(".persona-flex-col");F?(z=F.parentNode)==null||z.insertBefore(V,F.nextSibling):Oe.appendChild(V)}break;case"body-top":{let F=Y.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");F?F.replaceWith(V):Y.insertBefore(V,Y.firstChild);break}case"body-bottom":Y.appendChild(V);break;case"footer-top":Ct.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 R=y.getAttribute("data-message-id");if(!R)return;let N=h.getAttribute("data-bubble-type");N==="reasoning"?(Kr.has(R)?Kr.delete(R):Kr.add(R),Qu(R,y)):N==="tool"&&(Gr.has(R)?Gr.delete(R):Gr.add(R),Ju(R,y,o)),mo.delete(R)};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 R=y.getAttribute("data-actions-for");if(!R)return;let N=h.getAttribute("data-action");if(N==="copy"){let F=T.getMessages().find(Ce=>Ce.id===R);if(F&&j.onCopy){let Ce=F.content||"";navigator.clipboard.writeText(Ce).then(()=>{h.classList.add("persona-message-action-success");let pe=Se("check",14,"currentColor",2);pe&&(h.innerHTML="",h.appendChild(pe)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let ne=Se("copy",14,"currentColor",2);ne&&(h.innerHTML="",h.appendChild(ne))},2e3)}).catch(pe=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",pe)}),j.onCopy(F)}}else if(N==="upvote"||N==="downvote"){let F=((V=Lo.get(R))!=null?V:null)===N,Ce=N==="upvote"?"thumbs-up":"thumbs-down";if(F){Lo.delete(R),h.classList.remove("persona-message-action-active");let pe=Se(Ce,14,"currentColor",2);pe&&(h.innerHTML="",h.appendChild(pe))}else{let pe=N==="upvote"?"downvote":"upvote",ne=y.querySelector(`[data-action="${pe}"]`);if(ne){ne.classList.remove("persona-message-action-active");let Ye=Se(pe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ye&&(ne.innerHTML="",ne.appendChild(Ye))}Lo.set(R,N),h.classList.add("persona-message-action-active");let he=Se(Ce,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 Be=T.getMessages().find(et=>et.id===R);Be&&j.onFeedback&&j.onFeedback({type:N,messageId:Be.id,message:Be})}}}),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 R=y.getAttribute("data-message-id");if(!R)return;let N=h.getAttribute("data-approval-action");if(!N)return;let V=N==="approve"?"approved":"denied",F=T.getMessages().find(pe=>pe.id===R);if(!(F!=null&&F.approval))return;let Ce=y.querySelector("[data-approval-buttons]");Ce&&Ce.querySelectorAll("button").forEach(ne=>{ne.disabled=!0,ne.style.opacity="0.5",ne.style.cursor="not-allowed"}),F.approval.toolType==="webmcp"?T.resolveWebMcpApproval(R,V):T.resolveApproval(F.approval,V)});let vt=null,_n=null,Vn={artifacts:[],selectedId:null},wn=!1,Rt={current:null};Ve.addEventListener("click",c=>{var ne,he,Te,Be,et;let h=c.target.closest("[data-download-artifact]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||((Te=(he=(ne=o.features)==null?void 0:ne.artifacts)==null?void 0:he.onArtifactAction)==null?void 0:Te.call(he,{type:"download",artifactId:y}))===!0)return;let N=T.getArtifactById(y),V=N==null?void 0:N.markdown,z=(N==null?void 0:N.title)||"artifact";if(!V){let Ye=h.closest("[data-open-artifact]"),it=Ye==null?void 0:Ye.closest("[data-message-id]"),lt=it==null?void 0:it.getAttribute("data-message-id");if(lt){let Me=T.getMessages().find($e=>$e.id===lt);if(Me!=null&&Me.rawContent)try{let $e=JSON.parse(Me.rawContent);V=(Be=$e==null?void 0:$e.props)==null?void 0:Be.markdown,z=((et=$e==null?void 0:$e.props)==null?void 0:et.title)||z}catch{}}}if(!V)return;let F=new Blob([V],{type:"text/markdown"}),Ce=URL.createObjectURL(F),pe=document.createElement("a");pe.href=Ce,pe.download=`${z}.md`,pe.click(),URL.revokeObjectURL(Ce)}),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(),wn=!1,T.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=Le.composerOverlay,to=(c,f,h)=>{var z,F,Ce,pe;let y=f.trim();if(!y||!Rt.current)return;let R=(z=c.getAttribute("data-tool-call-id"))!=null?z:"",N=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:R,answer:y,answers:h.structured,values:(F=h.values)!=null?F:h.source==="multi"?y.split(", "):[y],isFreeText:N,source:h.source},bubbles:!0,composed:!0})),Jr(eo,R);let V=Rt.current.getMessages().find(ne=>{var he;return((he=ne.toolCall)==null?void 0:he.id)===R});(Ce=V==null?void 0:V.agentMetadata)!=null&&Ce.awaitingLocalTool?Rt.current.resolveAskUserQuestion(V,(pe=h.structured)!=null?pe:y):Rt.current.sendMessage(y)},$n=c=>{var R;let f=Rt.current;if(!f)return;let h=(R=c.getAttribute("data-tool-call-id"))!=null?R:"",y=f.getMessages().find(N=>{var V;return((V=N.toolCall)==null?void 0:V.id)===h});y&&f.persistAskUserQuestionProgress(y,{answers:xi(c,y),currentIndex:lo(c)})},Uo=c=>Object.entries(c).map(([f,h])=>`${f}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Io=c=>{var R,N,V;if(((N=(R=o.features)==null?void 0:R.askUserQuestion)==null?void 0:N.groupedAutoAdvance)===!1)return;let f=lo(c),h=Qr(c);if(f>=h-1)return;let y=(V=Rt.current)==null?void 0:V.getMessages().find(z=>{var F;return((F=z.toolCall)==null?void 0:F.id)===c.getAttribute("data-tool-call-id")});y&&(Ci(c,y,o,f+1),$n(c))};eo.addEventListener("click",c=>{var N,V,z,F,Ce,pe,ne,he,Te,Be,et,Ye,it,lt;let h=c.target.closest("[data-ask-user-action]");if(!h)return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;let R=h.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),R==="dismiss"){let Ie=(N=y.getAttribute("data-tool-call-id"))!=null?N:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),Jr(eo,Ie);let Me=(V=Rt.current)==null?void 0:V.getMessages().find($e=>{var L;return((L=$e.toolCall)==null?void 0:L.id)===Ie});(z=Me==null?void 0:Me.agentMetadata)!=null&&z.awaitingLocalTool&&((F=Rt.current)==null||F.markAskUserQuestionResolved(Me),(Ce=Rt.current)==null||Ce.resolveAskUserQuestion(Me,"(dismissed)"));return}if(R==="pick"){let Ie=h.getAttribute("data-option-label");if(!Ie)return;let Me=y.getAttribute("data-multi-select")==="true",$e=rr(y);if($e&&Me){let L=Tr(y)[lo(y)],ke=new Set(Array.isArray(L)?L:[]);ke.has(Ie)?ke.delete(Ie):ke.add(Ie),sr(y,Array.from(ke)),$n(y);return}if($e){sr(y,Ie),$n(y),Io(y);return}if(Me){let L=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",L?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!L);let ke=y.querySelector('[data-ask-user-action="submit-multi"]');ke&&(ke.disabled=kl(y).length===0);return}to(y,Ie,{source:"pick",values:[Ie]});return}if(R==="submit-multi"){let Ie=kl(y);if(Ie.length===0)return;to(y,Ie.join(", "),{source:"multi",values:Ie});return}if(R==="open-free-text"){let Ie=y.querySelector('[data-ask-free-text-row="true"]');if(Ie){Ie.classList.remove("persona-hidden");let Me=Ie.querySelector('[data-ask-free-text-input="true"]');Me==null||Me.focus()}return}if(R==="focus-free-text"){let Ie=y.querySelector('[data-ask-free-text-input="true"]');Ie==null||Ie.focus();return}if(R==="submit-free-text"){let Ie=y.querySelector('[data-ask-free-text-input="true"]'),Me=(pe=Ie==null?void 0:Ie.value)!=null?pe:"";if(!Me.trim())return;if(rr(y)){sr(y,Me.trim()),$n(y),Io(y);return}to(y,Me,{source:"free-text"});return}if(R==="next"||R==="back"){if(!Rt.current)return;let Ie=(ne=y.getAttribute("data-tool-call-id"))!=null?ne:"",Me=Rt.current.getMessages().find(qe=>{var xe;return((xe=qe.toolCall)==null?void 0:xe.id)===Ie});if(!Me)return;let $e=y.querySelector('[data-ask-free-text-input="true"]'),L=(Te=(he=$e==null?void 0:$e.value)==null?void 0:he.trim())!=null?Te:"";if(L){let qe=Tr(y)[lo(y)];(typeof qe!="string"||qe!==L)&&sr(y,L)}let ke=R==="next"?1:-1,Pe=lo(y)+ke;Ci(y,Me,o,Pe),$n(y);return}if(R==="submit-all"){if(!Rt.current)return;let Ie=(Be=y.getAttribute("data-tool-call-id"))!=null?Be:"",Me=Rt.current.getMessages().find(qe=>{var xe;return((xe=qe.toolCall)==null?void 0:xe.id)===Ie});if(!Me)return;let $e=y.querySelector('[data-ask-free-text-input="true"]'),L=(Ye=(et=$e==null?void 0:$e.value)==null?void 0:et.trim())!=null?Ye:"";L&&sr(y,L);let ke=xi(y,Me);Rt.current.persistAskUserQuestionProgress(Me,{answers:ke,currentIndex:lo(y)});let Pe=Uo(ke);to(y,Pe||"(submitted)",{source:"submit-all",structured:ke});return}if(R==="skip"){if(!Rt.current)return;let Ie=(it=y.getAttribute("data-tool-call-id"))!=null?it:"",Me=Rt.current.getMessages().find(xe=>{var It;return((It=xe.toolCall)==null?void 0:It.id)===Ie});if(!Me)return;let $e=rr(y),L=lo(y),ke=Qr(y),Pe=L>=ke-1;if(!$e){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),Jr(eo,Ie),(lt=Me.agentMetadata)!=null&<.awaitingLocalTool&&(Rt.current.markAskUserQuestionResolved(Me),Rt.current.resolveAskUserQuestion(Me,"(dismissed)"));return}sr(y,"");let qe=y.querySelector('[data-ask-free-text-input="true"]');if(qe&&(qe.value=""),Pe){let xe=xi(y,Me),It=Uo(xe);to(y,It||"(skipped)",{source:"submit-all",structured:xe});return}Ci(y,Me,o,L+1),$n(y);return}}),eo.addEventListener("keydown",c=>{var N;if(c.key!=="Enter")return;let h=c.target;if(!((N=h.matches)!=null&&N.call(h,'[data-ask-free-text-input="true"]')))return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;c.preventDefault();let R=h.value;if(R.trim()){if(rr(y)){sr(y,R.trim()),$n(y),Io(y);return}to(y,R,{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,Cn=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 R=10;Wt.style.position="absolute",Wt.style.top="0",Wt.style.bottom="0",Wt.style.width=`${R}px`,Wt.style.zIndex="5";let N=y.offsetWidth-R/2;Wt.style.left=`${Math.max(0,N)}px`},Co=()=>{},zn=()=>{var h,y,R,N,V;if(!vt||!co(o))return;Ai(e,o),Ti(e,o),Co();let c=(N=(R=(y=(h=o.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:R.narrowHostMaxWidth)!=null?N:520,f=ce.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",f>0&&f<=c),vt.update(Vn),wn?(vt.setMobileOpen(!1),vt.element.classList.add("persona-hidden"),(V=vt.backdrop)==null||V.classList.add("persona-hidden")):Vn.artifacts.length>0&&(vt.element.classList.remove("persona-hidden"),vt.setMobileOpen(!0)),qo()};if(co(o)){ce.style.position="relative";let c=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),f=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(de),vt=bm(o,{onSelect:h=>{var y;return(y=Rt.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{wn=!0,zn()}}),vt.element.classList.add("persona-hidden"),Un=f,f.appendChild(c),f.appendChild(vt.element),vt.backdrop&&ce.appendChild(vt.backdrop),ce.appendChild(f),qo=()=>{var y,R,N,V;if(!Un||!vt)return;if(!(((N=(R=(y=o.features)==null?void 0:y.artifacts)==null?void 0:R.layout)==null?void 0:N.resizable)===!0)){Cn==null||Cn(),Cn=null,Ro(),Wt&&(Wt.remove(),Wt=null),vt.element.style.removeProperty("width"),vt.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 F=e.ownerDocument,Ce=(V=F.defaultView)!=null?V:window,pe=ne=>{var it,lt;if(!vt||ne.button!==0||e.classList.contains("persona-artifact-narrow-host")||Ce.innerWidth<=640)return;ne.preventDefault(),Ro();let he=ne.clientX,Te=vt.element.getBoundingClientRect().width,Be=(lt=(it=o.features)==null?void 0:it.artifacts)==null?void 0:lt.layout,et=Ie=>{let Me=Un.getBoundingClientRect().width,$e=e.classList.contains("persona-artifact-appearance-seamless"),L=$e?0:wm(Un,Ce),ke=$e?0:z.getBoundingClientRect().width||6,Pe=Te-(Ie.clientX-he),qe=Cm(Pe,Me,L,ke,Be==null?void 0:Be.resizableMinWidth,Be==null?void 0:Be.resizableMaxWidth);vt.element.style.width=`${qe}px`,vt.element.style.maxWidth="none",jo()},Ye=()=>{F.removeEventListener("pointermove",et),F.removeEventListener("pointerup",Ye),F.removeEventListener("pointercancel",Ye),no=null;try{z.releasePointerCapture(ne.pointerId)}catch{}};no=Ye,F.addEventListener("pointermove",et),F.addEventListener("pointerup",Ye),F.addEventListener("pointercancel",Ye);try{z.setPointerCapture(ne.pointerId)}catch{}};z.addEventListener("pointerdown",pe),Wt=z,Un.insertBefore(z,vt.element),Cn=()=>{z.removeEventListener("pointerdown",pe)}}if(Wt){let z=Vn.artifacts.length>0&&!wn;Wt.classList.toggle("persona-hidden",!z),jo()}},Co=()=>{var Ce,pe,ne,he,Te,Be,et,Ye,it,lt,Ie,Me,$e,L;if(!P||!vt||((pe=(Ce=o.launcher)==null?void 0:Ce.sidebarMode)!=null?pe:!1)||un(o)&&Mo(o).reveal==="emerge")return;let y=(ne=e.ownerDocument.defaultView)!=null?ne:window,R=(Te=(he=o.launcher)==null?void 0:he.mobileFullscreen)!=null?Te:!0,N=(et=(Be=o.launcher)==null?void 0:Be.mobileBreakpoint)!=null?et:640;if(R&&y.innerWidth<=N||!xm(o,P))return;let V=(lt=(it=(Ye=o.launcher)==null?void 0:Ye.width)!=null?it:o.launcherWidth)!=null?lt:io,z=(L=($e=(Me=(Ie=o.features)==null?void 0:Ie.artifacts)==null?void 0:Me.layout)==null?void 0:$e.expandedPanelWidth)!=null?L:"min(720px, calc(100vw - 24px))";Vn.artifacts.length>0&&!wn?(ce.style.width=z,ce.style.maxWidth=z):(ce.style.width=V,ce.style.maxWidth=V)},typeof ResizeObserver!="undefined"&&(_n=new ResizeObserver(()=>{zn()}),_n.observe(ce))}else ce.appendChild(de),E()&&_e&&(Le.peekBanner&&_e.appendChild(Le.peekBanner),_e.appendChild(Ne));e.appendChild(fe),_e&&e.appendChild(_e);let po=()=>{var qe,xe,It,st,Xt,dn,Pt,An,pn,Je,ct,Tn,fn,ur,mr,fr,Nr,_r,zt,gr,tr,bt,Pn,Oo,kn,Wn,Ht,Vt;if(E()){ce.style.width="100%",ce.style.maxWidth="100%";let Dt=(xe=(qe=o.launcher)==null?void 0:qe.composerBar)!=null?xe:{},qt=fe.dataset.state==="expanded",Bn=(It=Dt.expandedSize)!=null?It:"anchored";if(!(qt&&Bn!=="fullscreen")){de.style.background="",de.style.border="",de.style.borderRadius="",de.style.overflow="",de.style.boxShadow="";return}let tn=(Xt=(st=o.theme)==null?void 0:st.components)==null?void 0:Xt.panel,To=Ta(o),No=(hr,Sa)=>{var Cs;return hr==null||hr===""?Sa:(Cs=Vr(To,hr))!=null?Cs:hr},xa="1px solid var(--persona-border)",wa="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Ca="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";de.style.background="var(--persona-surface, #ffffff)",de.style.border=No(tn==null?void 0:tn.border,xa),de.style.borderRadius=No(tn==null?void 0:tn.borderRadius,Ca),de.style.boxShadow=No(tn==null?void 0:tn.shadow,wa),de.style.overflow="hidden";return}let c=un(o),f=(Pt=(dn=o.launcher)==null?void 0:dn.sidebarMode)!=null?Pt:!1,h=c||f||((pn=(An=o.launcher)==null?void 0:An.fullHeight)!=null?pn:!1),y=((Je=o.launcher)==null?void 0:Je.enabled)===!1,R=(Tn=(ct=o.theme)==null?void 0:ct.components)==null?void 0:Tn.panel,N=Ta(o),V=(Dt,qt)=>{var Bn;return Dt==null||Dt===""?qt:(Bn=Vr(N,Dt))!=null?Bn:Dt},z=(fn=e.ownerDocument.defaultView)!=null?fn:window,F=(mr=(ur=o.launcher)==null?void 0:ur.mobileFullscreen)!=null?mr:!0,Ce=(Nr=(fr=o.launcher)==null?void 0:fr.mobileBreakpoint)!=null?Nr:640,pe=z.innerWidth<=Ce,ne=F&&pe&&P,he=(zt=(_r=o.launcher)==null?void 0:_r.position)!=null?zt:"bottom-left",Te=he==="bottom-left"||he==="top-left",Be=(tr=(gr=o.launcher)==null?void 0:gr.zIndex)!=null?tr:bn,et=f||ne?"none":"1px solid var(--persona-border)",Ye=ne?"none":f?Te?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!ne&&(Ye="none",et="none");let it=f||ne?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",lt=V(R==null?void 0:R.border,et),Ie=V(R==null?void 0:R.shadow,Ye),Me=V(R==null?void 0:R.borderRadius,it),$e=Y.scrollTop;e.style.cssText="",fe.style.cssText="",ce.style.cssText="",de.style.cssText="",Y.style.cssText="",Ne.style.cssText="";let L=()=>{var qt;if($e<=0)return;((qt=Y.ownerDocument.defaultView)!=null?qt:window).requestAnimationFrame(()=>{if(Y.scrollTop===$e)return;let Bn=Y.scrollHeight-Y.clientHeight;Bn<=0||(Y.scrollTop=Math.min($e,Bn))})};if(ne){fe.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"),fe.style.cssText=`
|
|
30
|
+
`,w.addEventListener("click",()=>{p=v,W.forEach((E,S)=>{let k=S<v;E.classList.toggle("selected",k),E.setAttribute("aria-checked",S===v-1?"true":"false")})}),W.push(w),M.appendChild(w)}f.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),f.appendChild(v)}let H=document.createElement("div");H.className="persona-feedback-actions";let D=document.createElement("button");D.type="button",D.className="persona-feedback-btn persona-feedback-btn-skip",D.textContent=i,D.addEventListener("click",()=>{n==null||n(),u.remove()});let B=document.createElement("button");return B.type="button",B.className="persona-feedback-btn persona-feedback-btn-submit",B.textContent=a,B.addEventListener("click",async()=>{if(p===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}B.disabled=!0,B.textContent="Submitting...";try{let v=(L==null?void 0:L.value.trim())||void 0;await t(p,v),u.remove()}catch(v){B.disabled=!1,B.textContent=a,console.error("[CSAT Feedback] Failed to submit:",v)}}),H.appendChild(D),H.appendChild(B),f.appendChild(H),u.appendChild(f),u}function Bm(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:u="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let f=null,g=document.createElement("div");g.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,x.appendChild(C);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=r,x.appendChild(M),g.appendChild(x);let W=document.createElement("div");W.className="persona-feedback-rating persona-feedback-rating-nps",W.setAttribute("role","radiogroup"),W.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=u,L.appendChild(H),L.appendChild(D);let B=document.createElement("div");B.className="persona-feedback-numbers";let v=[];for(let F=0;F<=10;F++){let $=document.createElement("button");$.type="button",$.className="persona-feedback-rating-btn persona-feedback-number-btn",$.setAttribute("role","radio"),$.setAttribute("aria-checked","false"),$.setAttribute("aria-label",`Rating ${F} out of 10`),$.textContent=String(F),$.dataset.rating=String(F),F<=6?$.classList.add("persona-feedback-detractor"):F<=8?$.classList.add("persona-feedback-passive"):$.classList.add("persona-feedback-promoter"),$.addEventListener("click",()=>{f=F,v.forEach((q,me)=>{q.classList.toggle("selected",me===F),q.setAttribute("aria-checked",me===F?"true":"false")})}),v.push($),B.appendChild($)}W.appendChild(L),W.appendChild(B),g.appendChild(W);let w=null;if(d){let F=document.createElement("div");F.className="persona-feedback-comment-container",w=document.createElement("textarea"),w.className="persona-feedback-comment",w.placeholder=s,w.rows=3,w.setAttribute("aria-label","Additional comments"),F.appendChild(w),g.appendChild(F)}let E=document.createElement("div");E.className="persona-feedback-actions";let S=document.createElement("button");S.type="button",S.className="persona-feedback-btn persona-feedback-btn-skip",S.textContent=i,S.addEventListener("click",()=>{n==null||n(),p.remove()});let k=document.createElement("button");return k.type="button",k.className="persona-feedback-btn persona-feedback-btn-submit",k.textContent=a,k.addEventListener("click",async()=>{if(f===null){B.classList.add("persona-feedback-shake"),setTimeout(()=>B.classList.remove("persona-feedback-shake"),500);return}k.disabled=!0,k.textContent="Submitting...";try{let F=(w==null?void 0:w.value.trim())||void 0;await t(f,F),p.remove()}catch(F){k.disabled=!1,k.textContent=a,console.error("[NPS Feedback] Failed to submit:",F)}}),E.appendChild(S),E.appendChild(k),g.appendChild(E),p.appendChild(g),p}var es="persona-chat-history",ex=30*1e3,tx={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function nx(e){var o,r,s;if(!e)return[];let t=[],n=Array.from((o=e.items)!=null?o:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(r=tx[i.type])!=null?r:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((s=e.files)!=null?s:[]))a.type.startsWith("image/")&&t.push(a);return t}function ki(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function ox(e){var t,n,o,r,s,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(r=(o=e.persist)==null?void 0:o.openState)!=null?r:!0,voiceState:(a=(s=e.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function rx(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Fl=e=>!e||typeof e!="object"?{}:{...e},Hm=e=>e.map(t=>({...t,streaming:!1})),Dm=(e,t,n)=>{let o=e!=null&&e.markdown?Na(e.markdown):null,r=_a(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&r&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var l,u,p;let a=(l=s.text)!=null?l:"",i=(u=s.message.rawContent)!=null?u:null;if(t){let f=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});f!==null&&(a=f.text,f.persist||(s.message.__skipPersist=!0),f.resubmit&&!s.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...s,text:a,raw:(p=i!=null?i:s.text)!=null?p:""}):o?d=o(a):d=Ls(a),r?r(d):d}};function Fm(e){var i,d,l,u;let t=b("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",o=(d=e==null?void 0:e.iconSize)!=null?d:"48px",r=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(u=e==null?void 0:e.iconStrokeWidth)!=null?u:.5,a=Se(n,o,r,s);if(a&&t.appendChild(a),e!=null&&e.label){let p=b("span","persona-drop-overlay-label");p.textContent=e.label,t.appendChild(p)}return t}var Om=(e,t,n)=>{var sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,bc,yc,vc,xc,wc,Cc,Sc,Ac,Tc,kc,Ec,Mc,Lc,Ic,Rc,Pc,Wc,Bc,Hc,Dc,Fc,Oc,Nc,_c,Vc,$c,Uc,zc,qc,jc,Kc,Gc,Yc,Xc,Qc,Jc;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=Qp(t),r=Wl.getForInstance(o.plugins);o.components&&Er.registerAll(o.components);let s=km(),i=o.persistState===!1?null:(sc=o.storageAdapter)!=null?sc:Mm(),d={},l=null,u=!1,p=c=>{if(o.onStateLoaded)try{let m=o.onStateLoaded(c);if(m&&typeof m=="object"&&"state"in m){let{state:h,open:y}=m;return y&&(u=!0),h}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(m=>{let h=m!=null?m:{messages:[],metadata:{}};return p(h)});else{let m=c!=null?c:{messages:[],metadata:{}},h=p(m);h.metadata&&(d=Fl(h.metadata)),(ac=h.messages)!=null&&ac.length&&(o={...o,initialMessages:h.messages}),(ic=h.artifacts)!=null&&ic.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(lc=h.selectedArtifactId)!=null?lc:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(o.onStateLoaded)try{let c=p({messages:[],metadata:{}});(cc=c.messages)!=null&&cc.length&&(o={...o,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let f=()=>d,g=c=>{var h;d=(h=c({...d}))!=null?h:{},Pr()},x=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Hl],C=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Js.message,Js.messageAndClick],M=Dl({parsers:x,handlers:C,getSessionMetadata:f,updateSessionMetadata:g,emit:s.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let W=(pc=(dc=o.launcher)==null?void 0:dc.enabled)!=null?pc:!0,L=(mc=(uc=o.launcher)==null?void 0:uc.autoExpand)!=null?mc:!1,H=(gc=o.autoFocusInput)!=null?gc:!1,D=L,B=W,v=(hc=(fc=o.layout)==null?void 0:fc.header)==null?void 0:hc.layout,w=!1,E=()=>zs(o),S=()=>W||E(),k=E()?!1:W?L:!0,F=!1,$=null,q=()=>{F=!0,$&&clearTimeout($),$=setTimeout(()=>{F&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),F=!1)},1e4)},me=Dm(o,M,q),re=(yc=(bc=o.features)==null?void 0:bc.showReasoning)!=null?yc:!0,be=(xc=(vc=o.features)==null?void 0:vc.showToolCalls)!=null?xc:!0,ie=(Cc=(wc=o.features)==null?void 0:wc.showEventStreamToggle)!=null?Cc:!1,we=(Ac=(Sc=o.features)==null?void 0:Sc.scrollToBottom)!=null?Ac:{},ye=`${(kc=typeof o.persistState=="object"?(Tc=o.persistState)==null?void 0:Tc.keyPrefix:void 0)!=null?kc:"persona-"}event-stream`,Z=ie?new Xs(ye):null,Ee=(Lc=(Mc=(Ec=o.features)==null?void 0:Ec.eventStream)==null?void 0:Mc.maxEvents)!=null?Lc:2e3,X=ie?new Ys(Ee,Z):null,Ae=ie?new Qs:null,fe=null,le=!1,ue=null,je=0;Z==null||Z.open().then(()=>X==null?void 0:X.restore()).catch(c=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let j={onCopy:c=>{var m,h;s.emit("message:copy",c),T!=null&&T.isClientTokenMode()&&T.submitMessageFeedback(c.id,"copy").catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",y)}),(h=(m=o.messageActions)==null?void 0:m.onCopy)==null||h.call(m,c)},onFeedback:c=>{var m,h;s.emit("message:feedback",c),T!=null&&T.isClientTokenMode()&&T.submitMessageFeedback(c.messageId,c.type).catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",y)}),(h=(m=o.messageActions)==null?void 0:m.onFeedback)==null||h.call(m,c)}},oe=(Ic=o.statusIndicator)!=null?Ic:{},Re=c=>{var m,h,y,P;return c==="idle"?(m=oe.idleText)!=null?m:hn.idle:c==="connecting"?(h=oe.connectingText)!=null?h:hn.connecting:c==="connected"?(y=oe.connectedText)!=null?y:hn.connected:c==="error"?(P=oe.errorText)!=null?P:hn.error:hn[c]};function tt(c,m,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=m,P.style.color="inherit",P.style.textDecoration="none",c.appendChild(P)}else c.textContent=m}let{wrapper:ge,panel:ce,pillRoot:_e}=Yu(o),Le=Xu(o,S()),{container:de,body:Y,messagesWrapper:Ve,suggestions:Ct,textarea:Q,sendButton:Fe,sendButtonWrapper:Ln,composerForm:Ft,statusText:ln,introTitle:Dn,introSubtitle:Jn,closeButton:N,iconHolder:se,headerTitle:He,headerSubtitle:Xe,header:Oe,footer:Ne,actionsRow:ot,leftActions:St,rightActions:Nt}=Le,jt=Le.setSendButtonMode,K=Le.micButton,gt=Le.micButtonWrapper,nt=Le.attachmentButton,$t=Le.attachmentButtonWrapper,ae=Le.attachmentInput,ve=Le.attachmentPreviewsContainer;de.classList.add("persona-relative"),Y.classList.add("persona-relative");let wt=12,_t=()=>{var c;return(c=we.label)!=null?c:""},Jt=()=>{var c;return(c=we.iconName)!=null?c:"arrow-down"},vn=()=>we.enabled!==!1,Et=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");Et.type="button",Et.style.display="none",Et.setAttribute("data-persona-scroll-to-bottom","true");let At=b("span","persona-flex persona-items-center"),ht=b("span","");Et.append(At,ht),de.appendChild(Et);let yt=()=>{let m=Ne.style.display==="none"?0:Ne.offsetHeight;Et.style.bottom=`${m+wt}px`};yt();let Ut=()=>{let c=!!_t();Et.setAttribute("aria-label",_t()||"Jump to latest"),Et.title=_t(),Et.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),At.innerHTML="";let m=Se(Jt(),"14px","currentColor",2);m?(At.appendChild(m),At.style.display=""):At.style.display="none",ht.textContent=_t(),ht.style.display=c?"":"none"};Ut();let Ze=null,Fn=null,Zn=r.find(c=>c.renderHeader);if(Zn!=null&&Zn.renderHeader){let c=Zn.renderHeader({config:o,defaultRenderer:()=>{let m=Sr({config:o,showClose:S()});return js(de,m,o),m.header},onClose:()=>Bt(!1,"user")});if(c){let m=de.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(c),Oe=c)}}let xn=()=>{var m,h,y,P;if(!X)return;if(le=!0,!fe&&X&&(fe=hm({buffer:X,getFullHistory:()=>X.getAllFromStore(),onClose:()=>On(),config:o,plugins:r,getThroughput:()=>{var _;return(_=Ae==null?void 0:Ae.getMetric())!=null?_:{status:"idle"}}})),fe&&(Y.style.display="none",(m=Ne.parentNode)==null||m.insertBefore(fe.element,Ne),fe.update()),ut){ut.style.boxShadow=`inset 0 0 0 1.5px ${Mn.actionIconColor}`;let _=(P=(y=(h=o.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:P.toggleButtonActive;_&&_.split(/\s+/).forEach(V=>V&&ut.classList.add(V))}let c=()=>{if(!le)return;let _=Date.now();_-je>=200&&(fe==null||fe.update(),je=_),ue=requestAnimationFrame(c)};je=0,ue=requestAnimationFrame(c),Ho(),s.emit("eventStream:opened",{timestamp:Date.now()})},On=()=>{var c,m,h;if(le){if(le=!1,fe&&fe.element.remove(),Y.style.display="",ut){ut.style.boxShadow="";let y=(h=(m=(c=o.features)==null?void 0:c.eventStream)==null?void 0:m.classNames)==null?void 0:h.toggleButtonActive;y&&y.split(/\s+/).forEach(P=>P&&ut.classList.remove(P))}ue!==null&&(cancelAnimationFrame(ue),ue=null),Ho(),s.emit("eventStream:closed",{timestamp:Date.now()})}},ut=null;if(ie){let c=(Pc=(Rc=o.features)==null?void 0:Rc.eventStream)==null?void 0:Pc.classNames,m="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",m),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=Se("activity","18px","currentColor",1.5);h&&ut.appendChild(h);let y=Le.clearChatButtonWrapper,P=Le.closeButtonWrapper,_=y||P;_&&_.parentNode===Oe?Oe.insertBefore(ut,_):Oe.appendChild(ut),ut.addEventListener("click",()=>{le?On():xn()})}let wo=c=>{var y,P,_;let m=o.attachments;if(!(m!=null&&m.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=m.allowedTypes)!=null?y:_o).join(","),V.multiple=((P=m.maxFiles)!=null?P:4)>1,V.style.display="none",V.setAttribute("aria-label",(_=m.buttonTooltipText)!=null?_:"Attach files"),c.appendChild(V)}},Nn=r.find(c=>c.renderComposer);if(Nn!=null&&Nn.renderComposer){let c=o.composer,m=Nn.renderComposer({config:o,defaultRenderer:()=>vi({config:o}).footer,onSubmit:h=>{var V;if(!T||T.isStreaming())return;let y=h.trim(),P=(V=Ze==null?void 0:Ze.hasAttachments())!=null?V:!1;if(!y&&!P)return;gs();let _;P&&(_=[],_.push(...Ze.getContentParts()),y&&_.push(il(y))),T.sendMessage(y,{contentParts:_}),P&&Ze.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{ae==null||ae.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:((Wc=o.voiceRecognition)==null?void 0:Wc.enabled)===!0?()=>{Fn==null||Fn()}:void 0});m&&(Ne.replaceWith(m),Ne=m)}let ar=c=>{let m=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]"),_=c.querySelector("[data-persona-composer-status]");m&&(Ft=m),h&&(Q=h),y&&(Fe=y),P&&(K=P,gt=P.parentElement),_&&(ln=_);let V=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");V&&(Ct=V);let z=c.querySelector(".persona-attachment-button");z&&(nt=z,$t=z.parentElement),ae=c.querySelector('input[type="file"]'),ve=c.querySelector(".persona-attachment-previews");let O=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");O&&(ot=O)};wo(Ne),ar(Ne);let In=(Oc=(Bc=o.layout)==null?void 0:Bc.contentMaxWidth)!=null?Oc:E()?(Fc=(Dc=(Hc=o.launcher)==null?void 0:Hc.composerBar)==null?void 0:Dc.contentMaxWidth)!=null?Fc:"720px":void 0;if(In&&(Ve.style.maxWidth=In,Ve.style.marginLeft="auto",Ve.style.marginRight="auto",Ve.style.width="100%"),In&&Ft&&!E()&&(Ft.style.maxWidth=In,Ft.style.marginLeft="auto",Ft.style.marginRight="auto"),In&&Ct&&!E()&&(Ct.style.maxWidth=In,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),In&&ve&&!E()&&(ve.style.maxWidth=In,ve.style.marginLeft="auto",ve.style.marginRight="auto"),(Nc=o.attachments)!=null&&Nc.enabled&&ae&&ve){Ze=Ds.fromConfig(o.attachments),Ze.setPreviewsContainer(ve),ae.addEventListener("change",h=>{let y=h.target;Ze==null||Ze.handleFileSelect(y.files),y.value=""});let c=o.attachments.dropOverlay,m=Fm(c);de.appendChild(m)}(()=>{var y,P;let c=(P=(y=o.layout)==null?void 0:y.slots)!=null?P:{},m=_=>{switch(_){case"body-top":return de.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ve;case"footer-top":return Ct;case"composer":return Ft;case"footer-bottom":return ln;default:return null}},h=(_,V)=>{var z;switch(_){case"header-left":case"header-center":case"header-right":if(_==="header-left")Oe.insertBefore(V,Oe.firstChild);else if(_==="header-right")Oe.appendChild(V);else{let O=Oe.querySelector(".persona-flex-col");O?(z=O.parentNode)==null||z.insertBefore(V,O.nextSibling):Oe.appendChild(V)}break;case"body-top":{let O=Y.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");O?O.replaceWith(V):Y.insertBefore(V,Y.firstChild);break}case"body-bottom":Y.appendChild(V);break;case"footer-top":Ct.replaceWith(V);break;case"footer-bottom":ln.replaceWith(V);break;default:break}};for(let[_,V]of Object.entries(c))if(V)try{let z=V({config:o,defaultContent:()=>m(_)});z&&h(_,z)}catch(z){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${_}":`,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 _=h.getAttribute("data-bubble-type");_==="reasoning"?(Kr.has(P)?Kr.delete(P):Kr.add(P),Zu(P,y)):_==="tool"&&(Gr.has(P)?Gr.delete(P):Gr.add(P),em(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 m=c.target;(c.key==="Enter"||c.key===" ")&&m.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 _=h.getAttribute("data-action");if(_==="copy"){let O=T.getMessages().find(Ce=>Ce.id===P);if(O&&j.onCopy){let Ce=O.content||"";navigator.clipboard.writeText(Ce).then(()=>{h.classList.add("persona-message-action-success");let pe=Se("check",14,"currentColor",2);pe&&(h.innerHTML="",h.appendChild(pe)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let ne=Se("copy",14,"currentColor",2);ne&&(h.innerHTML="",h.appendChild(ne))},2e3)}).catch(pe=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",pe)}),j.onCopy(O)}}else if(_==="upvote"||_==="downvote"){let O=((V=Lo.get(P))!=null?V:null)===_,Ce=_==="upvote"?"thumbs-up":"thumbs-down";if(O){Lo.delete(P),h.classList.remove("persona-message-action-active");let pe=Se(Ce,14,"currentColor",2);pe&&(h.innerHTML="",h.appendChild(pe))}else{let pe=_==="upvote"?"downvote":"upvote",ne=y.querySelector(`[data-action="${pe}"]`);if(ne){ne.classList.remove("persona-message-action-active");let Ye=Se(pe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ye&&(ne.innerHTML="",ne.appendChild(Ye))}Lo.set(P,_),h.classList.add("persona-message-action-active");let he=Se(Ce,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 Be=T.getMessages().find(et=>et.id===P);Be&&j.onFeedback&&j.onFeedback({type:_,messageId:Be.id,message:Be})}}}),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 _=h.getAttribute("data-approval-action");if(!_)return;let V=_==="approve"?"approved":"denied",O=T.getMessages().find(pe=>pe.id===P);if(!(O!=null&&O.approval))return;let Ce=y.querySelector("[data-approval-buttons]");Ce&&Ce.querySelectorAll("button").forEach(ne=>{ne.disabled=!0,ne.style.opacity="0.5",ne.style.cursor="not-allowed"}),O.approval.toolType==="webmcp"?T.resolveWebMcpApproval(P,V):T.resolveApproval(O.approval,V)});let vt=null,_n=null,Vn={artifacts:[],selectedId:null},wn=!1,Rt={current:null};Ve.addEventListener("click",c=>{var ne,he,Te,Be,et;let h=c.target.closest("[data-download-artifact]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||((Te=(he=(ne=o.features)==null?void 0:ne.artifacts)==null?void 0:he.onArtifactAction)==null?void 0:Te.call(he,{type:"download",artifactId:y}))===!0)return;let _=T.getArtifactById(y),V=_==null?void 0:_.markdown,z=(_==null?void 0:_.title)||"artifact";if(!V){let Ye=h.closest("[data-open-artifact]"),it=Ye==null?void 0:Ye.closest("[data-message-id]"),lt=it==null?void 0:it.getAttribute("data-message-id");if(lt){let Me=T.getMessages().find($e=>$e.id===lt);if(Me!=null&&Me.rawContent)try{let $e=JSON.parse(Me.rawContent);V=(Be=$e==null?void 0:$e.props)==null?void 0:Be.markdown,z=((et=$e==null?void 0:$e.props)==null?void 0:et.title)||z}catch{}}}if(!V)return;let O=new Blob([V],{type:"text/markdown"}),Ce=URL.createObjectURL(O),pe=document.createElement("a");pe.href=Ce,pe.download=`${z}.md`,pe.click(),URL.revokeObjectURL(Ce)}),Ve.addEventListener("click",c=>{var _,V,z;let h=c.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||((z=(V=(_=o.features)==null?void 0:_.artifacts)==null?void 0:V.onArtifactAction)==null?void 0:z.call(V,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),wn=!1,T.selectArtifact(y),zn())}),Ve.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let m=c.target;m.hasAttribute("data-open-artifact")&&(c.preventDefault(),m.click())});let eo=Le.composerOverlay,to=(c,m,h)=>{var z,O,Ce,pe;let y=m.trim();if(!y||!Rt.current)return;let P=(z=c.getAttribute("data-tool-call-id"))!=null?z:"",_=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:_,source:h.source},bubbles:!0,composed:!0})),Jr(eo,P);let V=Rt.current.getMessages().find(ne=>{var he;return((he=ne.toolCall)==null?void 0:he.id)===P});(Ce=V==null?void 0:V.agentMetadata)!=null&&Ce.awaitingLocalTool?Rt.current.resolveAskUserQuestion(V,(pe=h.structured)!=null?pe:y):Rt.current.sendMessage(y)},$n=c=>{var P;let m=Rt.current;if(!m)return;let h=(P=c.getAttribute("data-tool-call-id"))!=null?P:"",y=m.getMessages().find(_=>{var V;return((V=_.toolCall)==null?void 0:V.id)===h});y&&m.persistAskUserQuestionProgress(y,{answers:xi(c,y),currentIndex:lo(c)})},Uo=c=>Object.entries(c).map(([m,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Io=c=>{var P,_,V;if(((_=(P=o.features)==null?void 0:P.askUserQuestion)==null?void 0:_.groupedAutoAdvance)===!1)return;let m=lo(c),h=Qr(c);if(m>=h-1)return;let y=(V=Rt.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&&(Ci(c,y,o,m+1),$n(c))};eo.addEventListener("click",c=>{var _,V,z,O,Ce,pe,ne,he,Te,Be,et,Ye,it,lt;let h=c.target.closest("[data-ask-user-action]");if(!h)return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;let P=h.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),P==="dismiss"){let Ie=(_=y.getAttribute("data-tool-call-id"))!=null?_:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),Jr(eo,Ie);let Me=(V=Rt.current)==null?void 0:V.getMessages().find($e=>{var I;return((I=$e.toolCall)==null?void 0:I.id)===Ie});(z=Me==null?void 0:Me.agentMetadata)!=null&&z.awaitingLocalTool&&((O=Rt.current)==null||O.markAskUserQuestionResolved(Me),(Ce=Rt.current)==null||Ce.resolveAskUserQuestion(Me,"(dismissed)"));return}if(P==="pick"){let Ie=h.getAttribute("data-option-label");if(!Ie)return;let Me=y.getAttribute("data-multi-select")==="true",$e=rr(y);if($e&&Me){let I=Tr(y)[lo(y)],ke=new Set(Array.isArray(I)?I:[]);ke.has(Ie)?ke.delete(Ie):ke.add(Ie),sr(y,Array.from(ke)),$n(y);return}if($e){sr(y,Ie),$n(y),Io(y);return}if(Me){let I=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",I?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!I);let ke=y.querySelector('[data-ask-user-action="submit-multi"]');ke&&(ke.disabled=kl(y).length===0);return}to(y,Ie,{source:"pick",values:[Ie]});return}if(P==="submit-multi"){let Ie=kl(y);if(Ie.length===0)return;to(y,Ie.join(", "),{source:"multi",values:Ie});return}if(P==="open-free-text"){let Ie=y.querySelector('[data-ask-free-text-row="true"]');if(Ie){Ie.classList.remove("persona-hidden");let Me=Ie.querySelector('[data-ask-free-text-input="true"]');Me==null||Me.focus()}return}if(P==="focus-free-text"){let Ie=y.querySelector('[data-ask-free-text-input="true"]');Ie==null||Ie.focus();return}if(P==="submit-free-text"){let Ie=y.querySelector('[data-ask-free-text-input="true"]'),Me=(pe=Ie==null?void 0:Ie.value)!=null?pe:"";if(!Me.trim())return;if(rr(y)){sr(y,Me.trim()),$n(y),Io(y);return}to(y,Me,{source:"free-text"});return}if(P==="next"||P==="back"){if(!Rt.current)return;let Ie=(ne=y.getAttribute("data-tool-call-id"))!=null?ne:"",Me=Rt.current.getMessages().find(qe=>{var xe;return((xe=qe.toolCall)==null?void 0:xe.id)===Ie});if(!Me)return;let $e=y.querySelector('[data-ask-free-text-input="true"]'),I=(Te=(he=$e==null?void 0:$e.value)==null?void 0:he.trim())!=null?Te:"";if(I){let qe=Tr(y)[lo(y)];(typeof qe!="string"||qe!==I)&&sr(y,I)}let ke=P==="next"?1:-1,Pe=lo(y)+ke;Ci(y,Me,o,Pe),$n(y);return}if(P==="submit-all"){if(!Rt.current)return;let Ie=(Be=y.getAttribute("data-tool-call-id"))!=null?Be:"",Me=Rt.current.getMessages().find(qe=>{var xe;return((xe=qe.toolCall)==null?void 0:xe.id)===Ie});if(!Me)return;let $e=y.querySelector('[data-ask-free-text-input="true"]'),I=(Ye=(et=$e==null?void 0:$e.value)==null?void 0:et.trim())!=null?Ye:"";I&&sr(y,I);let ke=xi(y,Me);Rt.current.persistAskUserQuestionProgress(Me,{answers:ke,currentIndex:lo(y)});let Pe=Uo(ke);to(y,Pe||"(submitted)",{source:"submit-all",structured:ke});return}if(P==="skip"){if(!Rt.current)return;let Ie=(it=y.getAttribute("data-tool-call-id"))!=null?it:"",Me=Rt.current.getMessages().find(xe=>{var It;return((It=xe.toolCall)==null?void 0:It.id)===Ie});if(!Me)return;let $e=rr(y),I=lo(y),ke=Qr(y),Pe=I>=ke-1;if(!$e){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),Jr(eo,Ie),(lt=Me.agentMetadata)!=null&<.awaitingLocalTool&&(Rt.current.markAskUserQuestionResolved(Me),Rt.current.resolveAskUserQuestion(Me,"(dismissed)"));return}sr(y,"");let qe=y.querySelector('[data-ask-free-text-input="true"]');if(qe&&(qe.value=""),Pe){let xe=xi(y,Me),It=Uo(xe);to(y,It||"(skipped)",{source:"submit-all",structured:xe});return}Ci(y,Me,o,I+1),$n(y);return}}),eo.addEventListener("keydown",c=>{var _;if(c.key!=="Enter")return;let h=c.target;if(!((_=h.matches)!=null&&_.call(h,'[data-ask-free-text-input="true"]')))return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;c.preventDefault();let P=h.value;if(P.trim()){if(rr(y)){sr(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 m=c.target;if((m==null?void 0:m.tagName)==="INPUT"||(m==null?void 0:m.tagName)==="TEXTAREA"||m!=null&&m.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),_=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];_&&(c.preventDefault(),_.click())};document.addEventListener("keydown",zo);let Un=null,Wt=null,Cn=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 _=y.offsetWidth-P/2;Wt.style.left=`${Math.max(0,_)}px`},Co=()=>{},zn=()=>{var h,y,P,_,V;if(!vt||!co(o))return;Ai(e,o),Ti(e,o),Co();let c=(_=(P=(y=(h=o.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:P.narrowHostMaxWidth)!=null?_:520,m=ce.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=c),vt.update(Vn),wn?(vt.setMobileOpen(!1),vt.element.classList.add("persona-hidden"),(V=vt.backdrop)==null||V.classList.add("persona-hidden")):Vn.artifacts.length>0&&(vt.element.classList.remove("persona-hidden"),vt.setMobileOpen(!0)),qo()};if(co(o)){ce.style.position="relative";let c=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(de),vt=vm(o,{onSelect:h=>{var y;return(y=Rt.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{wn=!0,zn()}}),vt.element.classList.add("persona-hidden"),Un=m,m.appendChild(c),m.appendChild(vt.element),vt.backdrop&&ce.appendChild(vt.backdrop),ce.appendChild(m),qo=()=>{var y,P,_,V;if(!Un||!vt)return;if(!(((_=(P=(y=o.features)==null?void 0:y.artifacts)==null?void 0:P.layout)==null?void 0:_.resizable)===!0)){Cn==null||Cn(),Cn=null,Ro(),Wt&&(Wt.remove(),Wt=null),vt.element.style.removeProperty("width"),vt.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,Ce=(V=O.defaultView)!=null?V:window,pe=ne=>{var it,lt;if(!vt||ne.button!==0||e.classList.contains("persona-artifact-narrow-host")||Ce.innerWidth<=640)return;ne.preventDefault(),Ro();let he=ne.clientX,Te=vt.element.getBoundingClientRect().width,Be=(lt=(it=o.features)==null?void 0:it.artifacts)==null?void 0:lt.layout,et=Ie=>{let Me=Un.getBoundingClientRect().width,$e=e.classList.contains("persona-artifact-appearance-seamless"),I=$e?0:Sm(Un,Ce),ke=$e?0:z.getBoundingClientRect().width||6,Pe=Te-(Ie.clientX-he),qe=Am(Pe,Me,I,ke,Be==null?void 0:Be.resizableMinWidth,Be==null?void 0:Be.resizableMaxWidth);vt.element.style.width=`${qe}px`,vt.element.style.maxWidth="none",jo()},Ye=()=>{O.removeEventListener("pointermove",et),O.removeEventListener("pointerup",Ye),O.removeEventListener("pointercancel",Ye),no=null;try{z.releasePointerCapture(ne.pointerId)}catch{}};no=Ye,O.addEventListener("pointermove",et),O.addEventListener("pointerup",Ye),O.addEventListener("pointercancel",Ye);try{z.setPointerCapture(ne.pointerId)}catch{}};z.addEventListener("pointerdown",pe),Wt=z,Un.insertBefore(z,vt.element),Cn=()=>{z.removeEventListener("pointerdown",pe)}}if(Wt){let z=Vn.artifacts.length>0&&!wn;Wt.classList.toggle("persona-hidden",!z),jo()}},Co=()=>{var Ce,pe,ne,he,Te,Be,et,Ye,it,lt,Ie,Me,$e,I;if(!W||!vt||((pe=(Ce=o.launcher)==null?void 0:Ce.sidebarMode)!=null?pe:!1)||un(o)&&Mo(o).reveal==="emerge")return;let y=(ne=e.ownerDocument.defaultView)!=null?ne:window,P=(Te=(he=o.launcher)==null?void 0:he.mobileFullscreen)!=null?Te:!0,_=(et=(Be=o.launcher)==null?void 0:Be.mobileBreakpoint)!=null?et:640;if(P&&y.innerWidth<=_||!Cm(o,W))return;let V=(lt=(it=(Ye=o.launcher)==null?void 0:Ye.width)!=null?it:o.launcherWidth)!=null?lt:io,z=(I=($e=(Me=(Ie=o.features)==null?void 0:Ie.artifacts)==null?void 0:Me.layout)==null?void 0:$e.expandedPanelWidth)!=null?I:"min(720px, calc(100vw - 24px))";Vn.artifacts.length>0&&!wn?(ce.style.width=z,ce.style.maxWidth=z):(ce.style.width=V,ce.style.maxWidth=V)},typeof ResizeObserver!="undefined"&&(_n=new ResizeObserver(()=>{zn()}),_n.observe(ce))}else ce.appendChild(de),E()&&_e&&(Le.peekBanner&&_e.appendChild(Le.peekBanner),_e.appendChild(Ne));e.appendChild(ge),_e&&e.appendChild(_e);let po=()=>{var qe,xe,It,st,Xt,dn,Pt,An,pn,Je,ct,Tn,gn,ur,mr,gr,Nr,_r,zt,fr,tr,bt,Pn,Oo,kn,Wn,Ht,Vt;if(E()){ce.style.width="100%",ce.style.maxWidth="100%";let Dt=(xe=(qe=o.launcher)==null?void 0:qe.composerBar)!=null?xe:{},qt=ge.dataset.state==="expanded",Bn=(It=Dt.expandedSize)!=null?It:"anchored";if(!(qt&&Bn!=="fullscreen")){de.style.background="",de.style.border="",de.style.borderRadius="",de.style.overflow="",de.style.boxShadow="";return}let tn=(Xt=(st=o.theme)==null?void 0:st.components)==null?void 0:Xt.panel,To=Ta(o),No=(hr,Sa)=>{var Cs;return hr==null||hr===""?Sa:(Cs=Vr(To,hr))!=null?Cs:hr},xa="1px solid var(--persona-border)",wa="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Ca="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";de.style.background="var(--persona-surface, #ffffff)",de.style.border=No(tn==null?void 0:tn.border,xa),de.style.borderRadius=No(tn==null?void 0:tn.borderRadius,Ca),de.style.boxShadow=No(tn==null?void 0:tn.shadow,wa),de.style.overflow="hidden";return}let c=un(o),m=(Pt=(dn=o.launcher)==null?void 0:dn.sidebarMode)!=null?Pt:!1,h=c||m||((pn=(An=o.launcher)==null?void 0:An.fullHeight)!=null?pn:!1),y=((Je=o.launcher)==null?void 0:Je.enabled)===!1,P=(Tn=(ct=o.theme)==null?void 0:ct.components)==null?void 0:Tn.panel,_=Ta(o),V=(Dt,qt)=>{var Bn;return Dt==null||Dt===""?qt:(Bn=Vr(_,Dt))!=null?Bn:Dt},z=(gn=e.ownerDocument.defaultView)!=null?gn:window,O=(mr=(ur=o.launcher)==null?void 0:ur.mobileFullscreen)!=null?mr:!0,Ce=(Nr=(gr=o.launcher)==null?void 0:gr.mobileBreakpoint)!=null?Nr:640,pe=z.innerWidth<=Ce,ne=O&&pe&&W,he=(zt=(_r=o.launcher)==null?void 0:_r.position)!=null?zt:"bottom-left",Te=he==="bottom-left"||he==="top-left",Be=(tr=(fr=o.launcher)==null?void 0:fr.zIndex)!=null?tr:bn,et=m||ne?"none":"1px solid var(--persona-border)",Ye=ne?"none":m?Te?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!ne&&(Ye="none",et="none");let it=m||ne?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",lt=V(P==null?void 0:P.border,et),Ie=V(P==null?void 0:P.shadow,Ye),Me=V(P==null?void 0:P.borderRadius,it),$e=Y.scrollTop;e.style.cssText="",ge.style.cssText="",ce.style.cssText="",de.style.cssText="",Y.style.cssText="",Ne.style.cssText="";let I=()=>{var qt;if($e<=0)return;((qt=Y.ownerDocument.defaultView)!=null?qt:window).requestAnimationFrame(()=>{if(Y.scrollTop===$e)return;let Bn=Y.scrollHeight-Y.clientHeight;Bn<=0||(Y.scrollTop=Math.min($e,Bn))})};if(ne){ge.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"),ge.style.cssText=`
|
|
31
31
|
position: fixed !important;
|
|
32
32
|
inset: 0 !important;
|
|
33
33
|
width: 100% !important;
|
|
@@ -63,7 +63,7 @@ _Details: ${n.message}_`:o}var Za=class e{constructor(t={},n){this.config=t;this
|
|
|
63
63
|
overflow: hidden !important;
|
|
64
64
|
border-radius: 0 !important;
|
|
65
65
|
border: none !important;
|
|
66
|
-
`,Y.style.flex="1 1 0%",Y.style.minHeight="0",Y.style.overflowY="auto",Ne.style.flexShrink="0",
|
|
66
|
+
`,Y.style.flex="1 1 0%",Y.style.minHeight="0",Y.style.overflowY="auto",Ne.style.flexShrink="0",w=!0,I();return}let ke=(Pn=(bt=o==null?void 0:o.launcher)==null?void 0:bt.width)!=null?Pn:o==null?void 0:o.launcherWidth,Pe=ke!=null?ke:io;if(!m&&!c)y&&h?(ce.style.width="100%",ce.style.maxWidth="100%"):(ce.style.width=Pe,ce.style.maxWidth=Pe);else if(c)if(Mo(o).reveal==="emerge"){let qt=Mo(o).width;ce.style.width=qt,ce.style.maxWidth=qt}else ce.style.width="100%",ce.style.maxWidth="100%";if(Co(),ce.style.boxShadow=Ie,ce.style.borderRadius=Me,de.style.border=lt,de.style.borderRadius=Me,c&&!ne&&(P==null?void 0:P.border)===void 0&&(de.style.border="none",Mo(o).side==="right"?de.style.borderLeft="1px solid var(--persona-border)":de.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",y&&(e.style.width="100%"),ge.style.display="flex",ge.style.flexDirection="column",ge.style.flex="1 1 0%",ge.style.minHeight="0",ge.style.maxHeight="100%",ge.style.height="100%",y&&(ge.style.overflow="hidden"),ce.style.display="flex",ce.style.flexDirection="column",ce.style.flex="1 1 0%",ce.style.minHeight="0",ce.style.maxHeight="100%",ce.style.height="100%",ce.style.overflow="hidden",de.style.display="flex",de.style.flexDirection="column",de.style.flex="1 1 0%",de.style.minHeight="0",de.style.maxHeight="100%",de.style.overflow="hidden",Y.style.flex="1 1 0%",Y.style.minHeight="0",Y.style.overflowY="auto",Ne.style.flexShrink="0"),ge.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"),!m&&!y&&!c&&((Oo=xo[he])!=null?Oo:xo["bottom-right"]).split(" ").forEach(qt=>ge.classList.add(qt)),m){let Dt=(Wn=(kn=o.launcher)==null?void 0:kn.sidebarWidth)!=null?Wn:"420px";ge.style.cssText=`
|
|
67
67
|
position: fixed !important;
|
|
68
68
|
top: 0 !important;
|
|
69
69
|
bottom: 0 !important;
|
|
@@ -104,7 +104,7 @@ _Details: ${n.message}_`:o}var Za=class e{constructor(t={},n){this.config=t;this
|
|
|
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;",qt=f?"":"padding-top: 1.25em !important;",Bn=f?"":`z-index: ${(Vt=(Ht=o.launcher)==null?void 0:Ht.zIndex)!=null?Vt:bn} !important;`;fe.style.cssText+=Dt+qt+Bn}L()};po(),$r(e,o),Ai(e,o),Ti(e,o);let gt=[];gt.push(()=>{document.removeEventListener("keydown",zo)});let Kt=null,Gt=null;gt.push(()=>{Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null}),_n&>.push(()=>{_n==null||_n.disconnect(),_n=null}),gt.push(()=>{Cn==null||Cn(),Cn=null,Ro(),Wt&&(Wt.remove(),Wt=null),vt==null||vt.element.style.removeProperty("width"),vt==null||vt.element.style.removeProperty("maxWidth")}),ie&>.push(()=>{ue!==null&&(cancelAnimationFrame(ue),ue=null),ge==null||ge.destroy(),ge=null,X==null||X.destroy(),X=null,Z=null});let qn=null,Ko=()=>{qn&&(qn(),qn=null),o.colorScheme==="auto"&&(qn=nu(()=>{$r(e,o)}))};Ko(),gt.push(()=>{qn&&(qn(),qn=null)});let oo=(_c=o.features)==null?void 0:_c.streamAnimation;if(oo!=null&&oo.type&&oo.type!=="none"){let c=_s(oo.type,oo.plugins);c&&(pl(c,e),gt.push(()=>$u(e)))}let uo=dm(Ct),jn=null,T,Kn=!1,mo=Du(),Po=new Map,So=new Map,ss=0,fo=oi(),go=0,ho=null,Wo=!1,ir=!1,ra=4,as=24,sa=80,Rr=new Map,mt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},is=($c=(Vc=o.voiceRecognition)==null?void 0:Vc.autoResume)!=null?$c:!1,ro=c=>{s.emit("voice:state",{active:mt.active,source:c,timestamp:Date.now()})},Rn=()=>{m(c=>({...c,voiceState:{active:mt.active,timestamp:Date.now(),manuallyDeactivated:mt.manuallyDeactivated}}))},aa=()=>{var y,R;if(((y=o.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=Fl(d.voiceState),f=!!c.active,h=Number((R=c.timestamp)!=null?R:0);mt.manuallyDeactivated=!!c.manuallyDeactivated,f&&Date.now()-h<Qv&&setTimeout(()=>{var N,V;mt.active||(mt.manuallyDeactivated=!1,((V=(N=o.voiceRecognition)==null?void 0:N.provider)==null?void 0:V.type)==="runtype"?T.toggleVoice().then(()=>{mt.active=T.isVoiceActive(),ro("restore"),T.isVoiceActive()&&I()}):pr("restore"))},1e3)},ia=()=>T?Wm(T.getMessages()).filter(c=>!c.__skipPersist):[];function Pr(c){if(!(i!=null&&i.save))return;let h={messages:c?Wm(c):T?ia():[],metadata:d,artifacts:Vn.artifacts,selectedArtifactId:Vn.selectedId};try{let y=i.save(h);y instanceof Promise&&y.catch(R=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",R)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let Bo=null,la=()=>fe.querySelector("#persona-scroll-container")||Y,lr=()=>{Bo!==null&&(cancelAnimationFrame(Bo),Bo=null),Wo=!1},ls=()=>{ho!==null&&(cancelAnimationFrame(ho),ho=null),ir=!1,lr()},Ho=()=>{if(!vn()||le){Et.parentNode&&Et.remove(),Et.style.display="none";return}Et.parentNode!==de&&de.appendChild(Et),yt();let c=Fs(Y)>0;Et.style.display=fo.isFollowing()||!c?"none":""},cs=()=>{fo.pause()&&(ls(),Ho())},Go=()=>{fo.resume(),Ho()},Yo=(c=!1)=>{fo.isFollowing()&&(!c&&!Kn||(ho!==null&&(cancelAnimationFrame(ho),ho=null),ir=!0,ho=requestAnimationFrame(()=>{ho=null,ir=!1,fo.isFollowing()&&ca(la(),c?220:140)})))},ca=(c,f=500)=>{let h=c.scrollTop,y=Fs(c),R=y-h;if(Math.abs(R)<1){go=c.scrollTop;return}if(Math.abs(R)>=sa){lr(),Wo=!0,c.scrollTop=y,go=c.scrollTop,Wo=!1;return}lr();let N=performance.now();Wo=!0;let V=F=>1-Math.pow(1-F,3),z=F=>{if(!fo.isFollowing()){lr();return}let Ce=Fs(c);Ce!==y&&(y=Ce,R=y-h);let pe=F-N,ne=Math.min(pe/f,1),he=V(ne),Te=h+R*he;c.scrollTop=Te,go=c.scrollTop,ne<1?Bo=requestAnimationFrame(z):(c.scrollTop=y,go=c.scrollTop,Bo=null,Wo=!1)};Bo=requestAnimationFrame(z)},da=c=>{let f=new Map;c.forEach(h=>{let y=Rr.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}))}),Rr.clear(),f.forEach((h,y)=>{Rr.set(y,h)})},cr=(c,f,h)=>{var Ye,it,lt,Ie,Me,$e;let y=document.createElement("div"),N=(()=>{var ke;let L=r.find(Pe=>Pe.renderLoadingIndicator);if(L!=null&&L.renderLoadingIndicator)return L.renderLoadingIndicator;if((ke=o.loadingIndicator)!=null&&ke.render)return o.loadingIndicator.render})(),V=(L,ke)=>ke==null?!1:typeof ke=="string"?(L.textContent=ke,!0):(L.appendChild(ke),!0),z=new Set,F=new Set,Ce=r.some(L=>L.renderAskUserQuestion),pe=[],ne=[],he=o.enableComponentStreaming!==!1;if(f.forEach(L=>{var An,pn,Je,ct,Tn,fn,ur,mr,fr,Nr,_r,zt,gr,tr;z.add(L.id);let ke=Ce&&Ar(L),Pe=!ke&&L.role==="assistant"&&!L.variant&&he&&Lm(L);if(!Pe&&So.has(L.id)){let bt=c.querySelector(`#wrapper-${L.id}`);bt==null||bt.removeAttribute("data-preserve-runtime"),So.delete(L.id)}let qe=Ar(L)?`:${(An=L.agentMetadata)!=null&&An.askUserQuestionAnswered?"a":"u"}:${(pn=L.agentMetadata)!=null&&pn.askUserQuestionAnswers?Object.keys(L.agentMetadata.askUserQuestionAnswers).length:0}`:"",xe=Hu(L,ss)+qe,It=ke||Pe?null:Fu(mo,L.id,xe);if(It){y.appendChild(It.cloneNode(!0)),Ar(L)&&((Je=L.toolCall)!=null&&Je.id)&&((ct=L.agentMetadata)==null?void 0:ct.awaitingLocalTool)===!0&&!((Tn=L.agentMetadata)!=null&&Tn.askUserQuestionAnswered)&&(F.add(L.toolCall.id),wi(L,o,Le.composerOverlay));return}let st=null,Xt=r.find(bt=>!!(L.variant==="reasoning"&&bt.renderReasoning||L.variant==="tool"&&bt.renderToolCall||L.variant==="approval"&&bt.renderApproval||!L.variant&&bt.renderMessage)),dn=(fn=o.layout)==null?void 0:fn.messages;if(Ar(L)&&((ur=L.agentMetadata)==null?void 0:ur.askUserQuestionAnswered)===!0){Po.delete(L.id);let bt=c.querySelector(`#wrapper-${L.id}`);bt==null||bt.removeAttribute("data-preserve-runtime");return}if(Ar(L)&&((fr=(mr=o.features)==null?void 0:mr.askUserQuestion)==null?void 0:fr.enabled)!==!1){let bt=r.find(Pn=>typeof Pn.renderAskUserQuestion=="function");if(bt&&Rt.current){let Pn=Po.get(L.id),Oo=Pn!==xe,kn=null;if(Oo){let{payload:Vt,complete:Dt}=Xr(L),qt=L.id,Bn=()=>{var Yn;return(Yn=Rt.current)==null?void 0:Yn.getMessages().find(tn=>tn.id===qt)};kn=bt.renderAskUserQuestion({message:L,payload:Vt,complete:Dt,resolve:Yn=>{var To;let tn=Bn();tn&&((To=Rt.current)==null||To.resolveAskUserQuestion(tn,Yn))},dismiss:()=>{var tn,To,No;let Yn=Bn();(tn=Yn==null?void 0:Yn.agentMetadata)!=null&&tn.awaitingLocalTool&&((To=Rt.current)==null||To.markAskUserQuestionResolved(Yn),(No=Rt.current)==null||No.resolveAskUserQuestion(Yn,"(dismissed)"))},config:o})}let Wn=Pn!=null;if(Oo&&kn===null&&!Wn){((Nr=L.agentMetadata)==null?void 0:Nr.awaitingLocalTool)===!0&&!((_r=L.agentMetadata)!=null&&_r.askUserQuestionAnswered)&&(F.add(L.toolCall.id),wi(L,o,Le.composerOverlay));return}let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${L.id}`,Ht.setAttribute("data-wrapper-id",L.id),Ht.setAttribute("data-ask-plugin-stub","true"),Ht.setAttribute("data-preserve-runtime","true"),y.appendChild(Ht),pe.push({messageId:L.id,fingerprint:xe,bubble:kn});return}else{((zt=L.agentMetadata)==null?void 0:zt.awaitingLocalTool)===!0&&!((gr=L.agentMetadata)!=null&&gr.askUserQuestionAnswered)&&(F.add(L.toolCall.id),wi(L,o,Le.composerOverlay));return}}else if(Xt)if(L.variant==="reasoning"&&L.reasoning&&Xt.renderReasoning){if(!re)return;st=Xt.renderReasoning({message:L,defaultRenderer:()=>yl(L,o),config:o})}else if(L.variant==="tool"&&L.toolCall&&Xt.renderToolCall){if(!be)return;st=Xt.renderToolCall({message:L,defaultRenderer:()=>vl(L,o),config:o})}else if(L.variant==="approval"&&L.approval&&Xt.renderApproval){if(o.approval===!1)return;st=Xt.renderApproval({message:L,defaultRenderer:()=>El(L,o),config:o})}else Xt.renderMessage&&(st=Xt.renderMessage({message:L,defaultRenderer:()=>{let bt=bl(L,h,dn,o.messageActions,j,{loadingIndicatorRenderer:N,widgetConfig:o});return L.role!=="user"&&Rl(bt,L,o,T),bt},config:o}));if(!st&&Pe){let bt=Im(L);if(bt){let Pn=So.get(L.id),Oo=Pn!==xe,kn=o.wrapComponentDirectiveInBubble!==!1,Wn=null;if(Oo){let Ht=Em(bt,{config:o,message:L,transform:h});if(Ht)if(kn){let Vt=document.createElement("div");if(Vt.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(" "),Vt.id=`bubble-${L.id}`,Vt.setAttribute("data-message-id",L.id),L.content&&L.content.trim()){let Dt=document.createElement("div");Dt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Dt.innerHTML=h({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),Vt.appendChild(Dt)}Vt.appendChild(Ht),Wn=Vt}else{let Vt=document.createElement("div");if(Vt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Vt.id=`bubble-${L.id}`,Vt.setAttribute("data-message-id",L.id),Vt.setAttribute("data-persona-component-directive","true"),L.content&&L.content.trim()){let Dt=document.createElement("div");Dt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Dt.innerHTML=h({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),Vt.appendChild(Dt)}Vt.appendChild(Ht),Wn=Vt}}if(Wn||Pn!=null){let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${L.id}`,Ht.setAttribute("data-wrapper-id",L.id),Ht.setAttribute("data-component-directive-stub","true"),Ht.setAttribute("data-preserve-runtime","true"),kn||Ht.classList.add("persona-w-full"),y.appendChild(Ht),ne.push({messageId:L.id,fingerprint:xe,bubble:Wn});return}}}if(!st)if(L.variant==="reasoning"&&L.reasoning){if(!re)return;st=yl(L,o)}else if(L.variant==="tool"&&L.toolCall){if(!be)return;st=vl(L,o)}else if(L.variant==="approval"&&L.approval){if(o.approval===!1)return;st=El(L,o)}else{let bt=(tr=o.layout)==null?void 0:tr.messages;bt!=null&&bt.renderUserMessage&&L.role==="user"?st=bt.renderUserMessage({message:L,config:o,streaming:!!L.streaming}):bt!=null&&bt.renderAssistantMessage&&L.role==="assistant"?st=bt.renderAssistantMessage({message:L,config:o,streaming:!!L.streaming}):st=bl(L,h,bt,o.messageActions,j,{loadingIndicatorRenderer:N,widgetConfig:o}),L.role!=="user"&&st&&Rl(st,L,o,T)}let Pt=document.createElement("div");Pt.className="persona-flex",Pt.id=`wrapper-${L.id}`,Pt.setAttribute("data-wrapper-id",L.id),L.role==="user"&&Pt.classList.add("persona-justify-end"),(st==null?void 0:st.getAttribute("data-persona-component-directive"))==="true"&&Pt.classList.add("persona-w-full"),Pt.appendChild(st),Ou(mo,L.id,xe,Pt),y.appendChild(Pt)}),Le.composerOverlay&&Le.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(ke=>{let Pe=ke.getAttribute("data-persona-ask-sheet-for");Pe&&!F.has(Pe)&&Jr(Le.composerOverlay,Pe)}),(it=(Ye=o.features)==null?void 0:Ye.toolCallDisplay)!=null&&it.grouped){let L=[],ke=[];f.forEach(Pe=>{if(Pe.variant==="tool"&&Pe.toolCall&&be){ke.push(Pe);return}ke.length>1&&L.push(ke),ke=[]}),ke.length>1&&L.push(ke),L.forEach((Pe,qe)=>{var pn,Je;let xe=Pe.map(ct=>Array.from(y.children).find(Tn=>Tn instanceof HTMLElement&&Tn.getAttribute("data-wrapper-id")===ct.id)).filter(ct=>!!ct);if(xe.length<2)return;let It=document.createElement("div");It.className="persona-flex",It.id=`wrapper-tool-group-${qe}-${Pe[0].id}`,It.setAttribute("data-wrapper-id",`tool-group-${qe}-${Pe[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 dn=`Called ${Pe.length} tools`,Pt=(Je=(pn=o.toolCall)==null?void 0:pn.renderGroupedSummary)==null?void 0:Je.call(pn,{messages:Pe,toolCalls:Pe.map(ct=>ct.toolCall).filter(ct=>!!ct),defaultSummary:dn,config:o});V(Xt,Pt)||(Xt.textContent=dn);let An=document.createElement("div");An.className="persona-tool-group-stack persona-flex persona-flex-col",st.append(Xt,An),It.appendChild(st),xe[0].before(It),xe.forEach((ct,Tn)=>{let fn=document.createElement("div");fn.className="persona-tool-group-item persona-relative",fn.setAttribute("data-persona-tool-group-item","true"),Tn<xe.length-1&&fn.setAttribute("data-persona-tool-group-connector","true"),fn.appendChild(ct),An.appendChild(fn)})})}Nu(mo,z);let Te=f.some(L=>L.role==="assistant"&&L.streaming),Be=f[f.length-1],et=(Be==null?void 0:Be.role)==="assistant"&&!Be.streaming&&Be.variant!=="approval";if(Kn&&f.some(L=>L.role==="user")&&!Te&&!et){let L={config:o,streaming:!0,location:"standalone",defaultRenderer:Ks},ke=r.find(qe=>qe.renderLoadingIndicator),Pe=null;if(ke!=null&&ke.renderLoadingIndicator&&(Pe=ke.renderLoadingIndicator(L)),Pe===null&&((lt=o.loadingIndicator)!=null&<.render)&&(Pe=o.loadingIndicator.render(L)),Pe===null&&(Pe=Ks()),Pe){let qe=document.createElement("div"),xe=((Ie=o.loadingIndicator)==null?void 0:Ie.showBubble)!==!1;qe.className=xe?["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(" "),qe.setAttribute("data-typing-indicator","true"),qe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",qe.appendChild(Pe);let It=document.createElement("div");It.className="persona-flex",It.id="wrapper-typing-indicator",It.setAttribute("data-wrapper-id","typing-indicator"),It.appendChild(qe),y.appendChild(It)}}if(!Kn&&f.length>0){let L=f[f.length-1],ke={config:o,lastMessage:L,messageCount:f.length},Pe=r.find(xe=>xe.renderIdleIndicator),qe=null;if(Pe!=null&&Pe.renderIdleIndicator&&(qe=Pe.renderIdleIndicator(ke)),qe===null&&((Me=o.loadingIndicator)!=null&&Me.renderIdle)&&(qe=o.loadingIndicator.renderIdle(ke)),qe){let xe=document.createElement("div"),It=(($e=o.loadingIndicator)==null?void 0:$e.showBubble)!==!1;xe.className=It?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),xe.setAttribute("data-idle-indicator","true"),xe.appendChild(qe);let st=document.createElement("div");st.className="persona-flex",st.id="wrapper-idle-indicator",st.setAttribute("data-wrapper-id","idle-indicator"),st.appendChild(xe),y.appendChild(st)}}if(ti(c,y),pe.length>0)for(let{messageId:L,fingerprint:ke,bubble:Pe}of pe){let qe=c.querySelector(`#wrapper-${L}`);qe&&Pe!==null&&(qe.replaceChildren(Pe),qe.setAttribute("data-bubble-fp",ke),Po.set(L,ke))}if(Po.size>0)for(let L of Po.keys())z.has(L)||Po.delete(L);if(ne.length>0)for(let{messageId:L,fingerprint:ke,bubble:Pe}of ne){let qe=c.querySelector(`#wrapper-${L}`);qe&&Pe!==null&&(qe.replaceChildren(Pe),qe.setAttribute("data-bubble-fp",ke),So.set(L,ke))}if(So.size>0)for(let L of So.keys())z.has(L)||So.delete(L)},Xo=null,pa=()=>{var h;if(Xo)return;let c=y=>{let R=y.composedPath();R.includes(fe)||_e&&R.includes(_e)||Bt(!1,"user")};Xo=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},ds=()=>{var f;if(!Xo)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("pointerdown",Xo,!0),Xo=null};gt.push(()=>ds());let Qo=null,ua=()=>{var h;if(Qo)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Bt(!1,"user"))};Qo=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},ps=()=>{var f;if(!Qo)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("keydown",Qo,!0),Qo=null};gt.push(()=>ps());let Jo=!1,us=new Set,ma=()=>{var f,h,y,R;let c=(y=(h=(f=o.launcher)==null?void 0:f.composerBar)==null?void 0:h.peek)==null?void 0:y.streamAnimation;return c||((R=o.features)==null?void 0:R.streamAnimation)},Do=()=>{var it,lt,Ie,Me;if(!E())return;let c=Le.peekBanner,f=Le.peekTextNode;if(!c||!f)return;if(k){c.classList.remove("persona-pill-peek--visible");return}let h=(it=T==null?void 0:T.getMessages())!=null?it:[],y;for(let $e=h.length-1;$e>=0;$e--){let L=h[$e];if(L.role==="assistant"&&L.content){y=L;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let R=y.content,N=!!y.streaming,V=ma(),z=ai(V),F=z.type!=="none"?_s(z.type,V==null?void 0:V.plugins):null,Ce=((lt=F==null?void 0:F.isAnimating)==null?void 0:lt.call(F,y))===!0,pe=F!==null&&(N||Ce);pe&&F&&!us.has(F.name)&&(pl(F,e),us.add(F.name));let ne=pe&&(F!=null&&F.containerClass)?F.containerClass:null,he=(Ie=f.dataset.personaPeekStreamClass)!=null?Ie:null;he&&he!==ne&&(f.classList.remove(he),delete f.dataset.personaPeekStreamClass),ne&&he!==ne&&(f.classList.add(ne),f.dataset.personaPeekStreamClass=ne),pe?(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 Te=pe?ii(R,z.buffer,F,y,N):R;if(pe&&z.placeholder==="skeleton"&&N&&(!Te||!Te.trim())){let $e=document.createElement("div"),L=$s();L.classList.add("persona-pill-peek__skeleton"),$e.appendChild(L),ti(f,$e)}else{let $e=Math.max(0,Te.length-100),L=Te.length>100?Te.slice(-100):Te,ke=Ls(L);if(!pe||!F){let Pe=Te.length>100?`\u2026${L}`:L;f.textContent!==Pe&&(f.textContent=Pe)}else{let Pe=ke;(F.wrap==="char"||F.wrap==="word")&&(Pe=Vs(ke,F.wrap,`peek-${y.id}`,{skipTags:F.skipTags,startIndex:$e}));let qe=document.createElement("div");if(qe.innerHTML=Pe,F.useCaret&&L.length>0){let xe=li(),It=qe.querySelectorAll(".persona-stream-char, .persona-stream-word"),st=It[It.length-1];st!=null&&st.parentNode?st.parentNode.insertBefore(xe,st.nextSibling):qe.appendChild(xe)}ti(f,qe),(Me=F.onAfterRender)==null||Me.call(F,{container:f,bubble:c,messageId:y.id,message:y,speed:z.speed,duration:z.duration})}}let Ye=Kn||Jo;c.classList.toggle("persona-pill-peek--visible",Ye)};if(E()){let c=Le.peekBanner;if(c){let y=R=>{R.preventDefault(),R.stopPropagation(),Bt(!0,"user")};c.addEventListener("pointerdown",y),gt.push(()=>{c.removeEventListener("pointerdown",y)})}let f=()=>{Jo||(Jo=!0,Do())},h=()=>{Jo&&(Jo=!1,Do())};ce.addEventListener("pointerenter",f),ce.addEventListener("pointerleave",h),gt.push(()=>{ce.removeEventListener("pointerenter",f),ce.removeEventListener("pointerleave",h)}),_e&&(_e.addEventListener("pointerenter",f),_e.addEventListener("pointerleave",h),gt.push(()=>{_e.removeEventListener("pointerenter",f),_e.removeEventListener("pointerleave",h)}))}let fa=c=>{var he,Te,Be,et,Ye,it,lt,Ie;let f=(Te=(he=o.launcher)==null?void 0:he.composerBar)!=null?Te:{},h=(Be=f.expandedSize)!=null?Be:"anchored",y=(et=f.bottomOffset)!=null?et:"16px",R=f.collapsedMaxWidth,N=(Ye=f.expandedMaxWidth)!=null?Ye:"880px",V=(it=f.expandedTopOffset)!=null?it:"5vh",z=(lt=f.modalMaxWidth)!=null?lt:"880px",F=(Ie=f.modalMaxHeight)!=null?Ie:"min(90vh, 800px)",Ce="calc(100vw - 32px)",pe="var(--persona-pill-area-height, 80px)",ne=fe.style;if(ne.left="",ne.right="",ne.top="",ne.bottom="",ne.transform="",ne.width="",ne.maxWidth="",ne.height="",ne.maxHeight="",_e){let Me=_e.style;Me.bottom=y,Me.width=R!=null?R:""}if(c&&h!=="fullscreen"){if(h==="modal"){ne.top="50%",ne.left="50%",ne.transform="translate(-50%, -50%)",ne.bottom="auto",ne.right="auto",ne.width=z,ne.maxWidth=Ce,ne.maxHeight=F,ne.height=F;return}ne.left="50%",ne.transform="translateX(-50%)",ne.bottom=`calc(${y} + ${pe})`,ne.top=V,ne.width=N,ne.maxWidth=Ce}},Zo=()=>{var F,Ce,pe,ne,he,Te,Be,et;if(!S())return;if(E()){let it=(pe=((Ce=(F=o.launcher)==null?void 0:F.composerBar)!=null?Ce:{}).expandedSize)!=null?pe:"anchored",lt=k?"expanded":"collapsed";fe.dataset.state=lt,fe.dataset.expandedSize=it,_e&&(_e.dataset.state=lt,_e.dataset.expandedSize=it),fe.style.removeProperty("display"),fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),fa(k),de.style.display=k?"flex":"none",po(),k?(pa(),ua()):(ds(),ps()),Do();return}let c=un(o),f=(ne=e.ownerDocument.defaultView)!=null?ne:window,h=(Te=(he=o.launcher)==null?void 0:he.mobileBreakpoint)!=null?Te:640,y=(et=(Be=o.launcher)==null?void 0:Be.mobileFullscreen)!=null?et:!0,R=f.innerWidth<=h,N=y&&R&&P,V=Mo(o).reveal;k?(fe.style.removeProperty("display"),fe.style.display=c?"flex":"",fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-95","persona-opacity-0"),ce.classList.add("persona-scale-100","persona-opacity-100"),Ge?Ge.element.style.display="none":Qe&&(Qe.style.display="none")):(c?c&&(V==="overlay"||V==="push")&&!N?(fe.style.removeProperty("display"),fe.style.display="flex",fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(fe.style.setProperty("display","none","important"),fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(fe.style.display="",fe.classList.add("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-100","persona-opacity-100"),ce.classList.add("persona-scale-95","persona-opacity-0")),Ge?Ge.element.style.display=c?"none":"":Qe&&(Qe.style.display=c?"none":""))},Bt=(c,f="user")=>{var N,V;if(!S()||k===c)return;let h=k;k=c,Zo();let y=(()=>{var Be,et,Ye,it,lt,Ie,Me,$e,L,ke;let z=(et=(Be=o.launcher)==null?void 0:Be.sidebarMode)!=null?et:!1,F=(Ye=e.ownerDocument.defaultView)!=null?Ye:window,Ce=(lt=(it=o.launcher)==null?void 0:it.mobileFullscreen)!=null?lt:!0,pe=(Me=(Ie=o.launcher)==null?void 0:Ie.mobileBreakpoint)!=null?Me:640,ne=F.innerWidth<=pe,he=un(o)&&Ce&&ne,Te=E()&&((ke=(L=($e=o.launcher)==null?void 0:$e.composerBar)==null?void 0:L.expandedSize)!=null?ke:"fullscreen")==="fullscreen";return z||Ce&&ne&&P||he||Te})();if(k&&y){if(!Kt){let z=e.getRootNode(),F=z instanceof ShadowRoot?z.host:e.closest(".persona-host");F&&(Kt=ul(F,(V=(N=o.launcher)==null?void 0:N.zIndex)!=null?V:bn))}Gt||(Gt=ml(e.ownerDocument))}else k||(Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null);k&&(Yt(),Yo(!0));let R={open:k,source:f,timestamp:Date.now()};k&&!h?s.emit("widget:opened",R):!k&&h&&s.emit("widget:closed",R),s.emit("widget:state",{open:k,launcherEnabled:P,voiceActive:mt.active,streaming:T.isStreaming()})},Wr=c=>{jt(c?"stop":"send"),K&&(K.disabled=c),uo.buttons.forEach(f=>{f.disabled=c}),Ne.dataset.personaComposerStreaming=c?"true":"false",Ne.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=c)})},Br=()=>{mt.active||Q&&Q.focus()};s.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Br(),200)});let ms=()=>{var h,y,R,N,V,z,F,Ce,pe,ne,he;Dn.textContent=(y=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",Jn.textContent=(N=(R=o.copy)==null?void 0:R.welcomeSubtitle)!=null?N:"Ask anything about your account or products.",Q.placeholder=(z=(V=o.copy)==null?void 0:V.inputPlaceholder)!=null?z:"How can I help...";let c=Y.querySelector("[data-persona-intro-card]");if(c){let Te=((F=o.copy)==null?void 0:F.showWelcomeCard)!==!1;c.style.display=Te?"":"none",Te?(Y.classList.remove("persona-gap-3"),Y.classList.add("persona-gap-6")):(Y.classList.remove("persona-gap-6"),Y.classList.add("persona-gap-3"))}!((pe=(Ce=o.sendButton)==null?void 0:Ce.useIcon)!=null&&pe)&&!(T!=null&&T.isStreaming())&&(Fe.textContent=(he=(ne=o.copy)==null?void 0:ne.sendButtonLabel)!=null?he:"Send"),Q.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Q.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(f=>({...f,sessionId:c}))}});let Ao=null,ga=()=>{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=Ua(f-y))})},100))};if(T=new Za(o,{onMessagesChanged(c){cr(Ve,c,me),ga(),T&&(c.some(R=>R.role==="user")?uo.render([],T,Q,c):uo.render(o.suggestionChips,T,Q,c,o.suggestionChipsConfig)),Yo(!Kn),da(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),Pr(c),Do()},onStatusChanged(c){var y;let f=(y=o.statusIndicator)!=null?y:{};tt(ln,(R=>{var N,V,z,F;return R==="idle"?(N=f.idleText)!=null?N:hn.idle:R==="connecting"?(V=f.connectingText)!=null?V:hn.connecting:R==="connected"?(z=f.connectedText)!=null?z:hn.connected:R==="error"?(F=f.errorText)!=null?F:hn.error:hn[R]})(c),f,c)},onStreamingChanged(c){Kn=c,Wr(c),T&&cr(Ve,T.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":G(),ee();break;case"speaking":G(),te();break;default:c==="idle"&&T.isBargeInActive()?(G(),I(),K==null||K.setAttribute("aria-label","End voice session")):(mt.active=!1,G(),ro("system"),Rn());break}},onArtifactsState(c){Vn=c,zn(),Pr()}}),Rt.current=T,((zc=(Uc=o.voiceRecognition)==null?void 0:Uc.provider)==null?void 0:zc.type)==="runtype")try{T.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}o.clientToken&&T.initClientSession().catch(c=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(X||o.onSSEEvent)&&T.setSSEEventCallback((c,f)=>{var h;(h=o.onSSEEvent)==null||h.call(o,c,f),Ae==null||Ae.processEvent(c,f),X==null||X.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(f)})}),l&&l.then(c=>{var f,h,y;c&&(c.metadata&&(d=Fl(c.metadata),M.syncFromMetadata()),(f=c.messages)!=null&&f.length&&T.hydrateMessages(c.messages),(h=c.artifacts)!=null&&h.length&&T.hydrateArtifacts(c.artifacts,(y=c.selectedArtifactId)!=null?y:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let fs=()=>{var f,h,y;!E()||k||!((y=(h=(f=o.launcher)==null?void 0:f.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||Bt(!0,"auto")},gs=c=>{var R;if(c.preventDefault(),T.isStreaming()){T.cancel(),Ae==null||Ae.reset(),ge==null||ge.update();return}let f=Q.value.trim(),h=(R=Ze==null?void 0:Ze.hasAttachments())!=null?R:!1;if(!f&&!h)return;fs();let y;h&&(y=[],y.push(...Ze.getContentParts()),f&&y.push(il(f))),Q.value="",Q.style.height="auto",dr(),T.sendMessage(f,{contentParts:y}),h&&Ze.clearAttachments()},ha=()=>{var c;return((c=o.features)==null?void 0:c.composerHistory)!==!1},Hr={...ni},Dr=!1,dr=()=>{Hr={...ni}},ba=()=>T.getMessages().filter(c=>c.role==="user").map(c=>{var f;return(f=c.content)!=null?f:""}).filter(c=>c.length>0),ya=c=>{if(!Q)return;Dr=!0,Q.value=c,Q.dispatchEvent(new Event("input",{bubbles:!0})),Dr=!1;let f=Q.value.length;Q.setSelectionRange(f,f)},hs=()=>{Dr||dr()},bs=c=>{if(Q){if(ha()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let f=Q.selectionStart===0&&Q.selectionEnd===0,h=Bu({direction:c.key==="ArrowUp"?"up":"down",history:ba(),currentValue:Q.value,atStart:f,state:Hr});if(Hr=h.state,h.handled){c.preventDefault(),h.value!==void 0&&ya(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(T.isStreaming()){c.preventDefault();return}dr(),c.preventDefault(),Fe.click()}}},ys=c=>{c.key!=="Escape"||c.isComposing||T.isStreaming()&&c.composedPath().includes(de)&&(T.cancel(),Ae==null||Ae.reset(),ge==null||ge.update(),dr(),c.preventDefault(),c.stopImmediatePropagation())},vs=async c=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!Ze)return;let f=Zv(c.clipboardData);f.length!==0&&(c.preventDefault(),await Ze.handleFiles(f))},Sn=null,Gn=!1,Fo=null,rt=null,xs=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,pr=(c="user")=>{var N,V,z,F,Ce,pe,ne;if(Gn||T.isStreaming())return;let f=xs();if(!f)return;Sn=new f;let y=(V=((N=o.voiceRecognition)!=null?N:{}).pauseDuration)!=null?V:2e3;Sn.continuous=!0,Sn.interimResults=!0,Sn.lang="en-US";let R=Q.value;Sn.onresult=he=>{let Te="",Be="";for(let Ye=0;Ye<he.results.length;Ye++){let it=he.results[Ye],lt=it[0].transcript;it.isFinal?Te+=lt+" ":Be=lt}let et=R+Te+Be;Q.value=et,Fo&&clearTimeout(Fo),(Te||Be)&&(Fo=window.setTimeout(()=>{let Ye=Q.value.trim();Ye&&Sn&&Gn&&(bo(),Q.value="",Q.style.height="auto",T.sendMessage(Ye,{viaVoice:!0}))},y))},Sn.onerror=he=>{he.error!=="no-speech"&&bo()},Sn.onend=()=>{if(Gn){let he=Q.value.trim();he&&he!==R.trim()&&(Q.value="",Q.style.height="auto",T.sendMessage(he,{viaVoice:!0})),bo()}};try{if(Sn.start(),Gn=!0,mt.active=!0,c!=="system"&&(mt.manuallyDeactivated=!1),ro(c),Rn(),K){let he=(z=o.voiceRecognition)!=null?z:{};rt={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:(F=he.iconName)!=null?F:"mic",iconSize:parseFloat((ne=(pe=he.iconSize)!=null?pe:(Ce=o.sendButton)==null?void 0:Ce.size)!=null?ne:"40")||24};let Te=he.recordingBackgroundColor,Be=he.recordingIconColor,et=he.recordingBorderColor;if(K.classList.add("persona-voice-recording"),K.style.backgroundColor=Te!=null?Te:"var(--persona-voice-recording-bg, #ef4444)",K.style.color=Be!=null?Be:"var(--persona-voice-recording-indicator, #ffffff)",Be){let Ye=K.querySelector("svg");Ye&&Ye.setAttribute("stroke",Be)}et&&(K.style.borderColor=et),K.setAttribute("aria-label","Stop voice recognition")}}catch{bo("system")}},bo=(c="user")=>{if(Gn){if(Gn=!1,Fo&&(clearTimeout(Fo),Fo=null),Sn){try{Sn.stop()}catch{}Sn=null}if(mt.active=!1,ro(c),Rn(),K){if(K.classList.remove("persona-voice-recording"),rt){K.style.backgroundColor=rt.backgroundColor,K.style.color=rt.color,K.style.borderColor=rt.borderColor;let f=K.querySelector("svg");f&&f.setAttribute("stroke",rt.color||"currentColor"),rt=null}K.setAttribute("aria-label","Start voice recognition")}}},Fr=(c,f)=>{var it,lt,Ie,Me,$e,L,ke,Pe;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((it=c==null?void 0:c.provider)==null?void 0:it.type)==="runtype";if(!(h||y))return null;let 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=(lt=c==null?void 0:c.iconName)!=null?lt:"mic",F=(Ie=f==null?void 0:f.size)!=null?Ie:"40px",Ce=(Me=c==null?void 0:c.iconSize)!=null?Me:F,pe=parseFloat(Ce)||24,ne=($e=c==null?void 0:c.backgroundColor)!=null?$e:f==null?void 0:f.backgroundColor,he=(L=c==null?void 0:c.iconColor)!=null?L:f==null?void 0:f.textColor;V.style.width=Ce,V.style.height=Ce,V.style.minWidth=Ce,V.style.minHeight=Ce,V.style.fontSize="18px",V.style.lineHeight="1",he?V.style.color=he:V.style.color="var(--persona-text, #111827)";let Be=Se(z,pe,he||"currentColor",1.5);Be?V.appendChild(Be):V.textContent="\u{1F3A4}",ne?V.style.backgroundColor=ne: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 et=(ke=c==null?void 0:c.tooltipText)!=null?ke:"Start voice recognition";if(((Pe=c==null?void 0:c.showTooltip)!=null?Pe:!1)&&et){let qe=b("div","persona-send-button-tooltip");qe.textContent=et,N.appendChild(qe)}return{micButton:V,micButtonWrapper:N}},Ue=()=>{var f,h,y,R,N;if(!K||rt)return;let c=(f=o.voiceRecognition)!=null?f:{};rt={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:(h=c.iconName)!=null?h:"mic",iconSize:parseFloat((N=(R=c.iconSize)!=null?R:(y=o.sendButton)==null?void 0:y.size)!=null?N:"40")||24}},A=(c,f)=>{var N,V,z,F,Ce;if(!K)return;let h=K.querySelector("svg");h&&h.remove();let y=(Ce=rt==null?void 0:rt.iconSize)!=null?Ce:parseFloat((F=(z=(N=o.voiceRecognition)==null?void 0:N.iconSize)!=null?z:(V=o.sendButton)==null?void 0:V.size)!=null?F:"40")||24,R=Se(c,y,f,1.5);R&&K.appendChild(R)},U=()=>{K&&K.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},I=()=>{var R;if(!K)return;Ue();let c=(R=o.voiceRecognition)!=null?R:{},f=c.recordingBackgroundColor,h=c.recordingIconColor,y=c.recordingBorderColor;if(U(),K.classList.add("persona-voice-recording"),K.style.backgroundColor=f!=null?f:"var(--persona-voice-recording-bg, #ef4444)",K.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let N=K.querySelector("svg");N&&N.setAttribute("stroke",h)}y&&(K.style.borderColor=y),K.setAttribute("aria-label","Stop voice recognition")},ee=()=>{var z,F,Ce,pe,ne,he,Te,Be;if(!K)return;Ue();let c=(z=o.voiceRecognition)!=null?z:{},f=T.getVoiceInterruptionMode(),h=(F=c.processingIconName)!=null?F:"loader",y=(pe=(Ce=c.processingIconColor)!=null?Ce:rt==null?void 0:rt.color)!=null?pe:"",R=(he=(ne=c.processingBackgroundColor)!=null?ne:rt==null?void 0:rt.backgroundColor)!=null?he:"",N=(Be=(Te=c.processingBorderColor)!=null?Te:rt==null?void 0:rt.borderColor)!=null?Be:"";U(),K.classList.add("persona-voice-processing"),K.style.backgroundColor=R,K.style.borderColor=N;let V=y||"currentColor";K.style.color=V,A(h,V),K.setAttribute("aria-label","Processing voice input"),f==="none"&&(K.style.cursor="default")},te=()=>{var Ce,pe,ne,he,Te,Be,et,Ye,it,lt,Ie,Me;if(!K)return;Ue();let c=(Ce=o.voiceRecognition)!=null?Ce:{},f=T.getVoiceInterruptionMode(),h=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",y=(pe=c.speakingIconName)!=null?pe:h,R=(Be=c.speakingIconColor)!=null?Be:f==="barge-in"?(he=(ne=c.recordingIconColor)!=null?ne:rt==null?void 0:rt.color)!=null?he:"":(Te=rt==null?void 0:rt.color)!=null?Te:"",N=(it=c.speakingBackgroundColor)!=null?it:f==="barge-in"?(et=c.recordingBackgroundColor)!=null?et:"var(--persona-voice-recording-bg, #ef4444)":(Ye=rt==null?void 0:rt.backgroundColor)!=null?Ye:"",V=(Me=c.speakingBorderColor)!=null?Me:f==="barge-in"?(lt=c.recordingBorderColor)!=null?lt:"":(Ie=rt==null?void 0:rt.borderColor)!=null?Ie:"";U(),K.classList.add("persona-voice-speaking"),K.style.backgroundColor=N,K.style.borderColor=V;let z=R||"currentColor";K.style.color=z,A(y,z);let F=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";K.setAttribute("aria-label",F),f==="none"&&(K.style.cursor="default"),f==="barge-in"&&K.classList.add("persona-voice-recording")},G=()=>{var c,f,h;K&&(U(),rt&&(K.style.backgroundColor=(c=rt.backgroundColor)!=null?c:"",K.style.color=(f=rt.color)!=null?f:"",K.style.borderColor=(h=rt.borderColor)!=null?h:"",A(rt.iconName,rt.color||"currentColor"),rt=null),K.style.cursor="",K.setAttribute("aria-label","Start voice recognition"))},ze=()=>{var c,f;if(((f=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"){let h=T.getVoiceStatus(),y=T.getVoiceInterruptionMode();if(y==="none"&&(h==="processing"||h==="speaking"))return;if(y==="cancel"&&(h==="processing"||h==="speaking")){T.stopVoicePlayback();return}if(T.isBargeInActive()){T.stopVoicePlayback(),T.deactivateBargeIn().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Rn(),ro("user"),G()});return}T.toggleVoice().then(()=>{mt.active=T.isVoiceActive(),mt.manuallyDeactivated=!T.isVoiceActive(),Rn(),ro("user"),T.isVoiceActive()?I():G()});return}if(Gn){let h=Q.value.trim();mt.manuallyDeactivated=!0,Rn(),bo("user"),h&&(Q.value="",Q.style.height="auto",T.sendMessage(h))}else mt.manuallyDeactivated=!1,Rn(),pr("user")};Fn=ze,K&&(K.addEventListener("click",ze),gt.push(()=>{var c,f;((f=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?(T.isVoiceActive()&&T.toggleVoice(),G()):bo("system"),K&&K.removeEventListener("click",ze)}));let De=s.on("assistant:complete",()=>{is&&(mt.active||mt.manuallyDeactivated||is==="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"?T.toggleVoice().then(()=>{mt.active=T.isVoiceActive(),ro("auto"),T.isVoiceActive()&&I()}):pr("auto"))},600))});gt.push(De);let at=s.on("action:resubmit",()=>{setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)});gt.push(at);let Ke=()=>{Bt(!k,"user")},Ge=null,Qe=null;if(P&&!E()){let c=r.find(f=>f.renderLauncher);if(c!=null&&c.renderLauncher){let f=c.renderLauncher({config:o,defaultRenderer:()=>qs(o,Ke).element,onToggle:Ke});f&&(Qe=f)}Qe||(Ge=qs(o,Ke))}Ge?e.appendChild(Ge.element):Qe&&e.appendChild(Qe),Zo(),uo.render(o.suggestionChips,T,Q,void 0,o.suggestionChipsConfig),ms(),Wr(T.isStreaming()),Yo(!0),aa(),H&&(!P||E()?setTimeout(()=>Br(),0):k&&setTimeout(()=>Br(),200));let Yt=()=>{var F,Ce,pe,ne,he,Te,Be,et,Ye,it,lt,Ie,Me,$e,L,ke,Pe,qe,xe,It,st,Xt;if(E()){yt(),Zo();return}let c=un(o),f=(Ce=(F=o.launcher)==null?void 0:F.sidebarMode)!=null?Ce:!1,h=c||f||((ne=(pe=o.launcher)==null?void 0:pe.fullHeight)!=null?ne:!1),y=(he=e.ownerDocument.defaultView)!=null?he:window,R=(Be=(Te=o.launcher)==null?void 0:Te.mobileFullscreen)!=null?Be:!0,N=(Ye=(et=o.launcher)==null?void 0:et.mobileBreakpoint)!=null?Ye:640,V=y.innerWidth<=N,z=R&&V&&P;try{if(z){po(),$r(e,o);return}if(C&&(C=!1,po(),$r(e,o)),!P&&!c){ce.style.height="",ce.style.width="";return}if(!f&&!c){let dn=(lt=(it=o==null?void 0:o.launcher)==null?void 0:it.width)!=null?lt:o==null?void 0:o.launcherWidth,Pt=dn!=null?dn:io;ce.style.width=Pt,ce.style.maxWidth=Pt}if(Co(),!h){let dn=y.innerHeight,Pt=64,An=(Me=(Ie=o.launcher)==null?void 0:Ie.heightOffset)!=null?Me:0,pn=Math.max(200,dn-Pt),Je=Math.min(640,pn),ct=Math.max(200,Je-An);ce.style.height=`${ct}px`}}finally{if(yt(),Zo(),k&&P){let Pt=(($e=e.ownerDocument.defaultView)!=null?$e:window).innerWidth<=((ke=(L=o.launcher)==null?void 0:L.mobileBreakpoint)!=null?ke:640),An=(qe=(Pe=o.launcher)==null?void 0:Pe.sidebarMode)!=null?qe:!1,pn=(It=(xe=o.launcher)==null?void 0:xe.mobileFullscreen)!=null?It:!0,Je=un(o)&&pn&&Pt,ct=An||pn&&Pt&&P||Je;if(ct&&!Gt){let Tn=e.getRootNode(),fn=Tn instanceof ShadowRoot?Tn.host:e.closest(".persona-host");fn&&!Kt&&(Kt=ul(fn,(Xt=(st=o.launcher)==null?void 0:st.zIndex)!=null?Xt:bn)),Gt=ml(e.ownerDocument)}else ct||(Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null)}}};Yt();let Tt=(qc=e.ownerDocument.defaultView)!=null?qc:window;if(Tt.addEventListener("resize",Yt),gt.push(()=>Tt.removeEventListener("resize",Yt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{yt()});c.observe(Ne),gt.push(()=>c.disconnect())}go=Y.scrollTop;let Lt=Y.scrollHeight,on=()=>{let c=Y.scrollTop,f=Y.scrollHeight,h=f<Lt;Lt=f;let{action:y,nextLastScrollTop:R}=ri({following:fo.isFollowing(),currentScrollTop:c,lastScrollTop:go,nearBottom:Os(Y,as),userScrollThreshold:ra,isAutoScrolling:Wo||ir||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(go=R,y==="resume"){Go();return}y==="pause"&&cs()};Y.addEventListener("scroll",on,{passive:!0}),gt.push(()=>Y.removeEventListener("scroll",on));let mn=c=>{let f=si({following:fo.isFollowing(),deltaY:c.deltaY,nearBottom:Os(Y,as),resumeWhenNearBottom:!0});f==="pause"?cs():f==="resume"&&Go()};Y.addEventListener("wheel",mn,{passive:!0}),gt.push(()=>Y.removeEventListener("wheel",mn)),Et.addEventListener("click",()=>{Y.scrollTop=Y.scrollHeight,go=Y.scrollTop,Go(),Yo(!0)}),gt.push(()=>Et.remove()),gt.push(()=>{ls()});let cn=()=>{O&&(jn&&(O.removeEventListener("click",jn),jn=null),S()?(O.style.display="",jn=()=>{Bt(!1,"user")},O.addEventListener("click",jn)):O.style.display="none")};cn(),(()=>{let{clearChatButton:c}=Le;c&&c.addEventListener("click",()=>{T.clearMessages(),mo.clear(),Go(),Jr(Le.composerOverlay);try{localStorage.removeItem(es),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${es}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==es)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let 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(),X==null||X.clear(),Ae==null||Ae.reset(),ge==null||ge.update()})})(),Ft&&Ft.addEventListener("submit",gs),Q==null||Q.addEventListener("keydown",bs),Q==null||Q.addEventListener("input",hs),Q==null||Q.addEventListener("paste",vs);let so=(jc=e.ownerDocument)!=null?jc:document;so.addEventListener("keydown",ys,!0);let Jl="persona-attachment-drop-active",ws=0,$i=()=>{ws=0,de.classList.remove(Jl)},Or=()=>{var c;return((c=o.attachments)==null?void 0:c.enabled)===!0&&Ze!==null},Zl=c=>{!ki(c.dataTransfer)||!Or()||(ws++,ws===1&&de.classList.add(Jl))},ec=c=>{!ki(c.dataTransfer)||!Or()||(ws--,ws<=0&&$i())},tc=c=>{!ki(c.dataTransfer)||!Or()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},nc=c=>{var h;if(!ki(c.dataTransfer)||!Or())return;c.preventDefault(),c.stopPropagation(),$i();let f=Array.from((h=c.dataTransfer.files)!=null?h:[]);f.length!==0&&Ze.handleFiles(f)},er=!0;de.addEventListener("dragenter",Zl,er),de.addEventListener("dragleave",ec,er),e.addEventListener("dragover",tc,er),e.addEventListener("drop",nc,er);let va=e.ownerDocument,oc=c=>{Or()&&c.preventDefault()},rc=c=>{Or()&&c.preventDefault()};va.addEventListener("dragover",oc),va.addEventListener("drop",rc),gt.push(()=>{Ft&&Ft.removeEventListener("submit",gs),Q==null||Q.removeEventListener("keydown",bs),Q==null||Q.removeEventListener("input",hs),Q==null||Q.removeEventListener("paste",vs),so.removeEventListener("keydown",ys,!0)}),gt.push(()=>{de.removeEventListener("dragenter",Zl,er),de.removeEventListener("dragleave",ec,er),e.removeEventListener("dragover",tc,er),e.removeEventListener("drop",nc,er),va.removeEventListener("dragover",oc),va.removeEventListener("drop",rc),$i()}),gt.push(()=>{T.cancel()}),Ge?gt.push(()=>{Ge==null||Ge.destroy()}):Qe&>.push(()=>{Qe==null||Qe.remove()});let en={update(c){var tn,To,No,xa,wa,Ca,hr,Sa,Cs,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,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;let f=o.toolCall,h=o.messageActions,y=(tn=o.layout)==null?void 0:tn.messages,R=o.colorScheme,N=o.loadingIndicator,V=o.iterationDisplay,z=(To=o.features)==null?void 0:To.showReasoning,F=(No=o.features)==null?void 0:No.showToolCalls,Ce=(xa=o.features)==null?void 0:xa.toolCallDisplay,pe=(wa=o.features)==null?void 0:wa.reasoningDisplay;o={...o,...c},po(),$r(e,o),Ai(e,o),Ti(e,o),zn(),o.colorScheme!==R&&Ko();let ne=Wl.getForInstance(o.plugins);r.length=0,r.push(...ne),P=(hr=(Ca=o.launcher)==null?void 0:Ca.enabled)!=null?hr:!0,W=(Cs=(Sa=o.launcher)==null?void 0:Sa.autoExpand)!=null?Cs:!1,re=(ed=(Zc=o.features)==null?void 0:Zc.showReasoning)!=null?ed:!0,be=(nd=(td=o.features)==null?void 0:td.showToolCalls)!=null?nd:!0,we=(rd=(od=o.features)==null?void 0:od.scrollToBottom)!=null?rd:{},Ut(),Ho();let he=ie;if(ie=(ad=(sd=o.features)==null?void 0:sd.showEventStreamToggle)!=null?ad:!1,ie&&!he){if(X||(Z=new Xs(ye),X=new Ys(Ee,Z),Ae=Ae!=null?Ae:new Qs,Z.open().then(()=>X==null?void 0:X.restore()).catch(()=>{}),T.setSSEEventCallback((J,xt)=>{var Ot;(Ot=o.onSSEEvent)==null||Ot.call(o,J,xt),Ae==null||Ae.processEvent(J,xt),X.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:J,timestamp:Date.now(),payload:JSON.stringify(xt)})})),!ut&&Oe){let J=(ld=(id=o.features)==null?void 0:id.eventStream)==null?void 0:ld.classNames,xt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(J!=null&&J.toggleButton?" "+J.toggleButton:"");ut=b("button",xt),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=Se("activity","18px","currentColor",1.5);Ot&&ut.appendChild(Ot);let dt=Le.clearChatButtonWrapper,Mt=Le.closeButtonWrapper,rn=dt||Mt;rn&&rn.parentNode===Oe?Oe.insertBefore(ut,rn):Oe.appendChild(ut),ut.addEventListener("click",()=>{le?On():xn()})}}else!ie&&he&&(On(),ut&&(ut.remove(),ut=null),X==null||X.clear(),Z==null||Z.destroy(),X=null,Z=null,Ae==null||Ae.reset(),Ae=null);if(((cd=o.launcher)==null?void 0:cd.enabled)===!1&&Ge&&(Ge.destroy(),Ge=null),((dd=o.launcher)==null?void 0:dd.enabled)===!1&&Qe&&(Qe.remove(),Qe=null),((pd=o.launcher)==null?void 0:pd.enabled)!==!1&&!Ge&&!Qe){let J=r.find(xt=>xt.renderLauncher);if(J!=null&&J.renderLauncher){let xt=J.renderLauncher({config:o,defaultRenderer:()=>qs(o,Ke).element,onToggle:Ke});xt&&(Qe=xt,e.appendChild(Qe))}Qe||(Ge=qs(o,Ke),e.appendChild(Ge.element))}Ge&&Ge.update(o),He&&((ud=o.launcher)==null?void 0:ud.title)!==void 0&&(He.textContent=o.launcher.title),Xe&&((md=o.launcher)==null?void 0:md.subtitle)!==void 0&&(Xe.textContent=o.launcher.subtitle);let Te=(fd=o.layout)==null?void 0:fd.header;if((Te==null?void 0:Te.layout)!==v&&Oe){let J=Te?ui(o,Te,{showClose:S(),onClose:()=>Bt(!1,"user")}):Sr({config:o,showClose:S(),onClose:()=>Bt(!1,"user")});Oe.replaceWith(J.header),Oe=J.header,se=J.iconHolder,He=J.headerTitle,Xe=J.headerSubtitle,O=J.closeButton,v=Te==null?void 0:Te.layout}else if(Te&&(se&&(se.style.display=Te.showIcon===!1?"none":""),He&&(He.style.display=Te.showTitle===!1?"none":""),Xe&&(Xe.style.display=Te.showSubtitle===!1?"none":""),O&&(O.style.display=Te.showCloseButton===!1?"none":""),Le.clearChatButtonWrapper)){let J=Te.showClearChat;if(J!==void 0){Le.clearChatButtonWrapper.style.display=J?"":"none";let{closeButtonWrapper:xt}=Le;xt&&!xt.classList.contains("persona-absolute")&&(J?xt.classList.remove("persona-ml-auto"):xt.classList.add("persona-ml-auto"))}}let et=((gd=o.layout)==null?void 0:gd.showHeader)!==!1;Oe&&(Oe.style.display=et?"":"none");let Ye=((hd=o.layout)==null?void 0:hd.showFooter)!==!1;Ne&&(Ne.style.display=Ye?"":"none"),yt(),Ho(),P!==B?P?Bt(W,"auto"):(k=!0,Zo()):W!==_&&Bt(W,"auto"),_=W,B=P,Yt(),cn();let Ie=JSON.stringify(c.toolCall)!==JSON.stringify(f),Me=JSON.stringify(o.messageActions)!==JSON.stringify(h),$e=JSON.stringify((bd=o.layout)==null?void 0:bd.messages)!==JSON.stringify(y),L=((yd=o.loadingIndicator)==null?void 0:yd.render)!==(N==null?void 0:N.render)||((vd=o.loadingIndicator)==null?void 0:vd.renderIdle)!==(N==null?void 0:N.renderIdle)||((xd=o.loadingIndicator)==null?void 0:xd.showBubble)!==(N==null?void 0:N.showBubble),ke=o.iterationDisplay!==V,Pe=((Cd=(wd=o.features)==null?void 0:wd.showReasoning)!=null?Cd:!0)!==(z!=null?z:!0)||((Ad=(Sd=o.features)==null?void 0:Sd.showToolCalls)!=null?Ad:!0)!==(F!=null?F:!0)||JSON.stringify((Td=o.features)==null?void 0:Td.toolCallDisplay)!==JSON.stringify(Ce)||JSON.stringify((kd=o.features)==null?void 0:kd.reasoningDisplay)!==JSON.stringify(pe);(Ie||Me||$e||L||ke||Pe)&&T&&(ss++,cr(Ve,T.getMessages(),me));let xe=(Ed=o.launcher)!=null?Ed:{},It=(Md=xe.headerIconHidden)!=null?Md:!1,st=(Id=(Ld=o.layout)==null?void 0:Ld.header)==null?void 0:Id.showIcon,Xt=It||st===!1,dn=xe.headerIconName,Pt=(Rd=xe.headerIconSize)!=null?Rd:"48px";if(se){let J=de.querySelector(".persona-border-b-persona-divider"),xt=J==null?void 0:J.querySelector(".persona-flex-col");if(Xt)se.style.display="none",J&&xt&&!J.contains(xt)&&J.insertBefore(xt,J.firstChild);else{if(se.style.display="",se.style.height=Pt,se.style.width=Pt,J&&xt&&(J.contains(se)?se.nextSibling!==xt&&(se.remove(),J.insertBefore(se,xt)):J.insertBefore(se,xt)),dn){let dt=parseFloat(Pt)||24,Mt=Se(dn,dt*.6,"#ffffff",2);Mt?se.replaceChildren(Mt):se.textContent=(Pd=xe.agentIconText)!=null?Pd:"\u{1F4AC}"}else if(xe.iconUrl){let dt=se.querySelector("img");if(dt)dt.src=xe.iconUrl,dt.style.height=Pt,dt.style.width=Pt;else{let Mt=document.createElement("img");Mt.src=xe.iconUrl,Mt.alt="",Mt.className="persona-rounded-xl persona-object-cover",Mt.style.height=Pt,Mt.style.width=Pt,se.replaceChildren(Mt)}}else{let dt=se.querySelector("svg"),Mt=se.querySelector("img");(dt||Mt)&&se.replaceChildren(),se.textContent=(Wd=xe.agentIconText)!=null?Wd:"\u{1F4AC}"}let Ot=se.querySelector("img");Ot&&(Ot.style.height=Pt,Ot.style.width=Pt)}}let An=(Hd=(Bd=o.layout)==null?void 0:Bd.header)==null?void 0:Hd.showTitle,pn=(Fd=(Dd=o.layout)==null?void 0:Dd.header)==null?void 0:Fd.showSubtitle;if(He&&(He.style.display=An===!1?"none":""),Xe&&(Xe.style.display=pn===!1?"none":""),O){((Nd=(Od=o.layout)==null?void 0:Od.header)==null?void 0:Nd.showCloseButton)===!1?O.style.display="none":O.style.display="";let xt=(_d=xe.closeButtonSize)!=null?_d:"32px",Ot=(Vd=xe.closeButtonPlacement)!=null?Vd:"inline";O.style.height=xt,O.style.width=xt;let{closeButtonWrapper:dt}=Le,Mt=Ot==="top-right",rn=dt==null?void 0:dt.classList.contains("persona-absolute");if(dt&&Mt!==rn)if(dt.remove(),Mt)dt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",de.style.position="relative",de.appendChild(dt);else{let pt=(Ud=($d=xe.clearChat)==null?void 0:$d.placement)!=null?Ud:"inline",sn=(qd=(zd=xe.clearChat)==null?void 0:zd.enabled)!=null?qd:!0;dt.className=sn&&pt==="inline"?"":"persona-ml-auto";let Hn=de.querySelector(".persona-border-b-persona-divider");Hn&&Hn.appendChild(dt)}if(O.style.color=xe.closeButtonColor||Mn.actionIconColor,xe.closeButtonBackgroundColor?(O.style.backgroundColor=xe.closeButtonBackgroundColor,O.classList.remove("hover:persona-bg-gray-100")):(O.style.backgroundColor="",O.classList.add("hover:persona-bg-gray-100")),xe.closeButtonBorderWidth||xe.closeButtonBorderColor){let pt=xe.closeButtonBorderWidth||"0px",sn=xe.closeButtonBorderColor||"transparent";O.style.border=`${pt} solid ${sn}`,O.classList.remove("persona-border-none")}else O.style.border="",O.classList.add("persona-border-none");xe.closeButtonBorderRadius?(O.style.borderRadius=xe.closeButtonBorderRadius,O.classList.remove("persona-rounded-full")):(O.style.borderRadius="",O.classList.add("persona-rounded-full")),xe.closeButtonPaddingX?(O.style.paddingLeft=xe.closeButtonPaddingX,O.style.paddingRight=xe.closeButtonPaddingX):(O.style.paddingLeft="",O.style.paddingRight=""),xe.closeButtonPaddingY?(O.style.paddingTop=xe.closeButtonPaddingY,O.style.paddingBottom=xe.closeButtonPaddingY):(O.style.paddingTop="",O.style.paddingBottom="");let gn=(jd=xe.closeButtonIconName)!=null?jd:"x",yo=(Kd=xe.closeButtonIconText)!=null?Kd:"\xD7";O.innerHTML="";let En=Se(gn,"28px","currentColor",1);En?O.appendChild(En):O.textContent=yo;let Qt=(Gd=xe.closeButtonTooltipText)!=null?Gd:"Close chat",Xn=(Yd=xe.closeButtonShowTooltip)!=null?Yd:!0;if(O.setAttribute("aria-label",Qt),dt&&(dt._cleanupTooltip&&(dt._cleanupTooltip(),delete dt._cleanupTooltip),Xn&&Qt)){let pt=null,sn=()=>{if(pt||!O)return;let br=O.ownerDocument,Ss=br.body;if(!Ss)return;pt=Eo(br,"div","persona-clear-chat-tooltip"),pt.textContent=Qt;let As=Eo(br,"div");As.className="persona-clear-chat-tooltip-arrow",pt.appendChild(As);let yr=O.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(nr),pt.style.left=`${yr.left+yr.width/2}px`,pt.style.top=`${yr.top-8}px`,pt.style.transform="translate(-50%, -100%)",Ss.appendChild(pt)},Hn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};dt.addEventListener("mouseenter",sn),dt.addEventListener("mouseleave",Hn),O.addEventListener("focus",sn),O.addEventListener("blur",Hn),dt._cleanupTooltip=()=>{Hn(),dt&&(dt.removeEventListener("mouseenter",sn),dt.removeEventListener("mouseleave",Hn)),O&&(O.removeEventListener("focus",sn),O.removeEventListener("blur",Hn))}}}let{clearChatButton:Je,clearChatButtonWrapper:ct}=Le;if(Je){let J=(Xd=xe.clearChat)!=null?Xd:{},xt=(Qd=J.enabled)!=null?Qd:!0,Ot=(Zd=(Jd=o.layout)==null?void 0:Jd.header)==null?void 0:Zd.showClearChat,dt=Ot!==void 0?Ot:xt,Mt=(ep=J.placement)!=null?ep:"inline";if(ct){ct.style.display=dt?"":"none";let{closeButtonWrapper:rn}=Le;!E()&&rn&&!rn.classList.contains("persona-absolute")&&(dt?rn.classList.remove("persona-ml-auto"):rn.classList.add("persona-ml-auto"));let gn=Mt==="top-right",yo=ct.classList.contains("persona-absolute");if(!E()&&gn!==yo&&dt){if(ct.remove(),gn)ct.className="persona-absolute persona-top-4 persona-z-50",ct.style.right="48px",de.style.position="relative",de.appendChild(ct);else{ct.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ct.style.right="";let Qt=de.querySelector(".persona-border-b-persona-divider"),Xn=Le.closeButtonWrapper;Qt&&Xn&&Xn.parentElement===Qt?Qt.insertBefore(ct,Xn):Qt&&Qt.appendChild(ct)}let En=Le.closeButtonWrapper;En&&!En.classList.contains("persona-absolute")&&(gn?En.classList.add("persona-ml-auto"):En.classList.remove("persona-ml-auto"))}}if(dt){if(!E()){let pt=(tp=J.size)!=null?tp:"32px";Je.style.height=pt,Je.style.width=pt}let rn=(np=J.iconName)!=null?np:"refresh-cw",gn=(op=J.iconColor)!=null?op:"";Je.style.color=gn||Mn.actionIconColor,Je.innerHTML="";let yo=E()?"14px":"20px",En=Se(rn,yo,"currentColor",2);if(En&&Je.appendChild(En),J.backgroundColor?(Je.style.backgroundColor=J.backgroundColor,Je.classList.remove("hover:persona-bg-gray-100")):(Je.style.backgroundColor="",Je.classList.add("hover:persona-bg-gray-100")),J.borderWidth||J.borderColor){let pt=J.borderWidth||"0px",sn=J.borderColor||"transparent";Je.style.border=`${pt} solid ${sn}`,Je.classList.remove("persona-border-none")}else Je.style.border="",Je.classList.add("persona-border-none");J.borderRadius?(Je.style.borderRadius=J.borderRadius,Je.classList.remove("persona-rounded-full")):(Je.style.borderRadius="",Je.classList.add("persona-rounded-full")),J.paddingX?(Je.style.paddingLeft=J.paddingX,Je.style.paddingRight=J.paddingX):(Je.style.paddingLeft="",Je.style.paddingRight=""),J.paddingY?(Je.style.paddingTop=J.paddingY,Je.style.paddingBottom=J.paddingY):(Je.style.paddingTop="",Je.style.paddingBottom="");let Qt=(rp=J.tooltipText)!=null?rp:"Clear chat",Xn=(sp=J.showTooltip)!=null?sp:!0;if(Je.setAttribute("aria-label",Qt),ct&&(ct._cleanupTooltip&&(ct._cleanupTooltip(),delete ct._cleanupTooltip),Xn&&Qt)){let pt=null,sn=()=>{if(pt||!Je)return;let br=Je.ownerDocument,Ss=br.body;if(!Ss)return;pt=Eo(br,"div","persona-clear-chat-tooltip"),pt.textContent=Qt;let As=Eo(br,"div");As.className="persona-clear-chat-tooltip-arrow",pt.appendChild(As);let yr=Je.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(nr),pt.style.left=`${yr.left+yr.width/2}px`,pt.style.top=`${yr.top-8}px`,pt.style.transform="translate(-50%, -100%)",Ss.appendChild(pt)},Hn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};ct.addEventListener("mouseenter",sn),ct.addEventListener("mouseleave",Hn),Je.addEventListener("focus",sn),Je.addEventListener("blur",Hn),ct._cleanupTooltip=()=>{Hn(),ct&&(ct.removeEventListener("mouseenter",sn),ct.removeEventListener("mouseleave",Hn)),Je&&(Je.removeEventListener("focus",sn),Je.removeEventListener("blur",Hn))}}}}let Tn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Hl],fn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Js.message,Js.messageAndClick];M=Dl({parsers:Tn,handlers:fn,getSessionMetadata:g,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),me=Bm(o,M,q),T.updateConfig(o),cr(Ve,T.getMessages(),me),uo.render(o.suggestionChips,T,Q,void 0,o.suggestionChipsConfig),ms(),Wr(T.isStreaming());let ur=((ap=o.voiceRecognition)==null?void 0:ap.enabled)===!0,mr=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),fr=((lp=(ip=o.voiceRecognition)==null?void 0:ip.provider)==null?void 0:lp.type)==="runtype";if(ur&&(mr||fr))if(!K||!ft){let J=Fr(o.voiceRecognition,o.sendButton);J&&(K=J.micButton,ft=J.micButtonWrapper,Nt.insertBefore(ft,Ln),K.addEventListener("click",ze),K.disabled=T.isStreaming())}else{let J=(cp=o.voiceRecognition)!=null?cp:{},xt=(dp=o.sendButton)!=null?dp:{},Ot=(pp=J.iconName)!=null?pp:"mic",dt=(up=xt.size)!=null?up:"40px",Mt=(mp=J.iconSize)!=null?mp:dt,rn=parseFloat(Mt)||24;K.style.width=Mt,K.style.height=Mt,K.style.minWidth=Mt,K.style.minHeight=Mt;let gn=(gp=(fp=J.iconColor)!=null?fp:xt.textColor)!=null?gp:"currentColor";K.innerHTML="";let yo=Se(Ot,rn,gn,2);yo?K.appendChild(yo):K.textContent="\u{1F3A4}";let En=(hp=J.backgroundColor)!=null?hp:xt.backgroundColor;En?K.style.backgroundColor=En:K.style.backgroundColor="",gn?K.style.color=gn: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 Qt=ft==null?void 0:ft.querySelector(".persona-send-button-tooltip"),Xn=(bp=J.tooltipText)!=null?bp:"Start voice recognition";if(((yp=J.showTooltip)!=null?yp:!1)&&Xn)if(Qt)Qt.textContent=Xn,Qt.style.display="";else{let sn=document.createElement("div");sn.className="persona-send-button-tooltip",sn.textContent=Xn,ft==null||ft.insertBefore(sn,K)}else Qt&&(Qt.style.display="none");ft.style.display="",K.disabled=T.isStreaming()}else K&&ft&&(ft.style.display="none",((xp=(vp=o.voiceRecognition)==null?void 0:vp.provider)==null?void 0:xp.type)==="runtype"?T.isVoiceActive()&&T.toggleVoice():Gn&&bo());if(((wp=o.attachments)==null?void 0:wp.enabled)===!0)if(!$t||!nt){let J=(Cp=o.attachments)!=null?Cp:{},Ot=(Ap=((Sp=o.sendButton)!=null?Sp:{}).size)!=null?Ap:"40px";ve||(ve=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ve.style.display="none",Ft.insertBefore(ve,Q)),ae||(ae=document.createElement("input"),ae.type="file",ae.accept=((Tp=J.allowedTypes)!=null?Tp:_o).join(","),ae.multiple=((kp=J.maxFiles)!=null?kp:4)>1,ae.style.display="none",ae.setAttribute("aria-label","Attach files"),Ft.insertBefore(ae,Q)),$t=b("div","persona-send-button-wrapper"),nt=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),nt.type="button",nt.setAttribute("aria-label",(Ep=J.buttonTooltipText)!=null?Ep:"Attach file");let dt=(Mp=J.buttonIconName)!=null?Mp:"paperclip",Mt=Ot,rn=parseFloat(Mt)||40,gn=Math.round(rn*.6);nt.style.width=Mt,nt.style.height=Mt,nt.style.minWidth=Mt,nt.style.minHeight=Mt,nt.style.fontSize="18px",nt.style.lineHeight="1",nt.style.backgroundColor="transparent",nt.style.color="var(--persona-primary, #111827)",nt.style.border="none",nt.style.borderRadius="6px",nt.style.transition="background-color 0.15s ease",nt.addEventListener("mouseenter",()=>{nt.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),nt.addEventListener("mouseleave",()=>{nt.style.backgroundColor="transparent"});let yo=Se(dt,gn,"currentColor",1.5);yo?nt.appendChild(yo):nt.textContent="\u{1F4CE}",nt.addEventListener("click",Xn=>{Xn.preventDefault(),ae==null||ae.click()}),$t.appendChild(nt);let En=(Lp=J.buttonTooltipText)!=null?Lp:"Attach file",Qt=b("div","persona-send-button-tooltip");Qt.textContent=En,$t.appendChild(Qt),St.append($t),!Ze&&ae&&ve&&(Ze=Ds.fromConfig(J),Ze.setPreviewsContainer(ve),ae.addEventListener("change",async()=>{Ze&&(ae!=null&&ae.files)&&(await Ze.handleFileSelect(ae.files),ae.value="")})),de.querySelector(".persona-attachment-drop-overlay")||de.appendChild(Hm(J.dropOverlay))}else{$t.style.display="";let J=(Ip=o.attachments)!=null?Ip:{};ae&&(ae.accept=((Rp=J.allowedTypes)!=null?Rp:_o).join(","),ae.multiple=((Pp=J.maxFiles)!=null?Pp:4)>1),Ze&&Ze.updateConfig({allowedTypes:J.allowedTypes,maxFileSize:J.maxFileSize,maxFiles:J.maxFiles})}else $t&&($t.style.display="none"),Ze&&Ze.clearAttachments(),(Wp=de.querySelector(".persona-attachment-drop-overlay"))==null||Wp.remove();let zt=(Bp=o.sendButton)!=null?Bp:{},gr=(Hp=zt.useIcon)!=null?Hp:!1,tr=(Dp=zt.iconText)!=null?Dp:"\u2191",bt=zt.iconName,Pn=(Fp=zt.tooltipText)!=null?Fp:"Send message",Oo=(Op=zt.showTooltip)!=null?Op:!1,kn=(Np=zt.size)!=null?Np:"40px",Wn=zt.backgroundColor,Ht=zt.textColor;if(gr){if(Fe.style.width=kn,Fe.style.height=kn,Fe.style.minWidth=kn,Fe.style.minHeight=kn,Fe.style.fontSize="18px",Fe.style.lineHeight="1",Fe.innerHTML="",Ht?Fe.style.color=Ht:Fe.style.color="var(--persona-button-primary-fg, #ffffff)",bt){let J=parseFloat(kn)||24,xt=(Ht==null?void 0:Ht.trim())||"currentColor",Ot=Se(bt,J,xt,2);Ot?Fe.appendChild(Ot):Fe.textContent=tr}else Fe.textContent=tr;Fe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Wn?(Fe.style.backgroundColor=Wn,Fe.classList.remove("persona-bg-persona-primary")):(Fe.style.backgroundColor="",Fe.classList.add("persona-bg-persona-primary"))}else Fe.textContent=(Vp=(_p=o.copy)==null?void 0:_p.sendButtonLabel)!=null?Vp:"Send",Fe.style.width="",Fe.style.height="",Fe.style.minWidth="",Fe.style.minHeight="",Fe.style.fontSize="",Fe.style.lineHeight="",Fe.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?(Fe.style.backgroundColor=Wn,Fe.classList.remove("persona-bg-persona-accent")):Fe.classList.add("persona-bg-persona-accent"),Ht?Fe.style.color=Ht:Fe.classList.add("persona-text-white");zt.borderWidth?(Fe.style.borderWidth=zt.borderWidth,Fe.style.borderStyle="solid"):(Fe.style.borderWidth="",Fe.style.borderStyle=""),zt.borderColor?Fe.style.borderColor=zt.borderColor:Fe.style.borderColor="",zt.paddingX?(Fe.style.paddingLeft=zt.paddingX,Fe.style.paddingRight=zt.paddingX):(Fe.style.paddingLeft="",Fe.style.paddingRight=""),zt.paddingY?(Fe.style.paddingTop=zt.paddingY,Fe.style.paddingBottom=zt.paddingY):(Fe.style.paddingTop="",Fe.style.paddingBottom="");let Vt=Ln==null?void 0:Ln.querySelector(".persona-send-button-tooltip");if(Oo&&Pn)if(Vt)Vt.textContent=Pn,Vt.style.display="";else{let J=document.createElement("div");J.className="persona-send-button-tooltip",J.textContent=Pn,Ln==null||Ln.insertBefore(J,Fe)}else Vt&&(Vt.style.display="none");let Dt=(jp=($p=o.layout)==null?void 0:$p.contentMaxWidth)!=null?jp:E()?(qp=(zp=(Up=o.launcher)==null?void 0:Up.composerBar)==null?void 0:zp.contentMaxWidth)!=null?qp:"720px":void 0;Dt?(Ve.style.maxWidth=Dt,Ve.style.marginLeft="auto",Ve.style.marginRight="auto",Ve.style.width="100%",Ft&&(Ft.style.maxWidth=Dt,Ft.style.marginLeft="auto",Ft.style.marginRight="auto"),Ct&&(Ct.style.maxWidth=Dt,Ct.style.marginLeft="auto",Ct.style.marginRight="auto")):(Ve.style.maxWidth="",Ve.style.marginLeft="",Ve.style.marginRight="",Ve.style.width="",Ft&&(Ft.style.maxWidth="",Ft.style.marginLeft="",Ft.style.marginRight=""),Ct&&(Ct.style.maxWidth="",Ct.style.marginLeft="",Ct.style.marginRight=""));let qt=(Kp=o.statusIndicator)!=null?Kp:{},Bn=(Gp=qt.visible)!=null?Gp:!0;if(ln.style.display=Bn?"":"none",T){let J=T.getStatus();tt(ln,(Ot=>{var dt,Mt,rn,gn;return Ot==="idle"?(dt=qt.idleText)!=null?dt:hn.idle:Ot==="connecting"?(Mt=qt.connectingText)!=null?Mt:hn.connecting:Ot==="connected"?(rn=qt.connectedText)!=null?rn:hn.connected:Ot==="error"?(gn=qt.errorText)!=null?gn:hn.error:hn[Ot]})(J),qt,J)}ln.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Yn=qt.align==="left"?"persona-text-left":qt.align==="center"?"persona-text-center":"persona-text-right";ln.classList.add(Yn)},open(){S()&&Bt(!0,"api")},close(){S()&&Bt(!1,"api")},toggle(){S()&&Bt(!k,"api")},clearChat(){wn=!1,T.clearMessages(),mo.clear(),Go();try{localStorage.removeItem(es),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${es}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==es)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(),X==null||X.clear(),Ae==null||Ae.reset(),ge==null||ge.update()},setMessage(c){return!Q||T.isStreaming()?!1:(!k&&S()&&Bt(!0,"system"),Q.value=c,Q.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(T.isStreaming())return!1;let f=(c==null?void 0:c.trim())||Q.value.trim();return f?(!k&&S()&&Bt(!0,"system"),Q.value="",Q.style.height="auto",T.sendMessage(f),!0):!1},startVoiceRecognition(){var f,h;return T.isStreaming()?!1:((h=(f=o.voiceRecognition)==null?void 0:f.provider)==null?void 0:h.type)==="runtype"?(T.isVoiceActive()||(!k&&S()&&Bt(!0,"system"),mt.manuallyDeactivated=!1,Rn(),T.toggleVoice().then(()=>{mt.active=T.isVoiceActive(),ro("user"),T.isVoiceActive()&&I()})),!0):Gn?!0:xs()?(!k&&S()&&Bt(!0,"system"),mt.manuallyDeactivated=!1,Rn(),pr("user"),!0):!1},stopVoiceRecognition(){var c,f;return((f=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?T.isVoiceActive()?(T.toggleVoice().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Rn(),ro("user"),G()}),!0):!1:Gn?(mt.manuallyDeactivated=!0,Rn(),bo("user"),!0):!1},injectMessage(c){return!k&&S()&&Bt(!0,"system"),T.injectMessage(c)},injectAssistantMessage(c){!k&&S()&&Bt(!0,"system");let f=T.injectAssistantMessage(c);return D&&(D=!1,$&&(clearTimeout($),$=null),setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)),f},injectUserMessage(c){return!k&&S()&&Bt(!0,"system"),T.injectUserMessage(c)},injectSystemMessage(c){return!k&&S()&&Bt(!0,"system"),T.injectSystemMessage(c)},injectMessageBatch(c){return!k&&S()&&Bt(!0,"system"),T.injectMessageBatch(c)},injectComponentDirective(c){return!k&&S()&&Bt(!0,"system"),T.injectComponentDirective(c)},injectTestMessage(c){!k&&S()&&Bt(!0,"system"),T.injectTestEvent(c)},async connectStream(c,f){return T.connectStream(c,f)},__pushEventStreamEvent(c){X&&(Ae==null||Ae.processEvent(c.type,c.payload),X.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!ie||!X||xn()},hideEventStream(){le&&On()},isEventStreamVisible(){return le},showArtifacts(){co(o)&&(wn=!1,zn(),vt==null||vt.setMobileOpen(!0))},hideArtifacts(){co(o)&&(wn=!0,zn())},upsertArtifact(c){return co(o)?(wn=!1,T.upsertArtifact(c)):null},selectArtifact(c){co(o)&&T.selectArtifact(c)},clearArtifacts(){co(o)&&T.clearArtifacts()},getArtifacts(){var c;return(c=T==null?void 0:T.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=T==null?void 0:T.getSelectedArtifactId())!=null?c:null},focusInput(){return P&&!k&&!E()||!Q?!1:(Q.focus(),!0)},async resolveApproval(c,f){let y=T.getMessages().find(R=>{var N;return R.variant==="approval"&&((N=R.approval)==null?void 0:N.id)===c});if(!(y!=null&&y.approval))throw new Error(`Approval not found: ${c}`);if(y.approval.toolType==="webmcp"){T.resolveWebMcpApproval(y.id,f);return}return T.resolveApproval(y.approval,f)},getMessages(){return T.getMessages()},getStatus(){return T.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){m(c)},on(c,f){return s.on(c,f)},off(c,f){s.off(c,f)},isOpen(){return S()&&k},isVoiceActive(){return mt.active},getState(){return{open:S()&&k,launcherEnabled:P,voiceActive:mt.active,streaming:T.isStreaming()}},showCSATFeedback(c){!k&&S()&&Bt(!0,"system");let f=Ve.querySelector(".persona-feedback-container");f&&f.remove();let h=Rm({onSubmit:async(y,R)=>{var N;T.isClientTokenMode()&&await T.submitCSATFeedback(y,R),(N=c==null?void 0:c.onSubmit)==null||N.call(c,y,R)},onDismiss:c==null?void 0:c.onDismiss,...c});Ve.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!k&&S()&&Bt(!0,"system");let f=Ve.querySelector(".persona-feedback-container");f&&f.remove();let h=Pm({onSubmit:async(y,R)=>{var N;T.isClientTokenMode()&&await T.submitNPSFeedback(y,R),(N=c==null?void 0:c.onSubmit)==null||N.call(c,y,R)},onDismiss:c==null?void 0:c.onDismiss,...c});Ve.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,f){return T.submitCSATFeedback(c,f)},async submitNPSFeedback(c,f){return T.submitNPSFeedback(c,f)},destroy(){Ao!=null&&(clearInterval(Ao),Ao=null),gt.forEach(c=>c()),fe.remove(),_e==null||_e.remove(),Ge==null||Ge.destroy(),Qe==null||Qe.remove(),jn&&O.removeEventListener("click",jn)}};if((((Kc=n==null?void 0:n.debugTools)!=null?Kc:!1)||!!o.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,f={controller:en,getMessages:en.getMessages,getStatus:en.getStatus,getMetadata:en.getPersistentMetadata,updateMetadata:en.updatePersistentMetadata,clearHistory:()=>en.clearChat(),setVoiceActive:h=>h?en.startVoiceRecognition():en.stopVoiceRecognition()};window.AgentWidgetBrowser=f,gt.push(()=>{window.AgentWidgetBrowser===f&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),f=z=>{let F=z.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&en.focusInput()};if(window.addEventListener("persona:focusInput",f),gt.push(()=>{window.removeEventListener("persona:focusInput",f)}),ie){let z=Ce=>{let pe=Ce.detail;(!(pe!=null&&pe.instanceId)||pe.instanceId===c)&&en.showEventStream()},F=Ce=>{let pe=Ce.detail;(!(pe!=null&&pe.instanceId)||pe.instanceId===c)&&en.hideEventStream()};window.addEventListener("persona:showEventStream",z),window.addEventListener("persona:hideEventStream",F),gt.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)&&en.showArtifacts()},y=z=>{let F=z.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&en.hideArtifacts()},R=z=>{let F=z.detail;F!=null&&F.instanceId&&F.instanceId!==c||F!=null&&F.artifact&&en.upsertArtifact(F.artifact)},N=z=>{let F=z.detail;F!=null&&F.instanceId&&F.instanceId!==c||typeof(F==null?void 0:F.id)=="string"&&en.selectArtifact(F.id)},V=z=>{let F=z.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&en.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",R),window.addEventListener("persona:selectArtifact",N),window.addEventListener("persona:clearArtifacts",V),gt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",R),window.removeEventListener("persona:selectArtifact",N),window.removeEventListener("persona:clearArtifacts",V)})}let ao=ex(o.persistState);if(ao&&S()){let c=tx(ao.storage),f=`${ao.keyPrefix}widget-open`,h=`${ao.keyPrefix}widget-voice`,y=`${ao.keyPrefix}widget-voice-mode`;if(c){let R=((Gc=ao.persist)==null?void 0:Gc.openState)&&c.getItem(f)==="true",N=((Yc=ao.persist)==null?void 0:Yc.voiceState)&&c.getItem(h)==="true",V=((Xc=ao.persist)==null?void 0:Xc.voiceState)&&c.getItem(y)==="true";if(R&&setTimeout(()=>{en.open(),setTimeout(()=>{var z;if(N||V)en.startVoiceRecognition();else if((z=ao.persist)!=null&&z.focusInput){let F=e.querySelector("textarea");F&&F.focus()}},100)},0),(Qc=ao.persist)!=null&&Qc.openState&&(s.on("widget:opened",()=>{c.setItem(f,"true")}),s.on("widget:closed",()=>{c.setItem(f,"false")})),(Jc=ao.persist)!=null&&Jc.voiceState&&(s.on("voice:state",z=>{c.setItem(h,z.active?"true":"false")}),s.on("user:message",z=>{c.setItem(y,z.viaVoice?"true":"false")})),ao.clearOnChatClear){let z=()=>{c.removeItem(f),c.removeItem(h),c.removeItem(y)},F=()=>z();window.addEventListener("persona:clear-chat",F),gt.push(()=>{window.removeEventListener("persona:clear-chat",F)})}}}return u&&S()&&setTimeout(()=>{en.open()},0),Do(),en};var nx=(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},Fm=(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"},Vl=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=""},Om=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Vl(e)},Ol=e=>{e.style.transition=""},Nl=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"},Ei=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},ox=(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))},rx=(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)},Nm=(e,t,n,o,r,s,a)=>{var w,x,M,P,W,H;let i=Mo(s),d=i.reveal==="push";ox(e,t,n,o,d),rx(e,t,n,o,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,u=(x=(w=s==null?void 0:s.launcher)==null?void 0:w.mobileFullscreen)!=null?x:!0,p=(P=(M=s==null?void 0:s.launcher)==null?void 0:M.mobileBreakpoint)!=null?P:640,g=l!=null?l.innerWidth<=p:!1;if(u&&g&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Nl(t),Ol(o),Om(o),_l(n),Ei(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=(W=s==null?void 0:s.launcher)==null?void 0:W.zIndex)!=null?H:bn),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Om(o),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Nl(t),Ol(o),_l(n),Ei(r,o);let _=i.animate?"transform 180ms ease":"none",B=i.side==="right"?"translateX(100%)":"translateX(-100%)",v=a?"translateX(0)":B;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=_,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",Ol(o),Vl(o),Ei(r,o);let _=nx(i.width,e.clientWidth),B=Math.max(0,e.clientWidth),v=i.animate?"transform 180ms ease":"none",C=i.side==="right"?a?`translateX(-${_}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${_}px)`;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${B+_}px`,t.style.transition=v,t.style.transform=C,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${B}px`,n.style.maxWidth=`${B}px`,n.style.minWidth=`${B}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.position="relative",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Nl(t),Vl(o),_l(n),Ei(r,o);let _=i.reveal==="emerge";_?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let B=a?i.width:"0px",v=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",C=!a;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${B}`,o.style.width=B,o.style.maxWidth=B,o.style.minWidth=B,o.style.minHeight="0",o.style.position="relative",o.style.overflow=_||C?"hidden":"visible",o.style.transition=v,_&&(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")}},sx=(e,t)=>{let n=e.ownerDocument.createElement("div");return Fm(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Fm(n,o)},destroy(){n.remove()}}},ax=(e,t)=>{var W,H,_,B;let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),u=n.createElement("div"),p=(H=(W=t==null?void 0:t.launcher)==null?void 0:W.enabled)==null||H?(B=(_=t==null?void 0:t.launcher)==null?void 0:_.autoExpand)!=null?B:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",l.appendChild(u),o.insertBefore(a,e),d.appendChild(e);let g=null,m=()=>{g==null||g.disconnect(),g=null},w=()=>{m(),Mo(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{Nm(a,i,d,l,u,t,p)}),g.observe(a))},x=()=>{Nm(a,i,d,l,u,t,p),w()},M=a.ownerDocument.defaultView,P=()=>{x()};return M==null||M.addEventListener("resize",P),Mo(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),x(),{mode:"docked",host:u,shell:a,syncWidgetState(v){let C=v.launcherEnabled?v.open:!0;p!==C&&(p=C,x())},updateConfig(v){var C,E;t=v,((E=(C=t==null?void 0:t.launcher)==null?void 0:C.enabled)!=null?E:!0)===!1&&(p=!0),x()},destroy(){M==null||M.removeEventListener("resize",P),m(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},_m=(e,t)=>un(t)?ax(e,t):sx(e,t);var ts={desktop:{w:1280,h:800},mobile:{w:390,h:844}},$l=.15,Ul=1.5,Mi="persona-preview-shell-theme",Vm={load:()=>null,save:()=>{},clear:()=>{}},$m=["How do I get started?","Pricing & plans","Talk to support"];function Li(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Um(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 zl(e){let t=Um(e);return`* { box-sizing: border-box; }
|
|
107
|
+
`}if(!y&&!c){let Dt="max-height: -moz-available !important; max-height: stretch !important;",qt=m?"":"padding-top: 1.25em !important;",Bn=m?"":`z-index: ${(Vt=(Ht=o.launcher)==null?void 0:Ht.zIndex)!=null?Vt:bn} !important;`;ge.style.cssText+=Dt+qt+Bn}I()};po(),$r(e,o),Ai(e,o),Ti(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(()=>{Cn==null||Cn(),Cn=null,Ro(),Wt&&(Wt.remove(),Wt=null),vt==null||vt.element.style.removeProperty("width"),vt==null||vt.element.style.removeProperty("maxWidth")}),ie&&ft.push(()=>{ue!==null&&(cancelAnimationFrame(ue),ue=null),fe==null||fe.destroy(),fe=null,X==null||X.destroy(),X=null,Z=null});let qn=null,Ko=()=>{qn&&(qn(),qn=null),o.colorScheme==="auto"&&(qn=nu(()=>{$r(e,o)}))};Ko(),ft.push(()=>{qn&&(qn(),qn=null)});let oo=(_c=o.features)==null?void 0:_c.streamAnimation;if(oo!=null&&oo.type&&oo.type!=="none"){let c=_s(oo.type,oo.plugins);c&&(pl(c,e),ft.push(()=>zu(e)))}let uo=um(Ct),jn=null,T,Kn=!1,mo=Ou(),Po=new Map,So=new Map,ss=0,go=oi(),fo=0,ho=null,Wo=!1,ir=!1,ra=4,as=24,sa=80,Rr=new Map,mt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},is=($c=(Vc=o.voiceRecognition)==null?void 0:Vc.autoResume)!=null?$c:!1,ro=c=>{s.emit("voice:state",{active:mt.active,source:c,timestamp:Date.now()})},Rn=()=>{g(c=>({...c,voiceState:{active:mt.active,timestamp:Date.now(),manuallyDeactivated:mt.manuallyDeactivated}}))},aa=()=>{var y,P;if(((y=o.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=Fl(d.voiceState),m=!!c.active,h=Number((P=c.timestamp)!=null?P:0);mt.manuallyDeactivated=!!c.manuallyDeactivated,m&&Date.now()-h<ex&&setTimeout(()=>{var _,V;mt.active||(mt.manuallyDeactivated=!1,((V=(_=o.voiceRecognition)==null?void 0:_.provider)==null?void 0:V.type)==="runtype"?T.toggleVoice().then(()=>{mt.active=T.isVoiceActive(),ro("restore"),T.isVoiceActive()&&R()}):pr("restore"))},1e3)},ia=()=>T?Hm(T.getMessages()).filter(c=>!c.__skipPersist):[];function Pr(c){if(!(i!=null&&i.save))return;let h={messages:c?Hm(c):T?ia():[],metadata:d,artifacts:Vn.artifacts,selectedArtifactId:Vn.selectedId};try{let y=i.save(h);y instanceof Promise&&y.catch(P=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",P)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let Bo=null,la=()=>ge.querySelector("#persona-scroll-container")||Y,lr=()=>{Bo!==null&&(cancelAnimationFrame(Bo),Bo=null),Wo=!1},ls=()=>{ho!==null&&(cancelAnimationFrame(ho),ho=null),ir=!1,lr()},Ho=()=>{if(!vn()||le){Et.parentNode&&Et.remove(),Et.style.display="none";return}Et.parentNode!==de&&de.appendChild(Et),yt();let c=Fs(Y)>0;Et.style.display=go.isFollowing()||!c?"none":""},cs=()=>{go.pause()&&(ls(),Ho())},Go=()=>{go.resume(),Ho()},Yo=(c=!1)=>{go.isFollowing()&&(!c&&!Kn||(ho!==null&&(cancelAnimationFrame(ho),ho=null),ir=!0,ho=requestAnimationFrame(()=>{ho=null,ir=!1,go.isFollowing()&&ca(la(),c?220:140)})))},ca=(c,m=500)=>{let h=c.scrollTop,y=Fs(c),P=y-h;if(Math.abs(P)<1){fo=c.scrollTop;return}if(Math.abs(P)>=sa){lr(),Wo=!0,c.scrollTop=y,fo=c.scrollTop,Wo=!1;return}lr();let _=performance.now();Wo=!0;let V=O=>1-Math.pow(1-O,3),z=O=>{if(!go.isFollowing()){lr();return}let Ce=Fs(c);Ce!==y&&(y=Ce,P=y-h);let pe=O-_,ne=Math.min(pe/m,1),he=V(ne),Te=h+P*he;c.scrollTop=Te,fo=c.scrollTop,ne<1?Bo=requestAnimationFrame(z):(c.scrollTop=y,fo=c.scrollTop,Bo=null,Wo=!1)};Bo=requestAnimationFrame(z)},da=c=>{let m=new Map;c.forEach(h=>{let y=Rr.get(h.id);m.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}))}),Rr.clear(),m.forEach((h,y)=>{Rr.set(y,h)})},cr=(c,m,h)=>{var Ye,it,lt,Ie,Me,$e;let y=document.createElement("div"),_=(()=>{var ke;let I=r.find(Pe=>Pe.renderLoadingIndicator);if(I!=null&&I.renderLoadingIndicator)return I.renderLoadingIndicator;if((ke=o.loadingIndicator)!=null&&ke.render)return o.loadingIndicator.render})(),V=(I,ke)=>ke==null?!1:typeof ke=="string"?(I.textContent=ke,!0):(I.appendChild(ke),!0),z=new Set,O=new Set,Ce=r.some(I=>I.renderAskUserQuestion),pe=[],ne=[],he=o.enableComponentStreaming!==!1;if(m.forEach(I=>{var An,pn,Je,ct,Tn,gn,ur,mr,gr,Nr,_r,zt,fr,tr;z.add(I.id);let ke=Ce&&Ar(I),Pe=!ke&&I.role==="assistant"&&!I.variant&&he&&Rm(I);if(!Pe&&So.has(I.id)){let bt=c.querySelector(`#wrapper-${I.id}`);bt==null||bt.removeAttribute("data-preserve-runtime"),So.delete(I.id)}let qe=Ar(I)?`:${(An=I.agentMetadata)!=null&&An.askUserQuestionAnswered?"a":"u"}:${(pn=I.agentMetadata)!=null&&pn.askUserQuestionAnswers?Object.keys(I.agentMetadata.askUserQuestionAnswers).length:0}`:"",xe=Fu(I,ss)+qe,It=ke||Pe?null:Nu(mo,I.id,xe);if(It){y.appendChild(It.cloneNode(!0)),Ar(I)&&((Je=I.toolCall)!=null&&Je.id)&&((ct=I.agentMetadata)==null?void 0:ct.awaitingLocalTool)===!0&&!((Tn=I.agentMetadata)!=null&&Tn.askUserQuestionAnswered)&&(O.add(I.toolCall.id),wi(I,o,Le.composerOverlay));return}let st=null,Xt=r.find(bt=>!!(I.variant==="reasoning"&&bt.renderReasoning||I.variant==="tool"&&bt.renderToolCall||I.variant==="approval"&&bt.renderApproval||!I.variant&&bt.renderMessage)),dn=(gn=o.layout)==null?void 0:gn.messages;if(Ar(I)&&((ur=I.agentMetadata)==null?void 0:ur.askUserQuestionAnswered)===!0){Po.delete(I.id);let bt=c.querySelector(`#wrapper-${I.id}`);bt==null||bt.removeAttribute("data-preserve-runtime");return}if(Ar(I)&&((gr=(mr=o.features)==null?void 0:mr.askUserQuestion)==null?void 0:gr.enabled)!==!1){let bt=r.find(Pn=>typeof Pn.renderAskUserQuestion=="function");if(bt&&Rt.current){let Pn=Po.get(I.id),Oo=Pn!==xe,kn=null;if(Oo){let{payload:Vt,complete:Dt}=Xr(I),qt=I.id,Bn=()=>{var Yn;return(Yn=Rt.current)==null?void 0:Yn.getMessages().find(tn=>tn.id===qt)};kn=bt.renderAskUserQuestion({message:I,payload:Vt,complete:Dt,resolve:Yn=>{var To;let tn=Bn();tn&&((To=Rt.current)==null||To.resolveAskUserQuestion(tn,Yn))},dismiss:()=>{var tn,To,No;let Yn=Bn();(tn=Yn==null?void 0:Yn.agentMetadata)!=null&&tn.awaitingLocalTool&&((To=Rt.current)==null||To.markAskUserQuestionResolved(Yn),(No=Rt.current)==null||No.resolveAskUserQuestion(Yn,"(dismissed)"))},config:o})}let Wn=Pn!=null;if(Oo&&kn===null&&!Wn){((Nr=I.agentMetadata)==null?void 0:Nr.awaitingLocalTool)===!0&&!((_r=I.agentMetadata)!=null&&_r.askUserQuestionAnswered)&&(O.add(I.toolCall.id),wi(I,o,Le.composerOverlay));return}let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${I.id}`,Ht.setAttribute("data-wrapper-id",I.id),Ht.setAttribute("data-ask-plugin-stub","true"),Ht.setAttribute("data-preserve-runtime","true"),y.appendChild(Ht),pe.push({messageId:I.id,fingerprint:xe,bubble:kn});return}else{((zt=I.agentMetadata)==null?void 0:zt.awaitingLocalTool)===!0&&!((fr=I.agentMetadata)!=null&&fr.askUserQuestionAnswered)&&(O.add(I.toolCall.id),wi(I,o,Le.composerOverlay));return}}else if(Xt)if(I.variant==="reasoning"&&I.reasoning&&Xt.renderReasoning){if(!re)return;st=Xt.renderReasoning({message:I,defaultRenderer:()=>yl(I,o),config:o})}else if(I.variant==="tool"&&I.toolCall&&Xt.renderToolCall){if(!be)return;st=Xt.renderToolCall({message:I,defaultRenderer:()=>vl(I,o),config:o})}else if(I.variant==="approval"&&I.approval&&Xt.renderApproval){if(o.approval===!1)return;st=Xt.renderApproval({message:I,defaultRenderer:()=>El(I,o),config:o})}else Xt.renderMessage&&(st=Xt.renderMessage({message:I,defaultRenderer:()=>{let bt=bl(I,h,dn,o.messageActions,j,{loadingIndicatorRenderer:_,widgetConfig:o});return I.role!=="user"&&Rl(bt,I,o,T),bt},config:o}));if(!st&&Pe){let bt=Pm(I);if(bt){let Pn=So.get(I.id),Oo=Pn!==xe,kn=o.wrapComponentDirectiveInBubble!==!1,Wn=null;if(Oo){let Ht=Lm(bt,{config:o,message:I,transform:h});if(Ht)if(kn){let Vt=document.createElement("div");if(Vt.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(" "),Vt.id=`bubble-${I.id}`,Vt.setAttribute("data-message-id",I.id),I.content&&I.content.trim()){let Dt=document.createElement("div");Dt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Dt.innerHTML=h({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),Vt.appendChild(Dt)}Vt.appendChild(Ht),Wn=Vt}else{let Vt=document.createElement("div");if(Vt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Vt.id=`bubble-${I.id}`,Vt.setAttribute("data-message-id",I.id),Vt.setAttribute("data-persona-component-directive","true"),I.content&&I.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:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),Vt.appendChild(Dt)}Vt.appendChild(Ht),Wn=Vt}}if(Wn||Pn!=null){let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${I.id}`,Ht.setAttribute("data-wrapper-id",I.id),Ht.setAttribute("data-component-directive-stub","true"),Ht.setAttribute("data-preserve-runtime","true"),kn||Ht.classList.add("persona-w-full"),y.appendChild(Ht),ne.push({messageId:I.id,fingerprint:xe,bubble:Wn});return}}}if(!st)if(I.variant==="reasoning"&&I.reasoning){if(!re)return;st=yl(I,o)}else if(I.variant==="tool"&&I.toolCall){if(!be)return;st=vl(I,o)}else if(I.variant==="approval"&&I.approval){if(o.approval===!1)return;st=El(I,o)}else{let bt=(tr=o.layout)==null?void 0:tr.messages;bt!=null&&bt.renderUserMessage&&I.role==="user"?st=bt.renderUserMessage({message:I,config:o,streaming:!!I.streaming}):bt!=null&&bt.renderAssistantMessage&&I.role==="assistant"?st=bt.renderAssistantMessage({message:I,config:o,streaming:!!I.streaming}):st=bl(I,h,bt,o.messageActions,j,{loadingIndicatorRenderer:_,widgetConfig:o}),I.role!=="user"&&st&&Rl(st,I,o,T)}let Pt=document.createElement("div");Pt.className="persona-flex",Pt.id=`wrapper-${I.id}`,Pt.setAttribute("data-wrapper-id",I.id),I.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,I.id,xe,Pt),y.appendChild(Pt)}),Le.composerOverlay&&Le.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(ke=>{let Pe=ke.getAttribute("data-persona-ask-sheet-for");Pe&&!O.has(Pe)&&Jr(Le.composerOverlay,Pe)}),(it=(Ye=o.features)==null?void 0:Ye.toolCallDisplay)!=null&&it.grouped){let I=[],ke=[];m.forEach(Pe=>{if(Pe.variant==="tool"&&Pe.toolCall&&be){ke.push(Pe);return}ke.length>1&&I.push(ke),ke=[]}),ke.length>1&&I.push(ke),I.forEach((Pe,qe)=>{var pn,Je;let xe=Pe.map(ct=>Array.from(y.children).find(Tn=>Tn instanceof HTMLElement&&Tn.getAttribute("data-wrapper-id")===ct.id)).filter(ct=>!!ct);if(xe.length<2)return;let It=document.createElement("div");It.className="persona-flex",It.id=`wrapper-tool-group-${qe}-${Pe[0].id}`,It.setAttribute("data-wrapper-id",`tool-group-${qe}-${Pe[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 dn=`Called ${Pe.length} tools`,Pt=(Je=(pn=o.toolCall)==null?void 0:pn.renderGroupedSummary)==null?void 0:Je.call(pn,{messages:Pe,toolCalls:Pe.map(ct=>ct.toolCall).filter(ct=>!!ct),defaultSummary:dn,config:o});V(Xt,Pt)||(Xt.textContent=dn);let An=document.createElement("div");An.className="persona-tool-group-stack persona-flex persona-flex-col",st.append(Xt,An),It.appendChild(st),xe[0].before(It),xe.forEach((ct,Tn)=>{let gn=document.createElement("div");gn.className="persona-tool-group-item persona-relative",gn.setAttribute("data-persona-tool-group-item","true"),Tn<xe.length-1&&gn.setAttribute("data-persona-tool-group-connector","true"),gn.appendChild(ct),An.appendChild(gn)})})}Vu(mo,z);let Te=m.some(I=>I.role==="assistant"&&I.streaming),Be=m[m.length-1],et=(Be==null?void 0:Be.role)==="assistant"&&!Be.streaming&&Be.variant!=="approval";if(Kn&&m.some(I=>I.role==="user")&&!Te&&!et){let I={config:o,streaming:!0,location:"standalone",defaultRenderer:Ks},ke=r.find(qe=>qe.renderLoadingIndicator),Pe=null;if(ke!=null&&ke.renderLoadingIndicator&&(Pe=ke.renderLoadingIndicator(I)),Pe===null&&((lt=o.loadingIndicator)!=null&<.render)&&(Pe=o.loadingIndicator.render(I)),Pe===null&&(Pe=Ks()),Pe){let qe=document.createElement("div"),xe=((Ie=o.loadingIndicator)==null?void 0:Ie.showBubble)!==!1;qe.className=xe?["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(" "),qe.setAttribute("data-typing-indicator","true"),qe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",qe.appendChild(Pe);let It=document.createElement("div");It.className="persona-flex",It.id="wrapper-typing-indicator",It.setAttribute("data-wrapper-id","typing-indicator"),It.appendChild(qe),y.appendChild(It)}}if(!Kn&&m.length>0){let I=m[m.length-1],ke={config:o,lastMessage:I,messageCount:m.length},Pe=r.find(xe=>xe.renderIdleIndicator),qe=null;if(Pe!=null&&Pe.renderIdleIndicator&&(qe=Pe.renderIdleIndicator(ke)),qe===null&&((Me=o.loadingIndicator)!=null&&Me.renderIdle)&&(qe=o.loadingIndicator.renderIdle(ke)),qe){let xe=document.createElement("div"),It=(($e=o.loadingIndicator)==null?void 0:$e.showBubble)!==!1;xe.className=It?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),xe.setAttribute("data-idle-indicator","true"),xe.appendChild(qe);let st=document.createElement("div");st.className="persona-flex",st.id="wrapper-idle-indicator",st.setAttribute("data-wrapper-id","idle-indicator"),st.appendChild(xe),y.appendChild(st)}}if(ti(c,y),pe.length>0)for(let{messageId:I,fingerprint:ke,bubble:Pe}of pe){let qe=c.querySelector(`#wrapper-${I}`);qe&&Pe!==null&&(qe.replaceChildren(Pe),qe.setAttribute("data-bubble-fp",ke),Po.set(I,ke))}if(Po.size>0)for(let I of Po.keys())z.has(I)||Po.delete(I);if(ne.length>0)for(let{messageId:I,fingerprint:ke,bubble:Pe}of ne){let qe=c.querySelector(`#wrapper-${I}`);qe&&Pe!==null&&(qe.replaceChildren(Pe),qe.setAttribute("data-bubble-fp",ke),So.set(I,ke))}if(So.size>0)for(let I of So.keys())z.has(I)||So.delete(I)},Xo=null,pa=()=>{var h;if(Xo)return;let c=y=>{let P=y.composedPath();P.includes(ge)||_e&&P.includes(_e)||Bt(!1,"user")};Xo=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},ds=()=>{var m;if(!Xo)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",Xo,!0),Xo=null};ft.push(()=>ds());let Qo=null,ua=()=>{var h;if(Qo)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Bt(!1,"user"))};Qo=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},ps=()=>{var m;if(!Qo)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",Qo,!0),Qo=null};ft.push(()=>ps());let Jo=!1,us=new Set,ma=()=>{var m,h,y,P;let c=(y=(h=(m=o.launcher)==null?void 0:m.composerBar)==null?void 0:h.peek)==null?void 0:y.streamAnimation;return c||((P=o.features)==null?void 0:P.streamAnimation)},Do=()=>{var it,lt,Ie,Me;if(!E())return;let c=Le.peekBanner,m=Le.peekTextNode;if(!c||!m)return;if(k){c.classList.remove("persona-pill-peek--visible");return}let h=(it=T==null?void 0:T.getMessages())!=null?it:[],y;for(let $e=h.length-1;$e>=0;$e--){let I=h[$e];if(I.role==="assistant"&&I.content){y=I;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let P=y.content,_=!!y.streaming,V=ma(),z=ai(V),O=z.type!=="none"?_s(z.type,V==null?void 0:V.plugins):null,Ce=((lt=O==null?void 0:O.isAnimating)==null?void 0:lt.call(O,y))===!0,pe=O!==null&&(_||Ce);pe&&O&&!us.has(O.name)&&(pl(O,e),us.add(O.name));let ne=pe&&(O!=null&&O.containerClass)?O.containerClass:null,he=(Ie=m.dataset.personaPeekStreamClass)!=null?Ie:null;he&&he!==ne&&(m.classList.remove(he),delete m.dataset.personaPeekStreamClass),ne&&he!==ne&&(m.classList.add(ne),m.dataset.personaPeekStreamClass=ne),pe?(m.style.setProperty("--persona-stream-step",`${z.speed}ms`),m.style.setProperty("--persona-stream-duration",`${z.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let Te=pe?ii(P,z.buffer,O,y,_):P;if(pe&&z.placeholder==="skeleton"&&_&&(!Te||!Te.trim())){let $e=document.createElement("div"),I=$s();I.classList.add("persona-pill-peek__skeleton"),$e.appendChild(I),ti(m,$e)}else{let $e=Math.max(0,Te.length-100),I=Te.length>100?Te.slice(-100):Te,ke=Ls(I);if(!pe||!O){let Pe=Te.length>100?`\u2026${I}`:I;m.textContent!==Pe&&(m.textContent=Pe)}else{let Pe=ke;(O.wrap==="char"||O.wrap==="word")&&(Pe=Vs(ke,O.wrap,`peek-${y.id}`,{skipTags:O.skipTags,startIndex:$e}));let qe=document.createElement("div");if(qe.innerHTML=Pe,O.useCaret&&I.length>0){let xe=li(),It=qe.querySelectorAll(".persona-stream-char, .persona-stream-word"),st=It[It.length-1];st!=null&&st.parentNode?st.parentNode.insertBefore(xe,st.nextSibling):qe.appendChild(xe)}ti(m,qe),(Me=O.onAfterRender)==null||Me.call(O,{container:m,bubble:c,messageId:y.id,message:y,speed:z.speed,duration:z.duration})}}let Ye=Kn||Jo;c.classList.toggle("persona-pill-peek--visible",Ye)};if(E()){let c=Le.peekBanner;if(c){let y=P=>{P.preventDefault(),P.stopPropagation(),Bt(!0,"user")};c.addEventListener("pointerdown",y),ft.push(()=>{c.removeEventListener("pointerdown",y)})}let m=()=>{Jo||(Jo=!0,Do())},h=()=>{Jo&&(Jo=!1,Do())};ce.addEventListener("pointerenter",m),ce.addEventListener("pointerleave",h),ft.push(()=>{ce.removeEventListener("pointerenter",m),ce.removeEventListener("pointerleave",h)}),_e&&(_e.addEventListener("pointerenter",m),_e.addEventListener("pointerleave",h),ft.push(()=>{_e.removeEventListener("pointerenter",m),_e.removeEventListener("pointerleave",h)}))}let ga=c=>{var he,Te,Be,et,Ye,it,lt,Ie;let m=(Te=(he=o.launcher)==null?void 0:he.composerBar)!=null?Te:{},h=(Be=m.expandedSize)!=null?Be:"anchored",y=(et=m.bottomOffset)!=null?et:"16px",P=m.collapsedMaxWidth,_=(Ye=m.expandedMaxWidth)!=null?Ye:"880px",V=(it=m.expandedTopOffset)!=null?it:"5vh",z=(lt=m.modalMaxWidth)!=null?lt:"880px",O=(Ie=m.modalMaxHeight)!=null?Ie:"min(90vh, 800px)",Ce="calc(100vw - 32px)",pe="var(--persona-pill-area-height, 80px)",ne=ge.style;if(ne.left="",ne.right="",ne.top="",ne.bottom="",ne.transform="",ne.width="",ne.maxWidth="",ne.height="",ne.maxHeight="",_e){let Me=_e.style;Me.bottom=y,Me.width=P!=null?P:""}if(c&&h!=="fullscreen"){if(h==="modal"){ne.top="50%",ne.left="50%",ne.transform="translate(-50%, -50%)",ne.bottom="auto",ne.right="auto",ne.width=z,ne.maxWidth=Ce,ne.maxHeight=O,ne.height=O;return}ne.left="50%",ne.transform="translateX(-50%)",ne.bottom=`calc(${y} + ${pe})`,ne.top=V,ne.width=_,ne.maxWidth=Ce}},Zo=()=>{var O,Ce,pe,ne,he,Te,Be,et;if(!S())return;if(E()){let it=(pe=((Ce=(O=o.launcher)==null?void 0:O.composerBar)!=null?Ce:{}).expandedSize)!=null?pe:"anchored",lt=k?"expanded":"collapsed";ge.dataset.state=lt,ge.dataset.expandedSize=it,_e&&(_e.dataset.state=lt,_e.dataset.expandedSize=it),ge.style.removeProperty("display"),ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ga(k),de.style.display=k?"flex":"none",po(),k?(pa(),ua()):(ds(),ps()),Do();return}let c=un(o),m=(ne=e.ownerDocument.defaultView)!=null?ne:window,h=(Te=(he=o.launcher)==null?void 0:he.mobileBreakpoint)!=null?Te:640,y=(et=(Be=o.launcher)==null?void 0:Be.mobileFullscreen)!=null?et:!0,P=m.innerWidth<=h,_=y&&P&&W,V=Mo(o).reveal;k?(ge.style.removeProperty("display"),ge.style.display=c?"flex":"",ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-95","persona-opacity-0"),ce.classList.add("persona-scale-100","persona-opacity-100"),Ge?Ge.element.style.display="none":Qe&&(Qe.style.display="none")):(c?c&&(V==="overlay"||V==="push")&&!_?(ge.style.removeProperty("display"),ge.style.display="flex",ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ge.style.setProperty("display","none","important"),ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ge.style.display="",ge.classList.add("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-100","persona-opacity-100"),ce.classList.add("persona-scale-95","persona-opacity-0")),Ge?Ge.element.style.display=c?"none":"":Qe&&(Qe.style.display=c?"none":""))},Bt=(c,m="user")=>{var _,V;if(!S()||k===c)return;let h=k;k=c,Zo();let y=(()=>{var Be,et,Ye,it,lt,Ie,Me,$e,I,ke;let z=(et=(Be=o.launcher)==null?void 0:Be.sidebarMode)!=null?et:!1,O=(Ye=e.ownerDocument.defaultView)!=null?Ye:window,Ce=(lt=(it=o.launcher)==null?void 0:it.mobileFullscreen)!=null?lt:!0,pe=(Me=(Ie=o.launcher)==null?void 0:Ie.mobileBreakpoint)!=null?Me:640,ne=O.innerWidth<=pe,he=un(o)&&Ce&&ne,Te=E()&&((ke=(I=($e=o.launcher)==null?void 0:$e.composerBar)==null?void 0:I.expandedSize)!=null?ke:"fullscreen")==="fullscreen";return z||Ce&&ne&&W||he||Te})();if(k&&y){if(!Kt){let z=e.getRootNode(),O=z instanceof ShadowRoot?z.host:e.closest(".persona-host");O&&(Kt=ul(O,(V=(_=o.launcher)==null?void 0:_.zIndex)!=null?V:bn))}Gt||(Gt=ml(e.ownerDocument))}else k||(Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null);k&&(Yt(),Yo(!0));let P={open:k,source:m,timestamp:Date.now()};k&&!h?s.emit("widget:opened",P):!k&&h&&s.emit("widget:closed",P),s.emit("widget:state",{open:k,launcherEnabled:W,voiceActive:mt.active,streaming:T.isStreaming()})},Wr=c=>{jt(c?"stop":"send"),K&&(K.disabled=c),uo.buttons.forEach(m=>{m.disabled=c}),Ne.dataset.personaComposerStreaming=c?"true":"false",Ne.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=c)})},Br=()=>{mt.active||Q&&Q.focus()};s.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Br(),200)});let ms=()=>{var h,y,P,_,V,z,O,Ce,pe,ne,he;Dn.textContent=(y=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",Jn.textContent=(_=(P=o.copy)==null?void 0:P.welcomeSubtitle)!=null?_:"Ask anything about your account or products.",Q.placeholder=(z=(V=o.copy)==null?void 0:V.inputPlaceholder)!=null?z:"How can I help...";let c=Y.querySelector("[data-persona-intro-card]");if(c){let Te=((O=o.copy)==null?void 0:O.showWelcomeCard)!==!1;c.style.display=Te?"":"none",Te?(Y.classList.remove("persona-gap-3"),Y.classList.add("persona-gap-6")):(Y.classList.remove("persona-gap-6"),Y.classList.add("persona-gap-3"))}!((pe=(Ce=o.sendButton)==null?void 0:Ce.useIcon)!=null&&pe)&&!(T!=null&&T.isStreaming())&&(Fe.textContent=(he=(ne=o.copy)==null?void 0:ne.sendButtonLabel)!=null?he:"Send"),Q.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Q.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=>{g(m=>({...m,sessionId:c}))}});let Ao=null,fa=()=>{Ao==null&&(Ao=setInterval(()=>{let c=Ve.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Ao),Ao=null;return}let m=Date.now();c.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=Ua(m-y))})},100))};if(T=new Za(o,{onMessagesChanged(c){cr(Ve,c,me),fa(),T&&(c.some(P=>P.role==="user")?uo.render([],T,Q,c):uo.render(o.suggestionChips,T,Q,c,o.suggestionChipsConfig)),Yo(!Kn),da(c);let m=[...c].reverse().find(y=>y.role==="user"),h=mt.lastUserMessageId;m&&m.id!==h&&(mt.lastUserMessageId=m.id,s.emit("user:message",m)),mt.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),Pr(c),Do()},onStatusChanged(c){var y;let m=(y=o.statusIndicator)!=null?y:{};tt(ln,(P=>{var _,V,z,O;return P==="idle"?(_=m.idleText)!=null?_:hn.idle:P==="connecting"?(V=m.connectingText)!=null?V:hn.connecting:P==="connected"?(z=m.connectedText)!=null?z:hn.connected:P==="error"?(O=m.errorText)!=null?O:hn.error:hn[P]})(c),m,c)},onStreamingChanged(c){Kn=c,Wr(c),T&&cr(Ve,T.getMessages(),me),c||Yo(!0),Do()},onVoiceStatusChanged(c){var m,h;if(((h=(m=o.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype")switch(c){case"listening":break;case"processing":G(),ee();break;case"speaking":G(),te();break;default:c==="idle"&&T.isBargeInActive()?(G(),R(),K==null||K.setAttribute("aria-label","End voice session")):(mt.active=!1,G(),ro("system"),Rn());break}},onArtifactsState(c){Vn=c,zn(),Pr()}}),Rt.current=T,((zc=(Uc=o.voiceRecognition)==null?void 0:Uc.provider)==null?void 0:zc.type)==="runtype")try{T.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}o.clientToken&&T.initClientSession().catch(c=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(X||o.onSSEEvent)&&T.setSSEEventCallback((c,m)=>{var h;(h=o.onSSEEvent)==null||h.call(o,c,m),Ae==null||Ae.processEvent(c,m),X==null||X.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(m)})}),l&&l.then(c=>{var m,h,y;c&&(c.metadata&&(d=Fl(c.metadata),M.syncFromMetadata()),(m=c.messages)!=null&&m.length&&T.hydrateMessages(c.messages),(h=c.artifacts)!=null&&h.length&&T.hydrateArtifacts(c.artifacts,(y=c.selectedArtifactId)!=null?y:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let gs=()=>{var m,h,y;!E()||k||!((y=(h=(m=o.launcher)==null?void 0:m.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||Bt(!0,"auto")},fs=c=>{var P;if(c.preventDefault(),T.isStreaming()){T.cancel(),Ae==null||Ae.reset(),fe==null||fe.update();return}let m=Q.value.trim(),h=(P=Ze==null?void 0:Ze.hasAttachments())!=null?P:!1;if(!m&&!h)return;gs();let y;h&&(y=[],y.push(...Ze.getContentParts()),m&&y.push(il(m))),Q.value="",Q.style.height="auto",dr(),T.sendMessage(m,{contentParts:y}),h&&Ze.clearAttachments()},ha=()=>{var c;return((c=o.features)==null?void 0:c.composerHistory)!==!1},Hr={...ni},Dr=!1,dr=()=>{Hr={...ni}},ba=()=>T.getMessages().filter(c=>c.role==="user").map(c=>{var m;return(m=c.content)!=null?m:""}).filter(c=>c.length>0),ya=c=>{if(!Q)return;Dr=!0,Q.value=c,Q.dispatchEvent(new Event("input",{bubbles:!0})),Dr=!1;let m=Q.value.length;Q.setSelectionRange(m,m)},hs=()=>{Dr||dr()},bs=c=>{if(Q){if(ha()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let m=Q.selectionStart===0&&Q.selectionEnd===0,h=Du({direction:c.key==="ArrowUp"?"up":"down",history:ba(),currentValue:Q.value,atStart:m,state:Hr});if(Hr=h.state,h.handled){c.preventDefault(),h.value!==void 0&&ya(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(T.isStreaming()){c.preventDefault();return}dr(),c.preventDefault(),Fe.click()}}},ys=c=>{c.key!=="Escape"||c.isComposing||T.isStreaming()&&c.composedPath().includes(de)&&(T.cancel(),Ae==null||Ae.reset(),fe==null||fe.update(),dr(),c.preventDefault(),c.stopImmediatePropagation())},vs=async c=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!Ze)return;let m=nx(c.clipboardData);m.length!==0&&(c.preventDefault(),await Ze.handleFiles(m))},Sn=null,Gn=!1,Fo=null,rt=null,xs=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,pr=(c="user")=>{var _,V,z,O,Ce,pe,ne;if(Gn||T.isStreaming())return;let m=xs();if(!m)return;Sn=new m;let y=(V=((_=o.voiceRecognition)!=null?_:{}).pauseDuration)!=null?V:2e3;Sn.continuous=!0,Sn.interimResults=!0,Sn.lang="en-US";let P=Q.value;Sn.onresult=he=>{let Te="",Be="";for(let Ye=0;Ye<he.results.length;Ye++){let it=he.results[Ye],lt=it[0].transcript;it.isFinal?Te+=lt+" ":Be=lt}let et=P+Te+Be;Q.value=et,Fo&&clearTimeout(Fo),(Te||Be)&&(Fo=window.setTimeout(()=>{let Ye=Q.value.trim();Ye&&Sn&&Gn&&(bo(),Q.value="",Q.style.height="auto",T.sendMessage(Ye,{viaVoice:!0}))},y))},Sn.onerror=he=>{he.error!=="no-speech"&&bo()},Sn.onend=()=>{if(Gn){let he=Q.value.trim();he&&he!==P.trim()&&(Q.value="",Q.style.height="auto",T.sendMessage(he,{viaVoice:!0})),bo()}};try{if(Sn.start(),Gn=!0,mt.active=!0,c!=="system"&&(mt.manuallyDeactivated=!1),ro(c),Rn(),K){let he=(z=o.voiceRecognition)!=null?z:{};rt={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:(O=he.iconName)!=null?O:"mic",iconSize:parseFloat((ne=(pe=he.iconSize)!=null?pe:(Ce=o.sendButton)==null?void 0:Ce.size)!=null?ne:"40")||24};let Te=he.recordingBackgroundColor,Be=he.recordingIconColor,et=he.recordingBorderColor;if(K.classList.add("persona-voice-recording"),K.style.backgroundColor=Te!=null?Te:"var(--persona-voice-recording-bg, #ef4444)",K.style.color=Be!=null?Be:"var(--persona-voice-recording-indicator, #ffffff)",Be){let Ye=K.querySelector("svg");Ye&&Ye.setAttribute("stroke",Be)}et&&(K.style.borderColor=et),K.setAttribute("aria-label","Stop voice recognition")}}catch{bo("system")}},bo=(c="user")=>{if(Gn){if(Gn=!1,Fo&&(clearTimeout(Fo),Fo=null),Sn){try{Sn.stop()}catch{}Sn=null}if(mt.active=!1,ro(c),Rn(),K){if(K.classList.remove("persona-voice-recording"),rt){K.style.backgroundColor=rt.backgroundColor,K.style.color=rt.color,K.style.borderColor=rt.borderColor;let m=K.querySelector("svg");m&&m.setAttribute("stroke",rt.color||"currentColor"),rt=null}K.setAttribute("aria-label","Start voice recognition")}}},Fr=(c,m)=>{var it,lt,Ie,Me,$e,I,ke,Pe;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((it=c==null?void 0:c.provider)==null?void 0:it.type)==="runtype";if(!(h||y))return null;let _=b("div","persona-send-button-wrapper"),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=(lt=c==null?void 0:c.iconName)!=null?lt:"mic",O=(Ie=m==null?void 0:m.size)!=null?Ie:"40px",Ce=(Me=c==null?void 0:c.iconSize)!=null?Me:O,pe=parseFloat(Ce)||24,ne=($e=c==null?void 0:c.backgroundColor)!=null?$e:m==null?void 0:m.backgroundColor,he=(I=c==null?void 0:c.iconColor)!=null?I:m==null?void 0:m.textColor;V.style.width=Ce,V.style.height=Ce,V.style.minWidth=Ce,V.style.minHeight=Ce,V.style.fontSize="18px",V.style.lineHeight="1",he?V.style.color=he:V.style.color="var(--persona-text, #111827)";let Be=Se(z,pe,he||"currentColor",1.5);Be?V.appendChild(Be):V.textContent="\u{1F3A4}",ne?V.style.backgroundColor=ne: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),_.appendChild(V);let et=(ke=c==null?void 0:c.tooltipText)!=null?ke:"Start voice recognition";if(((Pe=c==null?void 0:c.showTooltip)!=null?Pe:!1)&&et){let qe=b("div","persona-send-button-tooltip");qe.textContent=et,_.appendChild(qe)}return{micButton:V,micButtonWrapper:_}},Ue=()=>{var m,h,y,P,_;if(!K||rt)return;let c=(m=o.voiceRecognition)!=null?m:{};rt={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:(h=c.iconName)!=null?h:"mic",iconSize:parseFloat((_=(P=c.iconSize)!=null?P:(y=o.sendButton)==null?void 0:y.size)!=null?_:"40")||24}},A=(c,m)=>{var _,V,z,O,Ce;if(!K)return;let h=K.querySelector("svg");h&&h.remove();let y=(Ce=rt==null?void 0:rt.iconSize)!=null?Ce:parseFloat((O=(z=(_=o.voiceRecognition)==null?void 0:_.iconSize)!=null?z:(V=o.sendButton)==null?void 0:V.size)!=null?O:"40")||24,P=Se(c,y,m,1.5);P&&K.appendChild(P)},U=()=>{K&&K.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},R=()=>{var P;if(!K)return;Ue();let c=(P=o.voiceRecognition)!=null?P:{},m=c.recordingBackgroundColor,h=c.recordingIconColor,y=c.recordingBorderColor;if(U(),K.classList.add("persona-voice-recording"),K.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",K.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let _=K.querySelector("svg");_&&_.setAttribute("stroke",h)}y&&(K.style.borderColor=y),K.setAttribute("aria-label","Stop voice recognition")},ee=()=>{var z,O,Ce,pe,ne,he,Te,Be;if(!K)return;Ue();let c=(z=o.voiceRecognition)!=null?z:{},m=T.getVoiceInterruptionMode(),h=(O=c.processingIconName)!=null?O:"loader",y=(pe=(Ce=c.processingIconColor)!=null?Ce:rt==null?void 0:rt.color)!=null?pe:"",P=(he=(ne=c.processingBackgroundColor)!=null?ne:rt==null?void 0:rt.backgroundColor)!=null?he:"",_=(Be=(Te=c.processingBorderColor)!=null?Te:rt==null?void 0:rt.borderColor)!=null?Be:"";U(),K.classList.add("persona-voice-processing"),K.style.backgroundColor=P,K.style.borderColor=_;let V=y||"currentColor";K.style.color=V,A(h,V),K.setAttribute("aria-label","Processing voice input"),m==="none"&&(K.style.cursor="default")},te=()=>{var Ce,pe,ne,he,Te,Be,et,Ye,it,lt,Ie,Me;if(!K)return;Ue();let c=(Ce=o.voiceRecognition)!=null?Ce:{},m=T.getVoiceInterruptionMode(),h=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",y=(pe=c.speakingIconName)!=null?pe:h,P=(Be=c.speakingIconColor)!=null?Be:m==="barge-in"?(he=(ne=c.recordingIconColor)!=null?ne:rt==null?void 0:rt.color)!=null?he:"":(Te=rt==null?void 0:rt.color)!=null?Te:"",_=(it=c.speakingBackgroundColor)!=null?it:m==="barge-in"?(et=c.recordingBackgroundColor)!=null?et:"var(--persona-voice-recording-bg, #ef4444)":(Ye=rt==null?void 0:rt.backgroundColor)!=null?Ye:"",V=(Me=c.speakingBorderColor)!=null?Me:m==="barge-in"?(lt=c.recordingBorderColor)!=null?lt:"":(Ie=rt==null?void 0:rt.borderColor)!=null?Ie:"";U(),K.classList.add("persona-voice-speaking"),K.style.backgroundColor=_,K.style.borderColor=V;let z=P||"currentColor";K.style.color=z,A(y,z);let O=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";K.setAttribute("aria-label",O),m==="none"&&(K.style.cursor="default"),m==="barge-in"&&K.classList.add("persona-voice-recording")},G=()=>{var c,m,h;K&&(U(),rt&&(K.style.backgroundColor=(c=rt.backgroundColor)!=null?c:"",K.style.color=(m=rt.color)!=null?m:"",K.style.borderColor=(h=rt.borderColor)!=null?h:"",A(rt.iconName,rt.color||"currentColor"),rt=null),K.style.cursor="",K.setAttribute("aria-label","Start voice recognition"))},ze=()=>{var c,m;if(((m=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"){let h=T.getVoiceStatus(),y=T.getVoiceInterruptionMode();if(y==="none"&&(h==="processing"||h==="speaking"))return;if(y==="cancel"&&(h==="processing"||h==="speaking")){T.stopVoicePlayback();return}if(T.isBargeInActive()){T.stopVoicePlayback(),T.deactivateBargeIn().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Rn(),ro("user"),G()});return}T.toggleVoice().then(()=>{mt.active=T.isVoiceActive(),mt.manuallyDeactivated=!T.isVoiceActive(),Rn(),ro("user"),T.isVoiceActive()?R():G()});return}if(Gn){let h=Q.value.trim();mt.manuallyDeactivated=!0,Rn(),bo("user"),h&&(Q.value="",Q.style.height="auto",T.sendMessage(h))}else mt.manuallyDeactivated=!1,Rn(),pr("user")};Fn=ze,K&&(K.addEventListener("click",ze),ft.push(()=>{var c,m;((m=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?(T.isVoiceActive()&&T.toggleVoice(),G()):bo("system"),K&&K.removeEventListener("click",ze)}));let De=s.on("assistant:complete",()=>{is&&(mt.active||mt.manuallyDeactivated||is==="assistant"&&!mt.lastUserMessageWasVoice||setTimeout(()=>{var c,m;!mt.active&&!mt.manuallyDeactivated&&(((m=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?T.toggleVoice().then(()=>{mt.active=T.isVoiceActive(),ro("auto"),T.isVoiceActive()&&R()}):pr("auto"))},600))});ft.push(De);let at=s.on("action:resubmit",()=>{setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)});ft.push(at);let Ke=()=>{Bt(!k,"user")},Ge=null,Qe=null;if(W&&!E()){let c=r.find(m=>m.renderLauncher);if(c!=null&&c.renderLauncher){let m=c.renderLauncher({config:o,defaultRenderer:()=>qs(o,Ke).element,onToggle:Ke});m&&(Qe=m)}Qe||(Ge=qs(o,Ke))}Ge?e.appendChild(Ge.element):Qe&&e.appendChild(Qe),Zo(),uo.render(o.suggestionChips,T,Q,void 0,o.suggestionChipsConfig),ms(),Wr(T.isStreaming()),Yo(!0),aa(),H&&(!W||E()?setTimeout(()=>Br(),0):k&&setTimeout(()=>Br(),200));let Yt=()=>{var O,Ce,pe,ne,he,Te,Be,et,Ye,it,lt,Ie,Me,$e,I,ke,Pe,qe,xe,It,st,Xt;if(E()){yt(),Zo();return}let c=un(o),m=(Ce=(O=o.launcher)==null?void 0:O.sidebarMode)!=null?Ce:!1,h=c||m||((ne=(pe=o.launcher)==null?void 0:pe.fullHeight)!=null?ne:!1),y=(he=e.ownerDocument.defaultView)!=null?he:window,P=(Be=(Te=o.launcher)==null?void 0:Te.mobileFullscreen)!=null?Be:!0,_=(Ye=(et=o.launcher)==null?void 0:et.mobileBreakpoint)!=null?Ye:640,V=y.innerWidth<=_,z=P&&V&&W;try{if(z){po(),$r(e,o);return}if(w&&(w=!1,po(),$r(e,o)),!W&&!c){ce.style.height="",ce.style.width="";return}if(!m&&!c){let dn=(lt=(it=o==null?void 0:o.launcher)==null?void 0:it.width)!=null?lt:o==null?void 0:o.launcherWidth,Pt=dn!=null?dn:io;ce.style.width=Pt,ce.style.maxWidth=Pt}if(Co(),!h){let dn=y.innerHeight,Pt=64,An=(Me=(Ie=o.launcher)==null?void 0:Ie.heightOffset)!=null?Me:0,pn=Math.max(200,dn-Pt),Je=Math.min(640,pn),ct=Math.max(200,Je-An);ce.style.height=`${ct}px`}}finally{if(yt(),Zo(),k&&W){let Pt=(($e=e.ownerDocument.defaultView)!=null?$e:window).innerWidth<=((ke=(I=o.launcher)==null?void 0:I.mobileBreakpoint)!=null?ke:640),An=(qe=(Pe=o.launcher)==null?void 0:Pe.sidebarMode)!=null?qe:!1,pn=(It=(xe=o.launcher)==null?void 0:xe.mobileFullscreen)!=null?It:!0,Je=un(o)&&pn&&Pt,ct=An||pn&&Pt&&W||Je;if(ct&&!Gt){let Tn=e.getRootNode(),gn=Tn instanceof ShadowRoot?Tn.host:e.closest(".persona-host");gn&&!Kt&&(Kt=ul(gn,(Xt=(st=o.launcher)==null?void 0:st.zIndex)!=null?Xt:bn)),Gt=ml(e.ownerDocument)}else ct||(Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null)}}};Yt();let Tt=(qc=e.ownerDocument.defaultView)!=null?qc:window;if(Tt.addEventListener("resize",Yt),ft.push(()=>Tt.removeEventListener("resize",Yt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{yt()});c.observe(Ne),ft.push(()=>c.disconnect())}fo=Y.scrollTop;let Lt=Y.scrollHeight,on=()=>{let c=Y.scrollTop,m=Y.scrollHeight,h=m<Lt;Lt=m;let{action:y,nextLastScrollTop:P}=ri({following:go.isFollowing(),currentScrollTop:c,lastScrollTop:fo,nearBottom:Os(Y,as),userScrollThreshold:ra,isAutoScrolling:Wo||ir||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(fo=P,y==="resume"){Go();return}y==="pause"&&cs()};Y.addEventListener("scroll",on,{passive:!0}),ft.push(()=>Y.removeEventListener("scroll",on));let mn=c=>{let m=si({following:go.isFollowing(),deltaY:c.deltaY,nearBottom:Os(Y,as),resumeWhenNearBottom:!0});m==="pause"?cs():m==="resume"&&Go()};Y.addEventListener("wheel",mn,{passive:!0}),ft.push(()=>Y.removeEventListener("wheel",mn)),Et.addEventListener("click",()=>{Y.scrollTop=Y.scrollHeight,fo=Y.scrollTop,Go(),Yo(!0)}),ft.push(()=>Et.remove()),ft.push(()=>{ls()});let cn=()=>{N&&(jn&&(N.removeEventListener("click",jn),jn=null),S()?(N.style.display="",jn=()=>{Bt(!1,"user")},N.addEventListener("click",jn)):N.style.display="none")};cn(),(()=>{let{clearChatButton:c}=Le;c&&c.addEventListener("click",()=>{T.clearMessages(),mo.clear(),Go(),Jr(Le.composerOverlay);try{localStorage.removeItem(es),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${es}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==es)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),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(),X==null||X.clear(),Ae==null||Ae.reset(),fe==null||fe.update()})})(),Ft&&Ft.addEventListener("submit",fs),Q==null||Q.addEventListener("keydown",bs),Q==null||Q.addEventListener("input",hs),Q==null||Q.addEventListener("paste",vs);let so=(jc=e.ownerDocument)!=null?jc:document;so.addEventListener("keydown",ys,!0);let Jl="persona-attachment-drop-active",ws=0,$i=()=>{ws=0,de.classList.remove(Jl)},Or=()=>{var c;return((c=o.attachments)==null?void 0:c.enabled)===!0&&Ze!==null},Zl=c=>{!ki(c.dataTransfer)||!Or()||(ws++,ws===1&&de.classList.add(Jl))},ec=c=>{!ki(c.dataTransfer)||!Or()||(ws--,ws<=0&&$i())},tc=c=>{!ki(c.dataTransfer)||!Or()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},nc=c=>{var h;if(!ki(c.dataTransfer)||!Or())return;c.preventDefault(),c.stopPropagation(),$i();let m=Array.from((h=c.dataTransfer.files)!=null?h:[]);m.length!==0&&Ze.handleFiles(m)},er=!0;de.addEventListener("dragenter",Zl,er),de.addEventListener("dragleave",ec,er),e.addEventListener("dragover",tc,er),e.addEventListener("drop",nc,er);let va=e.ownerDocument,oc=c=>{Or()&&c.preventDefault()},rc=c=>{Or()&&c.preventDefault()};va.addEventListener("dragover",oc),va.addEventListener("drop",rc),ft.push(()=>{Ft&&Ft.removeEventListener("submit",fs),Q==null||Q.removeEventListener("keydown",bs),Q==null||Q.removeEventListener("input",hs),Q==null||Q.removeEventListener("paste",vs),so.removeEventListener("keydown",ys,!0)}),ft.push(()=>{de.removeEventListener("dragenter",Zl,er),de.removeEventListener("dragleave",ec,er),e.removeEventListener("dragover",tc,er),e.removeEventListener("drop",nc,er),va.removeEventListener("dragover",oc),va.removeEventListener("drop",rc),$i()}),ft.push(()=>{T.cancel()}),Ge?ft.push(()=>{Ge==null||Ge.destroy()}):Qe&&ft.push(()=>{Qe==null||Qe.remove()});let en={update(c){var tn,To,No,xa,wa,Ca,hr,Sa,Cs,Zc,ed,td,nd,od,rd,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,bd,yd,vd,xd,wd,Cd,Sd,Ad,Td,kd,Ed,Md,Ld,Id,Rd,Pd,Wd,Bd,Hd,Dd,Fd,Od,Nd,_d,Vd,$d,Ud,zd,qd,jd,Kd,Gd,Yd,Xd,Qd,Jd,Zd,ep,tp,np,op,rp,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,bp,yp,vp,xp,wp,Cp,Sp,Ap,Tp,kp,Ep,Mp,Lp,Ip,Rp,Pp,Wp,Bp,Hp,Dp,Fp,Op,Np,_p,Vp,$p,Up,zp,qp,jp,Kp,Gp;let m=o.toolCall,h=o.messageActions,y=(tn=o.layout)==null?void 0:tn.messages,P=o.colorScheme,_=o.loadingIndicator,V=o.iterationDisplay,z=(To=o.features)==null?void 0:To.showReasoning,O=(No=o.features)==null?void 0:No.showToolCalls,Ce=(xa=o.features)==null?void 0:xa.toolCallDisplay,pe=(wa=o.features)==null?void 0:wa.reasoningDisplay;o={...o,...c},po(),$r(e,o),Ai(e,o),Ti(e,o),zn(),o.colorScheme!==P&&Ko();let ne=Wl.getForInstance(o.plugins);r.length=0,r.push(...ne),W=(hr=(Ca=o.launcher)==null?void 0:Ca.enabled)!=null?hr:!0,L=(Cs=(Sa=o.launcher)==null?void 0:Sa.autoExpand)!=null?Cs:!1,re=(ed=(Zc=o.features)==null?void 0:Zc.showReasoning)!=null?ed:!0,be=(nd=(td=o.features)==null?void 0:td.showToolCalls)!=null?nd:!0,we=(rd=(od=o.features)==null?void 0:od.scrollToBottom)!=null?rd:{},Ut(),Ho();let he=ie;if(ie=(ad=(sd=o.features)==null?void 0:sd.showEventStreamToggle)!=null?ad:!1,ie&&!he){if(X||(Z=new Xs(ye),X=new Ys(Ee,Z),Ae=Ae!=null?Ae:new Qs,Z.open().then(()=>X==null?void 0:X.restore()).catch(()=>{}),T.setSSEEventCallback((J,xt)=>{var Ot;(Ot=o.onSSEEvent)==null||Ot.call(o,J,xt),Ae==null||Ae.processEvent(J,xt),X.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:J,timestamp:Date.now(),payload:JSON.stringify(xt)})})),!ut&&Oe){let J=(ld=(id=o.features)==null?void 0:id.eventStream)==null?void 0:ld.classNames,xt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(J!=null&&J.toggleButton?" "+J.toggleButton:"");ut=b("button",xt),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=Se("activity","18px","currentColor",1.5);Ot&&ut.appendChild(Ot);let dt=Le.clearChatButtonWrapper,Mt=Le.closeButtonWrapper,rn=dt||Mt;rn&&rn.parentNode===Oe?Oe.insertBefore(ut,rn):Oe.appendChild(ut),ut.addEventListener("click",()=>{le?On():xn()})}}else!ie&&he&&(On(),ut&&(ut.remove(),ut=null),X==null||X.clear(),Z==null||Z.destroy(),X=null,Z=null,Ae==null||Ae.reset(),Ae=null);if(((cd=o.launcher)==null?void 0:cd.enabled)===!1&&Ge&&(Ge.destroy(),Ge=null),((dd=o.launcher)==null?void 0:dd.enabled)===!1&&Qe&&(Qe.remove(),Qe=null),((pd=o.launcher)==null?void 0:pd.enabled)!==!1&&!Ge&&!Qe){let J=r.find(xt=>xt.renderLauncher);if(J!=null&&J.renderLauncher){let xt=J.renderLauncher({config:o,defaultRenderer:()=>qs(o,Ke).element,onToggle:Ke});xt&&(Qe=xt,e.appendChild(Qe))}Qe||(Ge=qs(o,Ke),e.appendChild(Ge.element))}Ge&&Ge.update(o),He&&((ud=o.launcher)==null?void 0:ud.title)!==void 0&&(He.textContent=o.launcher.title),Xe&&((md=o.launcher)==null?void 0:md.subtitle)!==void 0&&(Xe.textContent=o.launcher.subtitle);let Te=(gd=o.layout)==null?void 0:gd.header;if((Te==null?void 0:Te.layout)!==v&&Oe){let J=Te?ui(o,Te,{showClose:S(),onClose:()=>Bt(!1,"user")}):Sr({config:o,showClose:S(),onClose:()=>Bt(!1,"user")});Oe.replaceWith(J.header),Oe=J.header,se=J.iconHolder,He=J.headerTitle,Xe=J.headerSubtitle,N=J.closeButton,v=Te==null?void 0:Te.layout}else if(Te&&(se&&(se.style.display=Te.showIcon===!1?"none":""),He&&(He.style.display=Te.showTitle===!1?"none":""),Xe&&(Xe.style.display=Te.showSubtitle===!1?"none":""),N&&(N.style.display=Te.showCloseButton===!1?"none":""),Le.clearChatButtonWrapper)){let J=Te.showClearChat;if(J!==void 0){Le.clearChatButtonWrapper.style.display=J?"":"none";let{closeButtonWrapper:xt}=Le;xt&&!xt.classList.contains("persona-absolute")&&(J?xt.classList.remove("persona-ml-auto"):xt.classList.add("persona-ml-auto"))}}let et=((fd=o.layout)==null?void 0:fd.showHeader)!==!1;Oe&&(Oe.style.display=et?"":"none");let Ye=((hd=o.layout)==null?void 0:hd.showFooter)!==!1;Ne&&(Ne.style.display=Ye?"":"none"),yt(),Ho(),W!==B?W?Bt(L,"auto"):(k=!0,Zo()):L!==D&&Bt(L,"auto"),D=L,B=W,Yt(),cn();let Ie=JSON.stringify(c.toolCall)!==JSON.stringify(m),Me=JSON.stringify(o.messageActions)!==JSON.stringify(h),$e=JSON.stringify((bd=o.layout)==null?void 0:bd.messages)!==JSON.stringify(y),I=((yd=o.loadingIndicator)==null?void 0:yd.render)!==(_==null?void 0:_.render)||((vd=o.loadingIndicator)==null?void 0:vd.renderIdle)!==(_==null?void 0:_.renderIdle)||((xd=o.loadingIndicator)==null?void 0:xd.showBubble)!==(_==null?void 0:_.showBubble),ke=o.iterationDisplay!==V,Pe=((Cd=(wd=o.features)==null?void 0:wd.showReasoning)!=null?Cd:!0)!==(z!=null?z:!0)||((Ad=(Sd=o.features)==null?void 0:Sd.showToolCalls)!=null?Ad:!0)!==(O!=null?O:!0)||JSON.stringify((Td=o.features)==null?void 0:Td.toolCallDisplay)!==JSON.stringify(Ce)||JSON.stringify((kd=o.features)==null?void 0:kd.reasoningDisplay)!==JSON.stringify(pe);(Ie||Me||$e||I||ke||Pe)&&T&&(ss++,cr(Ve,T.getMessages(),me));let xe=(Ed=o.launcher)!=null?Ed:{},It=(Md=xe.headerIconHidden)!=null?Md:!1,st=(Id=(Ld=o.layout)==null?void 0:Ld.header)==null?void 0:Id.showIcon,Xt=It||st===!1,dn=xe.headerIconName,Pt=(Rd=xe.headerIconSize)!=null?Rd:"48px";if(se){let J=de.querySelector(".persona-border-b-persona-divider"),xt=J==null?void 0:J.querySelector(".persona-flex-col");if(Xt)se.style.display="none",J&&xt&&!J.contains(xt)&&J.insertBefore(xt,J.firstChild);else{if(se.style.display="",se.style.height=Pt,se.style.width=Pt,J&&xt&&(J.contains(se)?se.nextSibling!==xt&&(se.remove(),J.insertBefore(se,xt)):J.insertBefore(se,xt)),dn){let dt=parseFloat(Pt)||24,Mt=Se(dn,dt*.6,"#ffffff",2);Mt?se.replaceChildren(Mt):se.textContent=(Pd=xe.agentIconText)!=null?Pd:"\u{1F4AC}"}else if(xe.iconUrl){let dt=se.querySelector("img");if(dt)dt.src=xe.iconUrl,dt.style.height=Pt,dt.style.width=Pt;else{let Mt=document.createElement("img");Mt.src=xe.iconUrl,Mt.alt="",Mt.className="persona-rounded-xl persona-object-cover",Mt.style.height=Pt,Mt.style.width=Pt,se.replaceChildren(Mt)}}else{let dt=se.querySelector("svg"),Mt=se.querySelector("img");(dt||Mt)&&se.replaceChildren(),se.textContent=(Wd=xe.agentIconText)!=null?Wd:"\u{1F4AC}"}let Ot=se.querySelector("img");Ot&&(Ot.style.height=Pt,Ot.style.width=Pt)}}let An=(Hd=(Bd=o.layout)==null?void 0:Bd.header)==null?void 0:Hd.showTitle,pn=(Fd=(Dd=o.layout)==null?void 0:Dd.header)==null?void 0:Fd.showSubtitle;if(He&&(He.style.display=An===!1?"none":""),Xe&&(Xe.style.display=pn===!1?"none":""),N){((Nd=(Od=o.layout)==null?void 0:Od.header)==null?void 0:Nd.showCloseButton)===!1?N.style.display="none":N.style.display="";let xt=(_d=xe.closeButtonSize)!=null?_d:"32px",Ot=(Vd=xe.closeButtonPlacement)!=null?Vd:"inline";N.style.height=xt,N.style.width=xt;let{closeButtonWrapper:dt}=Le,Mt=Ot==="top-right",rn=dt==null?void 0:dt.classList.contains("persona-absolute");if(dt&&Mt!==rn)if(dt.remove(),Mt)dt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",de.style.position="relative",de.appendChild(dt);else{let pt=(Ud=($d=xe.clearChat)==null?void 0:$d.placement)!=null?Ud:"inline",sn=(qd=(zd=xe.clearChat)==null?void 0:zd.enabled)!=null?qd:!0;dt.className=sn&&pt==="inline"?"":"persona-ml-auto";let Hn=de.querySelector(".persona-border-b-persona-divider");Hn&&Hn.appendChild(dt)}if(N.style.color=xe.closeButtonColor||Mn.actionIconColor,xe.closeButtonBackgroundColor?(N.style.backgroundColor=xe.closeButtonBackgroundColor,N.classList.remove("hover:persona-bg-gray-100")):(N.style.backgroundColor="",N.classList.add("hover:persona-bg-gray-100")),xe.closeButtonBorderWidth||xe.closeButtonBorderColor){let pt=xe.closeButtonBorderWidth||"0px",sn=xe.closeButtonBorderColor||"transparent";N.style.border=`${pt} solid ${sn}`,N.classList.remove("persona-border-none")}else N.style.border="",N.classList.add("persona-border-none");xe.closeButtonBorderRadius?(N.style.borderRadius=xe.closeButtonBorderRadius,N.classList.remove("persona-rounded-full")):(N.style.borderRadius="",N.classList.add("persona-rounded-full")),xe.closeButtonPaddingX?(N.style.paddingLeft=xe.closeButtonPaddingX,N.style.paddingRight=xe.closeButtonPaddingX):(N.style.paddingLeft="",N.style.paddingRight=""),xe.closeButtonPaddingY?(N.style.paddingTop=xe.closeButtonPaddingY,N.style.paddingBottom=xe.closeButtonPaddingY):(N.style.paddingTop="",N.style.paddingBottom="");let fn=(jd=xe.closeButtonIconName)!=null?jd:"x",yo=(Kd=xe.closeButtonIconText)!=null?Kd:"\xD7";N.innerHTML="";let En=Se(fn,"28px","currentColor",1);En?N.appendChild(En):N.textContent=yo;let Qt=(Gd=xe.closeButtonTooltipText)!=null?Gd:"Close chat",Xn=(Yd=xe.closeButtonShowTooltip)!=null?Yd:!0;if(N.setAttribute("aria-label",Qt),dt&&(dt._cleanupTooltip&&(dt._cleanupTooltip(),delete dt._cleanupTooltip),Xn&&Qt)){let pt=null,sn=()=>{if(pt||!N)return;let br=N.ownerDocument,Ss=br.body;if(!Ss)return;pt=Eo(br,"div","persona-clear-chat-tooltip"),pt.textContent=Qt;let As=Eo(br,"div");As.className="persona-clear-chat-tooltip-arrow",pt.appendChild(As);let yr=N.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(nr),pt.style.left=`${yr.left+yr.width/2}px`,pt.style.top=`${yr.top-8}px`,pt.style.transform="translate(-50%, -100%)",Ss.appendChild(pt)},Hn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};dt.addEventListener("mouseenter",sn),dt.addEventListener("mouseleave",Hn),N.addEventListener("focus",sn),N.addEventListener("blur",Hn),dt._cleanupTooltip=()=>{Hn(),dt&&(dt.removeEventListener("mouseenter",sn),dt.removeEventListener("mouseleave",Hn)),N&&(N.removeEventListener("focus",sn),N.removeEventListener("blur",Hn))}}}let{clearChatButton:Je,clearChatButtonWrapper:ct}=Le;if(Je){let J=(Xd=xe.clearChat)!=null?Xd:{},xt=(Qd=J.enabled)!=null?Qd:!0,Ot=(Zd=(Jd=o.layout)==null?void 0:Jd.header)==null?void 0:Zd.showClearChat,dt=Ot!==void 0?Ot:xt,Mt=(ep=J.placement)!=null?ep:"inline";if(ct){ct.style.display=dt?"":"none";let{closeButtonWrapper:rn}=Le;!E()&&rn&&!rn.classList.contains("persona-absolute")&&(dt?rn.classList.remove("persona-ml-auto"):rn.classList.add("persona-ml-auto"));let fn=Mt==="top-right",yo=ct.classList.contains("persona-absolute");if(!E()&&fn!==yo&&dt){if(ct.remove(),fn)ct.className="persona-absolute persona-top-4 persona-z-50",ct.style.right="48px",de.style.position="relative",de.appendChild(ct);else{ct.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ct.style.right="";let Qt=de.querySelector(".persona-border-b-persona-divider"),Xn=Le.closeButtonWrapper;Qt&&Xn&&Xn.parentElement===Qt?Qt.insertBefore(ct,Xn):Qt&&Qt.appendChild(ct)}let En=Le.closeButtonWrapper;En&&!En.classList.contains("persona-absolute")&&(fn?En.classList.add("persona-ml-auto"):En.classList.remove("persona-ml-auto"))}}if(dt){if(!E()){let pt=(tp=J.size)!=null?tp:"32px";Je.style.height=pt,Je.style.width=pt}let rn=(np=J.iconName)!=null?np:"refresh-cw",fn=(op=J.iconColor)!=null?op:"";Je.style.color=fn||Mn.actionIconColor,Je.innerHTML="";let yo=E()?"14px":"20px",En=Se(rn,yo,"currentColor",2);if(En&&Je.appendChild(En),J.backgroundColor?(Je.style.backgroundColor=J.backgroundColor,Je.classList.remove("hover:persona-bg-gray-100")):(Je.style.backgroundColor="",Je.classList.add("hover:persona-bg-gray-100")),J.borderWidth||J.borderColor){let pt=J.borderWidth||"0px",sn=J.borderColor||"transparent";Je.style.border=`${pt} solid ${sn}`,Je.classList.remove("persona-border-none")}else Je.style.border="",Je.classList.add("persona-border-none");J.borderRadius?(Je.style.borderRadius=J.borderRadius,Je.classList.remove("persona-rounded-full")):(Je.style.borderRadius="",Je.classList.add("persona-rounded-full")),J.paddingX?(Je.style.paddingLeft=J.paddingX,Je.style.paddingRight=J.paddingX):(Je.style.paddingLeft="",Je.style.paddingRight=""),J.paddingY?(Je.style.paddingTop=J.paddingY,Je.style.paddingBottom=J.paddingY):(Je.style.paddingTop="",Je.style.paddingBottom="");let Qt=(rp=J.tooltipText)!=null?rp:"Clear chat",Xn=(sp=J.showTooltip)!=null?sp:!0;if(Je.setAttribute("aria-label",Qt),ct&&(ct._cleanupTooltip&&(ct._cleanupTooltip(),delete ct._cleanupTooltip),Xn&&Qt)){let pt=null,sn=()=>{if(pt||!Je)return;let br=Je.ownerDocument,Ss=br.body;if(!Ss)return;pt=Eo(br,"div","persona-clear-chat-tooltip"),pt.textContent=Qt;let As=Eo(br,"div");As.className="persona-clear-chat-tooltip-arrow",pt.appendChild(As);let yr=Je.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(nr),pt.style.left=`${yr.left+yr.width/2}px`,pt.style.top=`${yr.top-8}px`,pt.style.transform="translate(-50%, -100%)",Ss.appendChild(pt)},Hn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};ct.addEventListener("mouseenter",sn),ct.addEventListener("mouseleave",Hn),Je.addEventListener("focus",sn),Je.addEventListener("blur",Hn),ct._cleanupTooltip=()=>{Hn(),ct&&(ct.removeEventListener("mouseenter",sn),ct.removeEventListener("mouseleave",Hn)),Je&&(Je.removeEventListener("focus",sn),Je.removeEventListener("blur",Hn))}}}}let Tn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Hl],gn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Js.message,Js.messageAndClick];M=Dl({parsers:Tn,handlers:gn,getSessionMetadata:f,updateSessionMetadata:g,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),me=Dm(o,M,q),T.updateConfig(o),cr(Ve,T.getMessages(),me),uo.render(o.suggestionChips,T,Q,void 0,o.suggestionChipsConfig),ms(),Wr(T.isStreaming());let ur=((ap=o.voiceRecognition)==null?void 0:ap.enabled)===!0,mr=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),gr=((lp=(ip=o.voiceRecognition)==null?void 0:ip.provider)==null?void 0:lp.type)==="runtype";if(ur&&(mr||gr))if(!K||!gt){let J=Fr(o.voiceRecognition,o.sendButton);J&&(K=J.micButton,gt=J.micButtonWrapper,Nt.insertBefore(gt,Ln),K.addEventListener("click",ze),K.disabled=T.isStreaming())}else{let J=(cp=o.voiceRecognition)!=null?cp:{},xt=(dp=o.sendButton)!=null?dp:{},Ot=(pp=J.iconName)!=null?pp:"mic",dt=(up=xt.size)!=null?up:"40px",Mt=(mp=J.iconSize)!=null?mp:dt,rn=parseFloat(Mt)||24;K.style.width=Mt,K.style.height=Mt,K.style.minWidth=Mt,K.style.minHeight=Mt;let fn=(fp=(gp=J.iconColor)!=null?gp:xt.textColor)!=null?fp:"currentColor";K.innerHTML="";let yo=Se(Ot,rn,fn,2);yo?K.appendChild(yo):K.textContent="\u{1F3A4}";let En=(hp=J.backgroundColor)!=null?hp:xt.backgroundColor;En?K.style.backgroundColor=En:K.style.backgroundColor="",fn?K.style.color=fn: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 Qt=gt==null?void 0:gt.querySelector(".persona-send-button-tooltip"),Xn=(bp=J.tooltipText)!=null?bp:"Start voice recognition";if(((yp=J.showTooltip)!=null?yp:!1)&&Xn)if(Qt)Qt.textContent=Xn,Qt.style.display="";else{let sn=document.createElement("div");sn.className="persona-send-button-tooltip",sn.textContent=Xn,gt==null||gt.insertBefore(sn,K)}else Qt&&(Qt.style.display="none");gt.style.display="",K.disabled=T.isStreaming()}else K&>&&(gt.style.display="none",((xp=(vp=o.voiceRecognition)==null?void 0:vp.provider)==null?void 0:xp.type)==="runtype"?T.isVoiceActive()&&T.toggleVoice():Gn&&bo());if(((wp=o.attachments)==null?void 0:wp.enabled)===!0)if(!$t||!nt){let J=(Cp=o.attachments)!=null?Cp:{},Ot=(Ap=((Sp=o.sendButton)!=null?Sp:{}).size)!=null?Ap:"40px";ve||(ve=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ve.style.display="none",Ft.insertBefore(ve,Q)),ae||(ae=document.createElement("input"),ae.type="file",ae.accept=((Tp=J.allowedTypes)!=null?Tp:_o).join(","),ae.multiple=((kp=J.maxFiles)!=null?kp:4)>1,ae.style.display="none",ae.setAttribute("aria-label","Attach files"),Ft.insertBefore(ae,Q)),$t=b("div","persona-send-button-wrapper"),nt=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),nt.type="button",nt.setAttribute("aria-label",(Ep=J.buttonTooltipText)!=null?Ep:"Attach file");let dt=(Mp=J.buttonIconName)!=null?Mp:"paperclip",Mt=Ot,rn=parseFloat(Mt)||40,fn=Math.round(rn*.6);nt.style.width=Mt,nt.style.height=Mt,nt.style.minWidth=Mt,nt.style.minHeight=Mt,nt.style.fontSize="18px",nt.style.lineHeight="1",nt.style.backgroundColor="transparent",nt.style.color="var(--persona-primary, #111827)",nt.style.border="none",nt.style.borderRadius="6px",nt.style.transition="background-color 0.15s ease",nt.addEventListener("mouseenter",()=>{nt.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),nt.addEventListener("mouseleave",()=>{nt.style.backgroundColor="transparent"});let yo=Se(dt,fn,"currentColor",1.5);yo?nt.appendChild(yo):nt.textContent="\u{1F4CE}",nt.addEventListener("click",Xn=>{Xn.preventDefault(),ae==null||ae.click()}),$t.appendChild(nt);let En=(Lp=J.buttonTooltipText)!=null?Lp:"Attach file",Qt=b("div","persona-send-button-tooltip");Qt.textContent=En,$t.appendChild(Qt),St.append($t),!Ze&&ae&&ve&&(Ze=Ds.fromConfig(J),Ze.setPreviewsContainer(ve),ae.addEventListener("change",async()=>{Ze&&(ae!=null&&ae.files)&&(await Ze.handleFileSelect(ae.files),ae.value="")})),de.querySelector(".persona-attachment-drop-overlay")||de.appendChild(Fm(J.dropOverlay))}else{$t.style.display="";let J=(Ip=o.attachments)!=null?Ip:{};ae&&(ae.accept=((Rp=J.allowedTypes)!=null?Rp:_o).join(","),ae.multiple=((Pp=J.maxFiles)!=null?Pp:4)>1),Ze&&Ze.updateConfig({allowedTypes:J.allowedTypes,maxFileSize:J.maxFileSize,maxFiles:J.maxFiles})}else $t&&($t.style.display="none"),Ze&&Ze.clearAttachments(),(Wp=de.querySelector(".persona-attachment-drop-overlay"))==null||Wp.remove();let zt=(Bp=o.sendButton)!=null?Bp:{},fr=(Hp=zt.useIcon)!=null?Hp:!1,tr=(Dp=zt.iconText)!=null?Dp:"\u2191",bt=zt.iconName,Pn=(Fp=zt.tooltipText)!=null?Fp:"Send message",Oo=(Op=zt.showTooltip)!=null?Op:!1,kn=(Np=zt.size)!=null?Np:"40px",Wn=zt.backgroundColor,Ht=zt.textColor;if(fr){if(Fe.style.width=kn,Fe.style.height=kn,Fe.style.minWidth=kn,Fe.style.minHeight=kn,Fe.style.fontSize="18px",Fe.style.lineHeight="1",Fe.innerHTML="",Ht?Fe.style.color=Ht:Fe.style.color="var(--persona-button-primary-fg, #ffffff)",bt){let J=parseFloat(kn)||24,xt=(Ht==null?void 0:Ht.trim())||"currentColor",Ot=Se(bt,J,xt,2);Ot?Fe.appendChild(Ot):Fe.textContent=tr}else Fe.textContent=tr;Fe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Wn?(Fe.style.backgroundColor=Wn,Fe.classList.remove("persona-bg-persona-primary")):(Fe.style.backgroundColor="",Fe.classList.add("persona-bg-persona-primary"))}else Fe.textContent=(Vp=(_p=o.copy)==null?void 0:_p.sendButtonLabel)!=null?Vp:"Send",Fe.style.width="",Fe.style.height="",Fe.style.minWidth="",Fe.style.minHeight="",Fe.style.fontSize="",Fe.style.lineHeight="",Fe.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?(Fe.style.backgroundColor=Wn,Fe.classList.remove("persona-bg-persona-accent")):Fe.classList.add("persona-bg-persona-accent"),Ht?Fe.style.color=Ht:Fe.classList.add("persona-text-white");zt.borderWidth?(Fe.style.borderWidth=zt.borderWidth,Fe.style.borderStyle="solid"):(Fe.style.borderWidth="",Fe.style.borderStyle=""),zt.borderColor?Fe.style.borderColor=zt.borderColor:Fe.style.borderColor="",zt.paddingX?(Fe.style.paddingLeft=zt.paddingX,Fe.style.paddingRight=zt.paddingX):(Fe.style.paddingLeft="",Fe.style.paddingRight=""),zt.paddingY?(Fe.style.paddingTop=zt.paddingY,Fe.style.paddingBottom=zt.paddingY):(Fe.style.paddingTop="",Fe.style.paddingBottom="");let Vt=Ln==null?void 0:Ln.querySelector(".persona-send-button-tooltip");if(Oo&&Pn)if(Vt)Vt.textContent=Pn,Vt.style.display="";else{let J=document.createElement("div");J.className="persona-send-button-tooltip",J.textContent=Pn,Ln==null||Ln.insertBefore(J,Fe)}else Vt&&(Vt.style.display="none");let Dt=(jp=($p=o.layout)==null?void 0:$p.contentMaxWidth)!=null?jp:E()?(qp=(zp=(Up=o.launcher)==null?void 0:Up.composerBar)==null?void 0:zp.contentMaxWidth)!=null?qp:"720px":void 0;Dt?(Ve.style.maxWidth=Dt,Ve.style.marginLeft="auto",Ve.style.marginRight="auto",Ve.style.width="100%",Ft&&(Ft.style.maxWidth=Dt,Ft.style.marginLeft="auto",Ft.style.marginRight="auto"),Ct&&(Ct.style.maxWidth=Dt,Ct.style.marginLeft="auto",Ct.style.marginRight="auto")):(Ve.style.maxWidth="",Ve.style.marginLeft="",Ve.style.marginRight="",Ve.style.width="",Ft&&(Ft.style.maxWidth="",Ft.style.marginLeft="",Ft.style.marginRight=""),Ct&&(Ct.style.maxWidth="",Ct.style.marginLeft="",Ct.style.marginRight=""));let qt=(Kp=o.statusIndicator)!=null?Kp:{},Bn=(Gp=qt.visible)!=null?Gp:!0;if(ln.style.display=Bn?"":"none",T){let J=T.getStatus();tt(ln,(Ot=>{var dt,Mt,rn,fn;return Ot==="idle"?(dt=qt.idleText)!=null?dt:hn.idle:Ot==="connecting"?(Mt=qt.connectingText)!=null?Mt:hn.connecting:Ot==="connected"?(rn=qt.connectedText)!=null?rn:hn.connected:Ot==="error"?(fn=qt.errorText)!=null?fn:hn.error:hn[Ot]})(J),qt,J)}ln.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Yn=qt.align==="left"?"persona-text-left":qt.align==="center"?"persona-text-center":"persona-text-right";ln.classList.add(Yn)},open(){S()&&Bt(!0,"api")},close(){S()&&Bt(!1,"api")},toggle(){S()&&Bt(!k,"api")},clearChat(){wn=!1,T.clearMessages(),mo.clear(),Go();try{localStorage.removeItem(es),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${es}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==es)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let m=i.clear();m instanceof Promise&&m.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",m)}d={},M.syncFromMetadata(),X==null||X.clear(),Ae==null||Ae.reset(),fe==null||fe.update()},setMessage(c){return!Q||T.isStreaming()?!1:(!k&&S()&&Bt(!0,"system"),Q.value=c,Q.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(T.isStreaming())return!1;let m=(c==null?void 0:c.trim())||Q.value.trim();return m?(!k&&S()&&Bt(!0,"system"),Q.value="",Q.style.height="auto",T.sendMessage(m),!0):!1},startVoiceRecognition(){var m,h;return T.isStreaming()?!1:((h=(m=o.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype"?(T.isVoiceActive()||(!k&&S()&&Bt(!0,"system"),mt.manuallyDeactivated=!1,Rn(),T.toggleVoice().then(()=>{mt.active=T.isVoiceActive(),ro("user"),T.isVoiceActive()&&R()})),!0):Gn?!0:xs()?(!k&&S()&&Bt(!0,"system"),mt.manuallyDeactivated=!1,Rn(),pr("user"),!0):!1},stopVoiceRecognition(){var c,m;return((m=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?T.isVoiceActive()?(T.toggleVoice().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Rn(),ro("user"),G()}),!0):!1:Gn?(mt.manuallyDeactivated=!0,Rn(),bo("user"),!0):!1},injectMessage(c){return!k&&S()&&Bt(!0,"system"),T.injectMessage(c)},injectAssistantMessage(c){!k&&S()&&Bt(!0,"system");let m=T.injectAssistantMessage(c);return F&&(F=!1,$&&(clearTimeout($),$=null),setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)),m},injectUserMessage(c){return!k&&S()&&Bt(!0,"system"),T.injectUserMessage(c)},injectSystemMessage(c){return!k&&S()&&Bt(!0,"system"),T.injectSystemMessage(c)},injectMessageBatch(c){return!k&&S()&&Bt(!0,"system"),T.injectMessageBatch(c)},injectComponentDirective(c){return!k&&S()&&Bt(!0,"system"),T.injectComponentDirective(c)},injectTestMessage(c){!k&&S()&&Bt(!0,"system"),T.injectTestEvent(c)},async connectStream(c,m){return T.connectStream(c,m)},__pushEventStreamEvent(c){X&&(Ae==null||Ae.processEvent(c.type,c.payload),X.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!ie||!X||xn()},hideEventStream(){le&&On()},isEventStreamVisible(){return le},showArtifacts(){co(o)&&(wn=!1,zn(),vt==null||vt.setMobileOpen(!0))},hideArtifacts(){co(o)&&(wn=!0,zn())},upsertArtifact(c){return co(o)?(wn=!1,T.upsertArtifact(c)):null},selectArtifact(c){co(o)&&T.selectArtifact(c)},clearArtifacts(){co(o)&&T.clearArtifacts()},getArtifacts(){var c;return(c=T==null?void 0:T.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=T==null?void 0:T.getSelectedArtifactId())!=null?c:null},focusInput(){return W&&!k&&!E()||!Q?!1:(Q.focus(),!0)},async resolveApproval(c,m){let y=T.getMessages().find(P=>{var _;return P.variant==="approval"&&((_=P.approval)==null?void 0:_.id)===c});if(!(y!=null&&y.approval))throw new Error(`Approval not found: ${c}`);if(y.approval.toolType==="webmcp"){T.resolveWebMcpApproval(y.id,m);return}return T.resolveApproval(y.approval,m)},getMessages(){return T.getMessages()},getStatus(){return T.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){g(c)},on(c,m){return s.on(c,m)},off(c,m){s.off(c,m)},isOpen(){return S()&&k},isVoiceActive(){return mt.active},getState(){return{open:S()&&k,launcherEnabled:W,voiceActive:mt.active,streaming:T.isStreaming()}},showCSATFeedback(c){!k&&S()&&Bt(!0,"system");let m=Ve.querySelector(".persona-feedback-container");m&&m.remove();let h=Wm({onSubmit:async(y,P)=>{var _;T.isClientTokenMode()&&await T.submitCSATFeedback(y,P),(_=c==null?void 0:c.onSubmit)==null||_.call(c,y,P)},onDismiss:c==null?void 0:c.onDismiss,...c});Ve.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!k&&S()&&Bt(!0,"system");let m=Ve.querySelector(".persona-feedback-container");m&&m.remove();let h=Bm({onSubmit:async(y,P)=>{var _;T.isClientTokenMode()&&await T.submitNPSFeedback(y,P),(_=c==null?void 0:c.onSubmit)==null||_.call(c,y,P)},onDismiss:c==null?void 0:c.onDismiss,...c});Ve.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,m){return T.submitCSATFeedback(c,m)},async submitNPSFeedback(c,m){return T.submitNPSFeedback(c,m)},destroy(){Ao!=null&&(clearInterval(Ao),Ao=null),ft.forEach(c=>c()),ge.remove(),_e==null||_e.remove(),Ge==null||Ge.destroy(),Qe==null||Qe.remove(),jn&&N.removeEventListener("click",jn)}};if((((Kc=n==null?void 0:n.debugTools)!=null?Kc:!1)||!!o.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,m={controller:en,getMessages:en.getMessages,getStatus:en.getStatus,getMetadata:en.getPersistentMetadata,updateMetadata:en.updatePersistentMetadata,clearHistory:()=>en.clearChat(),setVoiceActive:h=>h?en.startVoiceRecognition():en.stopVoiceRecognition()};window.AgentWidgetBrowser=m,ft.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&en.focusInput()};if(window.addEventListener("persona:focusInput",m),ft.push(()=>{window.removeEventListener("persona:focusInput",m)}),ie){let z=Ce=>{let pe=Ce.detail;(!(pe!=null&&pe.instanceId)||pe.instanceId===c)&&en.showEventStream()},O=Ce=>{let pe=Ce.detail;(!(pe!=null&&pe.instanceId)||pe.instanceId===c)&&en.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)&&en.showArtifacts()},y=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&en.hideArtifacts()},P=z=>{let O=z.detail;O!=null&&O.instanceId&&O.instanceId!==c||O!=null&&O.artifact&&en.upsertArtifact(O.artifact)},_=z=>{let O=z.detail;O!=null&&O.instanceId&&O.instanceId!==c||typeof(O==null?void 0:O.id)=="string"&&en.selectArtifact(O.id)},V=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&en.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",P),window.addEventListener("persona:selectArtifact",_),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",_),window.removeEventListener("persona:clearArtifacts",V)})}let ao=ox(o.persistState);if(ao&&S()){let c=rx(ao.storage),m=`${ao.keyPrefix}widget-open`,h=`${ao.keyPrefix}widget-voice`,y=`${ao.keyPrefix}widget-voice-mode`;if(c){let P=((Gc=ao.persist)==null?void 0:Gc.openState)&&c.getItem(m)==="true",_=((Yc=ao.persist)==null?void 0:Yc.voiceState)&&c.getItem(h)==="true",V=((Xc=ao.persist)==null?void 0:Xc.voiceState)&&c.getItem(y)==="true";if(P&&setTimeout(()=>{en.open(),setTimeout(()=>{var z;if(_||V)en.startVoiceRecognition();else if((z=ao.persist)!=null&&z.focusInput){let O=e.querySelector("textarea");O&&O.focus()}},100)},0),(Qc=ao.persist)!=null&&Qc.openState&&(s.on("widget:opened",()=>{c.setItem(m,"true")}),s.on("widget:closed",()=>{c.setItem(m,"false")})),(Jc=ao.persist)!=null&&Jc.voiceState&&(s.on("voice:state",z=>{c.setItem(h,z.active?"true":"false")}),s.on("user:message",z=>{c.setItem(y,z.viaVoice?"true":"false")})),ao.clearOnChatClear){let z=()=>{c.removeItem(m),c.removeItem(h),c.removeItem(y)},O=()=>z();window.addEventListener("persona:clear-chat",O),ft.push(()=>{window.removeEventListener("persona:clear-chat",O)})}}}return u&&S()&&setTimeout(()=>{en.open()},0),Do(),en};var sx=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},Nm=(e,t)=>{var o,r;let n=(r=(o=t==null?void 0:t.launcher)==null?void 0:o.enabled)!=null?r:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},Vl=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="",Vl(e)},Ol=e=>{e.style.transition=""},Nl=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"},Ei=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},ax=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},ix=(e,t,n,o,r,s)=>{let a=s?t:e;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},Vm=(e,t,n,o,r,s,a)=>{var x,C,M,W,L,H;let i=Mo(s),d=i.reveal==="push";ax(e,t,n,o,d),ix(e,t,n,o,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,u=(C=(x=s==null?void 0:s.launcher)==null?void 0:x.mobileFullscreen)!=null?C:!0,p=(W=(M=s==null?void 0:s.launcher)==null?void 0:M.mobileBreakpoint)!=null?W:640,f=l!=null?l.innerWidth<=p:!1;if(u&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Nl(t),Ol(o),_m(o),_l(n),Ei(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:bn),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),_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",Nl(t),Ol(o),_l(n),Ei(r,o);let D=i.animate?"transform 180ms ease":"none",B=i.side==="right"?"translateX(100%)":"translateX(-100%)",v=a?"translateX(0)":B;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=D,o.style.transform=v,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",i.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Ol(o),Vl(o),Ei(r,o);let D=sx(i.width,e.clientWidth),B=Math.max(0,e.clientWidth),v=i.animate?"transform 180ms ease":"none",w=i.side==="right"?a?`translateX(-${D}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${D}px)`;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${B+D}px`,t.style.transition=v,t.style.transform=w,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${B}px`,n.style.maxWidth=`${B}px`,n.style.minWidth=`${B}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.position="relative",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Nl(t),Vl(o),_l(n),Ei(r,o);let D=i.reveal==="emerge";D?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let B=a?i.width:"0px",v=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",w=!a;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${B}`,o.style.width=B,o.style.maxWidth=B,o.style.minWidth=B,o.style.minHeight="0",o.style.position="relative",o.style.overflow=D||w?"hidden":"visible",o.style.transition=v,D&&(o.style.alignItems=i.side==="right"?"flex-start":"flex-end",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.boxSizing="border-box")}},lx=(e,t)=>{let n=e.ownerDocument.createElement("div");return Nm(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Nm(n,o)},destroy(){n.remove()}}},cx=(e,t)=>{var L,H,D,B;let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),u=n.createElement("div"),p=(H=(L=t==null?void 0:t.launcher)==null?void 0:L.enabled)==null||H?(B=(D=t==null?void 0:t.launcher)==null?void 0:D.autoExpand)!=null?B:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",l.appendChild(u),o.insertBefore(a,e),d.appendChild(e);let f=null,g=()=>{f==null||f.disconnect(),f=null},x=()=>{g(),Mo(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Vm(a,i,d,l,u,t,p)}),f.observe(a))},C=()=>{Vm(a,i,d,l,u,t,p),x()},M=a.ownerDocument.defaultView,W=()=>{C()};return M==null||M.addEventListener("resize",W),Mo(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),C(),{mode:"docked",host:u,shell:a,syncWidgetState(v){let w=v.launcherEnabled?v.open:!0;p!==w&&(p=w,C())},updateConfig(v){var w,E;t=v,((E=(w=t==null?void 0:t.launcher)==null?void 0:w.enabled)!=null?E:!0)===!1&&(p=!0),C()},destroy(){M==null||M.removeEventListener("resize",W),g(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},$m=(e,t)=>un(t)?cx(e,t):lx(e,t);var ts={desktop:{w:1280,h:800},mobile:{w:390,h:844}},$l=.15,Ul=1.5,Mi="persona-preview-shell-theme",Um={load:()=>null,save:()=>{},clear:()=>{}},zm=["How do I get started?","Pricing & plans","Talk to support"];function Li(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function qm(e){return e==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function zl(e){let t=qm(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 Za=class e{constructor(t={},n){this.config=t;this
|
|
|
128
128
|
.preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
|
|
129
129
|
.preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
|
|
130
130
|
.preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${t.cardBg}; box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
|
|
131
|
-
.preview-workspace-card.short { height: 96px; }`}function ql(e,t){let n=e.contentDocument;if(!(n!=null&&n.documentElement))return;let o=n.getElementById(Mi);o||(o=n.createElement("style"),o.id=Mi,n.head.appendChild(o)),o.textContent=zl(t)}var
|
|
131
|
+
.preview-workspace-card.short { height: 96px; }`}function ql(e,t){let n=e.contentDocument;if(!(n!=null&&n.documentElement))return;let o=n.getElementById(Mi);o||(o=n.createElement("style"),o.id=Mi,n.head.appendChild(o)),o.textContent=zl(t)}var jm=`
|
|
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 Za=class e{constructor(t={},n){this.config=t;this
|
|
|
147
147
|
<div class="preview-iframe-line body"></div>
|
|
148
148
|
<div class="preview-iframe-line body"></div>
|
|
149
149
|
</div>
|
|
150
|
-
</div>`,
|
|
150
|
+
</div>`,Km=`
|
|
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>
|
|
@@ -161,7 +161,7 @@ _Details: ${n.message}_`:o}var Za=class e{constructor(t={},n){this.config=t;this
|
|
|
161
161
|
<div class="preview-workspace-card short"></div>
|
|
162
162
|
</div>
|
|
163
163
|
</div>`;function jl(e,t,n,o){let r=`
|
|
164
|
-
${
|
|
164
|
+
${jm}
|
|
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 Za=class e{constructor(t={},n){this.config=t;this
|
|
|
173
173
|
</div>
|
|
174
174
|
<div class="preview-workspace-body">
|
|
175
175
|
<div id="preview-content-${e}" class="preview-workspace-content" data-mount-id="${e}">
|
|
176
|
-
${
|
|
176
|
+
${Km}
|
|
177
177
|
</div>
|
|
178
178
|
</div>
|
|
179
179
|
</div>`;return`<!DOCTYPE html>
|
|
@@ -187,13 +187,13 @@ _Details: ${n.message}_`:o}var Za=class e{constructor(t={},n){this.config=t;this
|
|
|
187
187
|
<body>
|
|
188
188
|
${n?s:r}
|
|
189
189
|
</body>
|
|
190
|
-
</html>`}var
|
|
190
|
+
</html>`}var dx={"user-message":"User message","assistant-message":"Assistant message","assistant-code-block":"Assistant \u2014 code block","assistant-markdown-table":"Assistant \u2014 markdown table","assistant-image":"Assistant \u2014 image","reasoning-streaming":"Reasoning (streaming)","reasoning-complete":"Reasoning (complete)","tool-running":"Tool call (running)","tool-complete":"Tool call (complete)"};function px(e){return dx[e]}function Kl(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
|
|
193
|
+
`),createdAt:n};case"reasoning-streaming":return{id:`preview-seq-reasoning-stream-${o}`,role:"assistant",content:"",createdAt:n,streaming:!0,variant:"reasoning",reasoning:{id:`preview-reasoning-stream-${o}`,status:"streaming",chunks:["Thinking through the next step in the workflow..."]}};case"reasoning-complete":return{id:`preview-seq-reasoning-complete-${o}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"reasoning",reasoning:{id:`preview-reasoning-complete-${o}`,status:"complete",chunks:["Reviewed the requirements and finalized the reasoning output."],durationMs:1200}};case"tool-complete":return{id:`preview-seq-tool-complete-${o}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"tool",toolCall:{id:`preview-tool-complete-${o}`,name:"Create build instructions",status:"complete",chunks:["Prepared the build instructions and validated the inputs."],result:{ok:!0},duration:420}};default:return{id:`preview-seq-tool-running-${o}`,role:"assistant",content:"",createdAt:n,streaming:!0,variant:"tool",toolCall:{id:`preview-tool-running-${o}`,name:"Get platform documentation",status:"running",chunks:["Fetching the relevant platform documentation..."]}}}}function ux(e,t){return[...e,Kl(t,e.length)]}function Gm(e){return e==="assistant-message"||e==="assistant-code-block"||e==="assistant-markdown-table"||e==="assistant-image"}function mx(e,t,n){var d,l;let o=Kl(e,t);if(!Gm(e)||typeof o.content!="string")return[{message:o,delayMs:0,done:!0}];let r=Math.max(1,(d=n==null?void 0:n.chunkSize)!=null?d:24),s=Math.max(0,(l=n==null?void 0:n.delayMs)!=null?l:42),a=o.content,i=[];i.push({message:{...o,content:"",streaming:!0},delayMs:0,done:!1});for(let u=r;u<a.length;u+=r)i.push({message:{...o,content:a.slice(0,u),streaming:!0},delayMs:s,done:!1});return i.push({message:{...o,content:a,streaming:!1},delayMs:s,done:!0}),i}var gx=()=>[{id:"preview-adv-1",role:"user",content:"Can you create the product and gather the docs?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-adv-2",role:"assistant",content:"",createdAt:new Date(Date.now()-15e4).toISOString(),streaming:!0,variant:"reasoning",reasoning:{id:"preview-reasoning",status:"streaming",chunks:["Now let me get the Persona embed documentation and builtin tools catalog."]}},{id:"preview-adv-3",role:"assistant",content:"",createdAt:new Date(Date.now()-12e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-1",name:"Load tools",status:"running",chunks:["Loaded tools, used Runtype integration"]}},{id:"preview-adv-4",role:"assistant",content:"",createdAt:new Date(Date.now()-9e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-2",name:"Get platform documentation",status:"running",chunks:["Get platform documentation"]}},{id:"preview-adv-5",role:"assistant",content:"I loaded the tools and fetched the docs. Next I can assemble the product details.",createdAt:new Date(Date.now()-3e4).toISOString()}],fx=e=>{var t,n,o,r,s,a,i,d;return!!((n=(t=e==null?void 0:e.features)==null?void 0:t.toolCallDisplay)!=null&&n.activePreview||(r=(o=e==null?void 0:e.features)==null?void 0:o.toolCallDisplay)!=null&&r.grouped||(a=(s=e==null?void 0:e.features)==null?void 0:s.toolCallDisplay)!=null&&a.collapsedMode&&e.features.toolCallDisplay.collapsedMode!=="tool-call"||(d=(i=e==null?void 0:e.features)==null?void 0:i.reasoningDisplay)!=null&&d.activePreview)};function Ym(e,t,n=[]){return e==="home"?[{id:"preview-home-1",role:"assistant",content:"Hi there! How can we help today?",createdAt:new Date().toISOString()}]:e==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:e==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:e==="conversation"&&fx(t)?[...gx(),...n]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...n]}function Gl(e,t,n=[]){var s,a;let o={...e.launcher,enabled:!0,autoExpand:t!=="minimized"},r={...e,launcher:o,suggestionChips:t==="home"?(s=e.suggestionChips)!=null&&s.length?e.suggestionChips:zm:e.suggestionChips,initialMessages:Ym(t,e,n),storageAdapter:Um};return t==="artifact"&&(r.features={...r.features,artifacts:{...(a=r.features)==null?void 0:a.artifacts,enabled:!0}}),r}function Mr(e,t){var s,a,i,d;let n=e.theme?nn(e.theme,{validate:!1}):nn(),o=(s=e.scene)!=null?s:"conversation",r={...kt,...e.config,theme:n,darkTheme:e.darkTheme,colorScheme:(i=t!=null?t:(a=e.config)==null?void 0:a.colorScheme)!=null?i:"light"};return Gl(r,o,(d=e.appendedMessages)!=null?d:[])}function hx(e,t,n){var a,i,d;let o=e.theme?nn(e.theme,{validate:!1}):nn(),r=(a=e.scene)!=null?a:"conversation",s={...kt,...e.config,theme:o,darkTheme:e.darkTheme,colorScheme:(d=n!=null?n:(i=e.config)==null?void 0:i.colorScheme)!=null?d:"light"};return Gl(s,r,t)}function Xm(e){var o,r,s,a,i;let t=(o=e.compareMode)!=null?o:"off",n=(r=e.shellMode)!=null?r:"light";if(t==="themes")return[{mountId:"preview-light",label:"Light",config:Mr(e,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Mr(e,"dark"),shellMode:"dark"}];if(t==="baseline"&&(e.baselineConfig||e.baselineTheme)){let d={...e,config:(s=e.baselineConfig)!=null?s:e.config,theme:(a=e.baselineTheme)!=null?a:e.theme,darkTheme:(i=e.baselineDarkTheme)!=null?i:e.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:Mr(d,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Mr(e,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Mr(e,n),shellMode:n}]}function bx(e,t){let n={...t},o=[],r=[],s=null,a=!1,i=1,d=1,l=0;function u(){var L;return(L=n.device)!=null?L:"desktop"}function p(){var L;return(L=n.zoom)!=null?L:i}function f(){var k,F;let L=getComputedStyle(e),H=parseFloat(L.paddingLeft)+parseFloat(L.paddingRight),D=parseFloat(L.paddingTop)+parseFloat(L.paddingBottom),B=40,v=((k=n.compareMode)!=null?k:"off")!=="off",w=(e.clientWidth-H-B)/(v?2:1),E=e.clientHeight-D-B;if(w<=0||E<=0)return 1;let S=(F=ts[u()])!=null?F:ts.desktop;return Math.min(w/S.w,E/S.h,1)}function g(){var D,B,v;i=f();let L=Math.max($l,Math.min(Ul,p()));d=L;let H=Array.from(e.querySelectorAll(".preview-iframe-wrapper"));for(let w of H){let E=(D=w.dataset.device)!=null?D:"desktop",S=(B=ts[E])!=null?B:ts.desktop;w.style.width=`${S.w*L}px`,w.style.height=`${S.h*L}px`,E==="mobile"&&(w.style.borderRadius=`${32*L}px`);let k=w.querySelector("iframe");k&&(k.style.width=`${S.w}px`,k.style.height=`${S.h}px`,k.style.transformOrigin="top left",k.style.transition="none",k.style.transform=`scale(${L})`)}(v=n.onScaleChange)==null||v.call(n,L)}function x(){var L;(L=n.onBeforeDestroy)==null||L.call(n);for(let H of o)H.destroy();for(let H of r)H();o=[],r=[]}function C(){return Array.from(e.querySelectorAll("iframe[data-mount-id]"))}function M(){var be,ie,we,We;if(a)return;x();let L=++l,H=Xm(n),D=u(),B=((be=n.compareMode)!=null?be:"off")!=="off",v=((ie=n.scene)!=null?ie:"conversation")==="minimized",w=(we=n.widgetCssPath)!=null?we:"/widget-dist/widget.css",E=(We=n.buildSrcdoc)!=null?We:jl,S=D==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",k=ye=>`<div class="${S}" data-mount-id="${ye.mountId}" data-device="${D}" data-shell-mode="${ye.shellMode}">
|
|
194
194
|
${B?`<div class="preview-frame-meta"><span class="preview-frame-label">${Li(ye.label)}</span></div>`:""}
|
|
195
195
|
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${ye.mountId}"></iframe>
|
|
196
|
-
</div>`,
|
|
196
|
+
</div>`,F=B?`<div class="preview-compare-grid">${H.map(ye=>`<div class="preview-compare-cell">${k(ye)}</div>`).join("")}</div>`:`<div class="preview-single">${k(H[0])}</div>`;n.morphContainer?n.morphContainer(e,F):e.innerHTML=F,g();let $=C(),q=0,me=$.length,re=()=>{var Z,Ee,X,Ae,fe;if(a||L!==l)return;for(let le of $){let ue=le.dataset.mountId;if(!ue||!le.contentDocument)continue;let je=H.find(ge=>ge.mountId===ue);if(!je)continue;let j=()=>{},oe=un(je.config),Re=oe?(()=>{var Y;let ge=(Y=le.contentDocument)==null?void 0:Y.getElementById(`preview-content-${ue}`);if(!ge)return null;let ce=$m(ge,je.config),_e=le.contentDocument.createElement("div");_e.id=ue,_e.style.height="100%",_e.style.display="flex",_e.style.flexDirection="column",_e.style.flex="1",_e.style.minHeight="0",ce.host.appendChild(_e);let Le=()=>ce.syncWidgetState(tt.getState()),de=j;return j=()=>{ce.destroy(),de()},_e.__syncDock=Le,_e.__hostLayout=ce,_e})():le.contentDocument.getElementById(ue);if(!Re)continue;let tt=Om(Re,je.config);if(o.push(tt),oe&&Re.__syncDock){let ge=Re.__syncDock,ce=tt.on("widget:opened",ge),_e=tt.on("widget:closed",ge),Le=j;j=()=>{ce(),_e(),Le()},ge()}r.push(j),v&&tt.close()}if(((Z=n.scene)!=null?Z:"conversation")==="artifact"||(Ae=(X=(Ee=n.config)==null?void 0:Ee.features)==null?void 0:X.artifacts)!=null&&Ae.enabled)for(let le of o)le.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`});(ge=n.onAfterMount)==null||ge.call(n,{iframes:$,controllers:[...o]})};for(let ye of $){let Z=ye.dataset.mountId;if(!Z)continue;let Ee=H.find(X=>X.mountId===Z);Ee&&(ye.addEventListener("load",()=>{q++,q>=me&&re()},{once:!0}),ye.srcdoc=E(Z,Ee.shellMode,un(Ee.config),C))}me===0&&re()}function P(){var _;if(a)return;let W=Gm(n);if(o.length!==W.length){M();return}if(W.some(B=>{let v=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${B.mountId}"]`);return!v||v.dataset.shellMode!==B.shellMode})){M();return}o.forEach((B,v)=>{var C;B.update(W[v].config),((C=n.scene)!=null?C:"conversation")==="minimized"&&B.close()});for(let B of W){let v=e.querySelector(`iframe[data-mount-id="${B.mountId}"]`);v&&ql(v,B.shellMode)}(_=n.onAfterUpdate)==null||_.call(n,{iframes:x(),controllers:[...o]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||m()}),s.observe(e)),M(),{update(W){if(a)return;let H=W.device!==void 0&&W.device!==n.device||W.scene!==void 0&&W.scene!==n.scene||W.compareMode!==void 0&&W.compareMode!==n.compareMode||W.widgetCssPath!==void 0&&W.widgetCssPath!==n.widgetCssPath;n={...n,...W},H?M():P()},destroy(){a||(a=!0,w(),s==null||s.disconnect(),e.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},m())},getIframes(){return x()},getScale(){return d},setZoom(W){a||(n={...n,zoom:W},m())}}}function Vo(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}var Ri={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"},gx=/^rgba?\(\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*(,\s*(0|1|0?\.\d+|\d{1,3}%)\s*)?\)$/;function hx(e){return gx.test(e)}function ns(e){if(typeof e!="string"||e.trim()==="")throw new Error('Color must be a non-empty string (e.g. "#2563eb" or "blue").');let t=e.trim().toLowerCase(),n=Ri[t];if(n)return n;let o=ks(t);if(Gi(o)||o==="transparent"||hx(o))return o;throw new Error(`"${e}" is not a recognized color. Pass a hex value like "#ef4444" or a CSS color name (e.g. ${Object.keys(Ri).slice(0,6).join(", ")}).`)}var Pi=Ea.map(e=>e==="gray"?"neutral":e),bx={...Object.fromEntries(Pi.map(e=>[e,e])),gray:"neutral",grey:"neutral"};function Wi(e,t=!0){let n=String(e!=null?e:"").trim().toLowerCase(),o=bx[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 Bi(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 Hi(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 yx={sharp:"sharp",square:"sharp",none:"sharp",default:"default",normal:"default",rounded:"rounded",round:"rounded",soft:"rounded",pill:"pill",circle:"pill",full:"pill"};function Di(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=yx[t];if(!n)throw new Error(`Unknown roundness "${e}". Valid: sharp, default, rounded, pill.`);return n}function Fi(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=ji(t);return Ki(n.value,n.unit)}throw new Error('Radius must be a number (px) or a CSS length string like "0.5rem".')}function Oi(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 Ym=Oi("typo-font-family"),Zs=Oi("typo-font-size"),ea=Oi("typo-font-weight"),Ii=Oi("typo-line-height"),Xm={...Ym,monospace:Ym.mono},Qm={...Zs,small:Zs.sm,md:Zs.base,medium:Zs.base,large:Zs.lg},Jm={...ea,400:ea.normal,500:ea.medium,600:ea.semibold,700:ea.bold},Zm={...Ii,"1.25":Ii.tight,"1.5":Ii.normal,"1.625":Ii.relaxed};function ef(e,t,n){let o=String(e!=null?e:"").trim().toLowerCase(),r=t[o];if(!r){let s=[...new Set(Object.values(t).map(a=>a.split(".").pop()))].join(", ");throw new Error(`Unknown ${n} "${e}". Valid: ${s}.`)}return r}var tf="theme.palette.radius.";function vx(){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(tf)&&typeof i=="string"&&(s[a.slice(tf.length)]=i);e[r[1]]=s}return e}var na=vx(),nf=["sm","md","lg","xl","full"];function _i(e,t,n="theme",o=0){if(o>6)return null;let r=e.get(`${n}.${t}`);return typeof r!="string"||r===""?n==="darkTheme"?_i(e,t,"theme",o):null:r.startsWith("#")||r.startsWith("rgb")||r==="transparent"?r:r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components.")?_i(e,r,n,o+1):null}function Ni(e,t){let n=e.get(t);if(typeof n!="string")return"unknown";let o=n.split(".");return o[o.length-1]||String(n)}function os(e){return e.replace(/^role-/,"")}function xx(e){for(let[t,n]of Object.entries(na))if(nf.every(o=>e[o]===n[o]))return t;return"custom"}function Lr(e){var o,r;let t={};for(let s of nf)t[s]=String((o=e.get(`theme.palette.radius.${s}`))!=null?o:"");let n={};for(let s of xr)n[os(s.roleId)]=Ji(a=>e.get(`theme.${a}`),s);return{brand:{primary:Yl(e.get("theme.palette.colors.primary.500")),secondary:Yl(e.get("theme.palette.colors.secondary.500")),accent:Yl(e.get("theme.palette.colors.accent.500"))},roles:n,typography:{fontFamily:Ni(e,"theme.semantic.typography.fontFamily"),fontSize:Ni(e,"theme.semantic.typography.fontSize"),fontWeight:Ni(e,"theme.semantic.typography.fontWeight"),lineHeight:Ni(e,"theme.semantic.typography.lineHeight")},roundness:{style:xx(t),radius:t},colorScheme:String((r=e.get("colorScheme"))!=null?r:"light"),history:{index:e.getHistoryIndex(),canUndo:e.canUndo(),canRedo:e.canRedo()}}}function Yl(e){return typeof e=="string"&&e!==""?e:null}var ta=[{key:"user-message",label:"User message text",fg:"components.message.user.text",bg:"components.message.user.background"},{key:"assistant-message",label:"Assistant message text",fg:"components.message.assistant.text",bg:"components.message.assistant.background"},{key:"header",label:"Header title",fg:"components.header.titleForeground",bg:"components.header.background"},{key:"primary-button",label:"Primary button label",fg:"components.button.primary.foreground",bg:"components.button.primary.background"},{key:"input",label:"Input placeholder",fg:"components.input.placeholder",bg:"components.input.background"},{key:"link",label:"Link text",fg:"components.markdown.link.foreground",bg:"semantic.colors.background"},{key:"scroll",label:"Scroll-to-bottom icon",fg:"components.scrollToBottom.foreground",bg:"components.scrollToBottom.background"},{key:"body",label:"Body text on background",fg:"semantic.colors.text",bg:"semantic.colors.background"},{key:"surface",label:"Body text on surface",fg:"semantic.colors.text",bg:"semantic.colors.surface"}];function of(e){let t=new Set(e.targets.map(n=>n.path));return ta.filter(n=>t.has(n.fg)||t.has(n.bg)).map(n=>n.key)}var wx={AA:4.5,AAA:7};function Cx(e){return Math.round(e*100)/100}function Sx(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,u=1/0;return Ur.forEach((p,g)=>{let m=e.get(`${r}.palette.colors.${i}.${p}`);if(!(typeof m!="string"||!(m.startsWith("#")||m.startsWith("rgb")))&&ka(m,n)>=o){let w=d>=0?Math.abs(g-d):g;w<u&&(u=w,l=`palette.colors.${i}.${p}`)}}),l}function oa(e,t="AA",n="both",o){let r=wx[t],s=n==="both"?["light","dark"]:[n],a=o?ta.filter(d=>o.includes(d.key)):ta,i=[];for(let d of s){let l=d==="light"?"theme":"darkTheme";for(let u of a){let p=_i(e,u.fg,l),g=_i(e,u.bg,l);if(!p||!g)continue;let m=Cx(ka(p,g)),w=m>=r,x={pair:u.key,label:u.label,variant:d,fg:p,bg:g,ratio:m,threshold:r,passes:w};if(!w){let M=Sx(e,u.fg,g,r,l);M&&(x.suggestion=M)}i.push(x)}}return{level:t,checks:i,failures:i.filter(d=>!d.passes)}}function rs(e,t,n="light",o="AA"){return t.length===0?[]:oa(e,o,n,t).failures.map(s=>({code:"contrast",pair:s.pair,variant:s.variant,ratio:s.ratio,threshold:s.threshold,message:`${s.label} (${s.variant}) has a contrast ratio of ${s.ratio}:1, below the ${o} threshold of ${s.threshold}:1${s.suggestion?`. Try ${s.suggestion} for the foreground.`:"."}`}))}var an={};for(let e of xr){let t=os(e.roleId);an[t]=e,an[e.roleId]=e}Object.assign(an,{surface:an.surfaces,background:an.surfaces,backgrounds:an.surfaces,user:an["user-messages"],"user-message":an["user-messages"],assistant:an["assistant-messages"],"assistant-message":an["assistant-messages"],actions:an["primary-actions"],buttons:an["primary-actions"],composer:an.input,links:an["links-focus"],focus:an["links-focus"],border:an.borders,dividers:an.borders,scroll:an["scroll-to-bottom"]});function Ax(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=an[t];if(!n){let o=xr.map(r=>os(r.roleId)).join(", ");throw new Error(`Unknown role "${e}". Valid roles: ${o}.`)}return n}function rf(){let e=new Map,t=n=>{for(let o of n)for(let r of o.fields)e.has(r.id)||e.set(r.id,r)};for(let n of el)t(n.sections);for(let n of Oa)t(n.sections);return e}var Tx={voice:"voiceRecognition.enabled",artifacts:"features.artifacts.enabled",attachments:"attachments.enabled",toolCalls:"features.showToolCalls",reasoning:"features.showReasoning",feedback:"messageActions.enabled"},kx={avatars:"layout.messages.avatar.show",timestamps:"layout.messages.timestamp.show",showHeader:"layout.showHeader",messageStyle:"layout.messages.layout"},Xl=["bottom-right","bottom-left","top-right","top-left"],Ql=["bubble","flat","minimal"],Ex={title:"copy.welcomeTitle",subtitle:"copy.welcomeSubtitle",placeholder:"copy.inputPlaceholder",sendLabel:"copy.sendButtonLabel"};function sf(e,t){var B;let n=(B=t==null?void 0:t.editTarget)!=null?B:"both",o=null,r=v=>v&&typeof v=="object"?v:{},s=(v,C,E=n)=>{let S={};return(E==="light"||E==="both")&&(S[`theme.${v}`]=C),(E==="dark"||E==="both")&&(S[`darkTheme.${v}`]=C),S},a=v=>{if(n==="both")return v;let C={};for(let[E,S]of Object.entries(v))(n==="light"&&E.startsWith("theme.")||n==="dark"&&E.startsWith("darkTheme."))&&(C[E]=S);return C},i=()=>n==="dark"?"dark":"light",d=(v,C=[])=>Vo({ok:!0,summary:Lr(e),warnings:C,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:C}=r(v),E={summary:Lr(e),availableRoles:xr.map(S=>({role:os(S.roleId),helper:S.helper})),availableFamilies:Pi,presets:Ms.map(S=>{var k;return{id:S.id,name:S.name,description:S.description,tags:(k=S.tags)!=null?k:[]}}),tools:[{tool:"set_brand_colors",hint:"Recolor the palette (primary/secondary/accent) \u2014 auto-generates shade scales."},{tool:"assign_color_role",hint:"Recolor a region (header, user/assistant messages, actions, input, links, borders, surfaces, scroll) with a family + intensity."},{tool:"set_typography",hint:"Set font family, size, weight, line height."},{tool:"set_roundness",hint:"Set corner roundness (sharp/default/rounded/pill) or granular radii."},{tool:"set_color_scheme",hint:"Set light/dark/auto and which variant edits target."},{tool:"apply_preset",hint:"Apply a complete built-in preset."},{tool:"configure_widget",hint:"Toggle launcher position, features, and layout."},{tool:"set_copy_and_suggestions",hint:"Set welcome copy, placeholder, and suggestion chips."},{tool:"set_theme_fields",hint:"Advanced escape hatch: set any field by id or dot-path."},{tool:"check_contrast",hint:"Audit WCAG contrast across key text/background pairs."},{tool:"manage_session",hint:"Undo, redo, reset, or export the theme."}]};return C==="full"&&(o!=null||(o=rf()),E.fieldIndex=Array.from(o.values()).map(S=>{var k;return{id:S.id,path:S.path,type:S.type,label:S.label,options:(k=S.options)==null?void 0:k.map(D=>D.value)}})),Vo(E)}},{name:"set_brand_colors",title:"Set brand colors",description:'Set one or more brand colors (primary, secondary, accent). Each color auto-generates a full 50\u2013950 shade scale and applies to the light and dark themes (per the current edit target). Accepts hex ("#2563eb", "2563eb", "#18f"), rgb()/rgba() ("rgb(37, 99, 235)"), or CSS color names ("blue", "slateblue").',inputSchema:{type:"object",properties:{primary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},secondary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},accent:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."}},additionalProperties:!1},execute(v){let C=r(v),E=["primary","secondary","accent"],S={},k={};for(let $ of E){if(C[$]===void 0)continue;let q=ns(C[$]);k[$]=q;let me=Xi(q);for(let re of Ur){let be=me[re];be!==void 0&&Object.assign(S,s(`palette.colors.${$}.${re}`,be))}}if(Object.keys(k).length===0)throw new Error("Provide at least one of: primary, secondary, accent.");e.setBatch(S);let D=rs(e,["primary-button","user-message"],i());return d(k,D)}},{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:Pi},intensity:{type:"string",enum:["solid","soft"],description:"Defaults to 'solid'."}},required:["role","family"],additionalProperties:!1},execute(v){let C=r(v),E=Ax(C.role),S=Wi(C.family,!0),k=Bi(C.intensity),D=a(Fa(S,k,E)),$=Object.keys(D).length;e.setBatch(D);let q=rs(e,of(E),i());return d({role:os(E.roleId),family:S,intensity:k,tokensWritten:$},q)}},{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 C=r(v),E={},S={},k=(D,$)=>{var me;if(C[D]===void 0)return;let q=ef(C[D],$,D);S[D]=(me=q.split(".").pop())!=null?me:q,Object.assign(E,s(`semantic.typography.${D}`,q))};if(k("fontFamily",Xm),k("fontSize",Qm),k("fontWeight",Jm),k("lineHeight",Zm),Object.keys(S).length===0)throw new Error("Provide at least one of: fontFamily, fontSize, fontWeight, lineHeight.");return e.setBatch(E),d(S)}},{name:"set_roundness",title:"Set corner roundness",description:"Set overall corner roundness with a keyword (sharp, default, rounded, pill) which maps the full radius scale, OR pass granular radius values. Provide at least one of `style` or `radius`.",inputSchema:{type:"object",properties:{style:{type:"string",enum:["sharp","default","rounded","pill"]},radius:{type:"object",description:"Granular overrides (px number or CSS length).",properties:{sm:{type:["string","number"]},md:{type:["string","number"]},lg:{type:["string","number"]},xl:{type:["string","number"]},full:{type:["string","number"]}},additionalProperties:!1}},additionalProperties:!1},execute(v){let C=r(v),E={},S={};if(C.style!==void 0){let k=Di(C.style);S.style=k;for(let[D,$]of Object.entries(na[k]))Object.assign(E,s(`palette.radius.${D}`,$))}if(C.radius!==void 0){let k=r(C.radius),D={};for(let $ of["sm","md","lg","xl","full"]){if(k[$]===void 0)continue;let q=Fi(k[$]);D[$]=q,Object.assign(E,s(`palette.radius.${$}`,q))}S.radius=D}if(Object.keys(E).length===0)throw new Error("Provide `style` (sharp|default|rounded|pill) or a `radius` object.");return e.setBatch(E),d(S)}},{name:"set_color_scheme",title:"Set color scheme",description:"Set the shipped widget color scheme (light, dark, or auto/follow-system). Optionally set `editTarget` to choose which theme variant subsequent styling edits write to (light, dark, or both \u2014 default both).",inputSchema:{type:"object",properties:{scheme:{type:"string",enum:["light","dark","auto"]},editTarget:{type:"string",enum:["light","dark","both"]}},additionalProperties:!1},execute(v){let C=r(v),E={};if(C.scheme!==void 0){let S=Hi(C.scheme);e.set("colorScheme",S),E.scheme=S}if(C.editTarget!==void 0){let S=String(C.editTarget).trim().toLowerCase();if(S!=="light"&&S!=="dark"&&S!=="both")throw new Error(`Unknown editTarget "${C.editTarget}". Valid: light, dark, both.`);n=S,E.editTarget=S}if(Object.keys(E).length===0)throw new Error("Provide `scheme` and/or `editTarget`.");return Vo({ok:!0,summary:Lr(e),warnings:[],applied:E,editTarget:n})}},{name:"apply_preset",title:"Apply a built-in theme preset",description:"Apply a complete built-in preset, replacing theme tokens. Call get_theme_overview to list preset ids.",inputSchema:{type:"object",properties:{presetId:{type:"string"}},required:["presetId"],additionalProperties:!1},execute(v){let{presetId:C}=r(v),E=tl(String(C!=null?C:""));if(!E){let $=Ms.map(q=>q.id).join(", ");throw new Error(`Unknown preset "${C}". Valid presets: ${$}.`)}let S=nn(E.theme,{validate:!1}),k={...e.getConfig()};E.darkTheme&&(k.darkTheme=nn(E.darkTheme,{validate:!1})),E.toolCall&&(k.toolCall=E.toolCall),e.setFullConfig(k,S);let D=rs(e,["body","assistant-message"],"light");return d({appliedPreset:{id:E.id,name:E.name}},D)}},{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:Xl},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:Ql}},additionalProperties:!1}},additionalProperties:!1},execute(v){var $,q,me;let C=r(v),E={},S={};if(C.launcherPosition!==void 0){let re=String(C.launcherPosition);if(!Xl.includes(re))throw new Error(`Unknown launcherPosition "${re}". Valid: ${Xl.join(", ")}.`);E["launcher.position"]=re,S.launcherPosition=re}let k=r(C.features);for(let[re,be]of Object.entries(Tx))k[re]!==void 0&&(E[be]=!!k[re],($=S.features)!=null||(S.features={}),S.features[re]=!!k[re]);let D=r(C.layout);for(let[re,be]of Object.entries(kx))if(D[re]!==void 0)if(re==="messageStyle"){let ie=String(D[re]);if(!Ql.includes(ie))throw new Error(`Unknown messageStyle "${ie}". Valid: ${Ql.join(", ")}.`);E[be]=ie,(q=S.layout)!=null||(S.layout={}),S.layout[re]=ie}else E[be]=!!D[re],(me=S.layout)!=null||(S.layout={}),S.layout[re]=!!D[re];if(Object.keys(E).length===0)throw new Error("Provide launcherPosition, features, and/or layout.");return e.setBatch(E),d(S)}},{name:"set_copy_and_suggestions",title:"Set welcome copy and suggestion chips",description:"Set the widget welcome copy and suggestion chips. title/subtitle are the welcome card text; placeholder is the input placeholder; sendLabel is the send button label; suggestions is an array of suggestion-chip strings (replaces the existing list).",inputSchema:{type:"object",properties:{title:{type:"string"},subtitle:{type:"string"},placeholder:{type:"string"},sendLabel:{type:"string"},suggestions:{type:"array",items:{type:"string"}}},additionalProperties:!1},execute(v){let C=r(v),E={},S={};for(let[k,D]of Object.entries(Ex))C[k]!==void 0&&(E[D]=String(C[k]),S[k]=String(C[k]));if(C.suggestions!==void 0){if(!Array.isArray(C.suggestions))throw new Error("`suggestions` must be an array of strings.");let k=C.suggestions.filter(D=>typeof D=="string");E.suggestionChips=k,S.suggestions=k}if(Object.keys(E).length===0)throw new Error("Provide at least one of: title, subtitle, placeholder, sendLabel, suggestions.");return e.setBatch(E),d(S)}},{name:"set_theme_fields",title:"Set theme fields by id or path (advanced)",description:'Advanced escape hatch: set individual editor fields by field id (see get_theme_overview verbosity:"full") \u2014 theme field ids follow the current edit target (light/dark/both) \u2014 or by raw dot-path (theme.* / darkTheme.* / a config path), which is written as-is. Use only when a higher-level tool does not cover the need. Values are validated against the field metadata.',inputSchema:{type:"object",properties:{updates:{type:"array",items:{type:"object",properties:{field:{type:"string",description:"Field id or dot-path."},value:{type:["string","number","boolean"]}},required:["field","value"],additionalProperties:!1}}},required:["updates"],additionalProperties:!1},execute(v){var D;let{updates:C}=r(v);if(!Array.isArray(C)||C.length===0)throw new Error("`updates` must be a non-empty array of { field, value }.");o!=null||(o=rf());let E={},S=[];for(let $ of C){let q=r($),me=String((D=q.field)!=null?D:"");try{let re=o.get(me),be=re?re.path:me;if(!re&&!/^(theme|darkTheme)\.|\./.test(be))throw new Error(`Unknown field "${me}". Pass a known field id or a dot-path (e.g. theme.palette.radius.md).`);let ie=Mx(re,q.value);if(re&&be.startsWith("theme.")){let we=s(be.slice(6),ie);Object.assign(E,we),S.push({field:me,resolvedPath:Object.keys(we),ok:!0})}else E[be]=ie,S.push({field:me,resolvedPath:be,ok:!0})}catch(re){S.push({field:me,ok:!1,error:re.message})}}let k=S.filter($=>$.ok);return Object.keys(E).length>0&&e.setBatch(E),Vo({ok:k.length>0,summary:Lr(e),warnings:[],applied:{updates:S}})}},{name:"check_contrast",title:"Check accessibility contrast",description:"Run WCAG contrast checks over the key text/background pairs (message text, header title, input/body text, primary button). Returns each ratio, whether it passes, and a suggested foreground shade for failures.",annotations:{readOnlyHint:!0},inputSchema:{type:"object",properties:{level:{type:"string",enum:["AA","AAA"],description:"Defaults to 'AA'."},variant:{type:"string",enum:["light","dark","both"],description:"Defaults to 'both'."}},additionalProperties:!1},execute(v){let C=r(v),E=C.level==="AAA"?"AAA":"AA",S=C.variant==="light"||C.variant==="dark"?C.variant:"both",k=oa(e,E,S);return Vo({level:k.level,passing:k.checks.length-k.failures.length,total:k.checks.length,checks:k.checks,failures:k.failures})}},{name:"manage_session",title:"Undo, redo, reset, or export the theme",description:'Session action. "undo"/"redo" step through edit history; "reset" restores defaults; "export" returns the embeddable theme snapshot (config + theme JSON) with no side effects.',inputSchema:{type:"object",properties:{action:{type:"string",enum:["undo","redo","reset","export"]}},required:["action"],additionalProperties:!1},execute(v){let{action:C}=r(v);switch(C){case"undo":return e.undo(),d({action:"undo"});case"redo":return e.redo(),d({action:"redo"});case"reset":return e.resetToDefaults(),d({action:"reset"});case"export":return Vo({ok:!0,snapshot:e.exportSnapshot()});default:throw new Error(`Unknown action "${C}". Valid: undo, redo, reset, export.`)}}}]}function Mx(e,t){if(!e)return t;switch(e.type){case"color":return e.parseValue?e.parseValue(ns(t)):ns(t);case"toggle":return typeof t=="boolean"?t:t==="true"||t===1;case"slider":{let n=Number(t);if(!Number.isFinite(n))throw new Error(`"${e.id}" expects a number.`);if(e.slider){let{min:o,max:r}=e.slider;if(n<o||n>r)throw new Error(`"${e.id}" must be between ${o} and ${r}.`)}return e.parseValue?e.parseValue(n):n}case"select":{let n=String(t);if(e.options&&!e.options.some(o=>o.value===n))throw new Error(`"${e.id}" must be one of: ${e.options.map(o=>o.value).join(", ")}.`);return e.parseValue?e.parseValue(n):n}default:return e.parseValue?e.parseValue(t):t}}export{bu as ADVANCED_TOKENS_SECTION,xr as ALL_ROLES,el as ALL_TABS,mu as BRAND_PALETTE_SECTION,vu as BUILT_IN_PRESETS,Ff as COLORS_SECTIONS,Qi as COLOR_FAMILIES,du as COMPONENTS_SECTIONS,cu as COMPONENT_COLOR_SECTIONS,lu as COMPONENT_SHAPE_SECTIONS,pu as CONFIGURE_SECTIONS,Oa as CONFIGURE_SUB_GROUPS,ta as CONTRAST_PAIRS,Ri as CSS_NAMED_COLORS,ts as DEVICE_DIMENSIONS,$m as HOME_SUGGESTION_CHIPS,gu as INTERFACE_ROLES_SECTION,zm as MOCK_BROWSER_CONTENT,qm as MOCK_WORKSPACE_CONTENT,Hf as PALETTE_SECTION,Vm as PREVIEW_STORAGE_ADAPTER,na as RADIUS_PRESETS,Ra as ROLE_ASSISTANT_MESSAGES,Da as ROLE_BORDERS,Ea as ROLE_FAMILIES,Cf as ROLE_FAMILY_LABELS,La as ROLE_HEADER,Ba as ROLE_INPUT,ko as ROLE_INTENSITIES,Ha as ROLE_LINKS_FOCUS,Pa as ROLE_PRIMARY_ACTIONS,Wa as ROLE_SCROLL_TO_BOTTOM,Ma as ROLE_SURFACES,Ia as ROLE_USER_MESSAGES,Df as SEMANTIC_COLORS_SECTION,Ur as SHADE_KEYS,Mi as SHELL_STYLE_ID,hu as STATUS_COLORS_SECTION,fu as STATUS_PALETTE_SECTION,zr as STYLE_SECTIONS,vg as STYLE_SECTIONS_V2,Ms as THEME_EDITOR_PRESETS,uu as THEME_SECTION,qi as ThemeEditorState,Ul as ZOOM_MAX,$l as ZOOM_MIN,cx as appendPreviewTranscriptEntry,Gl as applySceneConfig,ql as applyShellTheme,Mr as buildPreviewConfig,mx as buildPreviewConfigWithMessages,zl as buildShellCss,jl as buildSrcdoc,Lr as buildSummary,dx as buildTranscriptStreamFrames,ns as coerceColor,Wi as coerceFamily,Bi as coerceIntensity,Fi as coerceRadius,Di as coerceRoundnessStyle,Hi as coerceScheme,vf as convertFromPx,yf as convertToPx,Km as createPreviewMessages,Kl as createPreviewTranscriptEntry,sf as createThemeEditorTools,fx as createThemePreview,Ji as detectRoleAssignment,Li as escapeHtml,wg as findSection,Ki as formatCssValue,Xi as generateColorScale,lx as getPreviewTranscriptPresetLabel,Um as getShellPalette,tl as getThemeEditorPreset,ou as hexToHsl,ru as hslToHex,Gi as isValidHex,ks as normalizeColorValue,xf as paletteColorPath,ji as parseCssValue,jm as presetStreamsText,rs as quickContrastWarnings,Fa as resolveRoleAssignment,su as resolveThemeColorPath,Yi as rgbToHex,oa as runContrastChecks,Cg as scopeSection,wf as tokenRefDisplayName,Vo as toolResult,ka as wcagContrastRatio};
|
|
204
|
+
- Resizable panes`});(fe=n.onAfterMount)==null||fe.call(n,{iframes:$,controllers:[...o]})};for(let ye of $){let Z=ye.dataset.mountId;if(!Z)continue;let Ee=H.find(X=>X.mountId===Z);Ee&&(ye.addEventListener("load",()=>{q++,q>=me&&re()},{once:!0}),ye.srcdoc=E(Z,Ee.shellMode,un(Ee.config),w))}me===0&&re()}function W(){var D;if(a)return;let L=Xm(n);if(o.length!==L.length){M();return}if(L.some(B=>{let v=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${B.mountId}"]`);return!v||v.dataset.shellMode!==B.shellMode})){M();return}o.forEach((B,v)=>{var w;B.update(L[v].config),((w=n.scene)!=null?w:"conversation")==="minimized"&&B.close()});for(let B of L){let v=e.querySelector(`iframe[data-mount-id="${B.mountId}"]`);v&&ql(v,B.shellMode)}(D=n.onAfterUpdate)==null||D.call(n,{iframes:C(),controllers:[...o]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||g()}),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():W()},destroy(){a||(a=!0,x(),s==null||s.disconnect(),e.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},g())},getIframes(){return C()},getScale(){return d},setZoom(L){a||(n={...n,zoom:L},g())}}}function Vo(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}var Ri={black:"#000000",white:"#ffffff",red:"#ff0000",green:"#008000",lime:"#00ff00",blue:"#0000ff",yellow:"#ffff00",cyan:"#00ffff",aqua:"#00ffff",magenta:"#ff00ff",fuchsia:"#ff00ff",silver:"#c0c0c0",gray:"#808080",grey:"#808080",maroon:"#800000",olive:"#808000",purple:"#800080",teal:"#008080",navy:"#000080",orange:"#ffa500",pink:"#ffc0cb",hotpink:"#ff69b4",gold:"#ffd700",indigo:"#4b0082",violet:"#ee82ee",brown:"#a52a2a",beige:"#f5f5dc",ivory:"#fffff0",khaki:"#f0e68c",coral:"#ff7f50",salmon:"#fa8072",tomato:"#ff6347",crimson:"#dc143c",turquoise:"#40e0d0",lavender:"#e6e6fa",plum:"#dda0dd",orchid:"#da70d6",tan:"#d2b48c",chocolate:"#d2691e",sienna:"#a0522d",slategray:"#708090",slategrey:"#708090",steelblue:"#4682b4",royalblue:"#4169e1",dodgerblue:"#1e90ff",skyblue:"#87ceeb",lightblue:"#add8e6",midnightblue:"#191970",forestgreen:"#228b22",seagreen:"#2e8b57",limegreen:"#32cd32",olivedrab:"#6b8e23",darkgreen:"#006400",emerald:"#50c878",mint:"#3eb489",goldenrod:"#daa520",firebrick:"#b22222",darkred:"#8b0000",indianred:"#cd5c5c",deeppink:"#ff1493",mediumpurple:"#9370db",rebeccapurple:"#663399",darkviolet:"#9400d3",slateblue:"#6a5acd",cornflowerblue:"#6495ed",teal2:"#008080",charcoal:"#36454f",graphite:"#3b3b3b",transparent:"transparent"},yx=/^rgba?\(\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*(,\s*(0|1|0?\.\d+|\d{1,3}%)\s*)?\)$/;function vx(e){return yx.test(e)}function ns(e){if(typeof e!="string"||e.trim()==="")throw new Error('Color must be a non-empty string (e.g. "#2563eb" or "blue").');let t=e.trim().toLowerCase(),n=Ri[t];if(n)return n;let o=ks(t);if(Gi(o)||o==="transparent"||vx(o))return o;throw new Error(`"${e}" is not a recognized color. Pass a hex value like "#ef4444" or a CSS color name (e.g. ${Object.keys(Ri).slice(0,6).join(", ")}).`)}var Pi=Ea.map(e=>e==="gray"?"neutral":e),xx={...Object.fromEntries(Pi.map(e=>[e,e])),gray:"neutral",grey:"neutral"};function Wi(e,t=!0){let n=String(e!=null?e:"").trim().toLowerCase(),o=xx[n];if(!o||!t&&o==="neutral"){let r=t?"primary, secondary, accent, neutral":"primary, secondary, accent";throw new Error(`Unknown color family "${e}". Valid families: ${r}.`)}return o}function Bi(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 Hi(e){let t=String(e!=null?e:"").trim().toLowerCase();if(t==="light"||t==="dark"||t==="auto")return t;if(t==="system")return"auto";throw new Error(`Unknown color scheme "${e}". Valid: light, dark, auto.`)}var wx={sharp:"sharp",square:"sharp",none:"sharp",default:"default",normal:"default",rounded:"rounded",round:"rounded",soft:"rounded",pill:"pill",circle:"pill",full:"pill"};function Di(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=wx[t];if(!n)throw new Error(`Unknown roundness "${e}". Valid: sharp, default, rounded, pill.`);return n}function Fi(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=ji(t);return Ki(n.value,n.unit)}throw new Error('Radius must be a number (px) or a CSS length string like "0.5rem".')}function Oi(e){for(let t of zr){let n=t.fields.find(o=>o.id===e);if(n!=null&&n.options){let o={};for(let r of n.options){let s=r.value.split(".").pop();s&&(o[s]=r.value)}return o}}return{}}var Qm=Oi("typo-font-family"),Zs=Oi("typo-font-size"),ea=Oi("typo-font-weight"),Ii=Oi("typo-line-height"),Jm={...Qm,monospace:Qm.mono},Zm={...Zs,small:Zs.sm,md:Zs.base,medium:Zs.base,large:Zs.lg},eg={...ea,400:ea.normal,500:ea.medium,600:ea.semibold,700:ea.bold},tg={...Ii,"1.25":Ii.tight,"1.5":Ii.normal,"1.625":Ii.relaxed};function ng(e,t,n){let o=String(e!=null?e:"").trim().toLowerCase(),r=t[o];if(!r){let s=[...new Set(Object.values(t).map(a=>a.split(".").pop()))].join(", ");throw new Error(`Unknown ${n} "${e}". Valid: ${s}.`)}return r}var og="theme.palette.radius.";function Cx(){var t;let e={pill:{sm:"9999px",md:"9999px",lg:"9999px",xl:"9999px",full:"9999px"}};for(let n of zr)for(let o of(t=n.presets)!=null?t:[]){let r=o.id.match(/^radius-(\w+)$/);if(!r)continue;let s={};for(let[a,i]of Object.entries(o.values))a.startsWith(og)&&typeof i=="string"&&(s[a.slice(og.length)]=i);e[r[1]]=s}return e}var na=Cx(),rg=["sm","md","lg","xl","full"];function _i(e,t,n="theme",o=0){if(o>6)return null;let r=e.get(`${n}.${t}`);return typeof r!="string"||r===""?n==="darkTheme"?_i(e,t,"theme",o):null:r.startsWith("#")||r.startsWith("rgb")||r==="transparent"?r:r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components.")?_i(e,r,n,o+1):null}function Ni(e,t){let n=e.get(t);if(typeof n!="string")return"unknown";let o=n.split(".");return o[o.length-1]||String(n)}function os(e){return e.replace(/^role-/,"")}function Sx(e){for(let[t,n]of Object.entries(na))if(rg.every(o=>e[o]===n[o]))return t;return"custom"}function Lr(e){var o,r;let t={};for(let s of rg)t[s]=String((o=e.get(`theme.palette.radius.${s}`))!=null?o:"");let n={};for(let s of xr)n[os(s.roleId)]=Ji(a=>e.get(`theme.${a}`),s);return{brand:{primary:Yl(e.get("theme.palette.colors.primary.500")),secondary:Yl(e.get("theme.palette.colors.secondary.500")),accent:Yl(e.get("theme.palette.colors.accent.500"))},roles:n,typography:{fontFamily:Ni(e,"theme.semantic.typography.fontFamily"),fontSize:Ni(e,"theme.semantic.typography.fontSize"),fontWeight:Ni(e,"theme.semantic.typography.fontWeight"),lineHeight:Ni(e,"theme.semantic.typography.lineHeight")},roundness:{style:Sx(t),radius:t},colorScheme:String((r=e.get("colorScheme"))!=null?r:"light"),history:{index:e.getHistoryIndex(),canUndo:e.canUndo(),canRedo:e.canRedo()}}}function Yl(e){return typeof e=="string"&&e!==""?e:null}var ta=[{key:"user-message",label:"User message text",fg:"components.message.user.text",bg:"components.message.user.background"},{key:"assistant-message",label:"Assistant message text",fg:"components.message.assistant.text",bg:"components.message.assistant.background"},{key:"header",label:"Header title",fg:"components.header.titleForeground",bg:"components.header.background"},{key:"primary-button",label:"Primary button label",fg:"components.button.primary.foreground",bg:"components.button.primary.background"},{key:"input",label:"Input placeholder",fg:"components.input.placeholder",bg:"components.input.background"},{key:"link",label:"Link text",fg:"components.markdown.link.foreground",bg:"semantic.colors.background"},{key:"scroll",label:"Scroll-to-bottom icon",fg:"components.scrollToBottom.foreground",bg:"components.scrollToBottom.background"},{key:"body",label:"Body text on background",fg:"semantic.colors.text",bg:"semantic.colors.background"},{key:"surface",label:"Body text on surface",fg:"semantic.colors.text",bg:"semantic.colors.surface"}];function sg(e){let t=new Set(e.targets.map(n=>n.path));return ta.filter(n=>t.has(n.fg)||t.has(n.bg)).map(n=>n.key)}var Ax={AA:4.5,AAA:7};function Tx(e){return Math.round(e*100)/100}function kx(e,t,n,o,r){let s=e.get(`${r}.${t}`);if(typeof s!="string")return null;let a=s.match(/^palette\.colors\.(\w+)\.(\d+)$/);if(!a)return null;let i=a[1],d=Ur.indexOf(a[2]),l=null,u=1/0;return Ur.forEach((p,f)=>{let g=e.get(`${r}.palette.colors.${i}.${p}`);if(!(typeof g!="string"||!(g.startsWith("#")||g.startsWith("rgb")))&&ka(g,n)>=o){let x=d>=0?Math.abs(f-d):f;x<u&&(u=x,l=`palette.colors.${i}.${p}`)}}),l}function oa(e,t="AA",n="both",o){let r=Ax[t],s=n==="both"?["light","dark"]:[n],a=o?ta.filter(d=>o.includes(d.key)):ta,i=[];for(let d of s){let l=d==="light"?"theme":"darkTheme";for(let u of a){let p=_i(e,u.fg,l),f=_i(e,u.bg,l);if(!p||!f)continue;let g=Tx(ka(p,f)),x=g>=r,C={pair:u.key,label:u.label,variant:d,fg:p,bg:f,ratio:g,threshold:r,passes:x};if(!x){let M=kx(e,u.fg,f,r,l);M&&(C.suggestion=M)}i.push(C)}}return{level:t,checks:i,failures:i.filter(d=>!d.passes)}}function rs(e,t,n="light",o="AA"){return t.length===0?[]:oa(e,o,n,t).failures.map(s=>({code:"contrast",pair:s.pair,variant:s.variant,ratio:s.ratio,threshold:s.threshold,message:`${s.label} (${s.variant}) has a contrast ratio of ${s.ratio}:1, below the ${o} threshold of ${s.threshold}:1${s.suggestion?`. Try ${s.suggestion} for the foreground.`:"."}`}))}var an={};for(let e of xr){let t=os(e.roleId);an[t]=e,an[e.roleId]=e}Object.assign(an,{surface:an.surfaces,background:an.surfaces,backgrounds:an.surfaces,user:an["user-messages"],"user-message":an["user-messages"],assistant:an["assistant-messages"],"assistant-message":an["assistant-messages"],actions:an["primary-actions"],buttons:an["primary-actions"],composer:an.input,links:an["links-focus"],focus:an["links-focus"],border:an.borders,dividers:an.borders,scroll:an["scroll-to-bottom"]});function Ex(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=an[t];if(!n){let o=xr.map(r=>os(r.roleId)).join(", ");throw new Error(`Unknown role "${e}". Valid roles: ${o}.`)}return n}function ag(){let e=new Map,t=n=>{for(let o of n)for(let r of o.fields)e.has(r.id)||e.set(r.id,r)};for(let n of el)t(n.sections);for(let n of Oa)t(n.sections);return e}var Mx={voice:"voiceRecognition.enabled",artifacts:"features.artifacts.enabled",attachments:"attachments.enabled",toolCalls:"features.showToolCalls",reasoning:"features.showReasoning",feedback:"messageActions.enabled"},Lx={avatars:"layout.messages.avatar.show",timestamps:"layout.messages.timestamp.show",showHeader:"layout.showHeader",messageStyle:"layout.messages.layout"},Xl=["bottom-right","bottom-left","top-right","top-left"],Ql=["bubble","flat","minimal"],Ix={title:"copy.welcomeTitle",subtitle:"copy.welcomeSubtitle",placeholder:"copy.inputPlaceholder",sendLabel:"copy.sendButtonLabel"};function ig(e,t){var B;let n=(B=t==null?void 0:t.editTarget)!=null?B:"both",o=null,r=v=>v&&typeof v=="object"?v:{},s=(v,w,E=n)=>{let S={};return(E==="light"||E==="both")&&(S[`theme.${v}`]=w),(E==="dark"||E==="both")&&(S[`darkTheme.${v}`]=w),S},a=v=>{if(n==="both")return v;let w={};for(let[E,S]of Object.entries(v))(n==="light"&&E.startsWith("theme.")||n==="dark"&&E.startsWith("darkTheme."))&&(w[E]=S);return w},i=()=>n==="dark"?"dark":"light",d=(v,w=[])=>Vo({ok:!0,summary:Lr(e),warnings:w,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:w}=r(v),E={summary:Lr(e),availableRoles:xr.map(S=>({role:os(S.roleId),helper:S.helper})),availableFamilies:Pi,presets:Ms.map(S=>{var k;return{id:S.id,name:S.name,description:S.description,tags:(k=S.tags)!=null?k:[]}}),tools:[{tool:"set_brand_colors",hint:"Recolor the palette (primary/secondary/accent) \u2014 auto-generates shade scales."},{tool:"assign_color_role",hint:"Recolor a region (header, user/assistant messages, actions, input, links, borders, surfaces, scroll) with a family + intensity."},{tool:"set_typography",hint:"Set font family, size, weight, line height."},{tool:"set_roundness",hint:"Set corner roundness (sharp/default/rounded/pill) or granular radii."},{tool:"set_color_scheme",hint:"Set light/dark/auto and which variant edits target."},{tool:"apply_preset",hint:"Apply a complete built-in preset."},{tool:"configure_widget",hint:"Toggle launcher position, features, and layout."},{tool:"set_copy_and_suggestions",hint:"Set welcome copy, placeholder, and suggestion chips."},{tool:"set_theme_fields",hint:"Advanced escape hatch: set any field by id or dot-path."},{tool:"check_contrast",hint:"Audit WCAG contrast across key text/background pairs."},{tool:"manage_session",hint:"Undo, redo, reset, or export the theme."}]};return w==="full"&&(o!=null||(o=ag()),E.fieldIndex=Array.from(o.values()).map(S=>{var k;return{id:S.id,path:S.path,type:S.type,label:S.label,options:(k=S.options)==null?void 0:k.map(F=>F.value)}})),Vo(E)}},{name:"set_brand_colors",title:"Set brand colors",description:'Set one or more brand colors (primary, secondary, accent). Each color auto-generates a full 50\u2013950 shade scale and applies to the light and dark themes (per the current edit target). Accepts hex ("#2563eb", "2563eb", "#18f"), rgb()/rgba() ("rgb(37, 99, 235)"), or CSS color names ("blue", "slateblue").',inputSchema:{type:"object",properties:{primary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},secondary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},accent:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."}},additionalProperties:!1},execute(v){let w=r(v),E=["primary","secondary","accent"],S={},k={};for(let $ of E){if(w[$]===void 0)continue;let q=ns(w[$]);k[$]=q;let me=Xi(q);for(let re of Ur){let be=me[re];be!==void 0&&Object.assign(S,s(`palette.colors.${$}.${re}`,be))}}if(Object.keys(k).length===0)throw new Error("Provide at least one of: primary, secondary, accent.");e.setBatch(S);let F=rs(e,["primary-button","user-message"],i());return d(k,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:Pi},intensity:{type:"string",enum:["solid","soft"],description:"Defaults to 'solid'."}},required:["role","family"],additionalProperties:!1},execute(v){let w=r(v),E=Ex(w.role),S=Wi(w.family,!0),k=Bi(w.intensity),F=a(Fa(S,k,E)),$=Object.keys(F).length;e.setBatch(F);let q=rs(e,sg(E),i());return d({role:os(E.roleId),family:S,intensity:k,tokensWritten:$},q)}},{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 w=r(v),E={},S={},k=(F,$)=>{var me;if(w[F]===void 0)return;let q=ng(w[F],$,F);S[F]=(me=q.split(".").pop())!=null?me:q,Object.assign(E,s(`semantic.typography.${F}`,q))};if(k("fontFamily",Jm),k("fontSize",Zm),k("fontWeight",eg),k("lineHeight",tg),Object.keys(S).length===0)throw new Error("Provide at least one of: fontFamily, fontSize, fontWeight, lineHeight.");return e.setBatch(E),d(S)}},{name:"set_roundness",title:"Set corner roundness",description:"Set overall corner roundness with a keyword (sharp, default, rounded, pill) which maps the full radius scale, OR pass granular radius values. Provide at least one of `style` or `radius`.",inputSchema:{type:"object",properties:{style:{type:"string",enum:["sharp","default","rounded","pill"]},radius:{type:"object",description:"Granular overrides (px number or CSS length).",properties:{sm:{type:["string","number"]},md:{type:["string","number"]},lg:{type:["string","number"]},xl:{type:["string","number"]},full:{type:["string","number"]}},additionalProperties:!1}},additionalProperties:!1},execute(v){let w=r(v),E={},S={};if(w.style!==void 0){let k=Di(w.style);S.style=k;for(let[F,$]of Object.entries(na[k]))Object.assign(E,s(`palette.radius.${F}`,$))}if(w.radius!==void 0){let k=r(w.radius),F={};for(let $ of["sm","md","lg","xl","full"]){if(k[$]===void 0)continue;let q=Fi(k[$]);F[$]=q,Object.assign(E,s(`palette.radius.${$}`,q))}S.radius=F}if(Object.keys(E).length===0)throw new Error("Provide `style` (sharp|default|rounded|pill) or a `radius` object.");return e.setBatch(E),d(S)}},{name:"set_color_scheme",title:"Set color scheme",description:"Set the shipped widget color scheme (light, dark, or auto/follow-system). Optionally set `editTarget` to choose which theme variant subsequent styling edits write to (light, dark, or both \u2014 default both).",inputSchema:{type:"object",properties:{scheme:{type:"string",enum:["light","dark","auto"]},editTarget:{type:"string",enum:["light","dark","both"]}},additionalProperties:!1},execute(v){let w=r(v),E={};if(w.scheme!==void 0){let S=Hi(w.scheme);e.set("colorScheme",S),E.scheme=S}if(w.editTarget!==void 0){let S=String(w.editTarget).trim().toLowerCase();if(S!=="light"&&S!=="dark"&&S!=="both")throw new Error(`Unknown editTarget "${w.editTarget}". Valid: light, dark, both.`);n=S,E.editTarget=S}if(Object.keys(E).length===0)throw new Error("Provide `scheme` and/or `editTarget`.");return Vo({ok:!0,summary:Lr(e),warnings:[],applied:E,editTarget:n})}},{name:"apply_preset",title:"Apply a built-in theme preset",description:"Apply a complete built-in preset, replacing theme tokens. Call get_theme_overview to list preset ids.",inputSchema:{type:"object",properties:{presetId:{type:"string"}},required:["presetId"],additionalProperties:!1},execute(v){let{presetId:w}=r(v),E=tl(String(w!=null?w:""));if(!E){let $=Ms.map(q=>q.id).join(", ");throw new Error(`Unknown preset "${w}". Valid presets: ${$}.`)}let S=nn(E.theme,{validate:!1}),k={...e.getConfig()};E.darkTheme&&(k.darkTheme=nn(E.darkTheme,{validate:!1})),E.toolCall&&(k.toolCall=E.toolCall),e.setFullConfig(k,S);let F=rs(e,["body","assistant-message"],"light");return d({appliedPreset:{id:E.id,name:E.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:Xl},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:Ql}},additionalProperties:!1}},additionalProperties:!1},execute(v){var $,q,me;let w=r(v),E={},S={};if(w.launcherPosition!==void 0){let re=String(w.launcherPosition);if(!Xl.includes(re))throw new Error(`Unknown launcherPosition "${re}". Valid: ${Xl.join(", ")}.`);E["launcher.position"]=re,S.launcherPosition=re}let k=r(w.features);for(let[re,be]of Object.entries(Mx))k[re]!==void 0&&(E[be]=!!k[re],($=S.features)!=null||(S.features={}),S.features[re]=!!k[re]);let F=r(w.layout);for(let[re,be]of Object.entries(Lx))if(F[re]!==void 0)if(re==="messageStyle"){let ie=String(F[re]);if(!Ql.includes(ie))throw new Error(`Unknown messageStyle "${ie}". Valid: ${Ql.join(", ")}.`);E[be]=ie,(q=S.layout)!=null||(S.layout={}),S.layout[re]=ie}else E[be]=!!F[re],(me=S.layout)!=null||(S.layout={}),S.layout[re]=!!F[re];if(Object.keys(E).length===0)throw new Error("Provide launcherPosition, features, and/or layout.");return e.setBatch(E),d(S)}},{name:"set_copy_and_suggestions",title:"Set welcome copy and suggestion chips",description:"Set the widget welcome copy and suggestion chips. title/subtitle are the welcome card text; placeholder is the input placeholder; sendLabel is the send button label; suggestions is an array of suggestion-chip strings (replaces the existing list).",inputSchema:{type:"object",properties:{title:{type:"string"},subtitle:{type:"string"},placeholder:{type:"string"},sendLabel:{type:"string"},suggestions:{type:"array",items:{type:"string"}}},additionalProperties:!1},execute(v){let w=r(v),E={},S={};for(let[k,F]of Object.entries(Ix))w[k]!==void 0&&(E[F]=String(w[k]),S[k]=String(w[k]));if(w.suggestions!==void 0){if(!Array.isArray(w.suggestions))throw new Error("`suggestions` must be an array of strings.");let k=w.suggestions.filter(F=>typeof F=="string");E.suggestionChips=k,S.suggestions=k}if(Object.keys(E).length===0)throw new Error("Provide at least one of: title, subtitle, placeholder, sendLabel, suggestions.");return e.setBatch(E),d(S)}},{name:"set_theme_fields",title:"Set theme fields by id or path (advanced)",description:'Advanced escape hatch: set individual editor fields by field id (see get_theme_overview verbosity:"full") \u2014 theme field ids follow the current edit target (light/dark/both) \u2014 or by raw dot-path (theme.* / darkTheme.* / a config path), which is written as-is. Use only when a higher-level tool does not cover the need. Values are validated against the field metadata.',inputSchema:{type:"object",properties:{updates:{type:"array",items:{type:"object",properties:{field:{type:"string",description:"Field id or dot-path."},value:{type:["string","number","boolean"]}},required:["field","value"],additionalProperties:!1}}},required:["updates"],additionalProperties:!1},execute(v){var F;let{updates:w}=r(v);if(!Array.isArray(w)||w.length===0)throw new Error("`updates` must be a non-empty array of { field, value }.");o!=null||(o=ag());let E={},S=[];for(let $ of w){let q=r($),me=String((F=q.field)!=null?F:"");try{let re=o.get(me),be=re?re.path:me;if(!re&&!/^(theme|darkTheme)\.|\./.test(be))throw new Error(`Unknown field "${me}". Pass a known field id or a dot-path (e.g. theme.palette.radius.md).`);let ie=Rx(re,q.value);if(re&&be.startsWith("theme.")){let we=s(be.slice(6),ie);Object.assign(E,we),S.push({field:me,resolvedPath:Object.keys(we),ok:!0})}else E[be]=ie,S.push({field:me,resolvedPath:be,ok:!0})}catch(re){S.push({field:me,ok:!1,error:re.message})}}let k=S.filter($=>$.ok);return Object.keys(E).length>0&&e.setBatch(E),Vo({ok:k.length>0,summary:Lr(e),warnings:[],applied:{updates:S}})}},{name:"check_contrast",title:"Check accessibility contrast",description:"Run WCAG contrast checks over the key text/background pairs (message text, header title, input/body text, primary button). Returns each ratio, whether it passes, and a suggested foreground shade for failures.",annotations:{readOnlyHint:!0},inputSchema:{type:"object",properties:{level:{type:"string",enum:["AA","AAA"],description:"Defaults to 'AA'."},variant:{type:"string",enum:["light","dark","both"],description:"Defaults to 'both'."}},additionalProperties:!1},execute(v){let w=r(v),E=w.level==="AAA"?"AAA":"AA",S=w.variant==="light"||w.variant==="dark"?w.variant:"both",k=oa(e,E,S);return Vo({level:k.level,passing:k.checks.length-k.failures.length,total:k.checks.length,checks:k.checks,failures:k.failures})}},{name:"manage_session",title:"Undo, redo, reset, or export the theme",description:'Session action. "undo"/"redo" step through edit history; "reset" restores defaults; "export" returns the embeddable theme snapshot (config + theme JSON) with no side effects.',inputSchema:{type:"object",properties:{action:{type:"string",enum:["undo","redo","reset","export"]}},required:["action"],additionalProperties:!1},execute(v){let{action:w}=r(v);switch(w){case"undo":return e.undo(),d({action:"undo"});case"redo":return e.redo(),d({action:"redo"});case"reset":return e.resetToDefaults(),d({action:"reset"});case"export":return Vo({ok:!0,snapshot:e.exportSnapshot()});default:throw new Error(`Unknown action "${w}". Valid: undo, redo, reset, export.`)}}}]}function Rx(e,t){if(!e)return t;switch(e.type){case"color":return e.parseValue?e.parseValue(ns(t)):ns(t);case"toggle":return typeof t=="boolean"?t:t==="true"||t===1;case"slider":{let n=Number(t);if(!Number.isFinite(n))throw new Error(`"${e.id}" expects a number.`);if(e.slider){let{min:o,max:r}=e.slider;if(n<o||n>r)throw new Error(`"${e.id}" must be between ${o} and ${r}.`)}return e.parseValue?e.parseValue(n):n}case"select":{let n=String(t);if(e.options&&!e.options.some(o=>o.value===n))throw new Error(`"${e.id}" must be one of: ${e.options.map(o=>o.value).join(", ")}.`);return e.parseValue?e.parseValue(n):n}default:return e.parseValue?e.parseValue(t):t}}export{bu as ADVANCED_TOKENS_SECTION,xr as ALL_ROLES,el as ALL_TABS,mu as BRAND_PALETTE_SECTION,vu as BUILT_IN_PRESETS,Og as COLORS_SECTIONS,Qi as COLOR_FAMILIES,du as COMPONENTS_SECTIONS,cu as COMPONENT_COLOR_SECTIONS,lu as COMPONENT_SHAPE_SECTIONS,pu as CONFIGURE_SECTIONS,Oa as CONFIGURE_SUB_GROUPS,ta as CONTRAST_PAIRS,Ri as CSS_NAMED_COLORS,ts as DEVICE_DIMENSIONS,zm as HOME_SUGGESTION_CHIPS,fu as INTERFACE_ROLES_SECTION,jm as MOCK_BROWSER_CONTENT,Km as MOCK_WORKSPACE_CONTENT,Dg as PALETTE_SECTION,Um as PREVIEW_STORAGE_ADAPTER,na as RADIUS_PRESETS,Ra as ROLE_ASSISTANT_MESSAGES,Da as ROLE_BORDERS,Ea as ROLE_FAMILIES,Sg as ROLE_FAMILY_LABELS,La as ROLE_HEADER,Ba as ROLE_INPUT,ko as ROLE_INTENSITIES,Ha as ROLE_LINKS_FOCUS,Pa as ROLE_PRIMARY_ACTIONS,Wa as ROLE_SCROLL_TO_BOTTOM,Ma as ROLE_SURFACES,Ia as ROLE_USER_MESSAGES,Fg as SEMANTIC_COLORS_SECTION,Ur as SHADE_KEYS,Mi as SHELL_STYLE_ID,hu as STATUS_COLORS_SECTION,gu as STATUS_PALETTE_SECTION,zr as STYLE_SECTIONS,wf as STYLE_SECTIONS_V2,Ms as THEME_EDITOR_PRESETS,uu as THEME_SECTION,qi as ThemeEditorState,Ul as ZOOM_MAX,$l as ZOOM_MIN,ux as appendPreviewTranscriptEntry,Gl as applySceneConfig,ql as applyShellTheme,Mr as buildPreviewConfig,hx as buildPreviewConfigWithMessages,zl as buildShellCss,jl as buildSrcdoc,Lr as buildSummary,mx as buildTranscriptStreamFrames,ns as coerceColor,Wi as coerceFamily,Bi as coerceIntensity,Fi as coerceRadius,Di as coerceRoundnessStyle,Hi as coerceScheme,xg as convertFromPx,vg as convertToPx,Ym as createPreviewMessages,Kl as createPreviewTranscriptEntry,ig as createThemeEditorTools,bx as createThemePreview,Ji as detectRoleAssignment,Li as escapeHtml,Sf as findSection,Ki as formatCssValue,Xi as generateColorScale,px as getPreviewTranscriptPresetLabel,qm as getShellPalette,tl as getThemeEditorPreset,ou as hexToHsl,ru as hslToHex,Gi as isValidHex,ks as normalizeColorValue,wg as paletteColorPath,ji as parseCssValue,Gm as presetStreamsText,rs as quickContrastWarnings,Fa as resolveRoleAssignment,su as resolveThemeColorPath,Yi as rgbToHex,oa as runContrastChecks,Af as scopeSection,Cg as tokenRefDisplayName,Vo as toolResult,ka as wcagContrastRatio};
|