@runtypelabs/persona 3.29.0 → 3.29.1
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/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/{types-CxvHw0X6.d.cts → types-B_Qazlm4.d.cts} +6 -0
- package/dist/animations/{types-CxvHw0X6.d.ts → types-B_Qazlm4.d.ts} +6 -0
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/index.cjs +39 -39
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +15 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.global.js +47 -47
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +39 -39
- package/dist/index.js.map +1 -1
- package/dist/smart-dom-reader.d.cts +6 -0
- package/dist/smart-dom-reader.d.ts +6 -0
- package/dist/theme-editor.cjs +30 -30
- package/dist/theme-editor.d.cts +6 -0
- package/dist/theme-editor.d.ts +6 -0
- package/dist/theme-editor.js +30 -30
- package/package.json +1 -1
- package/src/client.test.ts +40 -0
- package/src/client.ts +18 -4
- package/src/generated/runtype-openapi-contract.ts +12 -0
- package/src/session.ts +190 -29
- package/src/session.webmcp.test.ts +326 -6
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))",Ta="440px",St={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:io,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Xp(e,t){if(!(!e&&!t))return e?t?Ts(e,t):e:t}function Qp(e){var t,n,o,r,s,a,i,d,l,p,m,f,u,w,C,M,I,R,H,D,B;return e?{...St,...e,theme:Xp(St.theme,e.theme),darkTheme:Xp(St.darkTheme,e.darkTheme),launcher:{...St.launcher,...e.launcher,dock:{...(t=St.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(o=St.launcher)==null?void 0:o.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...St.copy,...e.copy},sendButton:{...St.sendButton,...e.sendButton},statusIndicator:{...St.statusIndicator,...e.statusIndicator},voiceRecognition:{...St.voiceRecognition,...e.voiceRecognition},features:(()=>{var be,Fe,ve,J,Le,Y,xe,Se;let v=(be=St.features)==null?void 0:be.artifacts,x=(Fe=e.features)==null?void 0:Fe.artifacts,k=(ve=St.features)==null?void 0:ve.scrollToBottom,S=(J=e.features)==null?void 0:J.scrollToBottom,E=(Le=St.features)==null?void 0:Le.streamAnimation,F=(Y=e.features)==null?void 0:Y.streamAnimation,$=(xe=St.features)==null?void 0:xe.askUserQuestion,j=(Se=e.features)==null?void 0:Se.askUserQuestion,me=v===void 0&&x===void 0?void 0:{...v,...x,layout:{...v==null?void 0:v.layout,...x==null?void 0:x.layout}},se=k===void 0&&S===void 0?void 0:{...k,...S},ge=E===void 0&&F===void 0?void 0:{...E,...F},ie=$===void 0&&j===void 0?void 0:{...$,...j,styles:{...$==null?void 0:$.styles,...j==null?void 0:j.styles}};return{...St.features,...e.features,...se!==void 0?{scrollToBottom:se}:{},...me!==void 0?{artifacts:me}:{},...ge!==void 0?{streamAnimation:ge}:{},...ie!==void 0?{askUserQuestion:ie}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:St.suggestionChips,suggestionChipsConfig:{...St.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...St.layout,...e.layout,header:{...(a=St.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=St.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(m=(p=St.layout)==null?void 0:p.messages)==null?void 0:m.avatar,...(u=(f=e.layout)==null?void 0:f.messages)==null?void 0:u.avatar},timestamp:{...(C=(w=St.layout)==null?void 0:w.messages)==null?void 0:C.timestamp,...(I=(M=e.layout)==null?void 0:M.messages)==null?void 0:I.timestamp}},slots:{...(R=St.layout)==null?void 0:R.slots,...(H=e.layout)==null?void 0:H.slots}},markdown:{...St.markdown,...e.markdown,options:{...(D=St.markdown)==null?void 0:D.options,...(B=e.markdown)==null?void 0:B.options}},messageActions:{...St.messageActions,...e.messageActions}}:St}var lg={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},cg={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},dg={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:io,maxWidth:Ta,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Vr(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Vr(e,o):o}function Jp(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let i=`${r}.${s}`;if(typeof a=="string"){let d=Vr(e,a);d!==void 0&&(t[i]={path:i,value:d,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function pg(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function Zp(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=Zp(s,r):n[o]=r}return n}function ug(e,t){return t?Zp(e,t):e}function tn(e,t={}){var r,s,a,i,d,l,p,m,f,u,w,C,M;let n={palette:lg,semantic:cg,components:dg},o={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(f=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(w=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:w.feedback}},spacing:{...n.semantic.spacing,...(C=e==null?void 0:e.semantic)==null?void 0:C.spacing},typography:{...n.semantic.typography,...(M=e==null?void 0:e.semantic)==null?void 0:M.typography}},components:ug(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let I=pg(o);if(!I.valid)throw new Error(`Theme validation failed: ${I.errors.map(R=>R.message).join(", ")}`)}if(t.plugins)for(let I of t.plugins)o=I.transform(o);return o}function eu(e){var C,M,I,R,H,D,B,v,x,k,S,E,F,$,j,me,se,ge,ie,be,Fe,ve,J,Le,Y,xe,Se,de,we,Ue,te,ne,re,nt,ye,le,$e,Be,ce,K,_e,Et,pe,ae,Ln,Nt,ln,Dn,Jn,ze,_,ke,He,De,Ve,dt,ot,At,Vt,q,_t,Qe,Ft,oe,fe,xt,$t,Jt,yn,Tt,wt,ft,bt,zt,et,Fn,Zn,vn,On,ut,wo,Nn,ir,In,Rr,$o,Lo,yt,_n,Vn,xn,It,eo,to,$n,Uo,Io,zo,Un,Wt,wn,no,qo,Ro,jo,Co,zn,po,gt,Kt,Gt,qn,Ko,oo,uo,jn;let t=Jp(e),n={};for(let[T,Kn]of Object.entries(t)){let mo=T.replace(/\./g,"-");n[`--persona-${mo}`]=Kn.value}n["--persona-primary"]=(C=n["--persona-semantic-colors-primary"])!=null?C:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(M=n["--persona-semantic-colors-secondary"])!=null?M:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(I=n["--persona-semantic-colors-accent"])!=null?I:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(R=n["--persona-semantic-colors-surface"])!=null?R:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(H=n["--persona-semantic-colors-background"])!=null?H:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(D=n["--persona-semantic-colors-container"])!=null?D:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(B=n["--persona-semantic-colors-text"])!=null?B:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(v=n["--persona-semantic-colors-text-muted"])!=null?v:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(x=n["--persona-semantic-colors-text-inverse"])!=null?x:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(k=n["--persona-semantic-colors-border"])!=null?k:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(S=n["--persona-semantic-colors-divider"])!=null?S:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(E=n["--persona-components-voice-recording-indicator"])!=null?E:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(F=n["--persona-components-voice-recording-background"])!=null?F:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=($=n["--persona-components-voice-processing-icon"])!=null?$:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(j=n["--persona-components-voice-speaking-icon"])!=null?j:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(me=n["--persona-components-approval-requested-background"])!=null?me:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(se=n["--persona-components-approval-requested-border"])!=null?se:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(ge=n["--persona-components-approval-requested-text"])!=null?ge:n["--persona-palette-colors-gray-900"],n["--persona-approval-approve-bg"]=(ie=n["--persona-components-approval-approve-background"])!=null?ie:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(be=n["--persona-components-approval-deny-background"])!=null?be:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Fe=n["--persona-components-attachment-image-background"])!=null?Fe:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(ve=n["--persona-components-attachment-image-border"])!=null?ve:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(J=n["--persona-semantic-typography-fontFamily"])!=null?J:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(Le=n["--persona-semantic-typography-fontSize"])!=null?Le:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(Y=n["--persona-semantic-typography-fontWeight"])!=null?Y:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(xe=n["--persona-semantic-typography-lineHeight"])!=null?xe:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(Se=n["--persona-palette-radius-sm"])!=null?Se:"0.125rem",n["--persona-radius-md"]=(de=n["--persona-palette-radius-md"])!=null?de:"0.375rem",n["--persona-radius-lg"]=(we=n["--persona-palette-radius-lg"])!=null?we:"0.5rem",n["--persona-radius-xl"]=(Ue=n["--persona-palette-radius-xl"])!=null?Ue:"0.75rem",n["--persona-radius-full"]=(te=n["--persona-palette-radius-full"])!=null?te:"9999px",n["--persona-launcher-radius"]=(re=(ne=n["--persona-components-launcher-borderRadius"])!=null?ne:n["--persona-palette-radius-full"])!=null?re:"9999px",n["--persona-launcher-bg"]=(nt=n["--persona-components-launcher-background"])!=null?nt:n["--persona-primary"],n["--persona-launcher-fg"]=(ye=n["--persona-components-launcher-foreground"])!=null?ye:n["--persona-text-inverse"],n["--persona-launcher-border"]=(le=n["--persona-components-launcher-border"])!=null?le:n["--persona-border"],n["--persona-button-primary-bg"]=($e=n["--persona-components-button-primary-background"])!=null?$e:n["--persona-primary"],n["--persona-button-primary-fg"]=(Be=n["--persona-components-button-primary-foreground"])!=null?Be:n["--persona-text-inverse"],n["--persona-button-radius"]=(K=(ce=n["--persona-components-button-primary-borderRadius"])!=null?ce:n["--persona-palette-radius-full"])!=null?K:"9999px",n["--persona-panel-radius"]=(Et=(_e=n["--persona-components-panel-borderRadius"])!=null?_e:n["--persona-radius-xl"])!=null?Et:"0.75rem",n["--persona-panel-border"]=(pe=n["--persona-components-panel-border"])!=null?pe:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Ln=(ae=n["--persona-components-panel-shadow"])!=null?ae:n["--persona-palette-shadows-xl"])!=null?Ln:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-input-radius"]=(ln=(Nt=n["--persona-components-input-borderRadius"])!=null?Nt:n["--persona-radius-lg"])!=null?ln:"0.5rem",n["--persona-message-user-radius"]=(Jn=(Dn=n["--persona-components-message-user-borderRadius"])!=null?Dn:n["--persona-radius-lg"])!=null?Jn:"0.5rem",n["--persona-message-assistant-radius"]=(_=(ze=n["--persona-components-message-assistant-borderRadius"])!=null?ze:n["--persona-radius-lg"])!=null?_:"0.5rem",n["--persona-header-bg"]=(ke=n["--persona-components-header-background"])!=null?ke:n["--persona-surface"],n["--persona-header-border"]=(He=n["--persona-components-header-border"])!=null?He:n["--persona-divider"],n["--persona-header-icon-bg"]=(De=n["--persona-components-header-iconBackground"])!=null?De:n["--persona-primary"],n["--persona-header-icon-fg"]=(Ve=n["--persona-components-header-iconForeground"])!=null?Ve:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(dt=n["--persona-components-header-titleForeground"])!=null?dt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(ot=n["--persona-components-header-subtitleForeground"])!=null?ot:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(At=n["--persona-components-header-actionIconForeground"])!=null?At:n["--persona-muted"];let o=(Vt=e.components)==null?void 0:Vt.header;o!=null&&o.shadow&&(n["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom);let r=(q=e.components)==null?void 0:q.introCard;n["--persona-intro-card-bg"]=(_t=n["--persona-components-introCard-background"])!=null?_t:n["--persona-surface"],n["--persona-intro-card-radius"]=(Qe=n["--persona-components-introCard-borderRadius"])!=null?Qe:"1rem",n["--persona-intro-card-padding"]=(Ft=n["--persona-components-introCard-padding"])!=null?Ft:"1.5rem",n["--persona-intro-card-shadow"]=(fe=(oe=r==null?void 0:r.shadow)!=null?oe:n["--persona-components-introCard-shadow"])!=null?fe:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(xt=n["--persona-components-input-background"])!=null?xt:n["--persona-surface"],n["--persona-input-placeholder"]=($t=n["--persona-components-input-placeholder"])!=null?$t:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Jt=n["--persona-components-message-user-background"])!=null?Jt:n["--persona-accent"],n["--persona-message-user-text"]=(yn=n["--persona-components-message-user-text"])!=null?yn:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Tt=n["--persona-components-message-user-shadow"])!=null?Tt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(wt=n["--persona-components-message-assistant-background"])!=null?wt:n["--persona-surface"],n["--persona-message-assistant-text"]=(ft=n["--persona-components-message-assistant-text"])!=null?ft:n["--persona-text"],n["--persona-message-assistant-border"]=(bt=n["--persona-components-message-assistant-border"])!=null?bt:n["--persona-border"],n["--persona-message-assistant-shadow"]=(zt=n["--persona-components-message-assistant-shadow"])!=null?zt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(Fn=(et=n["--persona-components-scrollToBottom-background"])!=null?et:n["--persona-button-primary-bg"])!=null?Fn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(vn=(Zn=n["--persona-components-scrollToBottom-foreground"])!=null?Zn:n["--persona-button-primary-fg"])!=null?vn:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(On=n["--persona-components-scrollToBottom-border"])!=null?On:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(ut=n["--persona-components-scrollToBottom-size"])!=null?ut:"40px",n["--persona-scroll-to-bottom-radius"]=(ir=(Nn=(wo=n["--persona-components-scrollToBottom-borderRadius"])!=null?wo:n["--persona-button-radius"])!=null?Nn:n["--persona-radius-full"])!=null?ir:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Rr=(In=n["--persona-components-scrollToBottom-shadow"])!=null?In:n["--persona-palette-shadows-sm"])!=null?Rr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=($o=n["--persona-components-scrollToBottom-padding"])!=null?$o:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Lo=n["--persona-components-scrollToBottom-gap"])!=null?Lo:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(_n=(yt=n["--persona-components-scrollToBottom-fontSize"])!=null?yt:n["--persona-palette-typography-fontSize-sm"])!=null?_n:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Vn=n["--persona-components-scrollToBottom-iconSize"])!=null?Vn:"14px",n["--persona-tool-bubble-shadow"]=(xn=n["--persona-components-toolBubble-shadow"])!=null?xn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(It=n["--persona-components-reasoningBubble-shadow"])!=null?It:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(eo=n["--persona-components-composer-shadow"])!=null?eo:"none",n["--persona-md-inline-code-bg"]=(to=n["--persona-components-markdown-inlineCode-background"])!=null?to:n["--persona-container"],n["--persona-md-inline-code-color"]=($n=n["--persona-components-markdown-inlineCode-foreground"])!=null?$n:n["--persona-text"],n["--persona-md-link-color"]=(Io=(Uo=n["--persona-components-markdown-link-foreground"])!=null?Uo:n["--persona-accent"])!=null?Io:"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let l=n["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(n["--persona-md-prose-font-family"]=l),n["--persona-md-code-block-bg"]=(zo=n["--persona-components-markdown-codeBlock-background"])!=null?zo:n["--persona-container"],n["--persona-md-code-block-border-color"]=(Un=n["--persona-components-markdown-codeBlock-borderColor"])!=null?Un:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Wt=n["--persona-components-markdown-codeBlock-textColor"])!=null?Wt:"inherit",n["--persona-md-table-header-bg"]=(wn=n["--persona-components-markdown-table-headerBackground"])!=null?wn:n["--persona-container"],n["--persona-md-table-border-color"]=(no=n["--persona-components-markdown-table-borderColor"])!=null?no:n["--persona-border"],n["--persona-md-hr-color"]=(qo=n["--persona-components-markdown-hr-color"])!=null?qo:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Ro=n["--persona-components-markdown-blockquote-borderColor"])!=null?Ro:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(jo=n["--persona-components-markdown-blockquote-background"])!=null?jo:"transparent",n["--persona-md-blockquote-text-color"]=(Co=n["--persona-components-markdown-blockquote-textColor"])!=null?Co:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(zn=n["--persona-components-collapsibleWidget-container"])!=null?zn:n["--persona-surface"],n["--cw-surface"]=(po=n["--persona-components-collapsibleWidget-surface"])!=null?po:n["--persona-surface"],n["--cw-border"]=(gt=n["--persona-components-collapsibleWidget-border"])!=null?gt:n["--persona-border"],n["--persona-message-border"]=(Kt=n["--persona-components-message-border"])!=null?Kt:n["--persona-border"];let p=e.components,m=p==null?void 0:p.iconButton;m&&(m.background&&(n["--persona-icon-btn-bg"]=m.background),m.border&&(n["--persona-icon-btn-border"]=m.border),m.color&&(n["--persona-icon-btn-color"]=m.color),m.padding&&(n["--persona-icon-btn-padding"]=m.padding),m.borderRadius&&(n["--persona-icon-btn-radius"]=m.borderRadius),m.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=m.hoverBackground),m.hoverColor&&(n["--persona-icon-btn-hover-color"]=m.hoverColor),m.activeBackground&&(n["--persona-icon-btn-active-bg"]=m.activeBackground),m.activeBorder&&(n["--persona-icon-btn-active-border"]=m.activeBorder));let f=p==null?void 0:p.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let u=p==null?void 0:p.toggleGroup;u&&(u.gap&&(n["--persona-toggle-group-gap"]=u.gap),u.borderRadius&&(n["--persona-toggle-group-radius"]=u.borderRadius));let w=p==null?void 0:p.artifact;if(w!=null&&w.toolbar){let T=w.toolbar;T.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=T.iconHoverColor),T.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=T.iconHoverBackground),T.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=T.iconPadding),T.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=T.iconBorderRadius),T.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=T.iconBorder),T.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=T.toggleGroupGap),T.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=T.toggleBorderRadius),T.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=T.copyBackground),T.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=T.copyBorder),T.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=T.copyColor),T.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=T.copyBorderRadius),T.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=T.copyPadding),T.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=T.copyMenuBackground,n["--persona-dropdown-bg"]=(Gt=n["--persona-dropdown-bg"])!=null?Gt:T.copyMenuBackground),T.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=T.copyMenuBorder,n["--persona-dropdown-border"]=(qn=n["--persona-dropdown-border"])!=null?qn:T.copyMenuBorder),T.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=T.copyMenuShadow,n["--persona-dropdown-shadow"]=(Ko=n["--persona-dropdown-shadow"])!=null?Ko:T.copyMenuShadow),T.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=T.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(oo=n["--persona-dropdown-radius"])!=null?oo:T.copyMenuBorderRadius),T.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=T.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(uo=n["--persona-dropdown-item-hover-bg"])!=null?uo:T.copyMenuItemHoverBackground),T.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=T.iconBackground),T.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=T.toolbarBorder)}if(w!=null&&w.tab){let T=w.tab;T.background&&(n["--persona-artifact-tab-bg"]=T.background),T.activeBackground&&(n["--persona-artifact-tab-active-bg"]=T.activeBackground),T.activeBorder&&(n["--persona-artifact-tab-active-border"]=T.activeBorder),T.borderRadius&&(n["--persona-artifact-tab-radius"]=T.borderRadius),T.textColor&&(n["--persona-artifact-tab-color"]=T.textColor),T.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=T.hoverBackground),T.listBackground&&(n["--persona-artifact-tab-list-bg"]=T.listBackground),T.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=T.listBorderColor),T.listPadding&&(n["--persona-artifact-tab-list-padding"]=T.listPadding)}if(w!=null&&w.pane){let T=w.pane;if(T.toolbarBackground){let Kn=(jn=Vr(e,T.toolbarBackground))!=null?jn:T.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Kn}}return n}var mg={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},tu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},zi=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},gg=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":zi()},fg=e=>gg(e),hg=e=>tn(e),bg=e=>{var n;let t=tn(void 0,{validate:!1});return tn({...e,palette:{...t.palette,colors:{...mg.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},ka=e=>{let t=fg(e),n=tu(e==null?void 0:e.theme),o=tu(e==null?void 0:e.darkTheme);return t==="dark"?bg(Ts(n!=null?n:{},o!=null?o:{})):hg(n)},yg=e=>eu(e),$r=(e,t)=>{var s;let n=ka(t),o=yg(n);for(let[a,i]of Object.entries(o))e.style.setProperty(a,i);let r=(s=t==null?void 0:t.toolCall)==null?void 0:s.shadow;r!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",r.trim()===""?"none":r)},nu=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(zi())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(zi());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};function qi(e,t){let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return o}function xr(e,t,n){var i;let o=t.split(".");if(o.length===1)return{...e,[o[0]]:n};let[r,...s]=o,a=e;return{...a,[r]:xr((i=a==null?void 0:a[r])!=null?i:{},s.join("."),n)}}var ji=class{constructor(t,n,o){this.listeners=[];this.history=[];this.historyIndex=-1;this.suppressHistory=!1;var s;let r=(s=o==null?void 0:o.mergeDefaults)!=null?s:!0;this.config=r?{...St,...n}:n!=null?n:St,this.theme=tn(t,{validate:!1}),this.syncThemeIntoConfig(),this.pushHistorySnapshot(this.exportSnapshot(),!0)}get(t){var n;return t.startsWith("theme.")?qi(this.theme,t.replace("theme.","")):t.startsWith("darkTheme.")?qi((n=this.config.darkTheme)!=null?n:{},t.replace("darkTheme.","")):qi(this.config,t)}getTheme(){return this.theme}getConfig(){return this.config}set(t,n){var o;if(t.startsWith("theme.")){let r=t.replace("theme.","");this.theme=xr(this.theme,r,n),this.syncThemeIntoConfig()}else if(t.startsWith("darkTheme.")){let r=t.replace("darkTheme.",""),s=(o=this.config.darkTheme)!=null?o:tn();this.config={...this.config,darkTheme:xr(s,r,n)}}else this.config=xr(this.config,t,n);this.recordHistory(),this.notifyListeners()}setBatch(t){var s;let n=!1,o=!1,r=!1;for(let[a,i]of Object.entries(t))if(a.startsWith("theme.")){let d=a.replace("theme.","");this.theme=xr(this.theme,d,i),n=!0}else if(a.startsWith("darkTheme.")){let d=a.replace("darkTheme.",""),l=(s=this.config.darkTheme)!=null?s:tn();this.config={...this.config,darkTheme:xr(l,d,i)},o=!0}else this.config=xr(this.config,a,i),r=!0;n&&this.syncThemeIntoConfig(),(n||o||r)&&(this.recordHistory(),this.notifyListeners())}setTheme(t){this.theme=t,this.syncThemeIntoConfig(),this.recordHistory(),this.notifyListeners()}setFullConfig(t,n){this.config={...t},n&&(this.theme=n),this.syncThemeIntoConfig(),this.recordHistory(),this.notifyListeners()}importSnapshot(t){var r,s;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Snapshot must be a JSON object");let n=t;if("config"in n||"theme"in n||n.version===2){let a=(r=n.config)!=null?r:this.config,i=tn((s=n.theme)!=null?s:this.theme,{validate:!1});this.setFullConfig(a,i);return}let o=tn(n,{validate:!1});this.setTheme(o)}resetToDefaults(){this.config={...St},this.theme=tn(),this.syncThemeIntoConfig(),this.history=[],this.historyIndex=-1,this.pushHistorySnapshot(this.exportSnapshot()),this.notifyListeners()}canUndo(){return this.historyIndex>0}canRedo(){return this.historyIndex>=0&&this.historyIndex<this.history.length-1}getHistoryLength(){return this.history.length}getHistoryIndex(){return this.historyIndex}undo(){this.canUndo()&&(this.historyIndex-=1,this.restoreSnapshot(this.history[this.historyIndex]))}redo(){this.canRedo()&&(this.historyIndex+=1,this.restoreSnapshot(this.history[this.historyIndex]))}exportSnapshot(){return{version:2,config:{...this.config,theme:void 0},theme:this.theme}}onChange(t){return this.listeners.push(t),()=>{let n=this.listeners.indexOf(t);n>=0&&this.listeners.splice(n,1)}}syncThemeIntoConfig(){this.config={...this.config,theme:this.theme}}notifyListeners(){for(let t of this.listeners)t(this.config,this.theme)}recordHistory(){this.pushHistorySnapshot(this.exportSnapshot())}pushHistorySnapshot(t,n=!1){if(this.suppressHistory)return;let o=JSON.stringify(t),r=this.historyIndex>=0&&this.history[this.historyIndex]?JSON.stringify(this.history[this.historyIndex]):null;if(n&&this.historyIndex>=0){this.history[this.historyIndex]=t;return}o!==r&&(this.history=this.history.slice(0,this.historyIndex+1),this.history.push(t),this.historyIndex=this.history.length-1)}restoreSnapshot(t){this.suppressHistory=!0,this.config=t.config,this.theme=tn(t.theme,{validate:!1}),this.syncThemeIntoConfig(),this.suppressHistory=!1,this.notifyListeners()}};function Ki(e){let t=e.trim();if(t==="9999px")return{value:100,unit:"px"};let n=t.match(/^([\d.]+)(px|rem)$/);if(!n){let o=parseFloat(t);return{value:isNaN(o)?0:o,unit:"px"}}return{value:parseFloat(n[1]),unit:n[2]}}function Gi(e,t){return t==="rem"?`${e}rem`:`${e}px`}function vg(e,t){return t==="rem"?e*16:e}function xg(e,t){return t==="rem"?e/16:e}function ks(e){if(!e)return"#000000";let t=e.trim().toLowerCase();return t==="transparent"?"transparent":t.startsWith("rgba")||t.startsWith("rgb")?t:t.startsWith("#")?t.length===4?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:t:`#${t}`}function Yi(e){return/^#[0-9A-Fa-f]{6}$/.test(e)}function Xi(e){let t=e.trim().toLowerCase().match(/^rgba?\(([^)]+)\)$/);if(!t)return null;let n=t[1].split(",").map(d=>d.trim());if(n.length<3)return null;let o=d=>{let l=d.endsWith("%"),p=parseFloat(l?d.slice(0,-1):d);return Number.isFinite(p)?Math.max(0,Math.min(255,Math.round(l?p/100*255:p))):NaN},r=o(n[0]),s=o(n[1]),a=o(n[2]);if(!Number.isFinite(r)||!Number.isFinite(s)||!Number.isFinite(a))return null;let i=d=>d.toString(16).padStart(2,"0");return`#${i(r)}${i(s)}${i(a)}`}function Ea(e,t){let n=s=>{var l;let a=ks(s),i=a.startsWith("rgb")?(l=Xi(a))!=null?l:"#000000":a,d=[1,3,5].map(p=>{let m=parseInt(i.slice(p,p+2),16)/255;return m<=.03928?m/12.92:Math.pow((m+.055)/1.055,2.4)});return .2126*d[0]+.7152*d[1]+.0722*d[2]},o=n(e),r=n(t);return(Math.max(o,r)+.05)/(Math.min(o,r)+.05)}function ou(e){var f;let t=ks(e),n=t.startsWith("rgb")?(f=Xi(t))!=null?f:"#000000":t,o=parseInt(n.slice(1,3),16)/255,r=parseInt(n.slice(3,5),16)/255,s=parseInt(n.slice(5,7),16)/255,a=Math.max(o,r,s),i=Math.min(o,r,s),d=(a+i)/2;if(a===i)return{h:0,s:0,l:d};let l=a-i,p=d>.5?l/(2-a-i):l/(a+i),m;switch(a){case o:m=((r-s)/l+(r<s?6:0))/6;break;case r:m=((s-o)/l+2)/6;break;default:m=((o-r)/l+4)/6;break}return{h:m*360,s:p,l:d}}function ru(e,t,n){let o=(e%360+360)%360,r=(1-Math.abs(2*n-1))*t,s=r*(1-Math.abs(o/60%2-1)),a=n-r/2,i,d,l;o<60?[i,d,l]=[r,s,0]:o<120?[i,d,l]=[s,r,0]:o<180?[i,d,l]=[0,r,s]:o<240?[i,d,l]=[0,s,r]:o<300?[i,d,l]=[s,0,r]:[i,d,l]=[r,0,s];let p=m=>{let f=Math.round((m+a)*255).toString(16);return f.length===1?"0"+f:f};return`#${p(i)}${p(d)}${p(l)}`}function Qi(e){let{h:t,s:n,l:o}=ou(e),r={50:.97,100:.94,200:.87,300:.77,400:.64,500:o,600:Math.max(.05,o-.1),700:Math.max(.05,o-.2),800:Math.max(.05,o-.28),900:Math.max(.05,o-.35),950:Math.max(.03,o-.42)},s={50:Math.min(1,n*.85),100:Math.min(1,n*.9),200:Math.min(1,n*.95),300:n,400:n,500:n,600:Math.min(1,n*1.05),700:Math.min(1,n*1.05),800:Math.min(1,n*1),900:Math.min(1,n*.95),950:Math.min(1,n*.9)},a={};for(let[i,d]of Object.entries(r)){let l=s[i];a[i]=ru(t,l,d)}return a}var Ur=["50","100","200","300","400","500","600","700","800","900","950"],Ji=["primary","secondary","accent","gray","success","warning","error","info"];function wg(e,t){return`palette.colors.${e}.${t}`}function su(e,t,n=0){if(n>5)return"#cbd5e1";let o=e(t);return typeof o!="string"?"#cbd5e1":o.startsWith("#")||o.startsWith("rgb")||o==="transparent"?o:o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components.")?su(e,`theme.${o}`,n+1):"#cbd5e1"}function Cg(e){if(!e.startsWith("palette.")&&!e.startsWith("semantic."))return e;let t=e.split(".");if(t[0]==="palette"&&t[1]==="colors"){let n=t[2],o=t[3];return`${n.charAt(0).toUpperCase()+n.slice(1)} ${o}`}return t[0]==="semantic"?t.slice(1).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):t[t.length-1]}var ko=[{id:"solid",label:"Solid"},{id:"soft",label:"Soft"}],Ma=["primary","secondary","accent","gray"],Sg={primary:"Primary",secondary:"Secondary",accent:"Accent",gray:"Neutral"},La={roleId:"role-surfaces",helper:"Page and panel backgrounds",previewZone:"container",intensities:ko,targets:[{path:"semantic.colors.background",kind:"background"},{path:"semantic.colors.surface",kind:"background"},{path:"semantic.colors.container",kind:"background"}]},Ia={roleId:"role-header",helper:"Widget header bar",previewZone:"header",intensities:ko,targets:[{path:"components.header.background",kind:"background"},{path:"components.header.border",kind:"border"},{path:"components.header.iconBackground",kind:"accent"},{path:"components.header.iconForeground",kind:"foreground"},{path:"components.header.titleForeground",kind:"accent"},{path:"components.header.subtitleForeground",kind:"foreground"},{path:"components.header.actionIconForeground",kind:"foreground"}]},Ra={roleId:"role-user-messages",helper:"User chat bubbles",previewZone:"user-message",intensities:ko,targets:[{path:"components.message.user.background",kind:"background"},{path:"components.message.user.text",kind:"foreground"}]},Pa={roleId:"role-assistant-messages",helper:"Assistant chat bubbles",previewZone:"assistant-message",intensities:ko,targets:[{path:"components.message.assistant.background",kind:"background"},{path:"components.message.assistant.text",kind:"foreground"}]},Wa={roleId:"role-primary-actions",helper:"Send button and primary buttons",intensities:ko,targets:[{path:"components.button.primary.background",kind:"background"},{path:"components.button.primary.foreground",kind:"foreground"},{path:"semantic.colors.interactive.default",kind:"accent"},{path:"semantic.colors.interactive.hover",kind:"accent"}]},Ba={roleId:"role-scroll-to-bottom",helper:"Scroll-to-bottom affordances in transcript and event stream",intensities:ko,targets:[{path:"components.scrollToBottom.background",kind:"background"},{path:"components.scrollToBottom.foreground",kind:"foreground"},{path:"components.scrollToBottom.border",kind:"border"}]},Ha={roleId:"role-input",helper:"Message input field",previewZone:"composer",intensities:ko,targets:[{path:"components.input.background",kind:"background"},{path:"components.input.placeholder",kind:"foreground"},{path:"components.input.focus.border",kind:"accent"},{path:"components.input.focus.ring",kind:"accent"}]},Da={roleId:"role-links-focus",helper:"Links, focus rings, and interactive highlights",intensities:ko,targets:[{path:"semantic.colors.accent",kind:"accent"},{path:"semantic.colors.interactive.focus",kind:"accent"},{path:"semantic.colors.interactive.active",kind:"accent"},{path:"components.markdown.link.foreground",kind:"accent"}]},Fa={roleId:"role-borders",helper:"Borders, dividers, and separators",intensities:ko,targets:[{path:"semantic.colors.border",kind:"border"},{path:"semantic.colors.divider",kind:"border"}]},wr=[La,Ia,Ra,Pa,Wa,Ba,Ha,Da,Fa];function Oa(e,t,n){let o={},r=e==="neutral"?"gray":e;for(let s of n.targets){let a=Ag(r,t,s,n.roleId);o[`theme.${s.path}`]=a,o[`darkTheme.${s.path}`]=a}if(n.roleId==="role-primary-actions"){let s=t==="solid"?`palette.colors.${r}.700`:`palette.colors.${r}.200`;o["theme.semantic.colors.interactive.hover"]=s,o["darkTheme.semantic.colors.interactive.hover"]=s}return o}function Ag(e,t,n,o){let r=t==="solid";if(o==="role-header")return Tg(e,r,n);if(o==="role-input")return kg(e,r,n);switch(n.kind){case"background":return r?`palette.colors.${e}.500`:`palette.colors.${e}.${e==="gray"?"50":"100"}`;case"foreground":return r?`palette.colors.${e==="gray"?"gray":e}.50`:`palette.colors.${e==="gray"?"gray":e}.900`;case"border":return r?`palette.colors.${e}.600`:`palette.colors.${e}.200`;case"accent":return r?`palette.colors.${e}.600`:`palette.colors.${e}.400`}}function Tg(e,t,n){let o=n.path;return o.endsWith(".background")?t?`palette.colors.${e}.500`:`palette.colors.${e}.${e==="gray"?"50":"100"}`:o.endsWith(".border")?t?`palette.colors.${e}.600`:`palette.colors.${e}.200`:o.endsWith(".iconBackground")?t?`palette.colors.${e}.${e==="gray"?"700":"600"}`:`palette.colors.${e}.500`:o.endsWith(".iconForeground")?t?`palette.colors.${e}.50`:`palette.colors.${e}.50`:o.endsWith(".titleForeground")?t?`palette.colors.${e}.50`:`palette.colors.${e}.${e==="gray"?"900":"700"}`:o.endsWith(".subtitleForeground")?t?`palette.colors.${e}.200`:`palette.colors.${e}.500`:o.endsWith(".actionIconForeground")?t?`palette.colors.${e}.200`:`palette.colors.${e}.500`:`palette.colors.${e}.500`}function kg(e,t,n){let o=n.path;return o.endsWith(".background")?t?`palette.colors.${e}.${e==="gray"?"100":"50"}`:`palette.colors.${e}.50`:o.endsWith(".placeholder")?`palette.colors.${e}.400`:o.endsWith(".border")||o.endsWith(".ring")?t?`palette.colors.${e}.500`:`palette.colors.${e}.400`:`palette.colors.${e}.500`}var Eg=/^palette\.colors\.(\w+)\.(\d+)$/;function Zi(e,t){var i,d;let n=(i=t.targets.find(l=>l.kind==="background"))!=null?i:t.targets[0];if(!n)return null;let r=String((d=e(n.path))!=null?d:"").match(Eg);if(!r)return null;let s=r[1],a=Ma.includes(s)?s:null;if(!a)return null;for(let l of["solid","soft"]){let p=Oa(a,l,t);if(t.targets.every(f=>{var w;return String((w=e(f.path))!=null?w:"")===p[`theme.${f.path}`]}))return{family:a,intensity:l}}return null}var Mg={id:"theme-mode",title:"Runtime Theme",description:"Controls how the shipped widget picks light or dark mode.",collapsed:!1,fields:[{id:"theme-mode",label:"Runtime Theme",description:"Always Light, Always Dark, or follow the visitor system preference",type:"select",path:"colorScheme",defaultValue:"auto",options:[{value:"light",label:"Light"},{value:"dark",label:"Dark"},{value:"auto",label:"Follow System"}]}]},Lg={id:"brand-colors",title:"Brand Colors",description:"Pick your brand colors. A full shade scale is generated automatically for both light and dark themes.",collapsed:!1,fields:[{id:"brand-primary",label:"Primary",description:"Main brand color for buttons, links, and accents",type:"color",path:"theme.palette.colors.primary.500",defaultValue:"#171717"},{id:"brand-secondary",label:"Secondary",description:"Supporting brand color",type:"color",path:"theme.palette.colors.secondary.500",defaultValue:"#7c3aed"},{id:"brand-accent",label:"Accent",description:"Highlight and decorative color",type:"color",path:"theme.palette.colors.accent.500",defaultValue:"#06b6d4"}]},Ig={id:"chat-colors",title:"Chat Colors",description:"Customize the main colors of the chat interface.",collapsed:!0,fields:[{id:"chat-header-bg",label:"Header Background",type:"token-ref",path:"theme.components.header.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"chat-header-icon-bg",label:"Header Icon Background",type:"token-ref",path:"theme.components.header.iconBackground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-header-icon-fg",label:"Header Icon Color",type:"token-ref",path:"theme.components.header.iconForeground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"chat-header-title-fg",label:"Header Title Color",type:"token-ref",path:"theme.components.header.titleForeground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-header-subtitle-fg",label:"Header Subtitle Color",type:"token-ref",path:"theme.components.header.subtitleForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"chat-header-action-icons-fg",label:"Header Button Icons",type:"token-ref",path:"theme.components.header.actionIconForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"chat-msg-user-bg",label:"User Message Background",type:"token-ref",path:"theme.components.message.user.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-msg-user-text",label:"User Message Text",type:"token-ref",path:"theme.components.message.user.text",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"chat-msg-assistant-bg",label:"Assistant Message Background",type:"token-ref",path:"theme.components.message.assistant.background",defaultValue:"semantic.colors.container",tokenRef:{tokenType:"color"}},{id:"chat-msg-assistant-text",label:"Assistant Message Text",type:"token-ref",path:"theme.components.message.assistant.text",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},Rg={id:"typography",title:"Typography",collapsed:!0,fields:[{id:"typo-font-family",label:"Font Family",type:"select",path:"theme.semantic.typography.fontFamily",defaultValue:"palette.typography.fontFamily.sans",options:[{value:"palette.typography.fontFamily.sans",label:"Sans Serif"},{value:"palette.typography.fontFamily.serif",label:"Serif"},{value:"palette.typography.fontFamily.mono",label:"Monospace"}]},{id:"typo-font-size",label:"Base Font Size",type:"select",path:"theme.semantic.typography.fontSize",defaultValue:"palette.typography.fontSize.base",options:[{value:"palette.typography.fontSize.xs",label:"Extra Small (0.75rem)"},{value:"palette.typography.fontSize.sm",label:"Small (0.875rem)"},{value:"palette.typography.fontSize.base",label:"Base (1rem)"},{value:"palette.typography.fontSize.lg",label:"Large (1.125rem)"},{value:"palette.typography.fontSize.xl",label:"Extra Large (1.25rem)"}]},{id:"typo-font-weight",label:"Font Weight",type:"select",path:"theme.semantic.typography.fontWeight",defaultValue:"palette.typography.fontWeight.normal",options:[{value:"palette.typography.fontWeight.normal",label:"Normal (400)"},{value:"palette.typography.fontWeight.medium",label:"Medium (500)"},{value:"palette.typography.fontWeight.semibold",label:"Semibold (600)"},{value:"palette.typography.fontWeight.bold",label:"Bold (700)"}]},{id:"typo-line-height",label:"Line Height",type:"select",path:"theme.semantic.typography.lineHeight",defaultValue:"palette.typography.lineHeight.normal",options:[{value:"palette.typography.lineHeight.tight",label:"Tight (1.25)"},{value:"palette.typography.lineHeight.normal",label:"Normal (1.5)"},{value:"palette.typography.lineHeight.relaxed",label:"Relaxed (1.625)"}]}]},Pg={id:"launcher-style",title:"Launcher",description:"Control launcher appearance.",collapsed:!0,fields:[{id:"style-launcher-size",label:"Launcher Size",type:"slider",path:"theme.components.launcher.size",defaultValue:"60px",slider:{min:32,max:80,step:2}},{id:"style-launcher-shape",label:"Launcher Shape",type:"select",path:"theme.components.launcher.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Rounded Square"},{value:"palette.radius.lg",label:"Rounded"},{value:"palette.radius.xl",label:"Very Rounded"},{value:"palette.radius.full",label:"Circle"}]},{id:"style-launcher-shadow",label:"Launcher Shadow",type:"select",path:"theme.components.launcher.shadow",defaultValue:"palette.shadows.lg",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},Wg={id:"shape",title:"Shape",description:"Control the corner roundness across the widget.",collapsed:!0,fields:[{id:"radius-sm",label:"Small",type:"slider",path:"theme.palette.radius.sm",defaultValue:"0.125rem",slider:{min:0,max:16,step:1}},{id:"radius-md",label:"Medium",type:"slider",path:"theme.palette.radius.md",defaultValue:"0.375rem",slider:{min:0,max:24,step:1}},{id:"radius-lg",label:"Large",type:"slider",path:"theme.palette.radius.lg",defaultValue:"0.5rem",slider:{min:0,max:32,step:1}},{id:"radius-xl",label:"Extra Large",type:"slider",path:"theme.palette.radius.xl",defaultValue:"0.75rem",slider:{min:0,max:48,step:1}},{id:"radius-full",label:"Full",type:"slider",path:"theme.palette.radius.full",defaultValue:"9999px",slider:{min:0,max:100,step:1,isRadiusFull:!0}}],presets:[{id:"radius-default",label:"Default",values:{"theme.palette.radius.sm":"0.125rem","theme.palette.radius.md":"0.375rem","theme.palette.radius.lg":"0.5rem","theme.palette.radius.xl":"0.75rem","theme.palette.radius.full":"9999px"}},{id:"radius-sharp",label:"Sharp",values:{"theme.palette.radius.sm":"1px","theme.palette.radius.md":"2px","theme.palette.radius.lg":"3px","theme.palette.radius.xl":"4px","theme.palette.radius.full":"4px"}},{id:"radius-rounded",label:"Rounded",values:{"theme.palette.radius.sm":"0.5rem","theme.palette.radius.md":"0.75rem","theme.palette.radius.lg":"1rem","theme.palette.radius.xl":"1.5rem","theme.palette.radius.full":"9999px"}}]},Bg={id:"shadows",title:"Shadows",collapsed:!0,fields:[{id:"shadow-sm",label:"Small",type:"text",path:"theme.palette.shadows.sm",defaultValue:"0 1px 2px 0 rgb(0 0 0 / 0.05)"},{id:"shadow-md",label:"Medium",type:"text",path:"theme.palette.shadows.md",defaultValue:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)"},{id:"shadow-lg",label:"Large",type:"text",path:"theme.palette.shadows.lg",defaultValue:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)"},{id:"shadow-xl",label:"Extra Large",type:"text",path:"theme.palette.shadows.xl",defaultValue:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)"}]},Hg={id:"widget-style",title:"Widget Surface",description:"Adjust the main panel and message bubble treatment.",collapsed:!0,fields:[{id:"style-panel-radius",label:"Panel Corner Radius",type:"select",path:"theme.components.panel.borderRadius",defaultValue:"palette.radius.xl",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"style-panel-shadow",label:"Panel Shadow",type:"select",path:"theme.components.panel.shadow",defaultValue:"palette.shadows.xl",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]},{id:"style-msg-user-radius",label:"User Message Radius",type:"select",path:"theme.components.message.user.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"style-msg-assistant-radius",label:"Assistant Message Radius",type:"select",path:"theme.components.message.assistant.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},zr=[Lg,Ig,Pg,Rg,Mg,Wg,Bg,Hg];function au(){return{id:"brand-palette",title:"Brand Palette",description:"Define your color palette. Edit the base color (500) to auto-generate the full scale.",collapsed:!1,fields:Ji.map(t=>({id:`palette-${t}`,label:`${t.charAt(0).toUpperCase()+t.slice(1)}`,description:`${t} color palette (edit shade 500, auto-generate scale)`,type:"color-scale",path:`theme.palette.colors.${t}`,colorScale:{colorFamily:t}}))}}var iu={id:"semantic-colors",title:"Semantic Colors",description:"Map intents to palette colors.",collapsed:!0,fields:[{id:"sem-primary",label:"Primary",description:"Main brand/action color",type:"token-ref",path:"theme.semantic.colors.primary",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sem-secondary",label:"Secondary",description:"Secondary actions",type:"token-ref",path:"theme.semantic.colors.secondary",defaultValue:"palette.colors.gray.500",tokenRef:{tokenType:"color"}},{id:"sem-accent",label:"Accent",description:"Accent/highlight color",type:"token-ref",path:"theme.semantic.colors.accent",defaultValue:"palette.colors.primary.600",tokenRef:{tokenType:"color"}},{id:"sem-surface",label:"Surface",description:"Primary surface background",type:"token-ref",path:"theme.semantic.colors.surface",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-background",label:"Background",description:"Page/widget background",type:"token-ref",path:"theme.semantic.colors.background",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-container",label:"Container",description:"Container/card background",type:"token-ref",path:"theme.semantic.colors.container",defaultValue:"palette.colors.gray.100",tokenRef:{tokenType:"color"}},{id:"sem-text",label:"Text",description:"Primary text color",type:"token-ref",path:"theme.semantic.colors.text",defaultValue:"palette.colors.gray.900",tokenRef:{tokenType:"color"}},{id:"sem-text-muted",label:"Text Muted",description:"Secondary/muted text",type:"token-ref",path:"theme.semantic.colors.textMuted",defaultValue:"palette.colors.gray.500",tokenRef:{tokenType:"color"}},{id:"sem-text-inverse",label:"Text Inverse",description:"Text on dark backgrounds",type:"token-ref",path:"theme.semantic.colors.textInverse",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-border",label:"Border",description:"Default border color",type:"token-ref",path:"theme.semantic.colors.border",defaultValue:"palette.colors.gray.200",tokenRef:{tokenType:"color"}},{id:"sem-divider",label:"Divider",description:"Divider/separator color",type:"token-ref",path:"theme.semantic.colors.divider",defaultValue:"palette.colors.gray.200",tokenRef:{tokenType:"color"}},{id:"sem-interactive-default",label:"Interactive Default",type:"token-ref",path:"theme.semantic.colors.interactive.default",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sem-interactive-hover",label:"Interactive Hover",type:"token-ref",path:"theme.semantic.colors.interactive.hover",defaultValue:"palette.colors.primary.600",tokenRef:{tokenType:"color"}},{id:"sem-interactive-focus",label:"Interactive Focus",type:"token-ref",path:"theme.semantic.colors.interactive.focus",defaultValue:"palette.colors.primary.700",tokenRef:{tokenType:"color"}},{id:"sem-interactive-active",label:"Interactive Active",type:"token-ref",path:"theme.semantic.colors.interactive.active",defaultValue:"palette.colors.primary.800",tokenRef:{tokenType:"color"}},{id:"sem-interactive-disabled",label:"Interactive Disabled",type:"token-ref",path:"theme.semantic.colors.interactive.disabled",defaultValue:"palette.colors.gray.300",tokenRef:{tokenType:"color"}},{id:"sem-feedback-success",label:"Success",type:"token-ref",path:"theme.semantic.colors.feedback.success",defaultValue:"palette.colors.success.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-warning",label:"Warning",type:"token-ref",path:"theme.semantic.colors.feedback.warning",defaultValue:"palette.colors.warning.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-error",label:"Error",type:"token-ref",path:"theme.semantic.colors.feedback.error",defaultValue:"palette.colors.error.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-info",label:"Info",type:"token-ref",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}}]},Dg=au(),Fg=iu,Og=[au(),iu],Ng={id:"comp-panel",title:"Panel",collapsed:!1,fields:[{id:"panel-width",label:"Width",type:"text",path:"theme.components.panel.width",defaultValue:io},{id:"panel-max-width",label:"Max Width",type:"text",path:"theme.components.panel.maxWidth",defaultValue:Ta},{id:"panel-height",label:"Height",type:"text",path:"theme.components.panel.height",defaultValue:"600px"},{id:"panel-max-height",label:"Max Height",type:"text",path:"theme.components.panel.maxHeight",defaultValue:"calc(100vh - 80px)"},{id:"panel-border-radius",label:"Border Radius",type:"select",path:"theme.components.panel.borderRadius",defaultValue:"palette.radius.xl",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"panel-shadow",label:"Shadow",type:"select",path:"theme.components.panel.shadow",defaultValue:"palette.shadows.xl",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},_g={id:"comp-launcher",title:"Launcher",collapsed:!0,fields:[{id:"launcher-size",label:"Size",type:"slider",path:"theme.components.launcher.size",defaultValue:"60px",slider:{min:32,max:80,step:2}},{id:"launcher-icon-size",label:"Icon Size",type:"slider",path:"theme.components.launcher.iconSize",defaultValue:"28px",slider:{min:16,max:48,step:2}},{id:"launcher-border-radius",label:"Border Radius",type:"select",path:"theme.components.launcher.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"},{value:"palette.radius.full",label:"Full (Circle)"}]},{id:"launcher-shadow",label:"Shadow",type:"select",path:"theme.components.launcher.shadow",defaultValue:"palette.shadows.lg",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},Vg={id:"comp-message-shape",title:"Message Shape",collapsed:!0,fields:[{id:"msg-user-radius",label:"User Bubble Radius",type:"select",path:"theme.components.message.user.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"msg-assistant-radius",label:"Assistant Bubble Radius",type:"select",path:"theme.components.message.assistant.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},$g={id:"comp-input-shape",title:"Input Shape",collapsed:!0,fields:[{id:"input-radius",label:"Border Radius",type:"select",path:"theme.components.input.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},Ug={id:"comp-button-shape",title:"Button Shape",collapsed:!0,fields:[{id:"btn-primary-radius",label:"Primary Radius",type:"select",path:"theme.components.button.primary.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.full",label:"Full"}]}]},zg={id:"comp-header-colors",title:"Header Colors",collapsed:!0,fields:[{id:"header-bg",label:"Background",type:"token-ref",path:"theme.components.header.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"header-icon-bg",label:"Icon background",type:"token-ref",path:"theme.components.header.iconBackground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"header-icon-fg",label:"Icon color",type:"token-ref",path:"theme.components.header.iconForeground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"header-title-fg",label:"Title color",type:"token-ref",path:"theme.components.header.titleForeground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"header-subtitle-fg",label:"Subtitle color",type:"token-ref",path:"theme.components.header.subtitleForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"header-action-icons-fg",label:"Clear / close icons",type:"token-ref",path:"theme.components.header.actionIconForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"header-border",label:"Border",type:"token-ref",path:"theme.components.header.border",defaultValue:"semantic.colors.border",tokenRef:{tokenType:"color"}}]},qg={id:"comp-message-colors",title:"Message Colors",collapsed:!0,fields:[{id:"msg-user-bg",label:"User Bubble Background",type:"token-ref",path:"theme.components.message.user.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"msg-user-text",label:"User Bubble Text",type:"token-ref",path:"theme.components.message.user.text",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"msg-assistant-bg",label:"Assistant Bubble Background",type:"token-ref",path:"theme.components.message.assistant.background",defaultValue:"semantic.colors.container",tokenRef:{tokenType:"color"}},{id:"msg-assistant-text",label:"Assistant Bubble Text",type:"token-ref",path:"theme.components.message.assistant.text",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},jg={id:"comp-input-colors",title:"Input Colors",collapsed:!0,fields:[{id:"input-bg",label:"Background",type:"token-ref",path:"theme.components.input.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"input-placeholder",label:"Placeholder Color",type:"token-ref",path:"theme.components.input.placeholder",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"input-focus-border",label:"Focus Border",type:"token-ref",path:"theme.components.input.focus.border",defaultValue:"semantic.colors.interactive.focus",tokenRef:{tokenType:"color"}},{id:"input-focus-ring",label:"Focus Ring",type:"token-ref",path:"theme.components.input.focus.ring",defaultValue:"semantic.colors.interactive.focus",tokenRef:{tokenType:"color"}}]},Kg={id:"comp-button-colors",title:"Button Colors",collapsed:!0,fields:[{id:"btn-primary-bg",label:"Primary Background",type:"token-ref",path:"theme.components.button.primary.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"btn-primary-fg",label:"Primary Foreground",type:"token-ref",path:"theme.components.button.primary.foreground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"btn-secondary-bg",label:"Secondary Background",type:"token-ref",path:"theme.components.button.secondary.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"btn-secondary-fg",label:"Secondary Foreground",type:"token-ref",path:"theme.components.button.secondary.foreground",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}},{id:"btn-ghost-bg",label:"Ghost Background",type:"color",path:"theme.components.button.ghost.background",defaultValue:"transparent"},{id:"btn-ghost-fg",label:"Ghost Foreground",type:"token-ref",path:"theme.components.button.ghost.foreground",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},Gg={id:"scroll-to-bottom-style",title:"Scroll To Bottom",description:"Style the floating jump-to-latest affordance.",collapsed:!0,fields:[{id:"scroll-bottom-bg",label:"Background",type:"token-ref",path:"theme.components.scrollToBottom.background",defaultValue:"components.button.primary.background",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-fg",label:"Foreground",type:"token-ref",path:"theme.components.scrollToBottom.foreground",defaultValue:"components.button.primary.foreground",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-border",label:"Border",type:"token-ref",path:"theme.components.scrollToBottom.border",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-size",label:"Size",type:"text",path:"theme.components.scrollToBottom.size",defaultValue:"40px"},{id:"scroll-bottom-radius",label:"Border Radius",type:"select",path:"theme.components.scrollToBottom.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"},{value:"palette.radius.full",label:"Full"}]},{id:"scroll-bottom-shadow",label:"Shadow",type:"select",path:"theme.components.scrollToBottom.shadow",defaultValue:"palette.shadows.sm",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]},{id:"scroll-bottom-padding",label:"Padding",type:"text",path:"theme.components.scrollToBottom.padding",defaultValue:"0.5rem 0.875rem"},{id:"scroll-bottom-gap",label:"Gap",type:"text",path:"theme.components.scrollToBottom.gap",defaultValue:"0.5rem"},{id:"scroll-bottom-font-size",label:"Font Size",type:"text",path:"theme.components.scrollToBottom.fontSize",defaultValue:"0.875rem"},{id:"scroll-bottom-icon-size",label:"Icon Size",type:"text",path:"theme.components.scrollToBottom.iconSize",defaultValue:"14px"}]},lu=[Ng,_g,Vg,$g,Ug],cu=[zg,qg,jg,Kg,Gg],du=[...lu,...cu],el=1024*1024,Yg=["What can you help me with?","Tell me about your features","How does this work?"],Es={images:["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],"images-pdf":["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf"],"images-text-pdf":["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf","text/plain","text/markdown","text/csv","application/json"],all:["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"]};function Xg(e){return Number(e)*el}function Qg(e){let t=Number(e);return Number.isFinite(t)?t>1024?String(Math.round(t/el)):String(t):"10"}function Jg(e){var t;return(t=Es[String(e)])!=null?t:Es.images}function Zg(e){let t=Array.isArray(e)?e:Es.images,n=[...new Set(t)].sort();for(let[o,r]of Object.entries(Es)){let s=[...r].sort();if(n.length===s.length&&n.every((a,i)=>a===s[i]))return o}return n.some(o=>o.startsWith("application/vnd")||o==="application/msword")?"all":n.some(o=>o==="text/plain"||o==="text/markdown"||o==="text/csv")?"images-text-pdf":n.includes("application/pdf")?"images-pdf":"images"}var ef={id:"copy",title:"Content & Copy",collapsed:!1,fields:[{id:"copy-show-welcome-card",label:"Show Welcome Card",type:"toggle",path:"copy.showWelcomeCard",defaultValue:!0},{id:"copy-welcome-title",label:"Welcome Title",type:"text",path:"copy.welcomeTitle",defaultValue:"Hello \u{1F44B}"},{id:"copy-welcome-subtitle",label:"Welcome Subtitle",type:"text",path:"copy.welcomeSubtitle",defaultValue:"Ask anything about your account or products."},{id:"copy-placeholder",label:"Input Placeholder",type:"text",path:"copy.inputPlaceholder",defaultValue:"Type your message\u2026"},{id:"copy-send-label",label:"Send Button Label",type:"text",path:"copy.sendButtonLabel",defaultValue:"Send"}]},tf={id:"suggestions",title:"Suggestion Chips",description:"Configure chip content and styling.",collapsed:!0,fields:[{id:"suggestions-list",label:"Suggestions",description:"Add, edit, and remove chips directly.",type:"chip-list",path:"suggestionChips",defaultValue:Yg}]},nf={id:"general-layout",title:"Layout Basics",collapsed:!0,fields:[{id:"layout-show-header",label:"Show Header",type:"toggle",path:"layout.showHeader",defaultValue:!0},{id:"layout-show-footer",label:"Show Footer",type:"toggle",path:"layout.showFooter",defaultValue:!0},{id:"layout-content-max-width",label:"Content Max Width",description:"Max width for messages + composer",type:"text",path:"layout.contentMaxWidth",defaultValue:""}]},of={id:"header-layout",title:"Header",collapsed:!0,fields:[{id:"layout-header",label:"Header Layout",type:"select",path:"layout.header.layout",defaultValue:"default",options:[{value:"default",label:"Default"},{value:"minimal",label:"Minimal"}]},{id:"layout-show-icon",label:"Show Header Icon",type:"toggle",path:"layout.header.showIcon",defaultValue:!0},{id:"layout-show-title",label:"Show Header Title",type:"toggle",path:"layout.header.showTitle",defaultValue:!0},{id:"layout-show-subtitle",label:"Show Header Subtitle",type:"toggle",path:"layout.header.showSubtitle",defaultValue:!0},{id:"layout-show-close",label:"Show Close Button",type:"toggle",path:"layout.header.showCloseButton",defaultValue:!0},{id:"layout-show-clear",label:"Show Clear Chat",type:"toggle",path:"layout.header.showClearChat",defaultValue:!0}]},rf={id:"messages-layout",title:"Messages",collapsed:!0,fields:[{id:"layout-messages",label:"Messages Layout",type:"select",path:"layout.messages.layout",defaultValue:"bubble",options:[{value:"bubble",label:"Bubble"},{value:"flat",label:"Flat"},{value:"minimal",label:"Minimal"}]},{id:"layout-group",label:"Group Consecutive",type:"toggle",path:"layout.messages.groupConsecutive",defaultValue:!1},{id:"layout-avatar-show",label:"Show Avatars",type:"toggle",path:"layout.messages.avatar.show",defaultValue:!1},{id:"layout-avatar-pos",label:"Avatar Position",type:"select",path:"layout.messages.avatar.position",defaultValue:"left",options:[{value:"left",label:"Left"},{value:"right",label:"Right"}]},{id:"layout-avatar-user",label:"User Avatar URL",type:"text",path:"layout.messages.avatar.userAvatar",defaultValue:""},{id:"layout-avatar-assistant",label:"Assistant Avatar URL",type:"text",path:"layout.messages.avatar.assistantAvatar",defaultValue:""},{id:"layout-timestamp-show",label:"Show Timestamps",type:"toggle",path:"layout.messages.timestamp.show",defaultValue:!1},{id:"layout-timestamp-pos",label:"Timestamp Position",type:"select",path:"layout.messages.timestamp.position",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"below",label:"Below"}]}]},sf={id:"message-actions",title:"Message Actions",collapsed:!0,fields:[{id:"msg-actions-enabled",label:"Enabled",type:"toggle",path:"messageActions.enabled",defaultValue:!0},{id:"msg-actions-copy",label:"Show Copy",type:"toggle",path:"messageActions.showCopy",defaultValue:!0},{id:"msg-actions-upvote",label:"Show Upvote",type:"toggle",path:"messageActions.showUpvote",defaultValue:!0},{id:"msg-actions-downvote",label:"Show Downvote",type:"toggle",path:"messageActions.showDownvote",defaultValue:!0},{id:"msg-actions-visibility",label:"Visibility",type:"select",path:"messageActions.visibility",defaultValue:"hover",options:[{value:"hover",label:"On Hover"},{value:"always",label:"Always Visible"}]},{id:"msg-actions-align",label:"Alignment",type:"select",path:"messageActions.align",defaultValue:"right",options:[{value:"left",label:"Left"},{value:"right",label:"Right"}]},{id:"msg-actions-layout",label:"Layout",type:"select",path:"messageActions.layout",defaultValue:"pill-inside",options:[{value:"pill-inside",label:"Pill"},{value:"row-inside",label:"Row"}]}]},af={id:"launcher-basics",title:"Launcher",collapsed:!0,fields:[{id:"launch-enabled",label:"Enabled",type:"toggle",path:"launcher.enabled",defaultValue:!0},{id:"launch-mount-mode",label:"Mount Mode",type:"select",path:"launcher.mountMode",defaultValue:"floating",options:[{value:"floating",label:"Floating"},{value:"docked",label:"Docked"}]},{id:"launch-position",label:"Position",type:"select",path:"launcher.position",defaultValue:"bottom-right",options:[{value:"bottom-right",label:"Bottom Right"},{value:"bottom-left",label:"Bottom Left"},{value:"top-right",label:"Top Right"},{value:"top-left",label:"Top Left"}]},{id:"launch-width",label:"Width",type:"text",path:"launcher.width",defaultValue:io},{id:"launch-auto-expand",label:"Auto Expand",type:"toggle",path:"launcher.autoExpand",defaultValue:!1},{id:"launch-title",label:"Title",type:"text",path:"launcher.title",defaultValue:"Chat Assistant"},{id:"launch-subtitle",label:"Subtitle",type:"text",path:"launcher.subtitle",defaultValue:"Here to help you get answers fast"}]},lf={id:"launcher-advanced",title:"Launcher Advanced",collapsed:!0,fields:[{id:"launch-dock-side",label:"Dock Side",type:"select",path:"launcher.dock.side",defaultValue:"right",options:[{value:"right",label:"Right"},{value:"left",label:"Left"}]},{id:"launch-dock-width",label:"Dock Width",type:"text",path:"launcher.dock.width",defaultValue:"420px"},{id:"launch-dock-animate",label:"Dock Animate",type:"toggle",path:"launcher.dock.animate",defaultValue:!0},{id:"launch-dock-reveal",label:"Dock Reveal",type:"select",path:"launcher.dock.reveal",defaultValue:"resize",options:[{value:"resize",label:"Resize"},{value:"overlay",label:"Overlay"},{value:"push",label:"Push"},{value:"emerge",label:"Emerge"}]},{id:"launch-text-hidden",label:"Hide Text",type:"toggle",path:"launcher.textHidden",defaultValue:!1},{id:"launch-icon-text",label:"Agent Icon Text",type:"text",path:"launcher.agentIconText",defaultValue:"\u{1F4AC}"},{id:"launch-icon-name",label:"Agent Icon Name (Lucide)",type:"text",path:"launcher.agentIconName",defaultValue:"bot"},{id:"launch-icon-hidden",label:"Hide Agent Icon",type:"toggle",path:"launcher.agentIconHidden",defaultValue:!1},{id:"launch-icon-size",label:"Agent Icon Size",type:"slider",path:"launcher.agentIconSize",defaultValue:"40px",slider:{min:16,max:72,step:2}},{id:"launch-icon-url",label:"Icon Image URL",description:"Custom image URL (overrides emoji/lucide)",type:"text",path:"launcher.iconUrl",defaultValue:""},{id:"launch-header-icon-name",label:"Header Icon Name (Lucide)",type:"text",path:"launcher.headerIconName",defaultValue:"bot"},{id:"launch-header-icon-size",label:"Header Icon Size",type:"slider",path:"launcher.headerIconSize",defaultValue:"48px",slider:{min:24,max:80,step:2}},{id:"launch-header-icon-hidden",label:"Hide Header Icon",type:"toggle",path:"launcher.headerIconHidden",defaultValue:!1},{id:"launch-full-height",label:"Full Height",type:"toggle",path:"launcher.fullHeight",defaultValue:!1},{id:"launch-sidebar",label:"Sidebar Mode",type:"toggle",path:"launcher.sidebarMode",defaultValue:!1},{id:"launch-sidebar-width",label:"Sidebar Width",type:"text",path:"launcher.sidebarWidth",defaultValue:"420px"},{id:"launch-mobile-fullscreen",label:"Mobile Fullscreen",description:"Fullscreen on mobile devices",type:"toggle",path:"launcher.mobileFullscreen",defaultValue:!0},{id:"launch-mobile-breakpoint",label:"Mobile Breakpoint (px)",type:"text",path:"launcher.mobileBreakpoint",defaultValue:640,formatValue:e=>String(e!=null?e:640),parseValue:e=>Number(e)},{id:"launch-height-offset",label:"Height Offset (px)",type:"text",path:"launcher.heightOffset",defaultValue:0,formatValue:e=>String(e!=null?e:0),parseValue:e=>Number(e)},{id:"launch-collapsed-max-width",label:"Collapsed Max Width",description:"Max width of launcher pill when closed",type:"text",path:"launcher.collapsedMaxWidth",defaultValue:""},{id:"launch-cta-text",label:"CTA Icon Text",type:"text",path:"launcher.callToActionIconText",defaultValue:"\u2197"},{id:"launch-cta-name",label:"CTA Icon Name",type:"text",path:"launcher.callToActionIconName",defaultValue:""},{id:"launch-cta-hidden",label:"Hide CTA Icon",type:"toggle",path:"launcher.callToActionIconHidden",defaultValue:!1},{id:"launch-cta-size",label:"CTA Icon Size",type:"slider",path:"launcher.callToActionIconSize",defaultValue:"32px",slider:{min:16,max:64,step:2}},{id:"launch-cta-padding",label:"CTA Icon Padding",type:"slider",path:"launcher.callToActionIconPadding",defaultValue:"5px",slider:{min:0,max:24,step:1}},{id:"launch-cta-bg",label:"CTA Icon Background",type:"color",path:"launcher.callToActionIconBackgroundColor",defaultValue:""}]},cf={id:"send-button",title:"Send Button",collapsed:!0,fields:[{id:"send-use-icon",label:"Use Icon",type:"toggle",path:"sendButton.useIcon",defaultValue:!1},{id:"send-icon-text",label:"Icon Text",type:"text",path:"sendButton.iconText",defaultValue:"\u2191"},{id:"send-icon-name",label:"Icon Name (Lucide)",type:"text",path:"sendButton.iconName",defaultValue:""},{id:"send-size",label:"Size",type:"slider",path:"sendButton.size",defaultValue:"40px",slider:{min:24,max:64,step:2}},{id:"send-border-width",label:"Border Width",type:"slider",path:"sendButton.borderWidth",defaultValue:"0px",slider:{min:0,max:10,step:1}},{id:"send-padding-x",label:"Padding X",type:"slider",path:"sendButton.paddingX",defaultValue:"10px",slider:{min:0,max:32,step:1}},{id:"send-padding-y",label:"Padding Y",type:"slider",path:"sendButton.paddingY",defaultValue:"6px",slider:{min:0,max:32,step:1}},{id:"send-show-tooltip",label:"Show Tooltip",type:"toggle",path:"sendButton.showTooltip",defaultValue:!1},{id:"send-tooltip-text",label:"Tooltip Text",type:"text",path:"sendButton.tooltipText",defaultValue:"Send message"}]},df={id:"close-button",title:"Close Button",collapsed:!0,fields:[{id:"close-size",label:"Size",type:"slider",path:"launcher.closeButtonSize",defaultValue:"32px",slider:{min:16,max:64,step:1}},{id:"close-placement",label:"Placement",type:"select",path:"launcher.closeButtonPlacement",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"top-right",label:"Top Right"}]},{id:"close-border-width",label:"Border Width",type:"slider",path:"launcher.closeButtonBorderWidth",defaultValue:"0px",slider:{min:0,max:8,step:1}},{id:"close-border-radius",label:"Border Radius",type:"slider",path:"launcher.closeButtonBorderRadius",defaultValue:"50%",slider:{min:0,max:100,step:1,isRadiusFull:!0}},{id:"close-icon-name",label:"Icon Name",type:"text",path:"launcher.closeButtonIconName",defaultValue:"x"},{id:"close-icon-text",label:"Icon Text",type:"text",path:"launcher.closeButtonIconText",defaultValue:"\xD7"},{id:"close-show-tooltip",label:"Show Tooltip",type:"toggle",path:"launcher.closeButtonShowTooltip",defaultValue:!0},{id:"close-tooltip-text",label:"Tooltip Text",type:"text",path:"launcher.closeButtonTooltipText",defaultValue:"Close chat"}]},pf={id:"clear-chat",title:"Clear Chat Button",collapsed:!0,fields:[{id:"clear-enabled",label:"Enabled",type:"toggle",path:"launcher.clearChat.enabled",defaultValue:!0},{id:"clear-placement",label:"Placement",type:"select",path:"launcher.clearChat.placement",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"top-right",label:"Top Right"}]},{id:"clear-icon-name",label:"Icon Name",type:"text",path:"launcher.clearChat.iconName",defaultValue:"refresh-cw"},{id:"clear-size",label:"Size",type:"slider",path:"launcher.clearChat.size",defaultValue:"32px",slider:{min:16,max:64,step:1}},{id:"clear-show-tooltip",label:"Show Tooltip",type:"toggle",path:"launcher.clearChat.showTooltip",defaultValue:!0},{id:"clear-tooltip-text",label:"Tooltip Text",type:"text",path:"launcher.clearChat.tooltipText",defaultValue:"Clear chat"}]},uf={id:"status-indicator",title:"Status Indicator",collapsed:!0,fields:[{id:"status-visible",label:"Visible",type:"toggle",path:"statusIndicator.visible",defaultValue:!0},{id:"status-align",label:"Alignment",type:"select",path:"statusIndicator.align",defaultValue:"right",options:[{value:"left",label:"Left"},{value:"center",label:"Center"},{value:"right",label:"Right"}]},{id:"status-idle-text",label:"Idle Text",type:"text",path:"statusIndicator.idleText",defaultValue:"Online"},{id:"status-connecting-text",label:"Connecting Text",type:"text",path:"statusIndicator.connectingText",defaultValue:"Connecting\u2026"},{id:"status-connected-text",label:"Connected Text",type:"text",path:"statusIndicator.connectedText",defaultValue:"Streaming\u2026"},{id:"status-error-text",label:"Error Text",type:"text",path:"statusIndicator.errorText",defaultValue:"Offline"}]},mf={id:"features",title:"Features",collapsed:!0,fields:[{id:"feat-voice",label:"Voice Recognition",description:"Enable voice input",type:"toggle",path:"voiceRecognition.enabled",defaultValue:!1},{id:"feat-auto-focus",label:"Auto Focus Input",description:"Focus input after panel opens",type:"toggle",path:"autoFocusInput",defaultValue:!1},{id:"feat-scroll-bottom-enabled",label:"Scroll To Bottom",description:"Show a jump-to-latest affordance when the user scrolls away from new content",type:"toggle",path:"features.scrollToBottom.enabled",defaultValue:!0},{id:"feat-scroll-bottom-icon",label:"Scroll To Bottom Icon",type:"text",path:"features.scrollToBottom.iconName",defaultValue:"arrow-down"},{id:"feat-scroll-bottom-label",label:"Scroll To Bottom Label",description:"Leave empty for icon-only mode",type:"text",path:"features.scrollToBottom.label",defaultValue:""}]},gf={id:"stream-animation",title:"Stream Animation",description:"Control how assistant text appears while streaming.",collapsed:!0,fields:[{id:"stream-anim-type",label:"Animation",description:"Reveal effect applied to each assistant reply as it streams.",type:"select",path:"features.streamAnimation.type",defaultValue:"none",options:[{value:"none",label:"None"},{value:"typewriter",label:"Typewriter"},{value:"word-fade",label:"Word fade"},{value:"letter-rise",label:"Letter rise"},{value:"glyph-cycle",label:"Glyph cycle"},{value:"wipe",label:"Wipe"},{value:"pop-bubble",label:"Pop bubble"}]},{id:"stream-anim-placeholder",label:"Pre-first-token Placeholder",description:"What to show before the first token arrives.",type:"select",path:"features.streamAnimation.placeholder",defaultValue:"none",options:[{value:"none",label:"Typing indicator (default)"},{value:"skeleton",label:"Skeleton shimmer"}]},{id:"stream-anim-buffer",label:"Content Buffering",description:"Trim in-progress units so only complete words/lines reveal.",type:"select",path:"features.streamAnimation.buffer",defaultValue:"none",options:[{value:"none",label:"None \u2014 stream every character"},{value:"word",label:"Word \u2014 hold until whitespace"},{value:"line",label:"Line \u2014 hold until newline"}]},{id:"stream-anim-speed",label:"Per-unit Duration (ms)",description:"Animation length for each character or word.",type:"select",path:"features.streamAnimation.speed",defaultValue:120,options:[{value:"40",label:"40ms \u2014 snappy"},{value:"80",label:"80ms"},{value:"120",label:"120ms (default)"},{value:"200",label:"200ms"},{value:"320",label:"320ms"},{value:"480",label:"480ms \u2014 slow"}],formatValue:e=>String(e!=null?e:120),parseValue:e=>Number(e)},{id:"stream-anim-duration",label:"Container Duration (ms)",description:"Length of container-level effects (pop-bubble, custom plugins).",type:"select",path:"features.streamAnimation.duration",defaultValue:1800,options:[{value:"600",label:"600ms"},{value:"1200",label:"1200ms"},{value:"1800",label:"1800ms (default)"},{value:"2400",label:"2400ms"},{value:"3600",label:"3600ms \u2014 slow"}],formatValue:e=>String(e!=null?e:1800),parseValue:e=>Number(e)}]},ff={id:"attachments-config",title:"Attachments",collapsed:!0,fields:[{id:"attach-enabled",label:"Enabled",type:"toggle",path:"attachments.enabled",defaultValue:!1},{id:"attach-max-files",label:"Max Files",type:"select",path:"attachments.maxFiles",defaultValue:4,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"4",label:"4"},{value:"6",label:"6"},{value:"8",label:"8"},{value:"10",label:"10"}],formatValue:e=>String(e!=null?e:4),parseValue:e=>Number(e)},{id:"attach-max-size",label:"Max File Size (MB)",type:"select",path:"attachments.maxFileSize",defaultValue:10*el,options:[{value:"1",label:"1 MB"},{value:"5",label:"5 MB"},{value:"10",label:"10 MB"},{value:"25",label:"25 MB"},{value:"50",label:"50 MB"}],formatValue:Qg,parseValue:Xg},{id:"attach-types",label:"Allowed File Types",type:"select",path:"attachments.allowedTypes",defaultValue:Es.images,options:[{value:"images",label:"Images only"},{value:"images-pdf",label:"Images + PDF"},{value:"images-text-pdf",label:"Images + text + PDF"},{value:"all",label:"All supported types"}],formatValue:Zg,parseValue:Jg}]},hf={id:"artifacts-config",title:"Artifacts",collapsed:!0,fields:[{id:"art-enabled",label:"Enabled",description:"Show artifact sidebar for documents and components",type:"toggle",path:"features.artifacts.enabled",defaultValue:!1},{id:"art-appearance",label:"Pane Appearance",type:"select",path:"features.artifacts.layout.paneAppearance",defaultValue:"panel",options:[{value:"panel",label:"Panel (bordered)"},{value:"seamless",label:"Seamless"}]}]},bf={id:"artifacts-customization",title:"Artifact Customization",collapsed:!0,fields:[{id:"art-toolbar",label:"Toolbar Preset",type:"select",path:"features.artifacts.layout.toolbarPreset",defaultValue:"default",options:[{value:"default",label:"Default"},{value:"document",label:"Document"}]},{id:"art-pane-width",label:"Pane Width",description:"CSS width (e.g. 40%, 28rem)",type:"text",path:"features.artifacts.layout.paneWidth",defaultValue:"40%"},{id:"art-pane-max-width",label:"Pane Max Width",type:"text",path:"features.artifacts.layout.paneMaxWidth",defaultValue:"28rem"},{id:"art-split-gap",label:"Split Gap",type:"text",path:"features.artifacts.layout.splitGap",defaultValue:"0.5rem"},{id:"art-pane-bg",label:"Pane Background",type:"color",path:"features.artifacts.layout.paneBackground",defaultValue:""},{id:"art-unified",label:"Unified Split Chrome",description:"Wrap chat and artifact in a single container",type:"toggle",path:"features.artifacts.layout.unifiedSplitChrome",defaultValue:!1},{id:"art-resizable",label:"Resizable",description:"Allow dragging the pane divider",type:"toggle",path:"features.artifacts.layout.resizable",defaultValue:!1},{id:"art-expand-panel",label:"Expand Panel When Open",description:"Widen the launcher panel to fit artifacts",type:"toggle",path:"features.artifacts.layout.expandLauncherPanelWhenOpen",defaultValue:!0}]},yf={id:"api-integration",title:"API & Integration",description:"Runtime and integration options.",collapsed:!0,fields:[{id:"dev-api-url",label:"API URL",type:"text",path:"apiUrl",defaultValue:""},{id:"dev-flow",label:"Flow ID",type:"text",path:"flowId",defaultValue:""},{id:"dev-parser",label:"Stream Parser",type:"select",path:"parserType",defaultValue:"plain",options:[{value:"plain",label:"Plain Text"},{value:"json",label:"JSON"},{value:"regex-json",label:"Regex JSON"},{value:"xml",label:"XML"}]}]},vf={id:"debug-inspection",title:"Debug & Inspection",collapsed:!0,fields:[{id:"dev-reasoning",label:"Show Reasoning",description:"Display AI reasoning steps",type:"toggle",path:"features.showReasoning",defaultValue:!1},{id:"dev-tool-calls",label:"Show Tool Calls",description:"Display tool call details",type:"toggle",path:"features.showToolCalls",defaultValue:!1},{id:"dev-tool-collapsed-mode",label:"Tool Call Summary",description:"Choose what collapsed tool rows show by default",type:"select",path:"features.toolCallDisplay.collapsedMode",defaultValue:"tool-call",options:[{value:"tool-call",label:"Tool Call"},{value:"tool-name",label:"Tool Name"},{value:"tool-preview",label:"Tool Preview"}]},{id:"dev-tool-active-preview",label:"Tool Preview While Active",description:"Show a lightweight preview in collapsed active tool rows",type:"toggle",path:"features.toolCallDisplay.activePreview",defaultValue:!1},{id:"dev-tool-preview-lines",label:"Tool Preview Lines",type:"select",path:"features.toolCallDisplay.previewMaxLines",defaultValue:3,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"3",label:"3"},{value:"4",label:"4"},{value:"5",label:"5"}],formatValue:e=>String(e!=null?e:3),parseValue:e=>Number(e)},{id:"dev-tool-active-min-height",label:"Tool Active Min Height",description:"CSS min-height for collapsed active tool rows (e.g. 5rem)",type:"text",path:"features.toolCallDisplay.activeMinHeight",defaultValue:""},{id:"dev-tool-expandable",label:"Tool Calls Expandable",description:"Allow expanding tool call rows to see full details",type:"toggle",path:"features.toolCallDisplay.expandable",defaultValue:!0},{id:"dev-tool-grouped",label:"Group Sequential Tool Calls",description:"Render consecutive tool rows inside a grouped container",type:"toggle",path:"features.toolCallDisplay.grouped",defaultValue:!1},{id:"dev-reasoning-expandable",label:"Reasoning Expandable",description:"Allow expanding reasoning rows to see full details",type:"toggle",path:"features.reasoningDisplay.expandable",defaultValue:!0},{id:"dev-reasoning-active-preview",label:"Reasoning Preview While Active",description:"Show a lightweight preview in collapsed active reasoning rows",type:"toggle",path:"features.reasoningDisplay.activePreview",defaultValue:!1},{id:"dev-reasoning-preview-lines",label:"Reasoning Preview Lines",type:"select",path:"features.reasoningDisplay.previewMaxLines",defaultValue:3,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"3",label:"3"},{value:"4",label:"4"},{value:"5",label:"5"}],formatValue:e=>String(e!=null?e:3),parseValue:e=>Number(e)},{id:"dev-reasoning-active-min-height",label:"Reasoning Active Min Height",description:"CSS min-height for collapsed active reasoning rows (e.g. 5rem)",type:"text",path:"features.reasoningDisplay.activeMinHeight",defaultValue:""},{id:"dev-debug",label:"Debug Mode",description:"Show debug information",type:"toggle",path:"debug",defaultValue:!1}]},xf={id:"markdown",title:"Markdown Options",collapsed:!0,fields:[{id:"md-gfm",label:"GitHub Flavored Markdown",type:"toggle",path:"markdown.options.gfm",defaultValue:!0},{id:"md-breaks",label:"Line Breaks",type:"toggle",path:"markdown.options.breaks",defaultValue:!0},{id:"md-header-ids",label:"Header IDs",type:"toggle",path:"markdown.options.headerIds",defaultValue:!1},{id:"md-pedantic",label:"Pedantic Mode",type:"toggle",path:"markdown.options.pedantic",defaultValue:!1},{id:"md-silent",label:"Silent",type:"toggle",path:"markdown.options.silent",defaultValue:!1},{id:"md-disable-styles",label:"Disable Default Styles",type:"toggle",path:"markdown.disableDefaultStyles",defaultValue:!1}]},Na=[{label:"Content",sections:[ef,tf]},{label:"Layout",sections:[nf,of,rf,sf]},{label:"Widget",sections:[af,lf,cf,df,pf,uf]},{label:"Features",sections:[mf,gf,ff,hf,bf]},{label:"Developer",collapsedByDefault:!0,sections:[yf,vf,xf]}],pu=Na.flatMap(e=>e.sections),uu={id:"theme-mode-v2",title:"Theme",description:"Choose how the interface adapts across light and dark mode.",collapsed:!1,fields:[{id:"color-mode",label:"Color Mode",type:"select",path:"colorScheme",defaultValue:"auto",options:[{value:"auto",label:"Auto"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}]}]},mu={id:"brand-palette-v2",title:"Brand Palette",description:"Set your brand, accent, and neutral colors. These are used to generate the interface theme.",collapsed:!1,fields:[{id:"bp-primary",label:"Primary",description:"Main brand color",type:"color",path:"theme.palette.colors.primary.500",defaultValue:"#171717"},{id:"bp-secondary",label:"Secondary",description:"Supporting brand color",type:"color",path:"theme.palette.colors.secondary.500",defaultValue:"#8b5cf6"},{id:"bp-accent",label:"Accent",description:"Highlight and decorative color",type:"color",path:"theme.palette.colors.accent.500",defaultValue:"#06b6d4"},{id:"bp-neutral",label:"Neutral",description:"Backgrounds, text, and borders",type:"color",path:"theme.palette.colors.gray.500",defaultValue:"#6b7280"}]},gu={id:"status-palette",title:"Status Palette",description:"Colors for system feedback states.",collapsed:!0,fields:[{id:"sp-success",label:"Success",type:"color",path:"theme.palette.colors.success.500",defaultValue:"#22c55e"},{id:"sp-warning",label:"Warning",type:"color",path:"theme.palette.colors.warning.500",defaultValue:"#eab308"},{id:"sp-error",label:"Error",type:"color",path:"theme.palette.colors.error.500",defaultValue:"#ef4444"},{id:"sp-notice",label:"Notice",description:"Info and notice states",type:"color",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500"}]},fu={id:"interface-roles",title:"Interface Roles",description:"Control where brand and neutral colors appear across the interface.",collapsed:!1,fields:[{id:"role-surfaces",label:"Background Surfaces",type:"role-assignment",path:"theme.semantic.colors.background",roleAssignment:La},{id:"role-header",label:"Header",type:"role-assignment",path:"theme.components.header.background",roleAssignment:Ia},{id:"role-user-messages",label:"User Messages",type:"role-assignment",path:"theme.components.message.user.background",roleAssignment:Ra},{id:"role-assistant-messages",label:"Assistant Messages",type:"role-assignment",path:"theme.components.message.assistant.background",roleAssignment:Pa},{id:"role-primary-actions",label:"Primary Actions",type:"role-assignment",path:"theme.components.button.primary.background",roleAssignment:Wa},{id:"role-scroll-to-bottom",label:"Scroll To Bottom",type:"role-assignment",path:"theme.components.scrollToBottom.background",roleAssignment:Ba},{id:"role-input",label:"Input Field",type:"role-assignment",path:"theme.components.input.background",roleAssignment:Ha},{id:"role-links-focus",label:"Links & Focus",type:"role-assignment",path:"theme.semantic.colors.accent",roleAssignment:Da},{id:"role-borders",label:"Borders & Dividers",type:"role-assignment",path:"theme.semantic.colors.border",roleAssignment:Fa}]},hu={id:"status-colors",title:"Status Colors",description:"Used for system states like success, warning, notice, and error.",collapsed:!0,fields:[{id:"sc-notice",label:"Notice",type:"token-ref",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sc-success",label:"Success",type:"token-ref",path:"theme.semantic.colors.feedback.success",defaultValue:"palette.colors.success.500",tokenRef:{tokenType:"color"}},{id:"sc-warning",label:"Warning",type:"token-ref",path:"theme.semantic.colors.feedback.warning",defaultValue:"palette.colors.warning.500",tokenRef:{tokenType:"color"}},{id:"sc-error",label:"Error",type:"token-ref",path:"theme.semantic.colors.feedback.error",defaultValue:"palette.colors.error.500",tokenRef:{tokenType:"color"}}]},bu={id:"advanced-tokens",title:"Advanced Tokens",description:"Override individual semantic and component values when you need precise control.",collapsed:!0,fields:[]},wf=[uu,mu,gu,fu,hu,bu],tl=[{id:"style",label:"Style",sections:zr},{id:"design-system",label:"Design System",sections:du},{id:"configure",label:"Configure",sections:pu}];function yu(e,t){return e.startsWith("theme.")?e.replace(/^theme\./,`${t}.`):e}function Cf(e,t,n){return{...e,id:`${n}-${e.id}`,path:yu(e.path,t)}}function Sf(e,t){let n=e.find(o=>o.id===t);if(!n)throw new Error(`Section "${t}" not found in definitions`);return n}function Af(e,t,n,o=e.collapsed){var a;let r=n==="light"?"Light":"Dark",s=n==="light"?"Applies when the widget is in light mode.":"Applies when the widget is in dark mode.";return{...e,id:`${n}-${e.id}`,title:`${r} ${e.title}`,description:e.description?`${s} ${e.description}`:s,collapsed:o,fields:e.fields.map(i=>Cf(i,t,n)),presets:(a=e.presets)==null?void 0:a.map(i=>({...i,id:`${n}-${i.id}`,values:Object.fromEntries(Object.entries(i.values).map(([d,l])=>[yu(d,t),l]))}))}}var vu=[{id:"default-light",name:"Default Light",description:"Clean monochrome light theme",theme:{components:{artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}}},preview:{primary:"#171717",surface:"#ffffff",accent:"#0f0f0f"},tags:["light"]},{id:"default-dark",name:"Default Dark",description:"Monochrome dark theme",theme:{palette:{colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},semantic:{colors:{primary:"palette.colors.primary.400",secondary:"palette.colors.gray.400",accent:"palette.colors.primary.500",surface:"palette.colors.gray.800",background:"palette.colors.gray.900",container:"palette.colors.gray.800",text:"palette.colors.gray.100",textMuted:"palette.colors.gray.400",textInverse:"palette.colors.gray.900",border:"palette.colors.gray.700",divider:"palette.colors.gray.700",interactive:{default:"palette.colors.primary.400",hover:"palette.colors.primary.300",focus:"palette.colors.primary.500",active:"palette.colors.primary.600",disabled:"palette.colors.gray.600"},feedback:{success:"palette.colors.success.400",warning:"palette.colors.warning.400",error:"palette.colors.error.400",info:"palette.colors.primary.400"}}}},preview:{primary:"#171717",surface:"#1f2937",accent:"#0f0f0f"},tags:["dark"]},{id:"high-contrast",name:"High Contrast",description:"Maximum contrast for accessibility",theme:{semantic:{colors:{primary:"palette.colors.primary.700",secondary:"palette.colors.gray.700",accent:"palette.colors.primary.800",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.200",text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.400",divider:"palette.colors.gray.400",interactive:{default:"palette.colors.primary.700",hover:"palette.colors.primary.800",focus:"palette.colors.primary.900",active:"palette.colors.primary.950",disabled:"palette.colors.gray.400"},feedback:{success:"palette.colors.success.700",warning:"palette.colors.warning.700",error:"palette.colors.error.700",info:"palette.colors.primary.700"}}}},preview:{primary:"#0a0a0a",surface:"#f9fafb",accent:"#050505"},tags:["light","high-contrast","accessibility"]}],Ms=[...vu];function nl(e){return Ms.find(t=>t.id===e)}import{Marked as Tf}from"marked";var kf=e=>{if(e)return e},ol=e=>{var r,s;let t=e==null?void 0:e.markedOptions,n=new Tf({gfm:(r=t==null?void 0:t.gfm)!=null?r:!0,breaks:(s=t==null?void 0:t.breaks)!=null?s:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),o=kf(e==null?void 0:e.renderer);return o&&n.use({renderer:o}),a=>n.parse(a)},_a=e=>e?ol({markedOptions:e.options,renderer:e.renderer}):ol(),Jx=ol();var Ls=e=>e.replace(/&/g,"&").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)},Va=e=>e===!1?null:typeof e=="function"?e:If();var rl="webmcp:",$a={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function wu(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var o,r;return[n.name,(o=n.description)!=null?o:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(r=n.origin)!=null?r:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${Rf(t.join(""))}`}function xu(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function Rf(e){let t=xu(e,0).toString(36),n=xu(e,2654435761).toString(36);return`${t}.${n}`}var Ua=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return $a.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",r),[]}let o=typeof location!="undefined"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=Bf(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return vo("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let u=typeof document!="undefined"&&!!document.modelContext;return vo(u?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=Pf(t),a;try{a=await r.getTools()}catch(u){let w=u instanceof Error?u.message:String(u);return vo(`Failed to read WebMCP registry: ${w}`)}let i=a.find(u=>u.name===s);if(!i)return vo(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return vo(`WebMCP tool not allowed by client allowlist: ${s}`);if(o!=null&&o.aborted)return vo("Aborted by cancel()");let d={toolName:s,args:n,description:i.description,reason:"gate"};if(!await this.requestConfirm(d))return vo("User declined the tool call.");if(o!=null&&o.aborted)return vo("Aborted by cancel()");let l=new AbortController,p=!1,m=setTimeout(()=>{p=!0,l.abort()},this.timeoutMs),f=()=>l.abort();o&&(o.aborted?l.abort():o.addEventListener("abort",f,{once:!0}));try{let u=await r.executeTool(i,Of(n),{signal:l.signal});return Hf(u)}catch(u){if(p)return vo(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return vo("Aborted by cancel()");let w=u instanceof Error?u.message:String(u);return vo(w)}finally{clearTimeout(m),o&&o.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){$a.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,$a.warn("document.modelContext is present but does not expose getTools()/executeTool() \u2014 WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var o;let n=(o=this.confirmHandler)!=null?o:Df;try{return await n(t)}catch(r){return $a.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,r),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>Wf(t,o))}},Pf=e=>e.startsWith(rl)?e.slice(rl.length):e,sl=e=>e.startsWith(rl),Wf=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Bf=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Hf=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:Nf(t)}]}},vo=e=>({isError:!0,content:[{type:"text",text:e}]}),Df=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Ff(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
1
|
+
var Xp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ks(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];Xp(s)&&Xp(r)?n[o]=ks(s,r):n[o]=r}return n}var io="min(440px, calc(100vw - 24px))",Ea="440px",St={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:io,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Qp(e,t){if(!(!e&&!t))return e?t?ks(e,t):e:t}function Jp(e){var t,n,o,r,s,a,i,d,l,m,u,g,p,w,S,M,I,L,H,D,W;return e?{...St,...e,theme:Qp(St.theme,e.theme),darkTheme:Qp(St.darkTheme,e.darkTheme),launcher:{...St.launcher,...e.launcher,dock:{...(t=St.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(o=St.launcher)==null?void 0:o.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...St.copy,...e.copy},sendButton:{...St.sendButton,...e.sendButton},statusIndicator:{...St.statusIndicator,...e.statusIndicator},voiceRecognition:{...St.voiceRecognition,...e.voiceRecognition},features:(()=>{var be,Oe,ve,Q,Le,Y,xe,Se;let v=(be=St.features)==null?void 0:be.artifacts,x=(Oe=e.features)==null?void 0:Oe.artifacts,k=(ve=St.features)==null?void 0:ve.scrollToBottom,C=(Q=e.features)==null?void 0:Q.scrollToBottom,T=(Le=St.features)==null?void 0:Le.streamAnimation,F=(Y=e.features)==null?void 0:Y.streamAnimation,$=(xe=St.features)==null?void 0:xe.askUserQuestion,j=(Se=e.features)==null?void 0:Se.askUserQuestion,me=v===void 0&&x===void 0?void 0:{...v,...x,layout:{...v==null?void 0:v.layout,...x==null?void 0:x.layout}},se=k===void 0&&C===void 0?void 0:{...k,...C},fe=T===void 0&&F===void 0?void 0:{...T,...F},ie=$===void 0&&j===void 0?void 0:{...$,...j,styles:{...$==null?void 0:$.styles,...j==null?void 0:j.styles}};return{...St.features,...e.features,...se!==void 0?{scrollToBottom:se}:{},...me!==void 0?{artifacts:me}:{},...fe!==void 0?{streamAnimation:fe}:{},...ie!==void 0?{askUserQuestion:ie}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:St.suggestionChips,suggestionChipsConfig:{...St.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...St.layout,...e.layout,header:{...(a=St.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=St.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(u=(m=St.layout)==null?void 0:m.messages)==null?void 0:u.avatar,...(p=(g=e.layout)==null?void 0:g.messages)==null?void 0:p.avatar},timestamp:{...(S=(w=St.layout)==null?void 0:w.messages)==null?void 0:S.timestamp,...(I=(M=e.layout)==null?void 0:M.messages)==null?void 0:I.timestamp}},slots:{...(L=St.layout)==null?void 0:L.slots,...(H=e.layout)==null?void 0:H.slots}},markdown:{...St.markdown,...e.markdown,options:{...(D=St.markdown)==null?void 0:D.options,...(W=e.markdown)==null?void 0:W.options}},messageActions:{...St.messageActions,...e.messageActions}}:St}var pf={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},uf={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},mf={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:io,maxWidth:Ea,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Vr(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Vr(e,o):o}function Zp(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let i=`${r}.${s}`;if(typeof a=="string"){let d=Vr(e,a);d!==void 0&&(t[i]={path:i,value:d,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function ff(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function eu(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=eu(s,r):n[o]=r}return n}function gf(e,t){return t?eu(e,t):e}function tn(e,t={}){var r,s,a,i,d,l,m,u,g,p,w,S,M;let n={palette:pf,semantic:uf,components:mf},o={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(m=e==null?void 0:e.semantic)==null?void 0:m.colors,interactive:{...n.semantic.colors.interactive,...(g=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:g.interactive},feedback:{...n.semantic.colors.feedback,...(w=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:w.feedback}},spacing:{...n.semantic.spacing,...(S=e==null?void 0:e.semantic)==null?void 0:S.spacing},typography:{...n.semantic.typography,...(M=e==null?void 0:e.semantic)==null?void 0:M.typography}},components:gf(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let I=ff(o);if(!I.valid)throw new Error(`Theme validation failed: ${I.errors.map(L=>L.message).join(", ")}`)}if(t.plugins)for(let I of t.plugins)o=I.transform(o);return o}function tu(e){var S,M,I,L,H,D,W,v,x,k,C,T,F,$,j,me,se,fe,ie,be,Oe,ve,Q,Le,Y,xe,Se,de,we,ze,te,ne,re,nt,ye,le,Ue,He,ce,G,Ve,Et,pe,ae,Ln,Nt,ln,Dn,Jn,qe,_,ke,De,Fe,$e,dt,ot,At,Vt,q,_t,Qe,Ft,oe,ge,xt,$t,Jt,yn,Tt,wt,gt,bt,zt,et,Fn,Zn,vn,On,ut,wo,Nn,ir,In,Rr,$o,Lo,yt,_n,Vn,xn,It,eo,to,$n,Uo,Io,zo,Un,Wt,wn,no,qo,Ro,jo,Co,zn,po,ft,Kt,Gt,qn,Ko,oo,uo,jn;let t=Zp(e),n={};for(let[E,Kn]of Object.entries(t)){let mo=E.replace(/\./g,"-");n[`--persona-${mo}`]=Kn.value}n["--persona-primary"]=(S=n["--persona-semantic-colors-primary"])!=null?S:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(M=n["--persona-semantic-colors-secondary"])!=null?M:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(I=n["--persona-semantic-colors-accent"])!=null?I:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(L=n["--persona-semantic-colors-surface"])!=null?L:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(H=n["--persona-semantic-colors-background"])!=null?H:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(D=n["--persona-semantic-colors-container"])!=null?D:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(W=n["--persona-semantic-colors-text"])!=null?W:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(v=n["--persona-semantic-colors-text-muted"])!=null?v:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(x=n["--persona-semantic-colors-text-inverse"])!=null?x:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(k=n["--persona-semantic-colors-border"])!=null?k:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(C=n["--persona-semantic-colors-divider"])!=null?C:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(T=n["--persona-components-voice-recording-indicator"])!=null?T:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(F=n["--persona-components-voice-recording-background"])!=null?F:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=($=n["--persona-components-voice-processing-icon"])!=null?$:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(j=n["--persona-components-voice-speaking-icon"])!=null?j:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(me=n["--persona-components-approval-requested-background"])!=null?me:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(se=n["--persona-components-approval-requested-border"])!=null?se:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(fe=n["--persona-components-approval-requested-text"])!=null?fe:n["--persona-palette-colors-gray-900"],n["--persona-approval-approve-bg"]=(ie=n["--persona-components-approval-approve-background"])!=null?ie:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(be=n["--persona-components-approval-deny-background"])!=null?be:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Oe=n["--persona-components-attachment-image-background"])!=null?Oe:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(ve=n["--persona-components-attachment-image-border"])!=null?ve:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(Q=n["--persona-semantic-typography-fontFamily"])!=null?Q:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(Le=n["--persona-semantic-typography-fontSize"])!=null?Le:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(Y=n["--persona-semantic-typography-fontWeight"])!=null?Y:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(xe=n["--persona-semantic-typography-lineHeight"])!=null?xe:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(Se=n["--persona-palette-radius-sm"])!=null?Se:"0.125rem",n["--persona-radius-md"]=(de=n["--persona-palette-radius-md"])!=null?de:"0.375rem",n["--persona-radius-lg"]=(we=n["--persona-palette-radius-lg"])!=null?we:"0.5rem",n["--persona-radius-xl"]=(ze=n["--persona-palette-radius-xl"])!=null?ze:"0.75rem",n["--persona-radius-full"]=(te=n["--persona-palette-radius-full"])!=null?te:"9999px",n["--persona-launcher-radius"]=(re=(ne=n["--persona-components-launcher-borderRadius"])!=null?ne:n["--persona-palette-radius-full"])!=null?re:"9999px",n["--persona-launcher-bg"]=(nt=n["--persona-components-launcher-background"])!=null?nt:n["--persona-primary"],n["--persona-launcher-fg"]=(ye=n["--persona-components-launcher-foreground"])!=null?ye:n["--persona-text-inverse"],n["--persona-launcher-border"]=(le=n["--persona-components-launcher-border"])!=null?le:n["--persona-border"],n["--persona-button-primary-bg"]=(Ue=n["--persona-components-button-primary-background"])!=null?Ue:n["--persona-primary"],n["--persona-button-primary-fg"]=(He=n["--persona-components-button-primary-foreground"])!=null?He:n["--persona-text-inverse"],n["--persona-button-radius"]=(G=(ce=n["--persona-components-button-primary-borderRadius"])!=null?ce:n["--persona-palette-radius-full"])!=null?G:"9999px",n["--persona-panel-radius"]=(Et=(Ve=n["--persona-components-panel-borderRadius"])!=null?Ve:n["--persona-radius-xl"])!=null?Et:"0.75rem",n["--persona-panel-border"]=(pe=n["--persona-components-panel-border"])!=null?pe:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Ln=(ae=n["--persona-components-panel-shadow"])!=null?ae:n["--persona-palette-shadows-xl"])!=null?Ln:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-input-radius"]=(ln=(Nt=n["--persona-components-input-borderRadius"])!=null?Nt:n["--persona-radius-lg"])!=null?ln:"0.5rem",n["--persona-message-user-radius"]=(Jn=(Dn=n["--persona-components-message-user-borderRadius"])!=null?Dn:n["--persona-radius-lg"])!=null?Jn:"0.5rem",n["--persona-message-assistant-radius"]=(_=(qe=n["--persona-components-message-assistant-borderRadius"])!=null?qe:n["--persona-radius-lg"])!=null?_:"0.5rem",n["--persona-header-bg"]=(ke=n["--persona-components-header-background"])!=null?ke:n["--persona-surface"],n["--persona-header-border"]=(De=n["--persona-components-header-border"])!=null?De:n["--persona-divider"],n["--persona-header-icon-bg"]=(Fe=n["--persona-components-header-iconBackground"])!=null?Fe:n["--persona-primary"],n["--persona-header-icon-fg"]=($e=n["--persona-components-header-iconForeground"])!=null?$e:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(dt=n["--persona-components-header-titleForeground"])!=null?dt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(ot=n["--persona-components-header-subtitleForeground"])!=null?ot:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(At=n["--persona-components-header-actionIconForeground"])!=null?At:n["--persona-muted"];let o=(Vt=e.components)==null?void 0:Vt.header;o!=null&&o.shadow&&(n["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom);let r=(q=e.components)==null?void 0:q.introCard;n["--persona-intro-card-bg"]=(_t=n["--persona-components-introCard-background"])!=null?_t:n["--persona-surface"],n["--persona-intro-card-radius"]=(Qe=n["--persona-components-introCard-borderRadius"])!=null?Qe:"1rem",n["--persona-intro-card-padding"]=(Ft=n["--persona-components-introCard-padding"])!=null?Ft:"1.5rem",n["--persona-intro-card-shadow"]=(ge=(oe=r==null?void 0:r.shadow)!=null?oe:n["--persona-components-introCard-shadow"])!=null?ge:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(xt=n["--persona-components-input-background"])!=null?xt:n["--persona-surface"],n["--persona-input-placeholder"]=($t=n["--persona-components-input-placeholder"])!=null?$t:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Jt=n["--persona-components-message-user-background"])!=null?Jt:n["--persona-accent"],n["--persona-message-user-text"]=(yn=n["--persona-components-message-user-text"])!=null?yn:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Tt=n["--persona-components-message-user-shadow"])!=null?Tt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(wt=n["--persona-components-message-assistant-background"])!=null?wt:n["--persona-surface"],n["--persona-message-assistant-text"]=(gt=n["--persona-components-message-assistant-text"])!=null?gt:n["--persona-text"],n["--persona-message-assistant-border"]=(bt=n["--persona-components-message-assistant-border"])!=null?bt:n["--persona-border"],n["--persona-message-assistant-shadow"]=(zt=n["--persona-components-message-assistant-shadow"])!=null?zt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(Fn=(et=n["--persona-components-scrollToBottom-background"])!=null?et:n["--persona-button-primary-bg"])!=null?Fn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(vn=(Zn=n["--persona-components-scrollToBottom-foreground"])!=null?Zn:n["--persona-button-primary-fg"])!=null?vn:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(On=n["--persona-components-scrollToBottom-border"])!=null?On:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(ut=n["--persona-components-scrollToBottom-size"])!=null?ut:"40px",n["--persona-scroll-to-bottom-radius"]=(ir=(Nn=(wo=n["--persona-components-scrollToBottom-borderRadius"])!=null?wo:n["--persona-button-radius"])!=null?Nn:n["--persona-radius-full"])!=null?ir:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Rr=(In=n["--persona-components-scrollToBottom-shadow"])!=null?In:n["--persona-palette-shadows-sm"])!=null?Rr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=($o=n["--persona-components-scrollToBottom-padding"])!=null?$o:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Lo=n["--persona-components-scrollToBottom-gap"])!=null?Lo:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(_n=(yt=n["--persona-components-scrollToBottom-fontSize"])!=null?yt:n["--persona-palette-typography-fontSize-sm"])!=null?_n:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Vn=n["--persona-components-scrollToBottom-iconSize"])!=null?Vn:"14px",n["--persona-tool-bubble-shadow"]=(xn=n["--persona-components-toolBubble-shadow"])!=null?xn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(It=n["--persona-components-reasoningBubble-shadow"])!=null?It:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(eo=n["--persona-components-composer-shadow"])!=null?eo:"none",n["--persona-md-inline-code-bg"]=(to=n["--persona-components-markdown-inlineCode-background"])!=null?to:n["--persona-container"],n["--persona-md-inline-code-color"]=($n=n["--persona-components-markdown-inlineCode-foreground"])!=null?$n:n["--persona-text"],n["--persona-md-link-color"]=(Io=(Uo=n["--persona-components-markdown-link-foreground"])!=null?Uo:n["--persona-accent"])!=null?Io:"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let l=n["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(n["--persona-md-prose-font-family"]=l),n["--persona-md-code-block-bg"]=(zo=n["--persona-components-markdown-codeBlock-background"])!=null?zo:n["--persona-container"],n["--persona-md-code-block-border-color"]=(Un=n["--persona-components-markdown-codeBlock-borderColor"])!=null?Un:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Wt=n["--persona-components-markdown-codeBlock-textColor"])!=null?Wt:"inherit",n["--persona-md-table-header-bg"]=(wn=n["--persona-components-markdown-table-headerBackground"])!=null?wn:n["--persona-container"],n["--persona-md-table-border-color"]=(no=n["--persona-components-markdown-table-borderColor"])!=null?no:n["--persona-border"],n["--persona-md-hr-color"]=(qo=n["--persona-components-markdown-hr-color"])!=null?qo:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Ro=n["--persona-components-markdown-blockquote-borderColor"])!=null?Ro:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(jo=n["--persona-components-markdown-blockquote-background"])!=null?jo:"transparent",n["--persona-md-blockquote-text-color"]=(Co=n["--persona-components-markdown-blockquote-textColor"])!=null?Co:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(zn=n["--persona-components-collapsibleWidget-container"])!=null?zn:n["--persona-surface"],n["--cw-surface"]=(po=n["--persona-components-collapsibleWidget-surface"])!=null?po:n["--persona-surface"],n["--cw-border"]=(ft=n["--persona-components-collapsibleWidget-border"])!=null?ft:n["--persona-border"],n["--persona-message-border"]=(Kt=n["--persona-components-message-border"])!=null?Kt:n["--persona-border"];let m=e.components,u=m==null?void 0:m.iconButton;u&&(u.background&&(n["--persona-icon-btn-bg"]=u.background),u.border&&(n["--persona-icon-btn-border"]=u.border),u.color&&(n["--persona-icon-btn-color"]=u.color),u.padding&&(n["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(n["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(n["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(n["--persona-icon-btn-active-border"]=u.activeBorder));let g=m==null?void 0:m.labelButton;g&&(g.background&&(n["--persona-label-btn-bg"]=g.background),g.border&&(n["--persona-label-btn-border"]=g.border),g.color&&(n["--persona-label-btn-color"]=g.color),g.padding&&(n["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(n["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(n["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(n["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(n["--persona-label-btn-gap"]=g.gap));let p=m==null?void 0:m.toggleGroup;p&&(p.gap&&(n["--persona-toggle-group-gap"]=p.gap),p.borderRadius&&(n["--persona-toggle-group-radius"]=p.borderRadius));let w=m==null?void 0:m.artifact;if(w!=null&&w.toolbar){let E=w.toolbar;E.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=E.iconHoverColor),E.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=E.iconHoverBackground),E.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=E.iconPadding),E.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=E.iconBorderRadius),E.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=E.iconBorder),E.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=E.toggleGroupGap),E.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=E.toggleBorderRadius),E.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=E.copyBackground),E.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=E.copyBorder),E.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=E.copyColor),E.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=E.copyBorderRadius),E.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=E.copyPadding),E.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=E.copyMenuBackground,n["--persona-dropdown-bg"]=(Gt=n["--persona-dropdown-bg"])!=null?Gt:E.copyMenuBackground),E.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=E.copyMenuBorder,n["--persona-dropdown-border"]=(qn=n["--persona-dropdown-border"])!=null?qn:E.copyMenuBorder),E.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=E.copyMenuShadow,n["--persona-dropdown-shadow"]=(Ko=n["--persona-dropdown-shadow"])!=null?Ko:E.copyMenuShadow),E.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=E.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(oo=n["--persona-dropdown-radius"])!=null?oo:E.copyMenuBorderRadius),E.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=E.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(uo=n["--persona-dropdown-item-hover-bg"])!=null?uo:E.copyMenuItemHoverBackground),E.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=E.iconBackground),E.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=E.toolbarBorder)}if(w!=null&&w.tab){let E=w.tab;E.background&&(n["--persona-artifact-tab-bg"]=E.background),E.activeBackground&&(n["--persona-artifact-tab-active-bg"]=E.activeBackground),E.activeBorder&&(n["--persona-artifact-tab-active-border"]=E.activeBorder),E.borderRadius&&(n["--persona-artifact-tab-radius"]=E.borderRadius),E.textColor&&(n["--persona-artifact-tab-color"]=E.textColor),E.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=E.hoverBackground),E.listBackground&&(n["--persona-artifact-tab-list-bg"]=E.listBackground),E.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=E.listBorderColor),E.listPadding&&(n["--persona-artifact-tab-list-padding"]=E.listPadding)}if(w!=null&&w.pane){let E=w.pane;if(E.toolbarBackground){let Kn=(jn=Vr(e,E.toolbarBackground))!=null?jn:E.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Kn}}return n}var hf={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},nu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},ji=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},bf=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":ji()},yf=e=>bf(e),vf=e=>tn(e),xf=e=>{var n;let t=tn(void 0,{validate:!1});return tn({...e,palette:{...t.palette,colors:{...hf.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Ma=e=>{let t=yf(e),n=nu(e==null?void 0:e.theme),o=nu(e==null?void 0:e.darkTheme);return t==="dark"?xf(ks(n!=null?n:{},o!=null?o:{})):vf(n)},wf=e=>tu(e),$r=(e,t)=>{var s;let n=Ma(t),o=wf(n);for(let[a,i]of Object.entries(o))e.style.setProperty(a,i);let r=(s=t==null?void 0:t.toolCall)==null?void 0:s.shadow;r!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",r.trim()===""?"none":r)},ou=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(ji())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(ji());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};function Ki(e,t){let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return o}function xr(e,t,n){var i;let o=t.split(".");if(o.length===1)return{...e,[o[0]]:n};let[r,...s]=o,a=e;return{...a,[r]:xr((i=a==null?void 0:a[r])!=null?i:{},s.join("."),n)}}var Gi=class{constructor(t,n,o){this.listeners=[];this.history=[];this.historyIndex=-1;this.suppressHistory=!1;var s;let r=(s=o==null?void 0:o.mergeDefaults)!=null?s:!0;this.config=r?{...St,...n}:n!=null?n:St,this.theme=tn(t,{validate:!1}),this.syncThemeIntoConfig(),this.pushHistorySnapshot(this.exportSnapshot(),!0)}get(t){var n;return t.startsWith("theme.")?Ki(this.theme,t.replace("theme.","")):t.startsWith("darkTheme.")?Ki((n=this.config.darkTheme)!=null?n:{},t.replace("darkTheme.","")):Ki(this.config,t)}getTheme(){return this.theme}getConfig(){return this.config}set(t,n){var o;if(t.startsWith("theme.")){let r=t.replace("theme.","");this.theme=xr(this.theme,r,n),this.syncThemeIntoConfig()}else if(t.startsWith("darkTheme.")){let r=t.replace("darkTheme.",""),s=(o=this.config.darkTheme)!=null?o:tn();this.config={...this.config,darkTheme:xr(s,r,n)}}else this.config=xr(this.config,t,n);this.recordHistory(),this.notifyListeners()}setBatch(t){var s;let n=!1,o=!1,r=!1;for(let[a,i]of Object.entries(t))if(a.startsWith("theme.")){let d=a.replace("theme.","");this.theme=xr(this.theme,d,i),n=!0}else if(a.startsWith("darkTheme.")){let d=a.replace("darkTheme.",""),l=(s=this.config.darkTheme)!=null?s:tn();this.config={...this.config,darkTheme:xr(l,d,i)},o=!0}else this.config=xr(this.config,a,i),r=!0;n&&this.syncThemeIntoConfig(),(n||o||r)&&(this.recordHistory(),this.notifyListeners())}setTheme(t){this.theme=t,this.syncThemeIntoConfig(),this.recordHistory(),this.notifyListeners()}setFullConfig(t,n){this.config={...t},n&&(this.theme=n),this.syncThemeIntoConfig(),this.recordHistory(),this.notifyListeners()}importSnapshot(t){var r,s;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Snapshot must be a JSON object");let n=t;if("config"in n||"theme"in n||n.version===2){let a=(r=n.config)!=null?r:this.config,i=tn((s=n.theme)!=null?s:this.theme,{validate:!1});this.setFullConfig(a,i);return}let o=tn(n,{validate:!1});this.setTheme(o)}resetToDefaults(){this.config={...St},this.theme=tn(),this.syncThemeIntoConfig(),this.history=[],this.historyIndex=-1,this.pushHistorySnapshot(this.exportSnapshot()),this.notifyListeners()}canUndo(){return this.historyIndex>0}canRedo(){return this.historyIndex>=0&&this.historyIndex<this.history.length-1}getHistoryLength(){return this.history.length}getHistoryIndex(){return this.historyIndex}undo(){this.canUndo()&&(this.historyIndex-=1,this.restoreSnapshot(this.history[this.historyIndex]))}redo(){this.canRedo()&&(this.historyIndex+=1,this.restoreSnapshot(this.history[this.historyIndex]))}exportSnapshot(){return{version:2,config:{...this.config,theme:void 0},theme:this.theme}}onChange(t){return this.listeners.push(t),()=>{let n=this.listeners.indexOf(t);n>=0&&this.listeners.splice(n,1)}}syncThemeIntoConfig(){this.config={...this.config,theme:this.theme}}notifyListeners(){for(let t of this.listeners)t(this.config,this.theme)}recordHistory(){this.pushHistorySnapshot(this.exportSnapshot())}pushHistorySnapshot(t,n=!1){if(this.suppressHistory)return;let o=JSON.stringify(t),r=this.historyIndex>=0&&this.history[this.historyIndex]?JSON.stringify(this.history[this.historyIndex]):null;if(n&&this.historyIndex>=0){this.history[this.historyIndex]=t;return}o!==r&&(this.history=this.history.slice(0,this.historyIndex+1),this.history.push(t),this.historyIndex=this.history.length-1)}restoreSnapshot(t){this.suppressHistory=!0,this.config=t.config,this.theme=tn(t.theme,{validate:!1}),this.syncThemeIntoConfig(),this.suppressHistory=!1,this.notifyListeners()}};function Yi(e){let t=e.trim();if(t==="9999px")return{value:100,unit:"px"};let n=t.match(/^([\d.]+)(px|rem)$/);if(!n){let o=parseFloat(t);return{value:isNaN(o)?0:o,unit:"px"}}return{value:parseFloat(n[1]),unit:n[2]}}function Xi(e,t){return t==="rem"?`${e}rem`:`${e}px`}function Cf(e,t){return t==="rem"?e*16:e}function Sf(e,t){return t==="rem"?e/16:e}function Es(e){if(!e)return"#000000";let t=e.trim().toLowerCase();return t==="transparent"?"transparent":t.startsWith("rgba")||t.startsWith("rgb")?t:t.startsWith("#")?t.length===4?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:t:`#${t}`}function Qi(e){return/^#[0-9A-Fa-f]{6}$/.test(e)}function Ji(e){let t=e.trim().toLowerCase().match(/^rgba?\(([^)]+)\)$/);if(!t)return null;let n=t[1].split(",").map(d=>d.trim());if(n.length<3)return null;let o=d=>{let l=d.endsWith("%"),m=parseFloat(l?d.slice(0,-1):d);return Number.isFinite(m)?Math.max(0,Math.min(255,Math.round(l?m/100*255:m))):NaN},r=o(n[0]),s=o(n[1]),a=o(n[2]);if(!Number.isFinite(r)||!Number.isFinite(s)||!Number.isFinite(a))return null;let i=d=>d.toString(16).padStart(2,"0");return`#${i(r)}${i(s)}${i(a)}`}function La(e,t){let n=s=>{var l;let a=Es(s),i=a.startsWith("rgb")?(l=Ji(a))!=null?l:"#000000":a,d=[1,3,5].map(m=>{let u=parseInt(i.slice(m,m+2),16)/255;return u<=.03928?u/12.92:Math.pow((u+.055)/1.055,2.4)});return .2126*d[0]+.7152*d[1]+.0722*d[2]},o=n(e),r=n(t);return(Math.max(o,r)+.05)/(Math.min(o,r)+.05)}function ru(e){var g;let t=Es(e),n=t.startsWith("rgb")?(g=Ji(t))!=null?g:"#000000":t,o=parseInt(n.slice(1,3),16)/255,r=parseInt(n.slice(3,5),16)/255,s=parseInt(n.slice(5,7),16)/255,a=Math.max(o,r,s),i=Math.min(o,r,s),d=(a+i)/2;if(a===i)return{h:0,s:0,l:d};let l=a-i,m=d>.5?l/(2-a-i):l/(a+i),u;switch(a){case o:u=((r-s)/l+(r<s?6:0))/6;break;case r:u=((s-o)/l+2)/6;break;default:u=((o-r)/l+4)/6;break}return{h:u*360,s:m,l:d}}function su(e,t,n){let o=(e%360+360)%360,r=(1-Math.abs(2*n-1))*t,s=r*(1-Math.abs(o/60%2-1)),a=n-r/2,i,d,l;o<60?[i,d,l]=[r,s,0]:o<120?[i,d,l]=[s,r,0]:o<180?[i,d,l]=[0,r,s]:o<240?[i,d,l]=[0,s,r]:o<300?[i,d,l]=[s,0,r]:[i,d,l]=[r,0,s];let m=u=>{let g=Math.round((u+a)*255).toString(16);return g.length===1?"0"+g:g};return`#${m(i)}${m(d)}${m(l)}`}function Zi(e){let{h:t,s:n,l:o}=ru(e),r={50:.97,100:.94,200:.87,300:.77,400:.64,500:o,600:Math.max(.05,o-.1),700:Math.max(.05,o-.2),800:Math.max(.05,o-.28),900:Math.max(.05,o-.35),950:Math.max(.03,o-.42)},s={50:Math.min(1,n*.85),100:Math.min(1,n*.9),200:Math.min(1,n*.95),300:n,400:n,500:n,600:Math.min(1,n*1.05),700:Math.min(1,n*1.05),800:Math.min(1,n*1),900:Math.min(1,n*.95),950:Math.min(1,n*.9)},a={};for(let[i,d]of Object.entries(r)){let l=s[i];a[i]=su(t,l,d)}return a}var Ur=["50","100","200","300","400","500","600","700","800","900","950"],el=["primary","secondary","accent","gray","success","warning","error","info"];function Af(e,t){return`palette.colors.${e}.${t}`}function au(e,t,n=0){if(n>5)return"#cbd5e1";let o=e(t);return typeof o!="string"?"#cbd5e1":o.startsWith("#")||o.startsWith("rgb")||o==="transparent"?o:o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components.")?au(e,`theme.${o}`,n+1):"#cbd5e1"}function Tf(e){if(!e.startsWith("palette.")&&!e.startsWith("semantic."))return e;let t=e.split(".");if(t[0]==="palette"&&t[1]==="colors"){let n=t[2],o=t[3];return`${n.charAt(0).toUpperCase()+n.slice(1)} ${o}`}return t[0]==="semantic"?t.slice(1).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):t[t.length-1]}var ko=[{id:"solid",label:"Solid"},{id:"soft",label:"Soft"}],Ia=["primary","secondary","accent","gray"],kf={primary:"Primary",secondary:"Secondary",accent:"Accent",gray:"Neutral"},Ra={roleId:"role-surfaces",helper:"Page and panel backgrounds",previewZone:"container",intensities:ko,targets:[{path:"semantic.colors.background",kind:"background"},{path:"semantic.colors.surface",kind:"background"},{path:"semantic.colors.container",kind:"background"}]},Pa={roleId:"role-header",helper:"Widget header bar",previewZone:"header",intensities:ko,targets:[{path:"components.header.background",kind:"background"},{path:"components.header.border",kind:"border"},{path:"components.header.iconBackground",kind:"accent"},{path:"components.header.iconForeground",kind:"foreground"},{path:"components.header.titleForeground",kind:"accent"},{path:"components.header.subtitleForeground",kind:"foreground"},{path:"components.header.actionIconForeground",kind:"foreground"}]},Wa={roleId:"role-user-messages",helper:"User chat bubbles",previewZone:"user-message",intensities:ko,targets:[{path:"components.message.user.background",kind:"background"},{path:"components.message.user.text",kind:"foreground"}]},Ba={roleId:"role-assistant-messages",helper:"Assistant chat bubbles",previewZone:"assistant-message",intensities:ko,targets:[{path:"components.message.assistant.background",kind:"background"},{path:"components.message.assistant.text",kind:"foreground"}]},Ha={roleId:"role-primary-actions",helper:"Send button and primary buttons",intensities:ko,targets:[{path:"components.button.primary.background",kind:"background"},{path:"components.button.primary.foreground",kind:"foreground"},{path:"semantic.colors.interactive.default",kind:"accent"},{path:"semantic.colors.interactive.hover",kind:"accent"}]},Da={roleId:"role-scroll-to-bottom",helper:"Scroll-to-bottom affordances in transcript and event stream",intensities:ko,targets:[{path:"components.scrollToBottom.background",kind:"background"},{path:"components.scrollToBottom.foreground",kind:"foreground"},{path:"components.scrollToBottom.border",kind:"border"}]},Fa={roleId:"role-input",helper:"Message input field",previewZone:"composer",intensities:ko,targets:[{path:"components.input.background",kind:"background"},{path:"components.input.placeholder",kind:"foreground"},{path:"components.input.focus.border",kind:"accent"},{path:"components.input.focus.ring",kind:"accent"}]},Oa={roleId:"role-links-focus",helper:"Links, focus rings, and interactive highlights",intensities:ko,targets:[{path:"semantic.colors.accent",kind:"accent"},{path:"semantic.colors.interactive.focus",kind:"accent"},{path:"semantic.colors.interactive.active",kind:"accent"},{path:"components.markdown.link.foreground",kind:"accent"}]},Na={roleId:"role-borders",helper:"Borders, dividers, and separators",intensities:ko,targets:[{path:"semantic.colors.border",kind:"border"},{path:"semantic.colors.divider",kind:"border"}]},wr=[Ra,Pa,Wa,Ba,Ha,Da,Fa,Oa,Na];function _a(e,t,n){let o={},r=e==="neutral"?"gray":e;for(let s of n.targets){let a=Ef(r,t,s,n.roleId);o[`theme.${s.path}`]=a,o[`darkTheme.${s.path}`]=a}if(n.roleId==="role-primary-actions"){let s=t==="solid"?`palette.colors.${r}.700`:`palette.colors.${r}.200`;o["theme.semantic.colors.interactive.hover"]=s,o["darkTheme.semantic.colors.interactive.hover"]=s}return o}function Ef(e,t,n,o){let r=t==="solid";if(o==="role-header")return Mf(e,r,n);if(o==="role-input")return Lf(e,r,n);switch(n.kind){case"background":return r?`palette.colors.${e}.500`:`palette.colors.${e}.${e==="gray"?"50":"100"}`;case"foreground":return r?`palette.colors.${e==="gray"?"gray":e}.50`:`palette.colors.${e==="gray"?"gray":e}.900`;case"border":return r?`palette.colors.${e}.600`:`palette.colors.${e}.200`;case"accent":return r?`palette.colors.${e}.600`:`palette.colors.${e}.400`}}function Mf(e,t,n){let o=n.path;return o.endsWith(".background")?t?`palette.colors.${e}.500`:`palette.colors.${e}.${e==="gray"?"50":"100"}`:o.endsWith(".border")?t?`palette.colors.${e}.600`:`palette.colors.${e}.200`:o.endsWith(".iconBackground")?t?`palette.colors.${e}.${e==="gray"?"700":"600"}`:`palette.colors.${e}.500`:o.endsWith(".iconForeground")?t?`palette.colors.${e}.50`:`palette.colors.${e}.50`:o.endsWith(".titleForeground")?t?`palette.colors.${e}.50`:`palette.colors.${e}.${e==="gray"?"900":"700"}`:o.endsWith(".subtitleForeground")?t?`palette.colors.${e}.200`:`palette.colors.${e}.500`:o.endsWith(".actionIconForeground")?t?`palette.colors.${e}.200`:`palette.colors.${e}.500`:`palette.colors.${e}.500`}function Lf(e,t,n){let o=n.path;return o.endsWith(".background")?t?`palette.colors.${e}.${e==="gray"?"100":"50"}`:`palette.colors.${e}.50`:o.endsWith(".placeholder")?`palette.colors.${e}.400`:o.endsWith(".border")||o.endsWith(".ring")?t?`palette.colors.${e}.500`:`palette.colors.${e}.400`:`palette.colors.${e}.500`}var If=/^palette\.colors\.(\w+)\.(\d+)$/;function tl(e,t){var i,d;let n=(i=t.targets.find(l=>l.kind==="background"))!=null?i:t.targets[0];if(!n)return null;let r=String((d=e(n.path))!=null?d:"").match(If);if(!r)return null;let s=r[1],a=Ia.includes(s)?s:null;if(!a)return null;for(let l of["solid","soft"]){let m=_a(a,l,t);if(t.targets.every(g=>{var w;return String((w=e(g.path))!=null?w:"")===m[`theme.${g.path}`]}))return{family:a,intensity:l}}return null}var Rf={id:"theme-mode",title:"Runtime Theme",description:"Controls how the shipped widget picks light or dark mode.",collapsed:!1,fields:[{id:"theme-mode",label:"Runtime Theme",description:"Always Light, Always Dark, or follow the visitor system preference",type:"select",path:"colorScheme",defaultValue:"auto",options:[{value:"light",label:"Light"},{value:"dark",label:"Dark"},{value:"auto",label:"Follow System"}]}]},Pf={id:"brand-colors",title:"Brand Colors",description:"Pick your brand colors. A full shade scale is generated automatically for both light and dark themes.",collapsed:!1,fields:[{id:"brand-primary",label:"Primary",description:"Main brand color for buttons, links, and accents",type:"color",path:"theme.palette.colors.primary.500",defaultValue:"#171717"},{id:"brand-secondary",label:"Secondary",description:"Supporting brand color",type:"color",path:"theme.palette.colors.secondary.500",defaultValue:"#7c3aed"},{id:"brand-accent",label:"Accent",description:"Highlight and decorative color",type:"color",path:"theme.palette.colors.accent.500",defaultValue:"#06b6d4"}]},Wf={id:"chat-colors",title:"Chat Colors",description:"Customize the main colors of the chat interface.",collapsed:!0,fields:[{id:"chat-header-bg",label:"Header Background",type:"token-ref",path:"theme.components.header.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"chat-header-icon-bg",label:"Header Icon Background",type:"token-ref",path:"theme.components.header.iconBackground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-header-icon-fg",label:"Header Icon Color",type:"token-ref",path:"theme.components.header.iconForeground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"chat-header-title-fg",label:"Header Title Color",type:"token-ref",path:"theme.components.header.titleForeground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-header-subtitle-fg",label:"Header Subtitle Color",type:"token-ref",path:"theme.components.header.subtitleForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"chat-header-action-icons-fg",label:"Header Button Icons",type:"token-ref",path:"theme.components.header.actionIconForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"chat-msg-user-bg",label:"User Message Background",type:"token-ref",path:"theme.components.message.user.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"chat-msg-user-text",label:"User Message Text",type:"token-ref",path:"theme.components.message.user.text",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"chat-msg-assistant-bg",label:"Assistant Message Background",type:"token-ref",path:"theme.components.message.assistant.background",defaultValue:"semantic.colors.container",tokenRef:{tokenType:"color"}},{id:"chat-msg-assistant-text",label:"Assistant Message Text",type:"token-ref",path:"theme.components.message.assistant.text",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},Bf={id:"typography",title:"Typography",collapsed:!0,fields:[{id:"typo-font-family",label:"Font Family",type:"select",path:"theme.semantic.typography.fontFamily",defaultValue:"palette.typography.fontFamily.sans",options:[{value:"palette.typography.fontFamily.sans",label:"Sans Serif"},{value:"palette.typography.fontFamily.serif",label:"Serif"},{value:"palette.typography.fontFamily.mono",label:"Monospace"}]},{id:"typo-font-size",label:"Base Font Size",type:"select",path:"theme.semantic.typography.fontSize",defaultValue:"palette.typography.fontSize.base",options:[{value:"palette.typography.fontSize.xs",label:"Extra Small (0.75rem)"},{value:"palette.typography.fontSize.sm",label:"Small (0.875rem)"},{value:"palette.typography.fontSize.base",label:"Base (1rem)"},{value:"palette.typography.fontSize.lg",label:"Large (1.125rem)"},{value:"palette.typography.fontSize.xl",label:"Extra Large (1.25rem)"}]},{id:"typo-font-weight",label:"Font Weight",type:"select",path:"theme.semantic.typography.fontWeight",defaultValue:"palette.typography.fontWeight.normal",options:[{value:"palette.typography.fontWeight.normal",label:"Normal (400)"},{value:"palette.typography.fontWeight.medium",label:"Medium (500)"},{value:"palette.typography.fontWeight.semibold",label:"Semibold (600)"},{value:"palette.typography.fontWeight.bold",label:"Bold (700)"}]},{id:"typo-line-height",label:"Line Height",type:"select",path:"theme.semantic.typography.lineHeight",defaultValue:"palette.typography.lineHeight.normal",options:[{value:"palette.typography.lineHeight.tight",label:"Tight (1.25)"},{value:"palette.typography.lineHeight.normal",label:"Normal (1.5)"},{value:"palette.typography.lineHeight.relaxed",label:"Relaxed (1.625)"}]}]},Hf={id:"launcher-style",title:"Launcher",description:"Control launcher appearance.",collapsed:!0,fields:[{id:"style-launcher-size",label:"Launcher Size",type:"slider",path:"theme.components.launcher.size",defaultValue:"60px",slider:{min:32,max:80,step:2}},{id:"style-launcher-shape",label:"Launcher Shape",type:"select",path:"theme.components.launcher.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Rounded Square"},{value:"palette.radius.lg",label:"Rounded"},{value:"palette.radius.xl",label:"Very Rounded"},{value:"palette.radius.full",label:"Circle"}]},{id:"style-launcher-shadow",label:"Launcher Shadow",type:"select",path:"theme.components.launcher.shadow",defaultValue:"palette.shadows.lg",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},Df={id:"shape",title:"Shape",description:"Control the corner roundness across the widget.",collapsed:!0,fields:[{id:"radius-sm",label:"Small",type:"slider",path:"theme.palette.radius.sm",defaultValue:"0.125rem",slider:{min:0,max:16,step:1}},{id:"radius-md",label:"Medium",type:"slider",path:"theme.palette.radius.md",defaultValue:"0.375rem",slider:{min:0,max:24,step:1}},{id:"radius-lg",label:"Large",type:"slider",path:"theme.palette.radius.lg",defaultValue:"0.5rem",slider:{min:0,max:32,step:1}},{id:"radius-xl",label:"Extra Large",type:"slider",path:"theme.palette.radius.xl",defaultValue:"0.75rem",slider:{min:0,max:48,step:1}},{id:"radius-full",label:"Full",type:"slider",path:"theme.palette.radius.full",defaultValue:"9999px",slider:{min:0,max:100,step:1,isRadiusFull:!0}}],presets:[{id:"radius-default",label:"Default",values:{"theme.palette.radius.sm":"0.125rem","theme.palette.radius.md":"0.375rem","theme.palette.radius.lg":"0.5rem","theme.palette.radius.xl":"0.75rem","theme.palette.radius.full":"9999px"}},{id:"radius-sharp",label:"Sharp",values:{"theme.palette.radius.sm":"1px","theme.palette.radius.md":"2px","theme.palette.radius.lg":"3px","theme.palette.radius.xl":"4px","theme.palette.radius.full":"4px"}},{id:"radius-rounded",label:"Rounded",values:{"theme.palette.radius.sm":"0.5rem","theme.palette.radius.md":"0.75rem","theme.palette.radius.lg":"1rem","theme.palette.radius.xl":"1.5rem","theme.palette.radius.full":"9999px"}}]},Ff={id:"shadows",title:"Shadows",collapsed:!0,fields:[{id:"shadow-sm",label:"Small",type:"text",path:"theme.palette.shadows.sm",defaultValue:"0 1px 2px 0 rgb(0 0 0 / 0.05)"},{id:"shadow-md",label:"Medium",type:"text",path:"theme.palette.shadows.md",defaultValue:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)"},{id:"shadow-lg",label:"Large",type:"text",path:"theme.palette.shadows.lg",defaultValue:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)"},{id:"shadow-xl",label:"Extra Large",type:"text",path:"theme.palette.shadows.xl",defaultValue:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)"}]},Of={id:"widget-style",title:"Widget Surface",description:"Adjust the main panel and message bubble treatment.",collapsed:!0,fields:[{id:"style-panel-radius",label:"Panel Corner Radius",type:"select",path:"theme.components.panel.borderRadius",defaultValue:"palette.radius.xl",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"style-panel-shadow",label:"Panel Shadow",type:"select",path:"theme.components.panel.shadow",defaultValue:"palette.shadows.xl",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]},{id:"style-msg-user-radius",label:"User Message Radius",type:"select",path:"theme.components.message.user.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"style-msg-assistant-radius",label:"Assistant Message Radius",type:"select",path:"theme.components.message.assistant.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},zr=[Pf,Wf,Hf,Bf,Rf,Df,Ff,Of];function iu(){return{id:"brand-palette",title:"Brand Palette",description:"Define your color palette. Edit the base color (500) to auto-generate the full scale.",collapsed:!1,fields:el.map(t=>({id:`palette-${t}`,label:`${t.charAt(0).toUpperCase()+t.slice(1)}`,description:`${t} color palette (edit shade 500, auto-generate scale)`,type:"color-scale",path:`theme.palette.colors.${t}`,colorScale:{colorFamily:t}}))}}var lu={id:"semantic-colors",title:"Semantic Colors",description:"Map intents to palette colors.",collapsed:!0,fields:[{id:"sem-primary",label:"Primary",description:"Main brand/action color",type:"token-ref",path:"theme.semantic.colors.primary",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sem-secondary",label:"Secondary",description:"Secondary actions",type:"token-ref",path:"theme.semantic.colors.secondary",defaultValue:"palette.colors.gray.500",tokenRef:{tokenType:"color"}},{id:"sem-accent",label:"Accent",description:"Accent/highlight color",type:"token-ref",path:"theme.semantic.colors.accent",defaultValue:"palette.colors.primary.600",tokenRef:{tokenType:"color"}},{id:"sem-surface",label:"Surface",description:"Primary surface background",type:"token-ref",path:"theme.semantic.colors.surface",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-background",label:"Background",description:"Page/widget background",type:"token-ref",path:"theme.semantic.colors.background",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-container",label:"Container",description:"Container/card background",type:"token-ref",path:"theme.semantic.colors.container",defaultValue:"palette.colors.gray.100",tokenRef:{tokenType:"color"}},{id:"sem-text",label:"Text",description:"Primary text color",type:"token-ref",path:"theme.semantic.colors.text",defaultValue:"palette.colors.gray.900",tokenRef:{tokenType:"color"}},{id:"sem-text-muted",label:"Text Muted",description:"Secondary/muted text",type:"token-ref",path:"theme.semantic.colors.textMuted",defaultValue:"palette.colors.gray.500",tokenRef:{tokenType:"color"}},{id:"sem-text-inverse",label:"Text Inverse",description:"Text on dark backgrounds",type:"token-ref",path:"theme.semantic.colors.textInverse",defaultValue:"palette.colors.gray.50",tokenRef:{tokenType:"color"}},{id:"sem-border",label:"Border",description:"Default border color",type:"token-ref",path:"theme.semantic.colors.border",defaultValue:"palette.colors.gray.200",tokenRef:{tokenType:"color"}},{id:"sem-divider",label:"Divider",description:"Divider/separator color",type:"token-ref",path:"theme.semantic.colors.divider",defaultValue:"palette.colors.gray.200",tokenRef:{tokenType:"color"}},{id:"sem-interactive-default",label:"Interactive Default",type:"token-ref",path:"theme.semantic.colors.interactive.default",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sem-interactive-hover",label:"Interactive Hover",type:"token-ref",path:"theme.semantic.colors.interactive.hover",defaultValue:"palette.colors.primary.600",tokenRef:{tokenType:"color"}},{id:"sem-interactive-focus",label:"Interactive Focus",type:"token-ref",path:"theme.semantic.colors.interactive.focus",defaultValue:"palette.colors.primary.700",tokenRef:{tokenType:"color"}},{id:"sem-interactive-active",label:"Interactive Active",type:"token-ref",path:"theme.semantic.colors.interactive.active",defaultValue:"palette.colors.primary.800",tokenRef:{tokenType:"color"}},{id:"sem-interactive-disabled",label:"Interactive Disabled",type:"token-ref",path:"theme.semantic.colors.interactive.disabled",defaultValue:"palette.colors.gray.300",tokenRef:{tokenType:"color"}},{id:"sem-feedback-success",label:"Success",type:"token-ref",path:"theme.semantic.colors.feedback.success",defaultValue:"palette.colors.success.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-warning",label:"Warning",type:"token-ref",path:"theme.semantic.colors.feedback.warning",defaultValue:"palette.colors.warning.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-error",label:"Error",type:"token-ref",path:"theme.semantic.colors.feedback.error",defaultValue:"palette.colors.error.500",tokenRef:{tokenType:"color"}},{id:"sem-feedback-info",label:"Info",type:"token-ref",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}}]},Nf=iu(),_f=lu,Vf=[iu(),lu],$f={id:"comp-panel",title:"Panel",collapsed:!1,fields:[{id:"panel-width",label:"Width",type:"text",path:"theme.components.panel.width",defaultValue:io},{id:"panel-max-width",label:"Max Width",type:"text",path:"theme.components.panel.maxWidth",defaultValue:Ea},{id:"panel-height",label:"Height",type:"text",path:"theme.components.panel.height",defaultValue:"600px"},{id:"panel-max-height",label:"Max Height",type:"text",path:"theme.components.panel.maxHeight",defaultValue:"calc(100vh - 80px)"},{id:"panel-border-radius",label:"Border Radius",type:"select",path:"theme.components.panel.borderRadius",defaultValue:"palette.radius.xl",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"panel-shadow",label:"Shadow",type:"select",path:"theme.components.panel.shadow",defaultValue:"palette.shadows.xl",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},Uf={id:"comp-launcher",title:"Launcher",collapsed:!0,fields:[{id:"launcher-size",label:"Size",type:"slider",path:"theme.components.launcher.size",defaultValue:"60px",slider:{min:32,max:80,step:2}},{id:"launcher-icon-size",label:"Icon Size",type:"slider",path:"theme.components.launcher.iconSize",defaultValue:"28px",slider:{min:16,max:48,step:2}},{id:"launcher-border-radius",label:"Border Radius",type:"select",path:"theme.components.launcher.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"},{value:"palette.radius.full",label:"Full (Circle)"}]},{id:"launcher-shadow",label:"Shadow",type:"select",path:"theme.components.launcher.shadow",defaultValue:"palette.shadows.lg",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]}]},zf={id:"comp-message-shape",title:"Message Shape",collapsed:!0,fields:[{id:"msg-user-radius",label:"User Bubble Radius",type:"select",path:"theme.components.message.user.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]},{id:"msg-assistant-radius",label:"Assistant Bubble Radius",type:"select",path:"theme.components.message.assistant.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},qf={id:"comp-input-shape",title:"Input Shape",collapsed:!0,fields:[{id:"input-radius",label:"Border Radius",type:"select",path:"theme.components.input.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.none",label:"None"},{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"}]}]},jf={id:"comp-button-shape",title:"Button Shape",collapsed:!0,fields:[{id:"btn-primary-radius",label:"Primary Radius",type:"select",path:"theme.components.button.primary.borderRadius",defaultValue:"palette.radius.lg",options:[{value:"palette.radius.sm",label:"Small"},{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.full",label:"Full"}]}]},Kf={id:"comp-header-colors",title:"Header Colors",collapsed:!0,fields:[{id:"header-bg",label:"Background",type:"token-ref",path:"theme.components.header.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"header-icon-bg",label:"Icon background",type:"token-ref",path:"theme.components.header.iconBackground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"header-icon-fg",label:"Icon color",type:"token-ref",path:"theme.components.header.iconForeground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"header-title-fg",label:"Title color",type:"token-ref",path:"theme.components.header.titleForeground",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"header-subtitle-fg",label:"Subtitle color",type:"token-ref",path:"theme.components.header.subtitleForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"header-action-icons-fg",label:"Clear / close icons",type:"token-ref",path:"theme.components.header.actionIconForeground",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"header-border",label:"Border",type:"token-ref",path:"theme.components.header.border",defaultValue:"semantic.colors.border",tokenRef:{tokenType:"color"}}]},Gf={id:"comp-message-colors",title:"Message Colors",collapsed:!0,fields:[{id:"msg-user-bg",label:"User Bubble Background",type:"token-ref",path:"theme.components.message.user.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"msg-user-text",label:"User Bubble Text",type:"token-ref",path:"theme.components.message.user.text",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"msg-assistant-bg",label:"Assistant Bubble Background",type:"token-ref",path:"theme.components.message.assistant.background",defaultValue:"semantic.colors.container",tokenRef:{tokenType:"color"}},{id:"msg-assistant-text",label:"Assistant Bubble Text",type:"token-ref",path:"theme.components.message.assistant.text",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},Yf={id:"comp-input-colors",title:"Input Colors",collapsed:!0,fields:[{id:"input-bg",label:"Background",type:"token-ref",path:"theme.components.input.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"input-placeholder",label:"Placeholder Color",type:"token-ref",path:"theme.components.input.placeholder",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"input-focus-border",label:"Focus Border",type:"token-ref",path:"theme.components.input.focus.border",defaultValue:"semantic.colors.interactive.focus",tokenRef:{tokenType:"color"}},{id:"input-focus-ring",label:"Focus Ring",type:"token-ref",path:"theme.components.input.focus.ring",defaultValue:"semantic.colors.interactive.focus",tokenRef:{tokenType:"color"}}]},Xf={id:"comp-button-colors",title:"Button Colors",collapsed:!0,fields:[{id:"btn-primary-bg",label:"Primary Background",type:"token-ref",path:"theme.components.button.primary.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"btn-primary-fg",label:"Primary Foreground",type:"token-ref",path:"theme.components.button.primary.foreground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"btn-secondary-bg",label:"Secondary Background",type:"token-ref",path:"theme.components.button.secondary.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"btn-secondary-fg",label:"Secondary Foreground",type:"token-ref",path:"theme.components.button.secondary.foreground",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}},{id:"btn-ghost-bg",label:"Ghost Background",type:"color",path:"theme.components.button.ghost.background",defaultValue:"transparent"},{id:"btn-ghost-fg",label:"Ghost Foreground",type:"token-ref",path:"theme.components.button.ghost.foreground",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},Qf={id:"scroll-to-bottom-style",title:"Scroll To Bottom",description:"Style the floating jump-to-latest affordance.",collapsed:!0,fields:[{id:"scroll-bottom-bg",label:"Background",type:"token-ref",path:"theme.components.scrollToBottom.background",defaultValue:"components.button.primary.background",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-fg",label:"Foreground",type:"token-ref",path:"theme.components.scrollToBottom.foreground",defaultValue:"components.button.primary.foreground",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-border",label:"Border",type:"token-ref",path:"theme.components.scrollToBottom.border",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"scroll-bottom-size",label:"Size",type:"text",path:"theme.components.scrollToBottom.size",defaultValue:"40px"},{id:"scroll-bottom-radius",label:"Border Radius",type:"select",path:"theme.components.scrollToBottom.borderRadius",defaultValue:"palette.radius.full",options:[{value:"palette.radius.md",label:"Medium"},{value:"palette.radius.lg",label:"Large"},{value:"palette.radius.xl",label:"Extra Large"},{value:"palette.radius.full",label:"Full"}]},{id:"scroll-bottom-shadow",label:"Shadow",type:"select",path:"theme.components.scrollToBottom.shadow",defaultValue:"palette.shadows.sm",options:[{value:"palette.shadows.none",label:"None"},{value:"palette.shadows.sm",label:"Small"},{value:"palette.shadows.md",label:"Medium"},{value:"palette.shadows.lg",label:"Large"},{value:"palette.shadows.xl",label:"Extra Large"}]},{id:"scroll-bottom-padding",label:"Padding",type:"text",path:"theme.components.scrollToBottom.padding",defaultValue:"0.5rem 0.875rem"},{id:"scroll-bottom-gap",label:"Gap",type:"text",path:"theme.components.scrollToBottom.gap",defaultValue:"0.5rem"},{id:"scroll-bottom-font-size",label:"Font Size",type:"text",path:"theme.components.scrollToBottom.fontSize",defaultValue:"0.875rem"},{id:"scroll-bottom-icon-size",label:"Icon Size",type:"text",path:"theme.components.scrollToBottom.iconSize",defaultValue:"14px"}]},cu=[$f,Uf,zf,qf,jf],du=[Kf,Gf,Yf,Xf,Qf],pu=[...cu,...du],nl=1024*1024,Jf=["What can you help me with?","Tell me about your features","How does this work?"],Ms={images:["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],"images-pdf":["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf"],"images-text-pdf":["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf","text/plain","text/markdown","text/csv","application/json"],all:["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"]};function Zf(e){return Number(e)*nl}function eg(e){let t=Number(e);return Number.isFinite(t)?t>1024?String(Math.round(t/nl)):String(t):"10"}function tg(e){var t;return(t=Ms[String(e)])!=null?t:Ms.images}function ng(e){let t=Array.isArray(e)?e:Ms.images,n=[...new Set(t)].sort();for(let[o,r]of Object.entries(Ms)){let s=[...r].sort();if(n.length===s.length&&n.every((a,i)=>a===s[i]))return o}return n.some(o=>o.startsWith("application/vnd")||o==="application/msword")?"all":n.some(o=>o==="text/plain"||o==="text/markdown"||o==="text/csv")?"images-text-pdf":n.includes("application/pdf")?"images-pdf":"images"}var og={id:"copy",title:"Content & Copy",collapsed:!1,fields:[{id:"copy-show-welcome-card",label:"Show Welcome Card",type:"toggle",path:"copy.showWelcomeCard",defaultValue:!0},{id:"copy-welcome-title",label:"Welcome Title",type:"text",path:"copy.welcomeTitle",defaultValue:"Hello \u{1F44B}"},{id:"copy-welcome-subtitle",label:"Welcome Subtitle",type:"text",path:"copy.welcomeSubtitle",defaultValue:"Ask anything about your account or products."},{id:"copy-placeholder",label:"Input Placeholder",type:"text",path:"copy.inputPlaceholder",defaultValue:"Type your message\u2026"},{id:"copy-send-label",label:"Send Button Label",type:"text",path:"copy.sendButtonLabel",defaultValue:"Send"}]},rg={id:"suggestions",title:"Suggestion Chips",description:"Configure chip content and styling.",collapsed:!0,fields:[{id:"suggestions-list",label:"Suggestions",description:"Add, edit, and remove chips directly.",type:"chip-list",path:"suggestionChips",defaultValue:Jf}]},sg={id:"general-layout",title:"Layout Basics",collapsed:!0,fields:[{id:"layout-show-header",label:"Show Header",type:"toggle",path:"layout.showHeader",defaultValue:!0},{id:"layout-show-footer",label:"Show Footer",type:"toggle",path:"layout.showFooter",defaultValue:!0},{id:"layout-content-max-width",label:"Content Max Width",description:"Max width for messages + composer",type:"text",path:"layout.contentMaxWidth",defaultValue:""}]},ag={id:"header-layout",title:"Header",collapsed:!0,fields:[{id:"layout-header",label:"Header Layout",type:"select",path:"layout.header.layout",defaultValue:"default",options:[{value:"default",label:"Default"},{value:"minimal",label:"Minimal"}]},{id:"layout-show-icon",label:"Show Header Icon",type:"toggle",path:"layout.header.showIcon",defaultValue:!0},{id:"layout-show-title",label:"Show Header Title",type:"toggle",path:"layout.header.showTitle",defaultValue:!0},{id:"layout-show-subtitle",label:"Show Header Subtitle",type:"toggle",path:"layout.header.showSubtitle",defaultValue:!0},{id:"layout-show-close",label:"Show Close Button",type:"toggle",path:"layout.header.showCloseButton",defaultValue:!0},{id:"layout-show-clear",label:"Show Clear Chat",type:"toggle",path:"layout.header.showClearChat",defaultValue:!0}]},ig={id:"messages-layout",title:"Messages",collapsed:!0,fields:[{id:"layout-messages",label:"Messages Layout",type:"select",path:"layout.messages.layout",defaultValue:"bubble",options:[{value:"bubble",label:"Bubble"},{value:"flat",label:"Flat"},{value:"minimal",label:"Minimal"}]},{id:"layout-group",label:"Group Consecutive",type:"toggle",path:"layout.messages.groupConsecutive",defaultValue:!1},{id:"layout-avatar-show",label:"Show Avatars",type:"toggle",path:"layout.messages.avatar.show",defaultValue:!1},{id:"layout-avatar-pos",label:"Avatar Position",type:"select",path:"layout.messages.avatar.position",defaultValue:"left",options:[{value:"left",label:"Left"},{value:"right",label:"Right"}]},{id:"layout-avatar-user",label:"User Avatar URL",type:"text",path:"layout.messages.avatar.userAvatar",defaultValue:""},{id:"layout-avatar-assistant",label:"Assistant Avatar URL",type:"text",path:"layout.messages.avatar.assistantAvatar",defaultValue:""},{id:"layout-timestamp-show",label:"Show Timestamps",type:"toggle",path:"layout.messages.timestamp.show",defaultValue:!1},{id:"layout-timestamp-pos",label:"Timestamp Position",type:"select",path:"layout.messages.timestamp.position",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"below",label:"Below"}]}]},lg={id:"message-actions",title:"Message Actions",collapsed:!0,fields:[{id:"msg-actions-enabled",label:"Enabled",type:"toggle",path:"messageActions.enabled",defaultValue:!0},{id:"msg-actions-copy",label:"Show Copy",type:"toggle",path:"messageActions.showCopy",defaultValue:!0},{id:"msg-actions-upvote",label:"Show Upvote",type:"toggle",path:"messageActions.showUpvote",defaultValue:!0},{id:"msg-actions-downvote",label:"Show Downvote",type:"toggle",path:"messageActions.showDownvote",defaultValue:!0},{id:"msg-actions-visibility",label:"Visibility",type:"select",path:"messageActions.visibility",defaultValue:"hover",options:[{value:"hover",label:"On Hover"},{value:"always",label:"Always Visible"}]},{id:"msg-actions-align",label:"Alignment",type:"select",path:"messageActions.align",defaultValue:"right",options:[{value:"left",label:"Left"},{value:"right",label:"Right"}]},{id:"msg-actions-layout",label:"Layout",type:"select",path:"messageActions.layout",defaultValue:"pill-inside",options:[{value:"pill-inside",label:"Pill"},{value:"row-inside",label:"Row"}]}]},cg={id:"launcher-basics",title:"Launcher",collapsed:!0,fields:[{id:"launch-enabled",label:"Enabled",type:"toggle",path:"launcher.enabled",defaultValue:!0},{id:"launch-mount-mode",label:"Mount Mode",type:"select",path:"launcher.mountMode",defaultValue:"floating",options:[{value:"floating",label:"Floating"},{value:"docked",label:"Docked"}]},{id:"launch-position",label:"Position",type:"select",path:"launcher.position",defaultValue:"bottom-right",options:[{value:"bottom-right",label:"Bottom Right"},{value:"bottom-left",label:"Bottom Left"},{value:"top-right",label:"Top Right"},{value:"top-left",label:"Top Left"}]},{id:"launch-width",label:"Width",type:"text",path:"launcher.width",defaultValue:io},{id:"launch-auto-expand",label:"Auto Expand",type:"toggle",path:"launcher.autoExpand",defaultValue:!1},{id:"launch-title",label:"Title",type:"text",path:"launcher.title",defaultValue:"Chat Assistant"},{id:"launch-subtitle",label:"Subtitle",type:"text",path:"launcher.subtitle",defaultValue:"Here to help you get answers fast"}]},dg={id:"launcher-advanced",title:"Launcher Advanced",collapsed:!0,fields:[{id:"launch-dock-side",label:"Dock Side",type:"select",path:"launcher.dock.side",defaultValue:"right",options:[{value:"right",label:"Right"},{value:"left",label:"Left"}]},{id:"launch-dock-width",label:"Dock Width",type:"text",path:"launcher.dock.width",defaultValue:"420px"},{id:"launch-dock-animate",label:"Dock Animate",type:"toggle",path:"launcher.dock.animate",defaultValue:!0},{id:"launch-dock-reveal",label:"Dock Reveal",type:"select",path:"launcher.dock.reveal",defaultValue:"resize",options:[{value:"resize",label:"Resize"},{value:"overlay",label:"Overlay"},{value:"push",label:"Push"},{value:"emerge",label:"Emerge"}]},{id:"launch-text-hidden",label:"Hide Text",type:"toggle",path:"launcher.textHidden",defaultValue:!1},{id:"launch-icon-text",label:"Agent Icon Text",type:"text",path:"launcher.agentIconText",defaultValue:"\u{1F4AC}"},{id:"launch-icon-name",label:"Agent Icon Name (Lucide)",type:"text",path:"launcher.agentIconName",defaultValue:"bot"},{id:"launch-icon-hidden",label:"Hide Agent Icon",type:"toggle",path:"launcher.agentIconHidden",defaultValue:!1},{id:"launch-icon-size",label:"Agent Icon Size",type:"slider",path:"launcher.agentIconSize",defaultValue:"40px",slider:{min:16,max:72,step:2}},{id:"launch-icon-url",label:"Icon Image URL",description:"Custom image URL (overrides emoji/lucide)",type:"text",path:"launcher.iconUrl",defaultValue:""},{id:"launch-header-icon-name",label:"Header Icon Name (Lucide)",type:"text",path:"launcher.headerIconName",defaultValue:"bot"},{id:"launch-header-icon-size",label:"Header Icon Size",type:"slider",path:"launcher.headerIconSize",defaultValue:"48px",slider:{min:24,max:80,step:2}},{id:"launch-header-icon-hidden",label:"Hide Header Icon",type:"toggle",path:"launcher.headerIconHidden",defaultValue:!1},{id:"launch-full-height",label:"Full Height",type:"toggle",path:"launcher.fullHeight",defaultValue:!1},{id:"launch-sidebar",label:"Sidebar Mode",type:"toggle",path:"launcher.sidebarMode",defaultValue:!1},{id:"launch-sidebar-width",label:"Sidebar Width",type:"text",path:"launcher.sidebarWidth",defaultValue:"420px"},{id:"launch-mobile-fullscreen",label:"Mobile Fullscreen",description:"Fullscreen on mobile devices",type:"toggle",path:"launcher.mobileFullscreen",defaultValue:!0},{id:"launch-mobile-breakpoint",label:"Mobile Breakpoint (px)",type:"text",path:"launcher.mobileBreakpoint",defaultValue:640,formatValue:e=>String(e!=null?e:640),parseValue:e=>Number(e)},{id:"launch-height-offset",label:"Height Offset (px)",type:"text",path:"launcher.heightOffset",defaultValue:0,formatValue:e=>String(e!=null?e:0),parseValue:e=>Number(e)},{id:"launch-collapsed-max-width",label:"Collapsed Max Width",description:"Max width of launcher pill when closed",type:"text",path:"launcher.collapsedMaxWidth",defaultValue:""},{id:"launch-cta-text",label:"CTA Icon Text",type:"text",path:"launcher.callToActionIconText",defaultValue:"\u2197"},{id:"launch-cta-name",label:"CTA Icon Name",type:"text",path:"launcher.callToActionIconName",defaultValue:""},{id:"launch-cta-hidden",label:"Hide CTA Icon",type:"toggle",path:"launcher.callToActionIconHidden",defaultValue:!1},{id:"launch-cta-size",label:"CTA Icon Size",type:"slider",path:"launcher.callToActionIconSize",defaultValue:"32px",slider:{min:16,max:64,step:2}},{id:"launch-cta-padding",label:"CTA Icon Padding",type:"slider",path:"launcher.callToActionIconPadding",defaultValue:"5px",slider:{min:0,max:24,step:1}},{id:"launch-cta-bg",label:"CTA Icon Background",type:"color",path:"launcher.callToActionIconBackgroundColor",defaultValue:""}]},pg={id:"send-button",title:"Send Button",collapsed:!0,fields:[{id:"send-use-icon",label:"Use Icon",type:"toggle",path:"sendButton.useIcon",defaultValue:!1},{id:"send-icon-text",label:"Icon Text",type:"text",path:"sendButton.iconText",defaultValue:"\u2191"},{id:"send-icon-name",label:"Icon Name (Lucide)",type:"text",path:"sendButton.iconName",defaultValue:""},{id:"send-size",label:"Size",type:"slider",path:"sendButton.size",defaultValue:"40px",slider:{min:24,max:64,step:2}},{id:"send-border-width",label:"Border Width",type:"slider",path:"sendButton.borderWidth",defaultValue:"0px",slider:{min:0,max:10,step:1}},{id:"send-padding-x",label:"Padding X",type:"slider",path:"sendButton.paddingX",defaultValue:"10px",slider:{min:0,max:32,step:1}},{id:"send-padding-y",label:"Padding Y",type:"slider",path:"sendButton.paddingY",defaultValue:"6px",slider:{min:0,max:32,step:1}},{id:"send-show-tooltip",label:"Show Tooltip",type:"toggle",path:"sendButton.showTooltip",defaultValue:!1},{id:"send-tooltip-text",label:"Tooltip Text",type:"text",path:"sendButton.tooltipText",defaultValue:"Send message"}]},ug={id:"close-button",title:"Close Button",collapsed:!0,fields:[{id:"close-size",label:"Size",type:"slider",path:"launcher.closeButtonSize",defaultValue:"32px",slider:{min:16,max:64,step:1}},{id:"close-placement",label:"Placement",type:"select",path:"launcher.closeButtonPlacement",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"top-right",label:"Top Right"}]},{id:"close-border-width",label:"Border Width",type:"slider",path:"launcher.closeButtonBorderWidth",defaultValue:"0px",slider:{min:0,max:8,step:1}},{id:"close-border-radius",label:"Border Radius",type:"slider",path:"launcher.closeButtonBorderRadius",defaultValue:"50%",slider:{min:0,max:100,step:1,isRadiusFull:!0}},{id:"close-icon-name",label:"Icon Name",type:"text",path:"launcher.closeButtonIconName",defaultValue:"x"},{id:"close-icon-text",label:"Icon Text",type:"text",path:"launcher.closeButtonIconText",defaultValue:"\xD7"},{id:"close-show-tooltip",label:"Show Tooltip",type:"toggle",path:"launcher.closeButtonShowTooltip",defaultValue:!0},{id:"close-tooltip-text",label:"Tooltip Text",type:"text",path:"launcher.closeButtonTooltipText",defaultValue:"Close chat"}]},mg={id:"clear-chat",title:"Clear Chat Button",collapsed:!0,fields:[{id:"clear-enabled",label:"Enabled",type:"toggle",path:"launcher.clearChat.enabled",defaultValue:!0},{id:"clear-placement",label:"Placement",type:"select",path:"launcher.clearChat.placement",defaultValue:"inline",options:[{value:"inline",label:"Inline"},{value:"top-right",label:"Top Right"}]},{id:"clear-icon-name",label:"Icon Name",type:"text",path:"launcher.clearChat.iconName",defaultValue:"refresh-cw"},{id:"clear-size",label:"Size",type:"slider",path:"launcher.clearChat.size",defaultValue:"32px",slider:{min:16,max:64,step:1}},{id:"clear-show-tooltip",label:"Show Tooltip",type:"toggle",path:"launcher.clearChat.showTooltip",defaultValue:!0},{id:"clear-tooltip-text",label:"Tooltip Text",type:"text",path:"launcher.clearChat.tooltipText",defaultValue:"Clear chat"}]},fg={id:"status-indicator",title:"Status Indicator",collapsed:!0,fields:[{id:"status-visible",label:"Visible",type:"toggle",path:"statusIndicator.visible",defaultValue:!0},{id:"status-align",label:"Alignment",type:"select",path:"statusIndicator.align",defaultValue:"right",options:[{value:"left",label:"Left"},{value:"center",label:"Center"},{value:"right",label:"Right"}]},{id:"status-idle-text",label:"Idle Text",type:"text",path:"statusIndicator.idleText",defaultValue:"Online"},{id:"status-connecting-text",label:"Connecting Text",type:"text",path:"statusIndicator.connectingText",defaultValue:"Connecting\u2026"},{id:"status-connected-text",label:"Connected Text",type:"text",path:"statusIndicator.connectedText",defaultValue:"Streaming\u2026"},{id:"status-error-text",label:"Error Text",type:"text",path:"statusIndicator.errorText",defaultValue:"Offline"}]},gg={id:"features",title:"Features",collapsed:!0,fields:[{id:"feat-voice",label:"Voice Recognition",description:"Enable voice input",type:"toggle",path:"voiceRecognition.enabled",defaultValue:!1},{id:"feat-auto-focus",label:"Auto Focus Input",description:"Focus input after panel opens",type:"toggle",path:"autoFocusInput",defaultValue:!1},{id:"feat-scroll-bottom-enabled",label:"Scroll To Bottom",description:"Show a jump-to-latest affordance when the user scrolls away from new content",type:"toggle",path:"features.scrollToBottom.enabled",defaultValue:!0},{id:"feat-scroll-bottom-icon",label:"Scroll To Bottom Icon",type:"text",path:"features.scrollToBottom.iconName",defaultValue:"arrow-down"},{id:"feat-scroll-bottom-label",label:"Scroll To Bottom Label",description:"Leave empty for icon-only mode",type:"text",path:"features.scrollToBottom.label",defaultValue:""}]},hg={id:"stream-animation",title:"Stream Animation",description:"Control how assistant text appears while streaming.",collapsed:!0,fields:[{id:"stream-anim-type",label:"Animation",description:"Reveal effect applied to each assistant reply as it streams.",type:"select",path:"features.streamAnimation.type",defaultValue:"none",options:[{value:"none",label:"None"},{value:"typewriter",label:"Typewriter"},{value:"word-fade",label:"Word fade"},{value:"letter-rise",label:"Letter rise"},{value:"glyph-cycle",label:"Glyph cycle"},{value:"wipe",label:"Wipe"},{value:"pop-bubble",label:"Pop bubble"}]},{id:"stream-anim-placeholder",label:"Pre-first-token Placeholder",description:"What to show before the first token arrives.",type:"select",path:"features.streamAnimation.placeholder",defaultValue:"none",options:[{value:"none",label:"Typing indicator (default)"},{value:"skeleton",label:"Skeleton shimmer"}]},{id:"stream-anim-buffer",label:"Content Buffering",description:"Trim in-progress units so only complete words/lines reveal.",type:"select",path:"features.streamAnimation.buffer",defaultValue:"none",options:[{value:"none",label:"None \u2014 stream every character"},{value:"word",label:"Word \u2014 hold until whitespace"},{value:"line",label:"Line \u2014 hold until newline"}]},{id:"stream-anim-speed",label:"Per-unit Duration (ms)",description:"Animation length for each character or word.",type:"select",path:"features.streamAnimation.speed",defaultValue:120,options:[{value:"40",label:"40ms \u2014 snappy"},{value:"80",label:"80ms"},{value:"120",label:"120ms (default)"},{value:"200",label:"200ms"},{value:"320",label:"320ms"},{value:"480",label:"480ms \u2014 slow"}],formatValue:e=>String(e!=null?e:120),parseValue:e=>Number(e)},{id:"stream-anim-duration",label:"Container Duration (ms)",description:"Length of container-level effects (pop-bubble, custom plugins).",type:"select",path:"features.streamAnimation.duration",defaultValue:1800,options:[{value:"600",label:"600ms"},{value:"1200",label:"1200ms"},{value:"1800",label:"1800ms (default)"},{value:"2400",label:"2400ms"},{value:"3600",label:"3600ms \u2014 slow"}],formatValue:e=>String(e!=null?e:1800),parseValue:e=>Number(e)}]},bg={id:"attachments-config",title:"Attachments",collapsed:!0,fields:[{id:"attach-enabled",label:"Enabled",type:"toggle",path:"attachments.enabled",defaultValue:!1},{id:"attach-max-files",label:"Max Files",type:"select",path:"attachments.maxFiles",defaultValue:4,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"4",label:"4"},{value:"6",label:"6"},{value:"8",label:"8"},{value:"10",label:"10"}],formatValue:e=>String(e!=null?e:4),parseValue:e=>Number(e)},{id:"attach-max-size",label:"Max File Size (MB)",type:"select",path:"attachments.maxFileSize",defaultValue:10*nl,options:[{value:"1",label:"1 MB"},{value:"5",label:"5 MB"},{value:"10",label:"10 MB"},{value:"25",label:"25 MB"},{value:"50",label:"50 MB"}],formatValue:eg,parseValue:Zf},{id:"attach-types",label:"Allowed File Types",type:"select",path:"attachments.allowedTypes",defaultValue:Ms.images,options:[{value:"images",label:"Images only"},{value:"images-pdf",label:"Images + PDF"},{value:"images-text-pdf",label:"Images + text + PDF"},{value:"all",label:"All supported types"}],formatValue:ng,parseValue:tg}]},yg={id:"artifacts-config",title:"Artifacts",collapsed:!0,fields:[{id:"art-enabled",label:"Enabled",description:"Show artifact sidebar for documents and components",type:"toggle",path:"features.artifacts.enabled",defaultValue:!1},{id:"art-appearance",label:"Pane Appearance",type:"select",path:"features.artifacts.layout.paneAppearance",defaultValue:"panel",options:[{value:"panel",label:"Panel (bordered)"},{value:"seamless",label:"Seamless"}]}]},vg={id:"artifacts-customization",title:"Artifact Customization",collapsed:!0,fields:[{id:"art-toolbar",label:"Toolbar Preset",type:"select",path:"features.artifacts.layout.toolbarPreset",defaultValue:"default",options:[{value:"default",label:"Default"},{value:"document",label:"Document"}]},{id:"art-pane-width",label:"Pane Width",description:"CSS width (e.g. 40%, 28rem)",type:"text",path:"features.artifacts.layout.paneWidth",defaultValue:"40%"},{id:"art-pane-max-width",label:"Pane Max Width",type:"text",path:"features.artifacts.layout.paneMaxWidth",defaultValue:"28rem"},{id:"art-split-gap",label:"Split Gap",type:"text",path:"features.artifacts.layout.splitGap",defaultValue:"0.5rem"},{id:"art-pane-bg",label:"Pane Background",type:"color",path:"features.artifacts.layout.paneBackground",defaultValue:""},{id:"art-unified",label:"Unified Split Chrome",description:"Wrap chat and artifact in a single container",type:"toggle",path:"features.artifacts.layout.unifiedSplitChrome",defaultValue:!1},{id:"art-resizable",label:"Resizable",description:"Allow dragging the pane divider",type:"toggle",path:"features.artifacts.layout.resizable",defaultValue:!1},{id:"art-expand-panel",label:"Expand Panel When Open",description:"Widen the launcher panel to fit artifacts",type:"toggle",path:"features.artifacts.layout.expandLauncherPanelWhenOpen",defaultValue:!0}]},xg={id:"api-integration",title:"API & Integration",description:"Runtime and integration options.",collapsed:!0,fields:[{id:"dev-api-url",label:"API URL",type:"text",path:"apiUrl",defaultValue:""},{id:"dev-flow",label:"Flow ID",type:"text",path:"flowId",defaultValue:""},{id:"dev-parser",label:"Stream Parser",type:"select",path:"parserType",defaultValue:"plain",options:[{value:"plain",label:"Plain Text"},{value:"json",label:"JSON"},{value:"regex-json",label:"Regex JSON"},{value:"xml",label:"XML"}]}]},wg={id:"debug-inspection",title:"Debug & Inspection",collapsed:!0,fields:[{id:"dev-reasoning",label:"Show Reasoning",description:"Display AI reasoning steps",type:"toggle",path:"features.showReasoning",defaultValue:!1},{id:"dev-tool-calls",label:"Show Tool Calls",description:"Display tool call details",type:"toggle",path:"features.showToolCalls",defaultValue:!1},{id:"dev-tool-collapsed-mode",label:"Tool Call Summary",description:"Choose what collapsed tool rows show by default",type:"select",path:"features.toolCallDisplay.collapsedMode",defaultValue:"tool-call",options:[{value:"tool-call",label:"Tool Call"},{value:"tool-name",label:"Tool Name"},{value:"tool-preview",label:"Tool Preview"}]},{id:"dev-tool-active-preview",label:"Tool Preview While Active",description:"Show a lightweight preview in collapsed active tool rows",type:"toggle",path:"features.toolCallDisplay.activePreview",defaultValue:!1},{id:"dev-tool-preview-lines",label:"Tool Preview Lines",type:"select",path:"features.toolCallDisplay.previewMaxLines",defaultValue:3,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"3",label:"3"},{value:"4",label:"4"},{value:"5",label:"5"}],formatValue:e=>String(e!=null?e:3),parseValue:e=>Number(e)},{id:"dev-tool-active-min-height",label:"Tool Active Min Height",description:"CSS min-height for collapsed active tool rows (e.g. 5rem)",type:"text",path:"features.toolCallDisplay.activeMinHeight",defaultValue:""},{id:"dev-tool-expandable",label:"Tool Calls Expandable",description:"Allow expanding tool call rows to see full details",type:"toggle",path:"features.toolCallDisplay.expandable",defaultValue:!0},{id:"dev-tool-grouped",label:"Group Sequential Tool Calls",description:"Render consecutive tool rows inside a grouped container",type:"toggle",path:"features.toolCallDisplay.grouped",defaultValue:!1},{id:"dev-reasoning-expandable",label:"Reasoning Expandable",description:"Allow expanding reasoning rows to see full details",type:"toggle",path:"features.reasoningDisplay.expandable",defaultValue:!0},{id:"dev-reasoning-active-preview",label:"Reasoning Preview While Active",description:"Show a lightweight preview in collapsed active reasoning rows",type:"toggle",path:"features.reasoningDisplay.activePreview",defaultValue:!1},{id:"dev-reasoning-preview-lines",label:"Reasoning Preview Lines",type:"select",path:"features.reasoningDisplay.previewMaxLines",defaultValue:3,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"3",label:"3"},{value:"4",label:"4"},{value:"5",label:"5"}],formatValue:e=>String(e!=null?e:3),parseValue:e=>Number(e)},{id:"dev-reasoning-active-min-height",label:"Reasoning Active Min Height",description:"CSS min-height for collapsed active reasoning rows (e.g. 5rem)",type:"text",path:"features.reasoningDisplay.activeMinHeight",defaultValue:""},{id:"dev-debug",label:"Debug Mode",description:"Show debug information",type:"toggle",path:"debug",defaultValue:!1}]},Cg={id:"markdown",title:"Markdown Options",collapsed:!0,fields:[{id:"md-gfm",label:"GitHub Flavored Markdown",type:"toggle",path:"markdown.options.gfm",defaultValue:!0},{id:"md-breaks",label:"Line Breaks",type:"toggle",path:"markdown.options.breaks",defaultValue:!0},{id:"md-header-ids",label:"Header IDs",type:"toggle",path:"markdown.options.headerIds",defaultValue:!1},{id:"md-pedantic",label:"Pedantic Mode",type:"toggle",path:"markdown.options.pedantic",defaultValue:!1},{id:"md-silent",label:"Silent",type:"toggle",path:"markdown.options.silent",defaultValue:!1},{id:"md-disable-styles",label:"Disable Default Styles",type:"toggle",path:"markdown.disableDefaultStyles",defaultValue:!1}]},Va=[{label:"Content",sections:[og,rg]},{label:"Layout",sections:[sg,ag,ig,lg]},{label:"Widget",sections:[cg,dg,pg,ug,mg,fg]},{label:"Features",sections:[gg,hg,bg,yg,vg]},{label:"Developer",collapsedByDefault:!0,sections:[xg,wg,Cg]}],uu=Va.flatMap(e=>e.sections),mu={id:"theme-mode-v2",title:"Theme",description:"Choose how the interface adapts across light and dark mode.",collapsed:!1,fields:[{id:"color-mode",label:"Color Mode",type:"select",path:"colorScheme",defaultValue:"auto",options:[{value:"auto",label:"Auto"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}]}]},fu={id:"brand-palette-v2",title:"Brand Palette",description:"Set your brand, accent, and neutral colors. These are used to generate the interface theme.",collapsed:!1,fields:[{id:"bp-primary",label:"Primary",description:"Main brand color",type:"color",path:"theme.palette.colors.primary.500",defaultValue:"#171717"},{id:"bp-secondary",label:"Secondary",description:"Supporting brand color",type:"color",path:"theme.palette.colors.secondary.500",defaultValue:"#8b5cf6"},{id:"bp-accent",label:"Accent",description:"Highlight and decorative color",type:"color",path:"theme.palette.colors.accent.500",defaultValue:"#06b6d4"},{id:"bp-neutral",label:"Neutral",description:"Backgrounds, text, and borders",type:"color",path:"theme.palette.colors.gray.500",defaultValue:"#6b7280"}]},gu={id:"status-palette",title:"Status Palette",description:"Colors for system feedback states.",collapsed:!0,fields:[{id:"sp-success",label:"Success",type:"color",path:"theme.palette.colors.success.500",defaultValue:"#22c55e"},{id:"sp-warning",label:"Warning",type:"color",path:"theme.palette.colors.warning.500",defaultValue:"#eab308"},{id:"sp-error",label:"Error",type:"color",path:"theme.palette.colors.error.500",defaultValue:"#ef4444"},{id:"sp-notice",label:"Notice",description:"Info and notice states",type:"color",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500"}]},hu={id:"interface-roles",title:"Interface Roles",description:"Control where brand and neutral colors appear across the interface.",collapsed:!1,fields:[{id:"role-surfaces",label:"Background Surfaces",type:"role-assignment",path:"theme.semantic.colors.background",roleAssignment:Ra},{id:"role-header",label:"Header",type:"role-assignment",path:"theme.components.header.background",roleAssignment:Pa},{id:"role-user-messages",label:"User Messages",type:"role-assignment",path:"theme.components.message.user.background",roleAssignment:Wa},{id:"role-assistant-messages",label:"Assistant Messages",type:"role-assignment",path:"theme.components.message.assistant.background",roleAssignment:Ba},{id:"role-primary-actions",label:"Primary Actions",type:"role-assignment",path:"theme.components.button.primary.background",roleAssignment:Ha},{id:"role-scroll-to-bottom",label:"Scroll To Bottom",type:"role-assignment",path:"theme.components.scrollToBottom.background",roleAssignment:Da},{id:"role-input",label:"Input Field",type:"role-assignment",path:"theme.components.input.background",roleAssignment:Fa},{id:"role-links-focus",label:"Links & Focus",type:"role-assignment",path:"theme.semantic.colors.accent",roleAssignment:Oa},{id:"role-borders",label:"Borders & Dividers",type:"role-assignment",path:"theme.semantic.colors.border",roleAssignment:Na}]},bu={id:"status-colors",title:"Status Colors",description:"Used for system states like success, warning, notice, and error.",collapsed:!0,fields:[{id:"sc-notice",label:"Notice",type:"token-ref",path:"theme.semantic.colors.feedback.info",defaultValue:"palette.colors.primary.500",tokenRef:{tokenType:"color"}},{id:"sc-success",label:"Success",type:"token-ref",path:"theme.semantic.colors.feedback.success",defaultValue:"palette.colors.success.500",tokenRef:{tokenType:"color"}},{id:"sc-warning",label:"Warning",type:"token-ref",path:"theme.semantic.colors.feedback.warning",defaultValue:"palette.colors.warning.500",tokenRef:{tokenType:"color"}},{id:"sc-error",label:"Error",type:"token-ref",path:"theme.semantic.colors.feedback.error",defaultValue:"palette.colors.error.500",tokenRef:{tokenType:"color"}}]},yu={id:"advanced-tokens",title:"Advanced Tokens",description:"Override individual semantic and component values when you need precise control.",collapsed:!0,fields:[]},Sg=[mu,fu,gu,hu,bu,yu],ol=[{id:"style",label:"Style",sections:zr},{id:"design-system",label:"Design System",sections:pu},{id:"configure",label:"Configure",sections:uu}];function vu(e,t){return e.startsWith("theme.")?e.replace(/^theme\./,`${t}.`):e}function Ag(e,t,n){return{...e,id:`${n}-${e.id}`,path:vu(e.path,t)}}function Tg(e,t){let n=e.find(o=>o.id===t);if(!n)throw new Error(`Section "${t}" not found in definitions`);return n}function kg(e,t,n,o=e.collapsed){var a;let r=n==="light"?"Light":"Dark",s=n==="light"?"Applies when the widget is in light mode.":"Applies when the widget is in dark mode.";return{...e,id:`${n}-${e.id}`,title:`${r} ${e.title}`,description:e.description?`${s} ${e.description}`:s,collapsed:o,fields:e.fields.map(i=>Ag(i,t,n)),presets:(a=e.presets)==null?void 0:a.map(i=>({...i,id:`${n}-${i.id}`,values:Object.fromEntries(Object.entries(i.values).map(([d,l])=>[vu(d,t),l]))}))}}var xu=[{id:"default-light",name:"Default Light",description:"Clean monochrome light theme",theme:{components:{artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}}},preview:{primary:"#171717",surface:"#ffffff",accent:"#0f0f0f"},tags:["light"]},{id:"default-dark",name:"Default Dark",description:"Monochrome dark theme",theme:{palette:{colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},semantic:{colors:{primary:"palette.colors.primary.400",secondary:"palette.colors.gray.400",accent:"palette.colors.primary.500",surface:"palette.colors.gray.800",background:"palette.colors.gray.900",container:"palette.colors.gray.800",text:"palette.colors.gray.100",textMuted:"palette.colors.gray.400",textInverse:"palette.colors.gray.900",border:"palette.colors.gray.700",divider:"palette.colors.gray.700",interactive:{default:"palette.colors.primary.400",hover:"palette.colors.primary.300",focus:"palette.colors.primary.500",active:"palette.colors.primary.600",disabled:"palette.colors.gray.600"},feedback:{success:"palette.colors.success.400",warning:"palette.colors.warning.400",error:"palette.colors.error.400",info:"palette.colors.primary.400"}}}},preview:{primary:"#171717",surface:"#1f2937",accent:"#0f0f0f"},tags:["dark"]},{id:"high-contrast",name:"High Contrast",description:"Maximum contrast for accessibility",theme:{semantic:{colors:{primary:"palette.colors.primary.700",secondary:"palette.colors.gray.700",accent:"palette.colors.primary.800",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.200",text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.400",divider:"palette.colors.gray.400",interactive:{default:"palette.colors.primary.700",hover:"palette.colors.primary.800",focus:"palette.colors.primary.900",active:"palette.colors.primary.950",disabled:"palette.colors.gray.400"},feedback:{success:"palette.colors.success.700",warning:"palette.colors.warning.700",error:"palette.colors.error.700",info:"palette.colors.primary.700"}}}},preview:{primary:"#0a0a0a",surface:"#f9fafb",accent:"#050505"},tags:["light","high-contrast","accessibility"]}],Ls=[...xu];function rl(e){return Ls.find(t=>t.id===e)}import{Marked as Eg}from"marked";var Mg=e=>{if(e)return e},sl=e=>{var r,s;let t=e==null?void 0:e.markedOptions,n=new Eg({gfm:(r=t==null?void 0:t.gfm)!=null?r:!0,breaks:(s=t==null?void 0:t.breaks)!=null?s:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),o=Mg(e==null?void 0:e.renderer);return o&&n.use({renderer:o}),a=>n.parse(a)},$a=e=>e?sl({markedOptions:e.options,renderer:e.renderer}):sl(),ew=sl();var Is=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");import Lg from"dompurify";var Ig={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},Rg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Pg=()=>{let e=Lg(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(t,n)=>{if(n.attrName==="src"||n.attrName==="href"){let o=n.attrValue;o.toLowerCase().startsWith("data:")&&!Rg.test(o)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,Ig)},Ua=e=>e===!1?null:typeof e=="function"?e:Pg();var al="webmcp:",za={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function Cu(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var o,r;return[n.name,(o=n.description)!=null?o:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(r=n.origin)!=null?r:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${Wg(t.join(""))}`}function wu(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function Wg(e){let t=wu(e,0).toString(36),n=wu(e,2654435761).toString(36);return`${t}.${n}`}var qa=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return za.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",r),[]}let o=typeof location!="undefined"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=Dg(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return vo("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let p=typeof document!="undefined"&&!!document.modelContext;return vo(p?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=Bg(t),a;try{a=await r.getTools()}catch(p){let w=p instanceof Error?p.message:String(p);return vo(`Failed to read WebMCP registry: ${w}`)}let i=a.find(p=>p.name===s);if(!i)return vo(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return vo(`WebMCP tool not allowed by client allowlist: ${s}`);if(o!=null&&o.aborted)return vo("Aborted by cancel()");let d={toolName:s,args:n,description:i.description,reason:"gate"};if(!await this.requestConfirm(d))return vo("User declined the tool call.");if(o!=null&&o.aborted)return vo("Aborted by cancel()");let l=new AbortController,m=!1,u=setTimeout(()=>{m=!0,l.abort()},this.timeoutMs),g=()=>l.abort();o&&(o.aborted?l.abort():o.addEventListener("abort",g,{once:!0}));try{let p=await r.executeTool(i,_g(n),{signal:l.signal});return Fg(p)}catch(p){if(m)return vo(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return vo("Aborted by cancel()");let w=p instanceof Error?p.message:String(p);return vo(w)}finally{clearTimeout(u),o&&o.removeEventListener("abort",g)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){za.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,za.warn("document.modelContext is present but does not expose getTools()/executeTool() \u2014 WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var o;let n=(o=this.confirmHandler)!=null?o:Og;try{return await n(t)}catch(r){return za.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,r),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>Hg(t,o))}},Bg=e=>e.startsWith(al)?e.slice(al.length):e,qr=e=>e.startsWith(al),Hg=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Dg=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Fg=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:Vg(t)}]}},vo=e=>({isError:!0,content:[{type:"text",text:e}]}),Og=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Ng(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
2
2
|
|
|
3
3
|
Arguments:
|
|
4
4
|
${t}`:"")+(e.description?`
|
|
5
5
|
|
|
6
|
-
${e.description}`:"");return window.confirm(n)},
|
|
7
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
6
|
+
${e.description}`:"");return window.confirm(n)},Ng=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)}},_g=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Vg=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};import{parse as $g,STR as Ug,OBJ as zg}from"partial-json";var Su=e=>e.replace(/\\n/g,`
|
|
7
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),jr=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},qg=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`},Au=e=>e.status==="complete"?qg(e):e.status==="pending"?"Waiting":"",jg=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 Tu=e=>e.status==="complete"?jg(e):"Using tool...",ja=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Ps=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 ja(t)},Ka=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 ja(t)},il=(e,t,n)=>{var s;if(!t)return n;let o=((s=e.name)==null?void 0:s.trim())||"tool",r=Ps(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},Ga=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Rs(o,n.slice(s,a.index),[]),a[1]!==void 0?Rs(o,a[1],["bold"]):a[2]!==void 0?Rs(o,a[2],["italic"]):a[3]!==void 0&&Rs(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Rs(o,n.slice(s),[]),o},Rs=(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})},Kg=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
|
|
8
8
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=o.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
|
|
9
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Cr=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Tu=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ku=()=>{var t;let e=qf();return{processChunk:async n=>{let o=n.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},Eu=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=_f(n,Vf|$f);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Cu(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Cu(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var Mu=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Ka=class{constructor(t,n=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=n}push(t,n){var s,a,i;let o=(i=(s=n==null?void 0:n.seq)!=null?s:n==null?void 0:n.sequenceIndex)!=null?i:(a=n==null?void 0:n.agentContext)==null?void 0:a.seq;if(o==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,n);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),o===this.nextExpectedSeq){this.emitter(t,n),this.nextExpectedSeq=o+1,this.drainConsecutive();return}if(o<this.nextExpectedSeq){this.emitter(t,n);return}let r=this.buffer.get(o);r!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${o} (${r.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(r.payloadType,r.payload)),this.buffer.set(o,{payloadType:t,payload:n,seq:o}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((n,o)=>n[0]-o[0]);for(let[n,o]of t)this.buffer.delete(n),this.emitter(o.payloadType,o.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var jf="https://api.runtype.com/v1/dispatch",Ga="https://api.runtype.com";function Kf(e){var s,a;let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let i=(a=(s=t.slice(r+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var il=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Gf(e){switch(e){case"json":return Eu;case"regex-json":return ku;case"xml":return Mu;default:return Tu}}var Lu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Yf(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=Lu(n);if(!Lu(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Cr(e);return Cr(t)!==null&&a===null?t:e}var Ps=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,o,r,s;this.apiUrl=(n=t.apiUrl)!=null?n:jf,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:Gf(t.parserType),this.contextProviders=(r=t.contextProviders)!=null?r:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new Ua(t.webmcp):null}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ga}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let o=await this.sessionInitPromise;return this.clientSession=o,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,o),o}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let t=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},o=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){let i=await o.json().catch(()=>({error:"Session initialization failed"}));throw o.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):o.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let r=await o.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(r.sessionId),{sessionId:r.sessionId,expiresAt:new Date(r.expiresAt),flow:r.flow,config:{welcomeMessage:r.config.welcomeMessage,placeholder:r.config.placeholder,theme:r.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ga}/v1/client/feedback`}async sendFeedback(t){var s,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var r,s,a,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(r=this.config).onSessionExpired)==null||s.call(r);let D=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:D}),D}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([D])=>D!=="sessionId"&&D!=="session_id")):void 0,m={sessionId:d.sessionId,messages:t.messages.filter(il).map(D=>{var B,v,x;return{id:D.id,role:D.role,content:(x=(v=(B=D.contentParts)!=null?B:D.llmContent)!=null?v:D.rawContent)!=null?x:D.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},f=l.clientTools,u=!!(f&&f.length>0),w=u?wu(f):void 0,C=this.clientToolsFingerprintSessionId===d.sessionId,M=u&&C&&this.lastSentClientToolsFingerprint===w,I=!1,R=null,H;for(let D=0;;D++){let v={...m,...u&&(I||!M)&&f?{clientTools:f}:{},...w?{clientToolsFingerprint:w}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",v),H=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v),signal:o.signal}),H.status===409&&D===0&&u){let x=await H.json().catch(()=>null);if((x==null?void 0:x.error)==="client_tools_resend_required"){I=!0,this.lastSentClientToolsFingerprint=null;continue}R=x!=null?x:{error:"Chat request failed"}}break}if(!H.ok){let D=R!=null?R:await H.json().catch(()=>({error:"Chat request failed"}));if(H.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let v=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:v}),v}if(H.status===429){let v=new Error(D.hint||"Message limit reached for this session.");throw n({type:"error",error:v}),v}let B=new Error(D.error||"Failed to send message");throw n({type:"error",error:B}),B}if(!H.body){let D=new Error("No response body received");throw n({type:"error",error:D}),D}this.lastSentClientToolsFingerprint=w!=null?w:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(H.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let r=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ga}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,o){var l,p;let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Ga}/resume`,a;r&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=o==null?void 0:o.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var s;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(il).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),o={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},r=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(r&&r.length>0&&(o.clientTools=r),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(o.context=a)}return o}async buildPayload(t){var s;let o={messages:t.slice().filter(il).sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},r=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(r&&r.length>0&&(o.clientTools=r),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(o.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...o},config:this.config});if(a&&typeof a=="object"){let i=a;return o.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=o.clientTools),i}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return o}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return o.current=m,r(m),m},l=p=>o.current?o.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,r(p)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o){var ln,Dn,Jn,ze;let r=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=_=>{let ke=_.reasoning?{..._.reasoning,chunks:[..._.reasoning.chunks]}:void 0,He=_.toolCall?{..._.toolCall,chunks:_.toolCall.chunks?[..._.toolCall.chunks]:void 0}:void 0,De=_.tools?_.tools.map(Ve=>({...Ve,chunks:Ve.chunks?[...Ve.chunks]:void 0})):void 0;return{..._,reasoning:ke,toolCall:He,tools:De}},m=_=>{if(_.role!=="assistant"||_.variant)return!0;let ke=Array.isArray(_.contentParts)&&_.contentParts.length>0,He=typeof _.rawContent=="string"&&_.rawContent.trim()!=="";return typeof _.content=="string"&&_.content.trim()!==""||ke||He||!!_.stopReason},f=_=>{m(_)&&n({type:"message",message:p(_)})},u=null,w=null,C={current:null},M={current:null},I=!1,R=new Map,H=new Map,D=new Map,B=new Map,v={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},k=(_,ke,He="")=>`${_}::${ke}::${He}`,S=(_,ke)=>`${_}::${ke}::`,E=(_,ke,He,De)=>{let Ve=k(_,ke,He),dt=D.get(Ve);if(dt)return dt;let ot=He?`-${He}`:"",At={id:`nested-${_}-${ke}${ot}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...He?{partId:He}:{},agentMetadata:{executionId:De,parentToolId:_,parentStepId:ke}};return D.set(Ve,At),f(At),At},F=_=>{if(_==null)return null;try{return String(_)}catch{return null}},$=_=>{var ke,He,De,Ve,dt;return F((dt=(Ve=(De=(He=(ke=_.stepId)!=null?ke:_.step_id)!=null?He:_.step)!=null?De:_.parentId)!=null?Ve:_.flowStepId)!=null?dt:_.flow_step_id)},j=_=>{var ke,He,De,Ve,dt,ot,At;return F((At=(ot=(dt=(Ve=(De=(He=(ke=_.callId)!=null?ke:_.call_id)!=null?He:_.requestId)!=null?De:_.request_id)!=null?Ve:_.toolCallId)!=null?dt:_.tool_call_id)!=null?ot:_.stepId)!=null?At:_.step_id)},me=o,se=!1,ge=()=>{if(u)return u;let _;return!se&&me?(_=me,se=!0):me&&M.current?_=`${me}_${M.current}`:_=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,u={id:_,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(u),u},ie=(_,ke)=>{v.lastId=ke,_&&v.byStep.set(_,ke)},be=(_,ke)=>{var dt;let He=(dt=_.reasoningId)!=null?dt:_.id,De=$(_);if(He){let ot=String(He);return ie(De,ot),ot}if(De){let ot=v.byStep.get(De);if(ot)return v.lastId=ot,ot}if(v.lastId&&!ke)return v.lastId;if(!ke)return null;let Ve=`reason-${l()}`;return ie(De,Ve),Ve},Fe=_=>{let ke=R.get(_);if(ke)return ke;let He={id:`reason-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:_,status:"streaming",chunks:[]}};return R.set(_,He),f(He),He},ve=(_,ke)=>{x.lastId=ke,_&&x.byCall.set(_,ke)},J=new Set,Le=new Map,Y=new Set,xe=new Map,Se=_=>{if(!_)return!1;let ke=_.replace(/_+/g,"_").replace(/^_|_$/g,"");return ke==="emit_artifact_markdown"||ke==="emit_artifact_component"},de=(_,ke)=>{var dt;let He=(dt=_.toolId)!=null?dt:_.id,De=j(_);if(He){let ot=String(He);return ve(De,ot),ot}if(De){let ot=x.byCall.get(De);if(ot)return x.lastId=ot,ot}if(x.lastId&&!ke)return x.lastId;if(!ke)return null;let Ve=`tool-${l()}`;return ve(De,Ve),Ve},we=_=>{let ke=H.get(_);if(ke)return ke;let He={id:`tool-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:_,status:"pending"}};return H.set(_,He),f(He),He},Ue=_=>{if(typeof _=="number"&&Number.isFinite(_))return _;if(typeof _=="string"){let ke=Number(_);if(!Number.isNaN(ke)&&Number.isFinite(ke))return ke;let He=Date.parse(_);if(!Number.isNaN(He))return He}return Date.now()},te=_=>{if(typeof _=="string")return _;if(_==null)return"";try{return JSON.stringify(_)}catch{return String(_)}},ne=new Map,re=new Map,nt=new Map,ye=new Map,le=null,$e=(_,ke,He)=>{var At;let De=nt.get(_);De||(De=[],nt.set(_,De));let Ve=0,dt=De.length;for(;Ve<dt;){let Vt=Ve+dt>>>1;De[Vt].seq<ke?Ve=Vt+1:dt=Vt}((At=De[Ve])==null?void 0:At.seq)===ke?De[Ve]={seq:ke,text:He}:De.splice(Ve,0,{seq:ke,text:He});let ot="";for(let Vt=0;Vt<De.length;Vt++)ot+=De[Vt].text;return ot},Be=(_,ke)=>{let He=te(ke),De=re.get(_.id),Ve=Yf(De,He);_.rawContent=Ve;let dt=ne.get(_.id),ot=Qe=>{var oe;let Ft=(oe=_.content)!=null?oe:"";Qe.trim()!==""&&(Ft.trim().length===0||Qe.startsWith(Ft)||Qe.trimStart().startsWith(Ft.trim()))&&(_.content=Qe)},At=()=>{var Qe;if(dt){let Ft=(Qe=dt.close)==null?void 0:Qe.call(dt);Ft instanceof Promise&&Ft.catch(()=>{})}ne.delete(_.id),re.delete(_.id),_.streaming=!1,f(_)};if(!dt){ot(He),At();return}let Vt=Cr(Ve);if(Vt!==null&&Vt.trim()!==""){ot(Vt),At();return}let q=Qe=>{var fe;let Ft=typeof Qe=="string"?Qe:(fe=Qe==null?void 0:Qe.text)!=null?fe:null;if(Ft!==null&&Ft.trim()!=="")return Ft;let oe=dt.getExtractedText();return oe!==null&&oe.trim()!==""?oe:He},_t;try{_t=dt.processChunk(Ve)}catch{ot(He),At();return}if(_t instanceof Promise){_t.then(Qe=>{ot(q(Qe)),At()}).catch(()=>{ot(He),At()});return}ot(q(_t)),At()},ce=[],K=!1,_e,Et=()=>{K||(K=!0,queueMicrotask(()=>{K=!1,_e()}))},pe=new Ka((_,ke)=>{ce.push({payloadType:_,payload:ke}),Et()}),ae=null,Ln=new Map,Nt=(ln=this.config.iterationDisplay)!=null?ln:"separate";for(_e=()=>{var _,ke,He,De,Ve,dt,ot,At,Vt,q,_t,Qe,Ft,oe,fe,xt,$t,Jt,yn,Tt,wt,ft,bt,zt,et,Fn,Zn,vn,On,ut,wo,Nn,ir,In,Rr,$o,Lo,yt,_n,Vn,xn,It,eo,to,$n,Uo,Io,zo,Un,Wt,wn,no,qo,Ro,jo,Co,zn,po,gt,Kt,Gt,qn,Ko,oo,uo,jn,T,Kn,mo,Po,So,ss,go,fo,ho,Wo,lr,ra,as,sa,Pr,mt,is,ro,Rn,aa,ia,Wr,Bo,la,cr,ls,Ho,cs,Go,Yo,ca,da,$i,dr,Xo,pa,ds,Qo,ua,ps,Jo,us,ma,Do,ga,Zo,Bt,Br,Hr,ms,Ao,fa,gs,fs,ha,Dr,Fr,pr,ba,ya,hs,bs,ys,vs,Cn,Gn,Fo,rt,xs,ur,bo,va;for(let er=0;er<ce.length;er++){let je=ce[er].payloadType,A=ce[er].payload;if(je==="reason_start"){let U=(_=be(A,!0))!=null?_:`reason-${l()}`,W=Fe(U);W.reasoning=(ke=W.reasoning)!=null?ke:{id:U,status:"streaming",chunks:[]},W.reasoning.startedAt=(De=W.reasoning.startedAt)!=null?De:Ue((He=A.startedAt)!=null?He:A.timestamp),W.reasoning.completedAt=void 0,W.reasoning.durationMs=void 0,W.streaming=!0,W.reasoning.status="streaming",f(W)}else if(je==="reason_delta"||je==="reason_chunk"){let U=(dt=(Ve=be(A,!1))!=null?Ve:be(A,!0))!=null?dt:`reason-${l()}`,W=Fe(U);W.reasoning=(ot=W.reasoning)!=null?ot:{id:U,status:"streaming",chunks:[]},W.reasoning.startedAt=(Vt=W.reasoning.startedAt)!=null?Vt:Ue((At=A.startedAt)!=null?At:A.timestamp);let Z=(Qe=(_t=(q=A.reasoningText)!=null?q:A.text)!=null?_t:A.delta)!=null?Qe:"";if(Z&&A.hidden!==!0){let G=typeof A.sequenceIndex=="number"?A.sequenceIndex:void 0;if(G!==void 0){let X=$e(U,G,String(Z));W.reasoning.chunks=[X]}else W.reasoning.chunks.push(String(Z))}if(W.reasoning.status=A.done?"complete":"streaming",A.done){W.reasoning.completedAt=Ue((Ft=A.completedAt)!=null?Ft:A.timestamp);let G=(oe=W.reasoning.startedAt)!=null?oe:Date.now();W.reasoning.durationMs=Math.max(0,((fe=W.reasoning.completedAt)!=null?fe:Date.now())-G)}W.streaming=W.reasoning.status!=="complete",f(W)}else if(je==="reason_complete"){let U=($t=(xt=be(A,!1))!=null?xt:be(A,!0))!=null?$t:`reason-${l()}`,W=R.get(U);if(W!=null&&W.reasoning){W.reasoning.status="complete",W.reasoning.completedAt=Ue((Jt=A.completedAt)!=null?Jt:A.timestamp);let G=(yn=W.reasoning.startedAt)!=null?yn:Date.now();W.reasoning.durationMs=Math.max(0,((Tt=W.reasoning.completedAt)!=null?Tt:Date.now())-G),W.streaming=!1,f(W)}let Z=$(A);Z&&v.byStep.delete(Z)}else if(je==="tool_start"){let U=(wt=de(A,!0))!=null?wt:`tool-${l()}`,W=(ft=A.toolName)!=null?ft:A.name;if(Se(W)){J.add(U);continue}let Z=we(U),G=(bt=Z.toolCall)!=null?bt:{id:U,status:"pending"};G.name=W!=null?W:G.name,G.status="running",A.args!==void 0?G.args=A.args:A.parameters!==void 0&&(G.args=A.parameters),G.startedAt=(et=G.startedAt)!=null?et:Ue((zt=A.startedAt)!=null?zt:A.timestamp),G.completedAt=void 0,G.durationMs=void 0,Z.toolCall=G,Z.streaming=!0;let X=A.agentContext;(X||A.executionId)&&(Z.agentMetadata={executionId:(Fn=X==null?void 0:X.executionId)!=null?Fn:A.executionId,iteration:(Zn=X==null?void 0:X.iteration)!=null?Zn:A.iteration}),f(Z)}else if(je==="tool_chunk"||je==="tool_delta"){let U=(On=(vn=de(A,!1))!=null?vn:de(A,!0))!=null?On:`tool-${l()}`;if(J.has(U))continue;let W=we(U),Z=(ut=W.toolCall)!=null?ut:{id:U,status:"running"};Z.startedAt=(Nn=Z.startedAt)!=null?Nn:Ue((wo=A.startedAt)!=null?wo:A.timestamp);let G=(Rr=(In=(ir=A.text)!=null?ir:A.delta)!=null?In:A.message)!=null?Rr:"";G&&(Z.chunks=($o=Z.chunks)!=null?$o:[],Z.chunks.push(String(G))),Z.status="running",W.toolCall=Z,W.streaming=!0;let X=A.agentContext;(X||A.executionId)&&(W.agentMetadata=(_n=W.agentMetadata)!=null?_n:{executionId:(Lo=X==null?void 0:X.executionId)!=null?Lo:A.executionId,iteration:(yt=X==null?void 0:X.iteration)!=null?yt:A.iteration}),f(W)}else if(je==="tool_complete"){let U=(xn=(Vn=de(A,!1))!=null?Vn:de(A,!0))!=null?xn:`tool-${l()}`;if(J.has(U)){J.delete(U);continue}let W=we(U),Z=(It=W.toolCall)!=null?It:{id:U,status:"running"};Z.status="complete",A.result!==void 0&&(Z.result=A.result),typeof A.duration=="number"&&(Z.duration=A.duration),Z.completedAt=Ue((eo=A.completedAt)!=null?eo:A.timestamp);let G=(to=A.duration)!=null?to:A.executionTime;if(typeof G=="number")Z.durationMs=G;else{let Ne=($n=Z.startedAt)!=null?$n:Date.now();Z.durationMs=Math.max(0,((Uo=Z.completedAt)!=null?Uo:Date.now())-Ne)}W.toolCall=Z,W.streaming=!1;let X=A.agentContext;(X||A.executionId)&&(W.agentMetadata=(Un=W.agentMetadata)!=null?Un:{executionId:(Io=X==null?void 0:X.executionId)!=null?Io:A.executionId,iteration:(zo=X==null?void 0:X.iteration)!=null?zo:A.iteration}),f(W);let Xe=j(A);Xe&&x.byCall.delete(Xe)}else if(je==="step_await"&&A.awaitReason==="local_tool_required"&&A.toolName){let U=typeof A.toolCallId=="string"&&A.toolCallId.length>0?A.toolCallId:void 0,W=(Wt=U!=null?U:A.toolId)!=null?Wt:`local-${l()}`,Z=we(W),G=(wn=Z.toolCall)!=null?wn:{id:W,status:"pending"};G.name=A.toolName,G.args=A.parameters,G.status="complete",G.chunks=(no=G.chunks)!=null?no:[],G.startedAt=(Ro=G.startedAt)!=null?Ro:Ue((qo=A.startedAt)!=null?qo:A.timestamp),G.completedAt=(jo=G.completedAt)!=null?jo:G.startedAt,Z.toolCall=G,Z.streaming=!1,Z.agentMetadata={...Z.agentMetadata,executionId:(zn=A.executionId)!=null?zn:(Co=Z.agentMetadata)==null?void 0:Co.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},f(Z)}else if(je==="text_start"){if((po=A.toolContext)!=null&&po.toolId)continue;let U=A.partId;if(U!==void 0&&M.current!==null&&U!==M.current){let W=u;W&&(W.streaming=!1,f(W),le=W,u=null,I=!0)}U!==void 0&&(M.current=U)}else if(je==="text_end"){if((gt=A.toolContext)!=null&>.toolId)continue;let U=u;U&&(U.streaming=!1,f(U),le=U,u=null,I=!0)}else if(je==="step_chunk"||je==="step_delta"){let U=A.stepType,W=A.executionType;if(U==="tool"||W==="context")continue;let Z=A.toolContext;if(Z!=null&&Z.toolId){let Ne=String((Gt=(Kt=A.id)!=null?Kt:Z.stepId)!=null?Gt:`step-${l()}`),Ze=A.partId!==void 0&&A.partId!==null?String(A.partId):"",Ie=`${Z.toolId}::${Ne}`,Ge=B.get(Ie);if(Ze!==""&&Ge!==void 0&&Ge!==""&&Ge!==Ze){let Ct=D.get(k(Z.toolId,Ne,Ge));Ct&&Ct.streaming!==!1&&(Ct.streaming=!1,f(Ct))}Ze!==""&&B.set(Ie,Ze);let Rt=E(Z.toolId,Ne,Ze,Z.executionId),nn=(uo=(oo=(Ko=(qn=A.text)!=null?qn:A.delta)!=null?Ko:A.content)!=null?oo:A.chunk)!=null?uo:"";nn&&(Rt.content+=String(nn),Rt.streaming=!0,f(Rt)),A.isComplete&&(Rt.streaming=!1,f(Rt));continue}let G=A.partId;if(G!==void 0&&M.current!==null&&G!==M.current){let Ne=u;Ne&&(Ne.streaming=!1,f(Ne),le=Ne,u=null,I=!0)}G!==void 0&&(M.current=G);let X=G!==void 0&&(jn=ye.get(G))!=null?jn:ge();G!==void 0&&(X.partId||(X.partId=G),ye.set(G,X));let Xe=(Po=(mo=(Kn=(T=A.text)!=null?T:A.delta)!=null?Kn:A.content)!=null?mo:A.chunk)!=null?Po:"";if(Xe){let Ne=typeof A.seq=="number"?A.seq:void 0,Ze=G!=null?G:X.id,Ie=Ne!==void 0?$e(Ze,Ne,String(Xe)):((So=re.get(X.id))!=null?So:"")+Xe;X.rawContent=Ie,ne.has(X.id)||ne.set(X.id,this.createStreamParser());let Ge=ne.get(X.id),Rt=Ie.trim().startsWith("{")||Ie.trim().startsWith("[");if(Rt&&re.set(X.id,Ie),Ge.__isPlainTextParser===!0){X.content=Ne!==void 0?Ie:X.content+Xe,re.delete(X.id),ne.delete(X.id),X.rawContent=void 0,f(X);continue}let Ct=Ge.processChunk(Ie);if(Ct instanceof Promise)Ct.then(Mt=>{var un;let on=typeof Mt=="string"?Mt:(un=Mt==null?void 0:Mt.text)!=null?un:null;if(on!==null&&on.trim()!=="")X.content=on,f(X);else if(!Rt&&!Ie.trim().startsWith("<")){let Sn=u,Yt=Sn&&Sn.id===X.id?Sn:X;Yt.id===X.id&&(Yt.content=Ne!==void 0?Ie:Yt.content+Xe,re.delete(Yt.id),ne.delete(Yt.id),Yt.rawContent=void 0,f(Yt))}}).catch(()=>{X.content=Ne!==void 0?Ie:X.content+Xe,re.delete(X.id),ne.delete(X.id),X.rawContent=void 0,f(X)});else{let Mt=typeof Ct=="string"?Ct:(ss=Ct==null?void 0:Ct.text)!=null?ss:null;Mt!==null&&Mt.trim()!==""?(X.content=Mt,f(X)):!Rt&&!Ie.trim().startsWith("<")&&(X.content=Ne!==void 0?Ie:X.content+Xe,re.delete(X.id),ne.delete(X.id),X.rawContent=void 0,f(X))}}if(A.isComplete){let Ne=(fo=(go=A.result)==null?void 0:go.response)!=null?fo:X.content;if(Ne){let Ze=re.get(X.id),Ie=Ze!=null?Ze:te(Ne);X.rawContent=Ie;let Ge=ne.get(X.id),Rt=null,nn=!1;if(Ge&&(Rt=Ge.getExtractedText(),Rt===null&&(Rt=Cr(Ie)),Rt===null)){let Ct=Ge.processChunk(Ie);Ct instanceof Promise?(nn=!0,Ct.then(Mt=>{var un;let on=typeof Mt=="string"?Mt:(un=Mt==null?void 0:Mt.text)!=null?un:null;if(on!==null){let Sn=u;Sn&&Sn.id===X.id&&(Sn.content=on,Sn.streaming=!1,ne.delete(Sn.id),re.delete(Sn.id),f(Sn))}})):Rt=typeof Ct=="string"?Ct:(ho=Ct==null?void 0:Ct.text)!=null?ho:null}if(!nn){Rt!==null&&Rt.trim()!==""?X.content=Rt:re.has(X.id)||(X.content=te(Ne));let Ct=ne.get(X.id);if(Ct){let Mt=(Wo=Ct.close)==null?void 0:Wo.call(Ct);Mt instanceof Promise&&Mt.catch(()=>{}),ne.delete(X.id)}re.delete(X.id),X.streaming=!1,f(X)}}}}else if(je==="step_complete"){let U=A.stepType,W=A.executionType;if(U==="tool"||W==="context")continue;let Z=A.toolContext;if(Z!=null&&Z.toolId){let Ne=String((ra=(lr=A.id)!=null?lr:Z.stepId)!=null?ra:"");if(Ne){let Ze=S(Z.toolId,Ne);for(let[Ie,Ge]of D)Ie.startsWith(Ze)&&Ge.streaming!==!1&&(Ge.streaming=!1,f(Ge));B.delete(`${Z.toolId}::${Ne}`)}continue}let G=A.stopReason;if(I){if(u!==null){let Ie=u;G&&(Ie.stopReason=G),ne.delete(Ie.id),re.delete(Ie.id),Ie.streaming!==!1&&(Ie.streaming=!1,f(Ie))}let Ne=(as=A.result)==null?void 0:as.response,Ze=le;Ze&&(G&&(Ze.stopReason=G),Ne!=null?Be(Ze,Ne):(ne.delete(Ze.id),re.delete(Ze.id))),le=null;continue}let X=(sa=A.result)==null?void 0:sa.response,Xe=ge();if(G&&(Xe.stopReason=G),X!=null){let Ne=ne.get(Xe.id),Ze=!1,Ie=!1;if(Ne){let Ge=Ne.getExtractedText(),Rt=re.get(Xe.id),nn=Rt!=null?Rt:te(X);if(Xe.rawContent=nn,Ge!==null&&Ge.trim()!=="")Xe.content=Ge,Ze=!0;else{let Ct=Cr(nn);if(Ct!==null)Xe.content=Ct,Ze=!0;else{let Mt=Ne.processChunk(nn);if(Mt instanceof Promise)Ie=!0,Mt.then(on=>{var Sn;let un=typeof on=="string"?on:(Sn=on==null?void 0:on.text)!=null?Sn:null;if(un!==null&&un.trim()!==""){let Yt=u;Yt&&Yt.id===Xe.id&&(Yt.content=un,Yt.streaming=!1,ne.delete(Yt.id),re.delete(Yt.id),f(Yt))}else{let Yt=Ne.getExtractedText(),so=u;so&&so.id===Xe.id&&(Yt!==null&&Yt.trim()!==""?so.content=Yt:re.has(so.id)||(so.content=te(X)),so.streaming=!1,ne.delete(so.id),re.delete(so.id),f(so))}});else{let on=typeof Mt=="string"?Mt:(Pr=Mt==null?void 0:Mt.text)!=null?Pr:null;if(on!==null&&on.trim()!=="")Xe.content=on,Ze=!0;else{let un=Ne.getExtractedText();un!==null&&un.trim()!==""&&(Xe.content=un,Ze=!0)}}}}}if(!Ie){if(!Xe.rawContent){let Ge=re.get(Xe.id);Xe.rawContent=Ge!=null?Ge:te(X)}if(!Ze&&!re.has(Xe.id)&&(Xe.content=te(X)),Ne){let Ge=(mt=Ne.close)==null?void 0:mt.call(Ne);Ge instanceof Promise&&Ge.catch(()=>{})}ne.delete(Xe.id),re.delete(Xe.id),Xe.streaming=!1,f(Xe)}}else ne.delete(Xe.id),re.delete(Xe.id),Xe.streaming=!1,f(Xe)}else if(je==="flow_complete"){let U=(is=A.result)==null?void 0:is.response;if(I){if(u!==null){let W=u;ne.delete(W.id),re.delete(W.id),W.streaming!==!1&&(W.streaming=!1,f(W))}}else if(U!=null){let W=ge(),Z=re.get(W.id),G=Z!=null?Z:te(U);W.rawContent=G;let X=te(U),Xe=ne.get(W.id);if(Xe){let Ie=Cr(G);if(Ie!==null)X=Ie;else{let Ge=Xe.processChunk(G);Ge instanceof Promise&&Ge.then(nn=>{var Mt;let Ct=typeof nn=="string"?nn:(Mt=nn==null?void 0:nn.text)!=null?Mt:null;Ct!==null&&(W.content=Ct,W.streaming=!1,f(W))});let Rt=Xe.getExtractedText();Rt!==null&&(X=Rt)}}ne.delete(W.id),re.delete(W.id);let Ne=X!==W.content,Ze=W.streaming!==!1;Ne&&(W.content=X),W.streaming=!1,(Ne||Ze)&&f(W)}else if(u!==null){let W=u;ne.delete(W.id),re.delete(W.id),W.streaming!==!1&&(W.streaming=!1,f(W))}n({type:"status",status:"idle"})}else if(je==="agent_start")ae={executionId:A.executionId,agentId:(ro=A.agentId)!=null?ro:"virtual",agentName:(Rn=A.agentName)!=null?Rn:"",status:"running",currentIteration:0,maxTurns:(aa=A.maxTurns)!=null?aa:1,startedAt:Ue(A.startedAt)};else if(je==="agent_iteration_start"){if(ae&&(ae.currentIteration=A.iteration),Nt==="separate"&&A.iteration>1){let U=u;U&&(U.streaming=!1,f(U),Ln.set(A.iteration-1,U),u=null)}}else if(je==="agent_turn_start")w=null;else if(je==="agent_turn_delta"){if(A.contentType==="text"){let U=ge();U.content+=(ia=A.delta)!=null?ia:"",U.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId,agentName:ae==null?void 0:ae.agentName},w=U,f(U)}else if(A.contentType==="thinking"){let U=(Wr=A.turnId)!=null?Wr:`agent-think-${A.iteration}`,W=Fe(U);W.reasoning=(Bo=W.reasoning)!=null?Bo:{id:U,status:"streaming",chunks:[]},W.reasoning.chunks.push((la=A.delta)!=null?la:""),W.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId},f(W)}else if(A.contentType==="tool_input"){let U=(cr=A.toolCallId)!=null?cr:x.lastId;if(U){let W=H.get(U);W!=null&&W.toolCall&&(W.toolCall.chunks=(ls=W.toolCall.chunks)!=null?ls:[],W.toolCall.chunks.push((Ho=A.delta)!=null?Ho:""),f(W))}}}else if(je==="agent_turn_complete"){let U=A.turnId;if(U){let G=R.get(U);if(G!=null&&G.reasoning){G.reasoning.status="complete",G.reasoning.completedAt=Ue(A.completedAt);let X=(cs=G.reasoning.startedAt)!=null?cs:Date.now();G.reasoning.durationMs=Math.max(0,((Go=G.reasoning.completedAt)!=null?Go:Date.now())-X),G.streaming=!1,f(G)}}let W=A.stopReason,Z=u!=null?u:w;if(W&&Z!==null){let G=A.turnId;(!G||((Yo=Z.agentMetadata)==null?void 0:Yo.turnId)===G)&&(Z.stopReason=W,f(Z))}}else if(je==="agent_tool_start"){u&&(u.streaming=!1,f(u),u=null);let U=(ca=A.toolCallId)!=null?ca:`agent-tool-${l()}`;ve(j(A),U);let W=we(U),Z=(da=W.toolCall)!=null?da:{id:U,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};Z.name=(dr=($i=A.toolName)!=null?$i:A.name)!=null?dr:Z.name,Z.status="running",A.parameters!==void 0&&(Z.args=A.parameters),Z.startedAt=Ue((Xo=A.startedAt)!=null?Xo:A.timestamp),W.toolCall=Z,W.streaming=!0,W.agentMetadata={executionId:A.executionId,iteration:A.iteration},f(W)}else if(je==="agent_tool_delta"){let U=(pa=A.toolCallId)!=null?pa:x.lastId;if(U){let W=(ds=H.get(U))!=null?ds:we(U);W.toolCall&&(W.toolCall.chunks=(Qo=W.toolCall.chunks)!=null?Qo:[],W.toolCall.chunks.push((ua=A.delta)!=null?ua:""),W.toolCall.status="running",W.streaming=!0,f(W))}}else if(je==="agent_tool_complete"){let U=(ps=A.toolCallId)!=null?ps:x.lastId;if(U){let W=(Jo=H.get(U))!=null?Jo:we(U);if(W.toolCall){W.toolCall.status="complete",A.result!==void 0&&(W.toolCall.result=A.result),typeof A.executionTime=="number"&&(W.toolCall.durationMs=A.executionTime),W.toolCall.completedAt=Ue((us=A.completedAt)!=null?us:A.timestamp),W.streaming=!1,f(W);let Z=j(A);Z&&x.byCall.delete(Z)}}}else if(je==="agent_media"){let U=Array.isArray(A.media)?A.media:[],W=[];for(let Z of U){if(!Z||typeof Z!="object")continue;let G=Z,X=typeof G.type=="string"?G.type:void 0,Xe=typeof G.mediaType=="string"?G.mediaType.toLowerCase():"",Ne=null,Ze="";if(X==="media"){let Ie=typeof G.data=="string"?G.data:void 0;if(!Ie)continue;Ze=Xe.length>0?Xe:"application/octet-stream",Ne=`data:${Ze};base64,${Ie}`}else if(X==="image-url"){let Ie=typeof G.url=="string"?G.url:void 0;if(!Ie)continue;Ze=Xe,Ne=Ie}else if(X==="file-url"){let Ie=typeof G.url=="string"?G.url:void 0;if(!Ie)continue;Ze=Xe,Ne=Ie}else continue;if(Ne)if(X==="image-url"||Ze.startsWith("image/"))W.push({type:"image",image:Ne,...Ze?{mimeType:Ze}:{}});else if(Ze.startsWith("audio/"))W.push({type:"audio",audio:Ne,mimeType:Ze});else if(Ze.startsWith("video/"))W.push({type:"video",video:Ne,mimeType:Ze});else{let Ie=Ze||"application/octet-stream";W.push({type:"file",data:Ne,mimeType:Ie,filename:Kf(Ie)})}}if(W.length>0){let Z=l(),G=A.toolCallId,Xe={id:`agent-media-${typeof G=="string"&&G.length>0?`${G}-${Z}`:String(Z)}`,role:"assistant",content:"",contentParts:W,createdAt:new Date().toISOString(),streaming:!1,sequence:Z,agentMetadata:{executionId:A.executionId,iteration:A.iteration}};f(Xe);let Ne=u;Ne&&(Ne.streaming=!1,f(Ne)),u=null,C.current=null}}else if(je!=="agent_iteration_complete"){if(je==="agent_reflection"||je==="agent_reflect"){let U=`agent-reflection-${A.executionId}-${A.iteration}`,W={id:U,role:"assistant",content:(ma=A.reflection)!=null?ma:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:U,status:"complete",chunks:[(Do=A.reflection)!=null?Do:""]},agentMetadata:{executionId:A.executionId,iteration:A.iteration}};f(W)}else if(je==="agent_complete"){ae&&(ae.status=A.success?"complete":"error",ae.completedAt=Ue(A.completedAt),ae.stopReason=A.stopReason);let U=u;U&&(U.streaming=!1,f(U)),n({type:"status",status:"idle"})}else if(je==="agent_error"){let U=typeof A.error=="string"?A.error:(Zo=(ga=A.error)==null?void 0:ga.message)!=null?Zo:"Agent execution error";A.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",U):n({type:"error",error:new Error(U)})}else if(je!=="agent_ping"){if(je==="agent_approval_start"){let U=(Bt=A.approvalId)!=null?Bt:`approval-${l()}`,W={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(Br=ae==null?void 0:ae.agentId)!=null?Br:"virtual",executionId:(ms=(Hr=A.executionId)!=null?Hr:ae==null?void 0:ae.executionId)!=null?ms:"",toolName:(Ao=A.toolName)!=null?Ao:"",toolType:A.toolType,description:(gs=A.description)!=null?gs:`Execute ${(fa=A.toolName)!=null?fa:"tool"}`,parameters:A.parameters}};f(W)}else if(je==="step_await"&&A.awaitReason==="approval_required"){let U=(fs=A.approvalId)!=null?fs:`approval-${l()}`,W={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(ha=ae==null?void 0:ae.agentId)!=null?ha:"virtual",executionId:(Fr=(Dr=A.executionId)!=null?Dr:ae==null?void 0:ae.executionId)!=null?Fr:"",toolName:(pr=A.toolName)!=null?pr:"",toolType:A.toolType,description:(ya=A.description)!=null?ya:`Execute ${(ba=A.toolName)!=null?ba:"tool"}`,parameters:A.parameters}};f(W)}else if(je==="agent_approval_complete"){let U=A.approvalId;if(U){let Z={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:(hs=A.decision)!=null?hs:"approved",agentId:(bs=ae==null?void 0:ae.agentId)!=null?bs:"virtual",executionId:(vs=(ys=A.executionId)!=null?ys:ae==null?void 0:ae.executionId)!=null?vs:"",toolName:(Cn=A.toolName)!=null?Cn:"",description:(Gn=A.description)!=null?Gn:"",resolvedAt:Date.now()}};f(Z)}}else if(je==="artifact_start"||je==="artifact_delta"||je==="artifact_update"||je==="artifact_complete"){if(je==="artifact_start"){let U=A.artifactType,W=String(A.id),Z=typeof A.title=="string"?A.title:void 0;if(n({type:"artifact_start",id:W,artifactType:U,title:Z,component:typeof A.component=="string"?A.component:void 0}),xe.set(W,{markdown:"",title:Z}),!Y.has(W)){Y.add(W);let G={id:`artifact-ref-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:W,title:Z,artifactType:U,status:"streaming"}})};Le.set(W,G),f(G)}}else if(je==="artifact_delta"){let U=String(A.id),W=typeof A.delta=="string"?A.delta:String((Fo=A.delta)!=null?Fo:"");n({type:"artifact_delta",id:U,artDelta:W});let Z=xe.get(U);Z&&(Z.markdown+=W)}else if(je==="artifact_update"){let U=A.props&&typeof A.props=="object"&&!Array.isArray(A.props)?A.props:{};n({type:"artifact_update",id:String(A.id),props:U,component:typeof A.component=="string"?A.component:void 0})}else if(je==="artifact_complete"){let U=String(A.id);n({type:"artifact_complete",id:U});let W=Le.get(U);if(W){W.streaming=!1;try{let Z=JSON.parse((rt=W.rawContent)!=null?rt:"{}");if(Z.props){Z.props.status="complete";let G=xe.get(U);G!=null&&G.markdown&&(Z.props.markdown=G.markdown)}W.rawContent=JSON.stringify(Z)}catch{}xe.delete(U),f(W),Le.delete(U)}}}else if(je==="transcript_insert"){let U=A.message;if(!U||typeof U!="object")continue;let W=String((xs=U.id)!=null?xs:`msg-${l()}`),Z=U.role,X={id:W,role:Z==="user"?"user":Z==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:l()};if(f(X),X.rawContent)try{let Xe=JSON.parse(X.rawContent),Ne=(ur=Xe==null?void 0:Xe.props)==null?void 0:ur.artifactId;typeof Ne=="string"&&Y.add(Ne)}catch{}u=null,C.current=null,ne.delete(W),re.delete(W)}else if(je==="error"||je==="step_error"||je==="dispatch_error"||je==="flow_error"){let U=null;if(A.error instanceof Error)U=A.error;else if(je==="dispatch_error"){let W=(bo=A.message)!=null?bo:A.error;W!=null&&W!==""&&(U=new Error(String(W)))}else if(je==="step_error"||je==="flow_error"){let W=A.error;typeof W=="string"&&W!==""?U=new Error(W):W!=null&&typeof W=="object"&&"message"in W&&(U=new Error(String((va=W.message)!=null?va:W)))}else je==="error"&&A.error!=null&&A.error!==""&&(U=new Error(String(A.error)));if(U){n({type:"error",error:U});let W=u;W&&W.streaming&&(W.streaming=!1,f(W)),n({type:"status",status:"idle"})}}}}}ce.length=0};;){let{done:_,value:ke}=await r.read();if(_)break;a+=s.decode(ke,{stream:!0});let He=a.split(`
|
|
9
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Cr=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},ku=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Eu=()=>{var t;let e=Kg();return{processChunk:async n=>{let o=n.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},Mu=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=$g(n,Ug|zg);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Su(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Su(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var Lu=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Ya=class{constructor(t,n=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=n}push(t,n){var s,a,i;let o=(i=(s=n==null?void 0:n.seq)!=null?s:n==null?void 0:n.sequenceIndex)!=null?i:(a=n==null?void 0:n.agentContext)==null?void 0:a.seq;if(o==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,n);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),o===this.nextExpectedSeq){this.emitter(t,n),this.nextExpectedSeq=o+1,this.drainConsecutive();return}if(o<this.nextExpectedSeq){this.emitter(t,n);return}let r=this.buffer.get(o);r!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${o} (${r.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(r.payloadType,r.payload)),this.buffer.set(o,{payloadType:t,payload:n,seq:o}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((n,o)=>n[0]-o[0]);for(let[n,o]of t)this.buffer.delete(n),this.emitter(o.payloadType,o.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Gg="https://api.runtype.com/v1/dispatch",Xa="https://api.runtype.com";function Yg(e){var s,a;let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let i=(a=(s=t.slice(r+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var ll=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Xg(e){switch(e){case"json":return Mu;case"regex-json":return Eu;case"xml":return Lu;default:return ku}}var Iu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Qg(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=Iu(n);if(!Iu(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Cr(e);return Cr(t)!==null&&a===null?t:e}var Ws=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,o,r,s;this.apiUrl=(n=t.apiUrl)!=null?n:Gg,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:Xg(t.parserType),this.contextProviders=(r=t.contextProviders)!=null?r:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new qa(t.webmcp):null}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Xa}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let o=await this.sessionInitPromise;return this.clientSession=o,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,o),o}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let t=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},o=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){let i=await o.json().catch(()=>({error:"Session initialization failed"}));throw o.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):o.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let r=await o.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(r.sessionId),{sessionId:r.sessionId,expiresAt:new Date(r.expiresAt),flow:r.flow,config:{welcomeMessage:r.config.welcomeMessage,placeholder:r.config.placeholder,theme:r.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Xa}/v1/client/feedback`}async sendFeedback(t){var s,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var r,s,a,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(r=this.config).onSessionExpired)==null||s.call(r);let D=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:D}),D}let l=await this.buildPayload(t.messages),m=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([D])=>D!=="sessionId"&&D!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(ll).map(D=>{var W,v,x;return{id:D.id,role:D.role,content:(x=(v=(W=D.contentParts)!=null?W:D.llmContent)!=null?v:D.rawContent)!=null?x:D.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...m&&Object.keys(m).length>0&&{metadata:m},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},g=l.clientTools,p=!!(g&&g.length>0),w=p?Cu(g):void 0,S=this.clientToolsFingerprintSessionId===d.sessionId,M=p&&S&&this.lastSentClientToolsFingerprint===w,I=!1,L=null,H;for(let D=0;;D++){let v={...u,...p&&(I||!M)&&g?{clientTools:g}:{},...w?{clientToolsFingerprint:w}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",v),H=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v),signal:o.signal}),H.status===409&&D===0&&p){let x=await H.json().catch(()=>null);if((x==null?void 0:x.error)==="client_tools_resend_required"){I=!0,this.lastSentClientToolsFingerprint=null;continue}L=x!=null?x:{error:"Chat request failed"}}break}if(!H.ok){let D=L!=null?L:await H.json().catch(()=>({error:"Chat request failed"}));if(H.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let v=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:v}),v}if(H.status===429){let v=new Error(D.hint||"Message limit reached for this session.");throw n({type:"error",error:v}),v}let W=new Error(D.error||"Failed to send message");throw n({type:"error",error:W}),W}if(!H.body){let D=new Error("No response body received");throw n({type:"error",error:D}),D}this.lastSentClientToolsFingerprint=w!=null?w:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(H.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let r=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Xa}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,o){var l,m;let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Xa}/resume`,a;r&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(m=o==null?void 0:o.streamResponse)!=null?m:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var s;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(ll).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),o={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},r=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(r&&r.length>0&&(o.clientTools=r),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(o.context=a)}return o}async buildPayload(t){var s;let o={messages:t.slice().filter(ll).sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},r=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(r&&r.length>0&&(o.clientTools=r),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(o.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...o},config:this.config});if(a&&typeof a=="object"){let i=a;return o.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=o.clientTools),i}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return o}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=m=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...m!==void 0&&{partId:m}};return o.current=u,r(u),u},l=m=>o.current?o.current:d(m);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let m=l(i.partId);i.partId!==void 0&&!m.partId&&(m.partId=i.partId),m.content+=i.text,r(m)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o){var ln,Dn,Jn,qe;let r=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,m=_=>{let ke=_.reasoning?{..._.reasoning,chunks:[..._.reasoning.chunks]}:void 0,De=_.toolCall?{..._.toolCall,chunks:_.toolCall.chunks?[..._.toolCall.chunks]:void 0}:void 0,Fe=_.tools?_.tools.map($e=>({...$e,chunks:$e.chunks?[...$e.chunks]:void 0})):void 0;return{..._,reasoning:ke,toolCall:De,tools:Fe}},u=_=>{if(_.role!=="assistant"||_.variant)return!0;let ke=Array.isArray(_.contentParts)&&_.contentParts.length>0,De=typeof _.rawContent=="string"&&_.rawContent.trim()!=="";return typeof _.content=="string"&&_.content.trim()!==""||ke||De||!!_.stopReason},g=_=>{u(_)&&n({type:"message",message:m(_)})},p=null,w=null,S={current:null},M={current:null},I=!1,L=new Map,H=new Map,D=new Map,W=new Map,v={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},k=(_,ke,De="")=>`${_}::${ke}::${De}`,C=(_,ke)=>`${_}::${ke}::`,T=(_,ke,De,Fe)=>{let $e=k(_,ke,De),dt=D.get($e);if(dt)return dt;let ot=De?`-${De}`:"",At={id:`nested-${_}-${ke}${ot}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...De?{partId:De}:{},agentMetadata:{executionId:Fe,parentToolId:_,parentStepId:ke}};return D.set($e,At),g(At),At},F=_=>{if(_==null)return null;try{return String(_)}catch{return null}},$=_=>{var ke,De,Fe,$e,dt;return F((dt=($e=(Fe=(De=(ke=_.stepId)!=null?ke:_.step_id)!=null?De:_.step)!=null?Fe:_.parentId)!=null?$e:_.flowStepId)!=null?dt:_.flow_step_id)},j=_=>{var ke,De,Fe,$e,dt,ot,At;return F((At=(ot=(dt=($e=(Fe=(De=(ke=_.callId)!=null?ke:_.call_id)!=null?De:_.requestId)!=null?Fe:_.request_id)!=null?$e:_.toolCallId)!=null?dt:_.tool_call_id)!=null?ot:_.stepId)!=null?At:_.step_id)},me=o,se=!1,fe=()=>{if(p)return p;let _;return!se&&me?(_=me,se=!0):me&&M.current?_=`${me}_${M.current}`:_=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,p={id:_,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},g(p),p},ie=(_,ke)=>{v.lastId=ke,_&&v.byStep.set(_,ke)},be=(_,ke)=>{var dt;let De=(dt=_.reasoningId)!=null?dt:_.id,Fe=$(_);if(De){let ot=String(De);return ie(Fe,ot),ot}if(Fe){let ot=v.byStep.get(Fe);if(ot)return v.lastId=ot,ot}if(v.lastId&&!ke)return v.lastId;if(!ke)return null;let $e=`reason-${l()}`;return ie(Fe,$e),$e},Oe=_=>{let ke=L.get(_);if(ke)return ke;let De={id:`reason-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:_,status:"streaming",chunks:[]}};return L.set(_,De),g(De),De},ve=(_,ke)=>{x.lastId=ke,_&&x.byCall.set(_,ke)},Q=new Set,Le=new Map,Y=new Set,xe=new Map,Se=_=>{if(!_)return!1;let ke=_.replace(/_+/g,"_").replace(/^_|_$/g,"");return ke==="emit_artifact_markdown"||ke==="emit_artifact_component"},de=(_,ke)=>{var dt;let De=(dt=_.toolId)!=null?dt:_.id,Fe=j(_);if(De){let ot=String(De);return ve(Fe,ot),ot}if(Fe){let ot=x.byCall.get(Fe);if(ot)return x.lastId=ot,ot}if(x.lastId&&!ke)return x.lastId;if(!ke)return null;let $e=`tool-${l()}`;return ve(Fe,$e),$e},we=_=>{let ke=H.get(_);if(ke)return ke;let De={id:`tool-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:_,status:"pending"}};return H.set(_,De),g(De),De},ze=_=>{if(typeof _=="number"&&Number.isFinite(_))return _;if(typeof _=="string"){let ke=Number(_);if(!Number.isNaN(ke)&&Number.isFinite(ke))return ke;let De=Date.parse(_);if(!Number.isNaN(De))return De}return Date.now()},te=_=>{if(typeof _=="string")return _;if(_==null)return"";try{return JSON.stringify(_)}catch{return String(_)}},ne=new Map,re=new Map,nt=new Map,ye=new Map,le=null,Ue=(_,ke,De)=>{var At;let Fe=nt.get(_);Fe||(Fe=[],nt.set(_,Fe));let $e=0,dt=Fe.length;for(;$e<dt;){let Vt=$e+dt>>>1;Fe[Vt].seq<ke?$e=Vt+1:dt=Vt}((At=Fe[$e])==null?void 0:At.seq)===ke?Fe[$e]={seq:ke,text:De}:Fe.splice($e,0,{seq:ke,text:De});let ot="";for(let Vt=0;Vt<Fe.length;Vt++)ot+=Fe[Vt].text;return ot},He=(_,ke)=>{let De=te(ke),Fe=re.get(_.id),$e=Qg(Fe,De);_.rawContent=$e;let dt=ne.get(_.id),ot=Qe=>{var oe;let Ft=(oe=_.content)!=null?oe:"";Qe.trim()!==""&&(Ft.trim().length===0||Qe.startsWith(Ft)||Qe.trimStart().startsWith(Ft.trim()))&&(_.content=Qe)},At=()=>{var Qe;if(dt){let Ft=(Qe=dt.close)==null?void 0:Qe.call(dt);Ft instanceof Promise&&Ft.catch(()=>{})}ne.delete(_.id),re.delete(_.id),_.streaming=!1,g(_)};if(!dt){ot(De),At();return}let Vt=Cr($e);if(Vt!==null&&Vt.trim()!==""){ot(Vt),At();return}let q=Qe=>{var ge;let Ft=typeof Qe=="string"?Qe:(ge=Qe==null?void 0:Qe.text)!=null?ge:null;if(Ft!==null&&Ft.trim()!=="")return Ft;let oe=dt.getExtractedText();return oe!==null&&oe.trim()!==""?oe:De},_t;try{_t=dt.processChunk($e)}catch{ot(De),At();return}if(_t instanceof Promise){_t.then(Qe=>{ot(q(Qe)),At()}).catch(()=>{ot(De),At()});return}ot(q(_t)),At()},ce=[],G=!1,Ve,Et=()=>{G||(G=!0,queueMicrotask(()=>{G=!1,Ve()}))},pe=new Ya((_,ke)=>{ce.push({payloadType:_,payload:ke}),Et()}),ae=null,Ln=new Map,Nt=(ln=this.config.iterationDisplay)!=null?ln:"separate";for(Ve=()=>{var _,ke,De,Fe,$e,dt,ot,At,Vt,q,_t,Qe,Ft,oe,ge,xt,$t,Jt,yn,Tt,wt,gt,bt,zt,et,Fn,Zn,vn,On,ut,wo,Nn,ir,In,Rr,$o,Lo,yt,_n,Vn,xn,It,eo,to,$n,Uo,Io,zo,Un,Wt,wn,no,qo,Ro,jo,Co,zn,po,ft,Kt,Gt,qn,Ko,oo,uo,jn,E,Kn,mo,Po,So,as,fo,go,ho,Wo,lr,aa,is,ia,Pr,mt,ls,ro,Rn,la,ca,Wr,Bo,da,cr,cs,Ho,ds,Go,Yo,pa,ua,zi,dr,Xo,ma,ps,Qo,fa,us,Jo,ms,ga,Do,ha,Zo,Bt,Br,Hr,fs,Ao,ba,gs,hs,ya,Dr,Fr,pr,va,xa,bs,ys,vs,xs,Cn,Gn,Fo,rt,ws,ur,bo,wa;for(let er=0;er<ce.length;er++){let Ke=ce[er].payloadType,A=ce[er].payload;if(Ke==="reason_start"){let U=(_=be(A,!0))!=null?_:`reason-${l()}`,B=Oe(U);B.reasoning=(ke=B.reasoning)!=null?ke:{id:U,status:"streaming",chunks:[]},B.reasoning.startedAt=(Fe=B.reasoning.startedAt)!=null?Fe:ze((De=A.startedAt)!=null?De:A.timestamp),B.reasoning.completedAt=void 0,B.reasoning.durationMs=void 0,B.streaming=!0,B.reasoning.status="streaming",g(B)}else if(Ke==="reason_delta"||Ke==="reason_chunk"){let U=(dt=($e=be(A,!1))!=null?$e:be(A,!0))!=null?dt:`reason-${l()}`,B=Oe(U);B.reasoning=(ot=B.reasoning)!=null?ot:{id:U,status:"streaming",chunks:[]},B.reasoning.startedAt=(Vt=B.reasoning.startedAt)!=null?Vt:ze((At=A.startedAt)!=null?At:A.timestamp);let J=(Qe=(_t=(q=A.reasoningText)!=null?q:A.text)!=null?_t:A.delta)!=null?Qe:"";if(J&&A.hidden!==!0){let ee=typeof A.sequenceIndex=="number"?A.sequenceIndex:void 0;if(ee!==void 0){let K=Ue(U,ee,String(J));B.reasoning.chunks=[K]}else B.reasoning.chunks.push(String(J))}if(B.reasoning.status=A.done?"complete":"streaming",A.done){B.reasoning.completedAt=ze((Ft=A.completedAt)!=null?Ft:A.timestamp);let ee=(oe=B.reasoning.startedAt)!=null?oe:Date.now();B.reasoning.durationMs=Math.max(0,((ge=B.reasoning.completedAt)!=null?ge:Date.now())-ee)}B.streaming=B.reasoning.status!=="complete",g(B)}else if(Ke==="reason_complete"){let U=($t=(xt=be(A,!1))!=null?xt:be(A,!0))!=null?$t:`reason-${l()}`,B=L.get(U);if(B!=null&&B.reasoning){B.reasoning.status="complete",B.reasoning.completedAt=ze((Jt=A.completedAt)!=null?Jt:A.timestamp);let ee=(yn=B.reasoning.startedAt)!=null?yn:Date.now();B.reasoning.durationMs=Math.max(0,((Tt=B.reasoning.completedAt)!=null?Tt:Date.now())-ee),B.streaming=!1,g(B)}let J=$(A);J&&v.byStep.delete(J)}else if(Ke==="tool_start"){let U=(wt=de(A,!0))!=null?wt:`tool-${l()}`,B=(gt=A.toolName)!=null?gt:A.name;if(Se(B)){Q.add(U);continue}let J=we(U),ee=(bt=J.toolCall)!=null?bt:{id:U,status:"pending"};ee.name=B!=null?B:ee.name,ee.status="running",A.args!==void 0?ee.args=A.args:A.parameters!==void 0&&(ee.args=A.parameters),ee.startedAt=(et=ee.startedAt)!=null?et:ze((zt=A.startedAt)!=null?zt:A.timestamp),ee.completedAt=void 0,ee.durationMs=void 0,J.toolCall=ee,J.streaming=!0;let K=A.agentContext;(K||A.executionId)&&(J.agentMetadata={executionId:(Fn=K==null?void 0:K.executionId)!=null?Fn:A.executionId,iteration:(Zn=K==null?void 0:K.iteration)!=null?Zn:A.iteration}),g(J)}else if(Ke==="tool_chunk"||Ke==="tool_delta"){let U=(On=(vn=de(A,!1))!=null?vn:de(A,!0))!=null?On:`tool-${l()}`;if(Q.has(U))continue;let B=we(U),J=(ut=B.toolCall)!=null?ut:{id:U,status:"running"};J.startedAt=(Nn=J.startedAt)!=null?Nn:ze((wo=A.startedAt)!=null?wo:A.timestamp);let ee=(Rr=(In=(ir=A.text)!=null?ir:A.delta)!=null?In:A.message)!=null?Rr:"";ee&&(J.chunks=($o=J.chunks)!=null?$o:[],J.chunks.push(String(ee))),J.status="running",B.toolCall=J,B.streaming=!0;let K=A.agentContext;(K||A.executionId)&&(B.agentMetadata=(_n=B.agentMetadata)!=null?_n:{executionId:(Lo=K==null?void 0:K.executionId)!=null?Lo:A.executionId,iteration:(yt=K==null?void 0:K.iteration)!=null?yt:A.iteration}),g(B)}else if(Ke==="tool_complete"){let U=(xn=(Vn=de(A,!1))!=null?Vn:de(A,!0))!=null?xn:`tool-${l()}`;if(Q.has(U)){Q.delete(U);continue}let B=we(U),J=(It=B.toolCall)!=null?It:{id:U,status:"running"};J.status="complete",A.result!==void 0&&(J.result=A.result),typeof A.duration=="number"&&(J.duration=A.duration),J.completedAt=ze((eo=A.completedAt)!=null?eo:A.timestamp);let ee=(to=A.duration)!=null?to:A.executionTime;if(typeof ee=="number")J.durationMs=ee;else{let _e=($n=J.startedAt)!=null?$n:Date.now();J.durationMs=Math.max(0,((Uo=J.completedAt)!=null?Uo:Date.now())-_e)}B.toolCall=J,B.streaming=!1;let K=A.agentContext;(K||A.executionId)&&(B.agentMetadata=(Un=B.agentMetadata)!=null?Un:{executionId:(Io=K==null?void 0:K.executionId)!=null?Io:A.executionId,iteration:(zo=K==null?void 0:K.iteration)!=null?zo:A.iteration}),g(B);let We=j(A);We&&x.byCall.delete(We)}else if(Ke==="step_await"&&A.awaitReason==="local_tool_required"&&A.toolName){let U=typeof A.toolCallId=="string"&&A.toolCallId.length>0?A.toolCallId:void 0,B=(Wt=U!=null?U:A.toolId)!=null?Wt:`local-${l()}`,J=we(B),ee=A.toolName,K=qr(ee),We=(wn=J.toolCall)!=null?wn:{id:B,status:"pending"};We.name=ee,We.args=A.parameters,We.status=K?"running":"complete",We.chunks=(no=We.chunks)!=null?no:[],We.startedAt=(Ro=We.startedAt)!=null?Ro:ze((qo=A.startedAt)!=null?qo:A.timestamp),K?(We.completedAt=void 0,We.duration=void 0,We.durationMs=void 0):We.completedAt=(jo=We.completedAt)!=null?jo:We.startedAt,J.toolCall=We,J.streaming=!1,J.agentMetadata={...J.agentMetadata,executionId:(zn=A.executionId)!=null?zn:(Co=J.agentMetadata)==null?void 0:Co.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},g(J)}else if(Ke==="text_start"){if((po=A.toolContext)!=null&&po.toolId)continue;let U=A.partId;if(U!==void 0&&M.current!==null&&U!==M.current){let B=p;B&&(B.streaming=!1,g(B),le=B,p=null,I=!0)}U!==void 0&&(M.current=U)}else if(Ke==="text_end"){if((ft=A.toolContext)!=null&&ft.toolId)continue;let U=p;U&&(U.streaming=!1,g(U),le=U,p=null,I=!0)}else if(Ke==="step_chunk"||Ke==="step_delta"){let U=A.stepType,B=A.executionType;if(U==="tool"||B==="context")continue;let J=A.toolContext;if(J!=null&&J.toolId){let _e=String((Gt=(Kt=A.id)!=null?Kt:J.stepId)!=null?Gt:`step-${l()}`),Ze=A.partId!==void 0&&A.partId!==null?String(A.partId):"",Ie=`${J.toolId}::${_e}`,Ye=W.get(Ie);if(Ze!==""&&Ye!==void 0&&Ye!==""&&Ye!==Ze){let Ct=D.get(k(J.toolId,_e,Ye));Ct&&Ct.streaming!==!1&&(Ct.streaming=!1,g(Ct))}Ze!==""&&W.set(Ie,Ze);let Rt=T(J.toolId,_e,Ze,J.executionId),nn=(uo=(oo=(Ko=(qn=A.text)!=null?qn:A.delta)!=null?Ko:A.content)!=null?oo:A.chunk)!=null?uo:"";nn&&(Rt.content+=String(nn),Rt.streaming=!0,g(Rt)),A.isComplete&&(Rt.streaming=!1,g(Rt));continue}let ee=A.partId;if(ee!==void 0&&M.current!==null&&ee!==M.current){let _e=p;_e&&(_e.streaming=!1,g(_e),le=_e,p=null,I=!0)}ee!==void 0&&(M.current=ee);let K=ee!==void 0&&(jn=ye.get(ee))!=null?jn:fe();ee!==void 0&&(K.partId||(K.partId=ee),ye.set(ee,K));let We=(Po=(mo=(Kn=(E=A.text)!=null?E:A.delta)!=null?Kn:A.content)!=null?mo:A.chunk)!=null?Po:"";if(We){let _e=typeof A.seq=="number"?A.seq:void 0,Ze=ee!=null?ee:K.id,Ie=_e!==void 0?Ue(Ze,_e,String(We)):((So=re.get(K.id))!=null?So:"")+We;K.rawContent=Ie,ne.has(K.id)||ne.set(K.id,this.createStreamParser());let Ye=ne.get(K.id),Rt=Ie.trim().startsWith("{")||Ie.trim().startsWith("[");if(Rt&&re.set(K.id,Ie),Ye.__isPlainTextParser===!0){K.content=_e!==void 0?Ie:K.content+We,re.delete(K.id),ne.delete(K.id),K.rawContent=void 0,g(K);continue}let Ct=Ye.processChunk(Ie);if(Ct instanceof Promise)Ct.then(Mt=>{var un;let on=typeof Mt=="string"?Mt:(un=Mt==null?void 0:Mt.text)!=null?un:null;if(on!==null&&on.trim()!=="")K.content=on,g(K);else if(!Rt&&!Ie.trim().startsWith("<")){let Sn=p,Yt=Sn&&Sn.id===K.id?Sn:K;Yt.id===K.id&&(Yt.content=_e!==void 0?Ie:Yt.content+We,re.delete(Yt.id),ne.delete(Yt.id),Yt.rawContent=void 0,g(Yt))}}).catch(()=>{K.content=_e!==void 0?Ie:K.content+We,re.delete(K.id),ne.delete(K.id),K.rawContent=void 0,g(K)});else{let Mt=typeof Ct=="string"?Ct:(as=Ct==null?void 0:Ct.text)!=null?as:null;Mt!==null&&Mt.trim()!==""?(K.content=Mt,g(K)):!Rt&&!Ie.trim().startsWith("<")&&(K.content=_e!==void 0?Ie:K.content+We,re.delete(K.id),ne.delete(K.id),K.rawContent=void 0,g(K))}}if(A.isComplete){let _e=(go=(fo=A.result)==null?void 0:fo.response)!=null?go:K.content;if(_e){let Ze=re.get(K.id),Ie=Ze!=null?Ze:te(_e);K.rawContent=Ie;let Ye=ne.get(K.id),Rt=null,nn=!1;if(Ye&&(Rt=Ye.getExtractedText(),Rt===null&&(Rt=Cr(Ie)),Rt===null)){let Ct=Ye.processChunk(Ie);Ct instanceof Promise?(nn=!0,Ct.then(Mt=>{var un;let on=typeof Mt=="string"?Mt:(un=Mt==null?void 0:Mt.text)!=null?un:null;if(on!==null){let Sn=p;Sn&&Sn.id===K.id&&(Sn.content=on,Sn.streaming=!1,ne.delete(Sn.id),re.delete(Sn.id),g(Sn))}})):Rt=typeof Ct=="string"?Ct:(ho=Ct==null?void 0:Ct.text)!=null?ho:null}if(!nn){Rt!==null&&Rt.trim()!==""?K.content=Rt:re.has(K.id)||(K.content=te(_e));let Ct=ne.get(K.id);if(Ct){let Mt=(Wo=Ct.close)==null?void 0:Wo.call(Ct);Mt instanceof Promise&&Mt.catch(()=>{}),ne.delete(K.id)}re.delete(K.id),K.streaming=!1,g(K)}}}}else if(Ke==="step_complete"){let U=A.stepType,B=A.executionType;if(U==="tool"||B==="context")continue;let J=A.toolContext;if(J!=null&&J.toolId){let _e=String((aa=(lr=A.id)!=null?lr:J.stepId)!=null?aa:"");if(_e){let Ze=C(J.toolId,_e);for(let[Ie,Ye]of D)Ie.startsWith(Ze)&&Ye.streaming!==!1&&(Ye.streaming=!1,g(Ye));W.delete(`${J.toolId}::${_e}`)}continue}let ee=A.stopReason;if(I){if(p!==null){let Ie=p;ee&&(Ie.stopReason=ee),ne.delete(Ie.id),re.delete(Ie.id),Ie.streaming!==!1&&(Ie.streaming=!1,g(Ie))}let _e=(is=A.result)==null?void 0:is.response,Ze=le;Ze&&(ee&&(Ze.stopReason=ee),_e!=null?He(Ze,_e):(ne.delete(Ze.id),re.delete(Ze.id))),le=null;continue}let K=(ia=A.result)==null?void 0:ia.response,We=fe();if(ee&&(We.stopReason=ee),K!=null){let _e=ne.get(We.id),Ze=!1,Ie=!1;if(_e){let Ye=_e.getExtractedText(),Rt=re.get(We.id),nn=Rt!=null?Rt:te(K);if(We.rawContent=nn,Ye!==null&&Ye.trim()!=="")We.content=Ye,Ze=!0;else{let Ct=Cr(nn);if(Ct!==null)We.content=Ct,Ze=!0;else{let Mt=_e.processChunk(nn);if(Mt instanceof Promise)Ie=!0,Mt.then(on=>{var Sn;let un=typeof on=="string"?on:(Sn=on==null?void 0:on.text)!=null?Sn:null;if(un!==null&&un.trim()!==""){let Yt=p;Yt&&Yt.id===We.id&&(Yt.content=un,Yt.streaming=!1,ne.delete(Yt.id),re.delete(Yt.id),g(Yt))}else{let Yt=_e.getExtractedText(),so=p;so&&so.id===We.id&&(Yt!==null&&Yt.trim()!==""?so.content=Yt:re.has(so.id)||(so.content=te(K)),so.streaming=!1,ne.delete(so.id),re.delete(so.id),g(so))}});else{let on=typeof Mt=="string"?Mt:(Pr=Mt==null?void 0:Mt.text)!=null?Pr:null;if(on!==null&&on.trim()!=="")We.content=on,Ze=!0;else{let un=_e.getExtractedText();un!==null&&un.trim()!==""&&(We.content=un,Ze=!0)}}}}}if(!Ie){if(!We.rawContent){let Ye=re.get(We.id);We.rawContent=Ye!=null?Ye:te(K)}if(!Ze&&!re.has(We.id)&&(We.content=te(K)),_e){let Ye=(mt=_e.close)==null?void 0:mt.call(_e);Ye instanceof Promise&&Ye.catch(()=>{})}ne.delete(We.id),re.delete(We.id),We.streaming=!1,g(We)}}else ne.delete(We.id),re.delete(We.id),We.streaming=!1,g(We)}else if(Ke==="flow_complete"){let U=(ls=A.result)==null?void 0:ls.response;if(I){if(p!==null){let B=p;ne.delete(B.id),re.delete(B.id),B.streaming!==!1&&(B.streaming=!1,g(B))}}else if(U!=null){let B=fe(),J=re.get(B.id),ee=J!=null?J:te(U);B.rawContent=ee;let K=te(U),We=ne.get(B.id);if(We){let Ie=Cr(ee);if(Ie!==null)K=Ie;else{let Ye=We.processChunk(ee);Ye instanceof Promise&&Ye.then(nn=>{var Mt;let Ct=typeof nn=="string"?nn:(Mt=nn==null?void 0:nn.text)!=null?Mt:null;Ct!==null&&(B.content=Ct,B.streaming=!1,g(B))});let Rt=We.getExtractedText();Rt!==null&&(K=Rt)}}ne.delete(B.id),re.delete(B.id);let _e=K!==B.content,Ze=B.streaming!==!1;_e&&(B.content=K),B.streaming=!1,(_e||Ze)&&g(B)}else if(p!==null){let B=p;ne.delete(B.id),re.delete(B.id),B.streaming!==!1&&(B.streaming=!1,g(B))}n({type:"status",status:"idle"})}else if(Ke==="agent_start")ae={executionId:A.executionId,agentId:(ro=A.agentId)!=null?ro:"virtual",agentName:(Rn=A.agentName)!=null?Rn:"",status:"running",currentIteration:0,maxTurns:(la=A.maxTurns)!=null?la:1,startedAt:ze(A.startedAt)};else if(Ke==="agent_iteration_start"){if(ae&&(ae.currentIteration=A.iteration),Nt==="separate"&&A.iteration>1){let U=p;U&&(U.streaming=!1,g(U),Ln.set(A.iteration-1,U),p=null)}}else if(Ke==="agent_turn_start")w=null;else if(Ke==="agent_turn_delta"){if(A.contentType==="text"){let U=fe();U.content+=(ca=A.delta)!=null?ca:"",U.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId,agentName:ae==null?void 0:ae.agentName},w=U,g(U)}else if(A.contentType==="thinking"){let U=(Wr=A.turnId)!=null?Wr:`agent-think-${A.iteration}`,B=Oe(U);B.reasoning=(Bo=B.reasoning)!=null?Bo:{id:U,status:"streaming",chunks:[]},B.reasoning.chunks.push((da=A.delta)!=null?da:""),B.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId},g(B)}else if(A.contentType==="tool_input"){let U=(cr=A.toolCallId)!=null?cr:x.lastId;if(U){let B=H.get(U);B!=null&&B.toolCall&&(B.toolCall.chunks=(cs=B.toolCall.chunks)!=null?cs:[],B.toolCall.chunks.push((Ho=A.delta)!=null?Ho:""),g(B))}}}else if(Ke==="agent_turn_complete"){let U=A.turnId;if(U){let ee=L.get(U);if(ee!=null&&ee.reasoning){ee.reasoning.status="complete",ee.reasoning.completedAt=ze(A.completedAt);let K=(ds=ee.reasoning.startedAt)!=null?ds:Date.now();ee.reasoning.durationMs=Math.max(0,((Go=ee.reasoning.completedAt)!=null?Go:Date.now())-K),ee.streaming=!1,g(ee)}}let B=A.stopReason,J=p!=null?p:w;if(B&&J!==null){let ee=A.turnId;(!ee||((Yo=J.agentMetadata)==null?void 0:Yo.turnId)===ee)&&(J.stopReason=B,g(J))}}else if(Ke==="agent_tool_start"){p&&(p.streaming=!1,g(p),p=null);let U=(pa=A.toolCallId)!=null?pa:`agent-tool-${l()}`;ve(j(A),U);let B=we(U),J=(ua=B.toolCall)!=null?ua:{id:U,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};J.name=(dr=(zi=A.toolName)!=null?zi:A.name)!=null?dr:J.name,J.status="running",A.parameters!==void 0&&(J.args=A.parameters),J.startedAt=ze((Xo=A.startedAt)!=null?Xo:A.timestamp),B.toolCall=J,B.streaming=!0,B.agentMetadata={executionId:A.executionId,iteration:A.iteration},g(B)}else if(Ke==="agent_tool_delta"){let U=(ma=A.toolCallId)!=null?ma:x.lastId;if(U){let B=(ps=H.get(U))!=null?ps:we(U);B.toolCall&&(B.toolCall.chunks=(Qo=B.toolCall.chunks)!=null?Qo:[],B.toolCall.chunks.push((fa=A.delta)!=null?fa:""),B.toolCall.status="running",B.streaming=!0,g(B))}}else if(Ke==="agent_tool_complete"){let U=(us=A.toolCallId)!=null?us:x.lastId;if(U){let B=(Jo=H.get(U))!=null?Jo:we(U);if(B.toolCall){B.toolCall.status="complete",A.result!==void 0&&(B.toolCall.result=A.result),typeof A.executionTime=="number"&&(B.toolCall.durationMs=A.executionTime),B.toolCall.completedAt=ze((ms=A.completedAt)!=null?ms:A.timestamp),B.streaming=!1,g(B);let J=j(A);J&&x.byCall.delete(J)}}}else if(Ke==="agent_media"){let U=Array.isArray(A.media)?A.media:[],B=[];for(let J of U){if(!J||typeof J!="object")continue;let ee=J,K=typeof ee.type=="string"?ee.type:void 0,We=typeof ee.mediaType=="string"?ee.mediaType.toLowerCase():"",_e=null,Ze="";if(K==="media"){let Ie=typeof ee.data=="string"?ee.data:void 0;if(!Ie)continue;Ze=We.length>0?We:"application/octet-stream",_e=`data:${Ze};base64,${Ie}`}else if(K==="image-url"){let Ie=typeof ee.url=="string"?ee.url:void 0;if(!Ie)continue;Ze=We,_e=Ie}else if(K==="file-url"){let Ie=typeof ee.url=="string"?ee.url:void 0;if(!Ie)continue;Ze=We,_e=Ie}else continue;if(_e)if(K==="image-url"||Ze.startsWith("image/"))B.push({type:"image",image:_e,...Ze?{mimeType:Ze}:{}});else if(Ze.startsWith("audio/"))B.push({type:"audio",audio:_e,mimeType:Ze});else if(Ze.startsWith("video/"))B.push({type:"video",video:_e,mimeType:Ze});else{let Ie=Ze||"application/octet-stream";B.push({type:"file",data:_e,mimeType:Ie,filename:Yg(Ie)})}}if(B.length>0){let J=l(),ee=A.toolCallId,We={id:`agent-media-${typeof ee=="string"&&ee.length>0?`${ee}-${J}`:String(J)}`,role:"assistant",content:"",contentParts:B,createdAt:new Date().toISOString(),streaming:!1,sequence:J,agentMetadata:{executionId:A.executionId,iteration:A.iteration}};g(We);let _e=p;_e&&(_e.streaming=!1,g(_e)),p=null,S.current=null}}else if(Ke!=="agent_iteration_complete"){if(Ke==="agent_reflection"||Ke==="agent_reflect"){let U=`agent-reflection-${A.executionId}-${A.iteration}`,B={id:U,role:"assistant",content:(ga=A.reflection)!=null?ga:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:U,status:"complete",chunks:[(Do=A.reflection)!=null?Do:""]},agentMetadata:{executionId:A.executionId,iteration:A.iteration}};g(B)}else if(Ke==="agent_complete"){ae&&(ae.status=A.success?"complete":"error",ae.completedAt=ze(A.completedAt),ae.stopReason=A.stopReason);let U=p;U&&(U.streaming=!1,g(U)),n({type:"status",status:"idle"})}else if(Ke==="agent_error"){let U=typeof A.error=="string"?A.error:(Zo=(ha=A.error)==null?void 0:ha.message)!=null?Zo:"Agent execution error";A.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",U):n({type:"error",error:new Error(U)})}else if(Ke!=="agent_ping"){if(Ke==="agent_approval_start"){let U=(Bt=A.approvalId)!=null?Bt:`approval-${l()}`,B={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(Br=ae==null?void 0:ae.agentId)!=null?Br:"virtual",executionId:(fs=(Hr=A.executionId)!=null?Hr:ae==null?void 0:ae.executionId)!=null?fs:"",toolName:(Ao=A.toolName)!=null?Ao:"",toolType:A.toolType,description:(gs=A.description)!=null?gs:`Execute ${(ba=A.toolName)!=null?ba:"tool"}`,parameters:A.parameters}};g(B)}else if(Ke==="step_await"&&A.awaitReason==="approval_required"){let U=(hs=A.approvalId)!=null?hs:`approval-${l()}`,B={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(ya=ae==null?void 0:ae.agentId)!=null?ya:"virtual",executionId:(Fr=(Dr=A.executionId)!=null?Dr:ae==null?void 0:ae.executionId)!=null?Fr:"",toolName:(pr=A.toolName)!=null?pr:"",toolType:A.toolType,description:(xa=A.description)!=null?xa:`Execute ${(va=A.toolName)!=null?va:"tool"}`,parameters:A.parameters}};g(B)}else if(Ke==="agent_approval_complete"){let U=A.approvalId;if(U){let J={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:(bs=A.decision)!=null?bs:"approved",agentId:(ys=ae==null?void 0:ae.agentId)!=null?ys:"virtual",executionId:(xs=(vs=A.executionId)!=null?vs:ae==null?void 0:ae.executionId)!=null?xs:"",toolName:(Cn=A.toolName)!=null?Cn:"",description:(Gn=A.description)!=null?Gn:"",resolvedAt:Date.now()}};g(J)}}else if(Ke==="artifact_start"||Ke==="artifact_delta"||Ke==="artifact_update"||Ke==="artifact_complete"){if(Ke==="artifact_start"){let U=A.artifactType,B=String(A.id),J=typeof A.title=="string"?A.title:void 0;if(n({type:"artifact_start",id:B,artifactType:U,title:J,component:typeof A.component=="string"?A.component:void 0}),xe.set(B,{markdown:"",title:J}),!Y.has(B)){Y.add(B);let ee={id:`artifact-ref-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:B,title:J,artifactType:U,status:"streaming"}})};Le.set(B,ee),g(ee)}}else if(Ke==="artifact_delta"){let U=String(A.id),B=typeof A.delta=="string"?A.delta:String((Fo=A.delta)!=null?Fo:"");n({type:"artifact_delta",id:U,artDelta:B});let J=xe.get(U);J&&(J.markdown+=B)}else if(Ke==="artifact_update"){let U=A.props&&typeof A.props=="object"&&!Array.isArray(A.props)?A.props:{};n({type:"artifact_update",id:String(A.id),props:U,component:typeof A.component=="string"?A.component:void 0})}else if(Ke==="artifact_complete"){let U=String(A.id);n({type:"artifact_complete",id:U});let B=Le.get(U);if(B){B.streaming=!1;try{let J=JSON.parse((rt=B.rawContent)!=null?rt:"{}");if(J.props){J.props.status="complete";let ee=xe.get(U);ee!=null&&ee.markdown&&(J.props.markdown=ee.markdown)}B.rawContent=JSON.stringify(J)}catch{}xe.delete(U),g(B),Le.delete(U)}}}else if(Ke==="transcript_insert"){let U=A.message;if(!U||typeof U!="object")continue;let B=String((ws=U.id)!=null?ws:`msg-${l()}`),J=U.role,K={id:B,role:J==="user"?"user":J==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:l()};if(g(K),K.rawContent)try{let We=JSON.parse(K.rawContent),_e=(ur=We==null?void 0:We.props)==null?void 0:ur.artifactId;typeof _e=="string"&&Y.add(_e)}catch{}p=null,S.current=null,ne.delete(B),re.delete(B)}else if(Ke==="error"||Ke==="step_error"||Ke==="dispatch_error"||Ke==="flow_error"){let U=null;if(A.error instanceof Error)U=A.error;else if(Ke==="dispatch_error"){let B=(bo=A.message)!=null?bo:A.error;B!=null&&B!==""&&(U=new Error(String(B)))}else if(Ke==="step_error"||Ke==="flow_error"){let B=A.error;typeof B=="string"&&B!==""?U=new Error(B):B!=null&&typeof B=="object"&&"message"in B&&(U=new Error(String((wa=B.message)!=null?wa:B)))}else Ke==="error"&&A.error!=null&&A.error!==""&&(U=new Error(String(A.error)));if(U){n({type:"error",error:U});let B=p;B&&B.streaming&&(B.streaming=!1,g(B)),n({type:"status",status:"idle"})}}}}}ce.length=0};;){let{done:_,value:ke}=await r.read();if(_)break;a+=s.decode(ke,{stream:!0});let De=a.split(`
|
|
10
10
|
|
|
11
|
-
`);a=(Dn=
|
|
12
|
-
`),dt="message",ot="";for(let q of Ve)q.startsWith("event:")?dt=q.replace("event:","").trim():q.startsWith("data:")&&(ot+=q.replace("data:","").trim());if(!ot)continue;let At;try{At=JSON.parse(ot)}catch(q){n({type:"error",error:q instanceof Error?q:new Error("Failed to parse chat stream payload")});continue}let Vt=dt!=="message"?dt:(Jn=At.type)!=null?Jn:"message";if((ze=this.onSSEEvent)==null||ze.call(this,Vt,At),this.parseSSEEvent){C.current=u;let q=await this.handleCustomSSEEvent(At,n,C,f,l,M);if(C.current&&C.current!==u&&(u=C.current),q)continue}pe.push(Vt,At),_e()}}pe.flushPending(),_e(),pe.destroy()}};function Ya(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Ws(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Xa="[Image]";function ll(e){return{type:"text",text:e}}var Iu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Xf=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],_o=[...Iu,...Xf];function Qf(e){return Iu.includes(e)||e.startsWith("image/")}function Qa(e){return Qf(e.type)}async function Ru(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Qa(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function Pu(e,t=_o,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Jf(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Wu(e,t){let n=Jf(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var Ja=class{constructor(t=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=t}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let d=new Uint8Array(this.remainder.length+t.length);d.set(this.remainder),d.set(t,this.remainder.length),n=d,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.ensureContext(),r=this.pcmToFloat32(n),s=o.createBuffer(1,r.length,this.sampleRate);s.getChannelData(0).set(r);let a=o.createBufferSource();a.buffer=s,a.connect(o.destination);let i=o.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=s.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=r.getInt16(s*2,!0);o[s]=a/32768}return o}};var Za=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,o,r,s){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(n),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let p=0;p<a.length;p++)i+=a[p]*a[p];let d=Math.sqrt(i/a.length);(o==="silence"?d<r.threshold:d>=r.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=r.duration&&(this.fired=!0,s()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Bs=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new Za;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,n,o;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let r=this.w;if(!r||!r.location)throw new Error("Window object or location not available");let s=r.location.protocol==="https:"?"wss:":"ws:",a=(t=this.config)==null?void 0:t.host,i=(n=this.config)==null?void 0:n.agentId,d=(o=this.config)==null?void 0:o.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let p=`${s}//${a}/ws/agents/${i}/voice?token=...`,m=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,u)=>{if(!this.ws)return u(new Error("WebSocket not created"));let w=!1,C=I=>{w||(w=!0,clearTimeout(M),u(new Error(I)))},M=setTimeout(()=>C("WebSocket connection timed out."+m),1e4);this.ws.addEventListener("open",()=>{w||(w=!0,clearTimeout(M),f())},{once:!0}),this.ws.addEventListener("error",()=>{C("WebSocket connection failed to "+p+"."+m)},{once:!0}),this.ws.addEventListener("close",I=>{if(!I.wasClean&&!w){let R=I.code!==1006?` (code ${I.code})`:"";C("WebSocket connection failed"+R+"."+m)}},{once:!0})}),this.sendHeartbeat()}catch(r){throw this.ws=null,this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(n=>n(new Error("WebSocket error"))),this.statusCallbacks.forEach(n=>n("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let n=JSON.parse(t.data);this.handleWebSocketMessage(n)}catch{this.errorCallbacks.forEach(o=>o(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var n,o;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(r=>r({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),(n=t.response.audio)!=null&&n.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(r=>r("speaking")),this.playAudio(t.response.audio).catch(r=>this.errorCallbacks.forEach(s=>s(r instanceof Error?r:new Error(String(r)))))):(o=t.response.audio)!=null&&o.base64;break;case"audio_end":if(t.requestId&&t.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(r=>r("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(r=>r(new Error(t.error))),this.statusCallbacks.forEach(r=>r("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Ja(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,n,o,r;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(r=(o=this.config)==null?void 0:o.silenceThreshold)!=null?r:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let p=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",m=new Blob(this.audioChunks,{type:p});await this.sendAudio(m),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var s,a;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let n=this.audioContext,o=(a=(s=this.config)==null?void 0:s.silenceThreshold)!=null?a:.01;this.vad.start(n,this.mediaStream,"speech",{threshold:o,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(n=>n(t instanceof Error?t:new Error(String(t))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(t){var n;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(o=>o(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(o=>o("error"));return}try{let o=await this.blobToBase64(t),r=this.getFormatFromMimeType(t.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:o,format:r,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:s}))}catch(o){this.errorCallbacks.forEach(r=>r(o)),this.statusCallbacks.forEach(r=>r("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,o)=>{let r=new FileReader;r.onload=()=>{let a=r.result.split(",")[1];n(a)},r.onerror=o,r.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let n=atob(t.base64),o=new Uint8Array(n.length);for(let l=0;l<n.length;l++)o[l]=n.charCodeAt(l);let r=t.format||"mp3",s=r==="mp3"?"audio/mpeg":`audio/${r}`,a=new Blob([o],{type:s}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Sr=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let o=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!o)throw new Error("Browser speech recognition not supported");this.recognition=new o,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=r=>{var i;let s=Array.from(r.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=r.results[r.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=r=>{this.errorCallbacks.forEach(s=>s(new Error(r.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(r=>r("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(r=>r("idle"))},this.recognition.start()}catch(o){throw this.errorCallbacks.forEach(r=>r(o)),this.statusCallbacks.forEach(r=>r("error")),o}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Hs(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Bs(e.runtype);case"browser":if(!Sr.isSupported())throw new Error("Browser speech recognition not supported");return new Sr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Bu(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Hs({type:"runtype",runtype:e.runtype});if(Sr.isSupported())return Hs({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function cl(e){try{return Bu(e),!0}catch{return!1}}function Hu(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let o="Sorry \u2014 I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
|
|
11
|
+
`);a=(Dn=De.pop())!=null?Dn:"";for(let Fe of De){let $e=Fe.split(`
|
|
12
|
+
`),dt="message",ot="";for(let q of $e)q.startsWith("event:")?dt=q.replace("event:","").trim():q.startsWith("data:")&&(ot+=q.replace("data:","").trim());if(!ot)continue;let At;try{At=JSON.parse(ot)}catch(q){n({type:"error",error:q instanceof Error?q:new Error("Failed to parse chat stream payload")});continue}let Vt=dt!=="message"?dt:(Jn=At.type)!=null?Jn:"message";if((qe=this.onSSEEvent)==null||qe.call(this,Vt,At),this.parseSSEEvent){S.current=p;let q=await this.handleCustomSSEEvent(At,n,S,g,l,M);if(S.current&&S.current!==p&&(p=S.current),q)continue}pe.push(Vt,At),Ve()}}pe.flushPending(),Ve(),pe.destroy()}};function Qa(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Bs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ja="[Image]";function cl(e){return{type:"text",text:e}}var Ru=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Jg=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],_o=[...Ru,...Jg];function Zg(e){return Ru.includes(e)||e.startsWith("image/")}function Za(e){return Zg(e.type)}async function Pu(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Za(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function Wu(e,t=_o,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function eh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Bu(e,t){let n=eh(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var ei=class{constructor(t=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=t}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let d=new Uint8Array(this.remainder.length+t.length);d.set(this.remainder),d.set(t,this.remainder.length),n=d,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.ensureContext(),r=this.pcmToFloat32(n),s=o.createBuffer(1,r.length,this.sampleRate);s.getChannelData(0).set(r);let a=o.createBufferSource();a.buffer=s,a.connect(o.destination);let i=o.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=s.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=r.getInt16(s*2,!0);o[s]=a/32768}return o}};var ti=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,o,r,s){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(n),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let m=0;m<a.length;m++)i+=a[m]*a[m];let d=Math.sqrt(i/a.length);(o==="silence"?d<r.threshold:d>=r.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=r.duration&&(this.fired=!0,s()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Hs=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new ti;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,n,o;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let r=this.w;if(!r||!r.location)throw new Error("Window object or location not available");let s=r.location.protocol==="https:"?"wss:":"ws:",a=(t=this.config)==null?void 0:t.host,i=(n=this.config)==null?void 0:n.agentId,d=(o=this.config)==null?void 0:o.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let m=`${s}//${a}/ws/agents/${i}/voice?token=...`,u=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((g,p)=>{if(!this.ws)return p(new Error("WebSocket not created"));let w=!1,S=I=>{w||(w=!0,clearTimeout(M),p(new Error(I)))},M=setTimeout(()=>S("WebSocket connection timed out."+u),1e4);this.ws.addEventListener("open",()=>{w||(w=!0,clearTimeout(M),g())},{once:!0}),this.ws.addEventListener("error",()=>{S("WebSocket connection failed to "+m+"."+u)},{once:!0}),this.ws.addEventListener("close",I=>{if(!I.wasClean&&!w){let L=I.code!==1006?` (code ${I.code})`:"";S("WebSocket connection failed"+L+"."+u)}},{once:!0})}),this.sendHeartbeat()}catch(r){throw this.ws=null,this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(n=>n(new Error("WebSocket error"))),this.statusCallbacks.forEach(n=>n("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let n=JSON.parse(t.data);this.handleWebSocketMessage(n)}catch{this.errorCallbacks.forEach(o=>o(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var n,o;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(r=>r({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),(n=t.response.audio)!=null&&n.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(r=>r("speaking")),this.playAudio(t.response.audio).catch(r=>this.errorCallbacks.forEach(s=>s(r instanceof Error?r:new Error(String(r)))))):(o=t.response.audio)!=null&&o.base64;break;case"audio_end":if(t.requestId&&t.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(r=>r("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(r=>r(new Error(t.error))),this.statusCallbacks.forEach(r=>r("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new ei(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,n,o,r;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(r=(o=this.config)==null?void 0:o.silenceThreshold)!=null?r:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(g=>g("processing")),this.processingStartCallbacks.forEach(g=>g());let m=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",u=new Blob(this.audioChunks,{type:m});await this.sendAudio(u),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var s,a;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let n=this.audioContext,o=(a=(s=this.config)==null?void 0:s.silenceThreshold)!=null?a:.01;this.vad.start(n,this.mediaStream,"speech",{threshold:o,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(n=>n(t instanceof Error?t:new Error(String(t))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(t){var n;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(o=>o(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(o=>o("error"));return}try{let o=await this.blobToBase64(t),r=this.getFormatFromMimeType(t.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:o,format:r,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:s}))}catch(o){this.errorCallbacks.forEach(r=>r(o)),this.statusCallbacks.forEach(r=>r("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,o)=>{let r=new FileReader;r.onload=()=>{let a=r.result.split(",")[1];n(a)},r.onerror=o,r.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let n=atob(t.base64),o=new Uint8Array(n.length);for(let l=0;l<n.length;l++)o[l]=n.charCodeAt(l);let r=t.format||"mp3",s=r==="mp3"?"audio/mpeg":`audio/${r}`,a=new Blob([o],{type:s}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Sr=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let o=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!o)throw new Error("Browser speech recognition not supported");this.recognition=new o,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=r=>{var i;let s=Array.from(r.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=r.results[r.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=r=>{this.errorCallbacks.forEach(s=>s(new Error(r.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(r=>r("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(r=>r("idle"))},this.recognition.start()}catch(o){throw this.errorCallbacks.forEach(r=>r(o)),this.statusCallbacks.forEach(r=>r("error")),o}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Ds(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Hs(e.runtype);case"browser":if(!Sr.isSupported())throw new Error("Browser speech recognition not supported");return new Sr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Hu(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Ds({type:"runtype",runtype:e.runtype});if(Sr.isSupported())return Ds({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function dl(e){try{return Hu(e),!0}catch{return!1}}function Du(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let o="Sorry \u2014 I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
|
|
13
13
|
|
|
14
|
-
_Details: ${n.message}_`:o}var ei=class e{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=t=>{var n,o,r,s,a,i,d,l;if(t.type==="message"){this.upsertMessage(t.message);let p=t.message.toolCall;((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&(p!=null&&p.name)&&sl(p.name)&&this.enqueueWebMcpAwait(t.message),(o=t.message.agentMetadata)!=null&&o.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(r=t.message.agentMetadata.agentName)!=null?r:"",status:"running",currentIteration:(s=t.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let p=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":p||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var o,r;this.messages=[...(o=t.initialMessages)!=null?o:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Ps(t),this.wireDefaultWebMcpConfirm();for(let s of(r=t.initialArtifacts)!=null?r:[])this.artifacts.set(s.id,{...s,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return cl((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,o;return(o=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?o:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(t){var n,o,r;try{let s=t||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=Hs(s);let a=(n=this.config.voiceRecognition)!=null?n:{},i=(o=a.processingText)!=null?o:"\u{1F3A4} Processing voice...",d=(r=a.processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var p,m,f,u,w,C;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((p=l.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=l.transcript)!=null&&m.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=l.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(u=l.text)!=null&&u.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let M=(C=this.pendingVoiceAssistantMessageId)!=null?C:(w=[...this.messages].reverse().find(I=>I.role==="assistant"))==null?void 0:w.id;M&&this.ttsSpokenMessageIds.add(M)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var p,m;this.voiceStatus=l,this.voiceActive=l==="listening",(m=(p=this.callbacks).onVoiceStatusChanged)==null||m.call(p,l)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,o,r,s,a,i,d,l,p;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((o=t.runtype)==null?void 0:o.agentId)||"",clientToken:((r=t.runtype)==null?void 0:r.clientToken)||"",host:(s=t.runtype)==null?void 0:s.host,voiceId:(a=t.runtype)==null?void 0:a.voiceId,pauseDuration:(i=t.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=t.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=t.browser)==null?void 0:l.language)||"en-US",continuous:(p=t.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let o=await this.client.initSession();return this.setClientSession(o),o}catch(o){return(n=(t=this.callbacks).onError)==null||n.call(t,o instanceof Error?o:new Error(String(o))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let n=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new Ps(this.config),this.wireDefaultWebMcpConfirm(),n&&this.client.setSSEEventCallback(n)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:p,rawContent:m}=t,u={id:a!=null?a:n==="user"?Ya():n==="assistant"?Ws():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};return this.upsertMessage(u),u}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:p,streaming:m=!1,voiceProcessing:f,rawContent:u}=o,C={id:d!=null?d:r==="user"?Ya():r==="assistant"?Ws():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...u!==void 0&&{rawContent:u}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:i,sequence:d}=t,l={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(l),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var l,p,m,f,u;let o=t.trim();if(!o&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let r=Ya(),s=Ws(),a={id:r,role:"user",content:o||Xa,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(w){let C=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));if(!C){let M=Hu(w,this.config.errorMessage);if(M){let I={id:s,role:"assistant",createdAt:new Date().toISOString(),content:M,sequence:this.nextSequence()};this.appendMessage(I)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,C||(w instanceof Error?(m=(p=this.callbacks).onError)==null||m.call(p,w):(u=(f=this.callbacks).onError)==null||u.call(f,new Error(String(w))))}}async continueConversation(){var r,s,a,i,d;if(this.streaming)return;(r=this.abortController)==null||r.abort();let t=Ws();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(l){let p=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!p){let m=Hu(l,this.config.errorMessage);if(m){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:m,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var r,s,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(r=this.abortController)==null||r.abort();let o=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var r,s,a;try{if(((s=(r=this.config.webmcp)==null?void 0:r.autoApprove)==null?void 0:s.call(r,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(o,i)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r!=null&&r.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n){var d,l,p,m;let o=`approval-${t.id}`,r={...t,status:n,resolvedAt:Date.now()},s={id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:r};this.upsertMessage(s),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let f;if(i?f=await i({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n):f=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),f){let u=null;if(f instanceof Response){if(!f.ok){let w=await f.json().catch(()=>null);throw new Error((l=w==null?void 0:w.error)!=null?l:`Approval request failed: ${f.status}`)}u=f.body}else f instanceof ReadableStream&&(u=f);u?await this.connectStream(u,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(f){let u=f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||(m=(p=this.callbacks).onError)==null||m.call(p,f instanceof Error?f:new Error(String(f)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,m,f,u,w,C,M,I,R,H,D,B;let o=this.messages.find(v=>v.id===t.id);if(((p=o==null?void 0:o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let r=(m=t.agentMetadata)==null?void 0:m.executionId,s=(f=t.toolCall)==null?void 0:f.name;if(!r||!s){(w=(u=this.callbacks).onError)==null||w.call(u,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let v=(C=t.toolCall)==null?void 0:C.args,x=Array.isArray(v==null?void 0:v.questions)?v.questions:[];if(x.length===1){let k=typeof((M=x[0])==null?void 0:M.question)=="string"?x[0].question:"";k&&(a={[k]:n})}}this.markAskUserQuestionResolved(t,a),(I=this.abortController)==null||I.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(R=t.toolCall)==null?void 0:R.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let v=typeof n=="string"?n:Object.entries(n).map(([x,k])=>`${x}: ${Array.isArray(k)?k.join(", "):k}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:v,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let v=a!=null?a:{};l.forEach((x,k)=>{let S=typeof(x==null?void 0:x.question)=="string"?x.question:"";if(!S)return;let E=v[S],F=Array.isArray(E)?E.join(", "):typeof E=="string"?E:"";this.appendMessage({id:`ask-user-q-${i}-${k}`,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${k}`,role:"user",content:F||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let v=await this.client.resumeFlow(r,{[s]:n});if(!v.ok){let x=await v.json().catch(()=>null);throw new Error((H=x==null?void 0:x.error)!=null?H:`Resume failed: ${v.status}`)}v.body?await this.connectStream(v.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,x||(B=(D=this.callbacks).onError)==null||B.call(D,v instanceof Error?v:new Error(String(v)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,o=(a=t.toolCall)==null?void 0:a.id;if(!n||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}async resolveWebMcpToolCallBatch(t,n){var i,d,l;let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async p=>{var R,H,D,B,v,x,k;let m=(R=p.toolCall)==null?void 0:R.name,f=(H=p.toolCall)==null?void 0:H.id;if(!m||!f)return null;let u=`${t}:${f}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u))return null;this.webMcpInflightKeys.add(u),o.push(u),this.upsertMessage({...p,agentMetadata:{...p.agentMetadata,awaitingLocalTool:!1}});let w=new AbortController;this.webMcpResolveControllers.add(w),r.push(w);let C=(B=(D=p.agentMetadata)==null?void 0:D.webMcpToolCallId)!=null?B:m,M=this.client.executeWebMcpToolCall(m,(v=p.toolCall)==null?void 0:v.args,w.signal),I;if(!M)I={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{I=await M}catch(S){return S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"))||(k=(x=this.callbacks).onError)==null||k.call(x,S instanceof Error?S:new Error(String(S))),this.webMcpInflightKeys.delete(u),null}return w.signal.aborted?(this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:C,output:I}}));try{let p=a.filter(u=>u!==null);if(p.length===0)return;let m={};for(let u of p)m[u.resumeKey]=u.output;let f=await this.client.resumeFlow(t,m,{signal:s.signal});if(!f.ok){let u=await f.json().catch(()=>null);throw new Error((i=u==null?void 0:u.error)!=null?i:`Resume failed: ${f.status}`)}for(let u of p)this.webMcpResolvedKeys.add(u.dedupeKey);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(p){p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))||(l=(d=this.callbacks).onError)==null||l.call(d,p instanceof Error?p:new Error(String(p)))}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of r)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var p,m,f,u,w,C,M,I,R,H,D,B;let n=(p=t.agentMetadata)==null?void 0:p.executionId,o=(m=t.toolCall)==null?void 0:m.name,r=(f=t.toolCall)==null?void 0:f.id;if(!n){(w=(u=this.callbacks).onError)==null||w.call(u,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!o)return;if(!r){let v=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v))return;this.webMcpInflightKeys.add(v);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(v)}catch(x){(M=(C=this.callbacks).onError)==null||M.call(C,x instanceof Error?x:new Error(String(x)))}finally{this.webMcpInflightKeys.delete(v)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s))return;this.webMcpInflightKeys.add(s),this.upsertMessage({...t,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1}});let a=new AbortController;this.webMcpResolveControllers.add(a);let{signal:i}=a;this.setStreaming(!0);let d=(I=t.toolCall)==null?void 0:I.args,l=this.client.executeWebMcpToolCall(o,d,i);try{let v;if(l?v=await l:v={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},i.aborted)return;let x=(H=(R=t.agentMetadata)==null?void 0:R.webMcpToolCallId)!=null?H:o;await this.resumeWithToolOutput(n,x,v,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s)},signal:i})}catch(v){v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"))||(B=(D=this.callbacks).onError)==null||B.call(D,v instanceof Error?v:new Error(String(v)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){var a,i;let s=await this.client.resumeFlow(t,{[n]:o},{signal:r==null?void 0:r.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=r==null?void 0:r.onHttpOk)==null||i.call(r),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var r;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let o={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(r=t.props)!=null?r:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),o}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,o;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let r=this.artifacts.get(t.id);(r==null?void 0:r.artifactType)==="markdown"&&(r.markdown=((o=r.markdown)!=null?o:"")+t.artDelta);break}case"artifact_update":{let r=this.artifacts.get(t.id);(r==null?void 0:r.artifactType)==="component"&&(r.props={...r.props,...t.props},t.component&&(r.component=t.component));break}case"artifact_complete":{let r=this.artifacts.get(t.id);r&&(r.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>{var r;return{...o,streaming:!1,sequence:(r=o.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=o.content;r.trim()&&this.speak(r,t)}speak(t,n){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t),s=o.getVoices();if(n.voice){let a=s.find(i=>i.name===n.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=n.pickVoice?n.pickVoice(s):e.pickBestVoice(s));n.rate!==void 0&&(r.rate=n.rate),n.pitch!==void 0&&(r.pitch=n.pitch),setTimeout(()=>o.speak(r),50)}static pickBestVoice(t){var o;let n=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of n){let s=t.find(a=>a.name===r);if(s)return s}return(o=t.find(r=>r.lang.startsWith("en")))!=null?o:t[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{var p,m,f,u,w,C;if(s!==o)return r;let a={...r,...n};((p=r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(m=n.toolCall)==null?void 0:m.name,d=(f=n.agentMetadata)==null?void 0:f.executionId,l=(u=n.toolCall)==null?void 0:u.id;if(i&&sl(i)&&d&&l&&((w=n.agentMetadata)==null?void 0:w.awaitingLocalTool)===!0){let M=`${d}:${l}`;(this.webMcpInflightKeys.has(M)||this.webMcpResolvedKeys.has(M))&&(a.agentMetadata={...(C=a.agentMetadata)!=null?C:{},awaitingLocalTool:!1})}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{var d,l;let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=(d=n.sequence)!=null?d:0,i=(l=o.sequence)!=null?l:0;return a!==i?a-i:n.id.localeCompare(o.id)})}};var b=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Eo=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o};import{Activity as Zf,ArrowDown as eh,ArrowUp as th,ArrowUpRight as nh,Bot as oh,ChevronDown as rh,ChevronUp as sh,ChevronRight as ah,ChevronLeft as ih,Check as lh,Clipboard as ch,ClipboardCopy as dh,Copy as ph,File as uh,FileCode as mh,FileSpreadsheet as gh,FileText as fh,ImagePlus as hh,Loader as bh,LoaderCircle as yh,Mic as vh,Paperclip as xh,RefreshCw as wh,Search as Ch,Send as Sh,ShieldAlert as Ah,ShieldCheck as Th,ShieldX as kh,Square as Eh,ThumbsDown as Mh,ThumbsUp as Lh,Upload as Ih,Volume2 as Rh,X as Ph,User as Wh,Mail as Bh,Phone as Hh,Calendar as Dh,Clock as Fh,Building as Oh,MapPin as Nh,Lock as _h,Key as Vh,CreditCard as $h,AtSign as Uh,Hash as zh,Globe as qh,Link as jh,CircleCheck as Kh,CircleX as Gh,TriangleAlert as Yh,Info as Xh,Ban as Qh,Shield as Jh,ArrowLeft as Zh,ArrowRight as eb,ExternalLink as tb,Ellipsis as nb,EllipsisVertical as ob,Menu as rb,House as sb,Plus as ab,Minus as ib,Pencil as lb,Trash as cb,Trash2 as db,Save as pb,Download as ub,Share as mb,Funnel as gb,Settings as fb,RotateCw as hb,Maximize as bb,Minimize as yb,ShoppingCart as vb,ShoppingBag as xb,Package as wb,Truck as Cb,Tag as Sb,Gift as Ab,Receipt as Tb,Wallet as kb,Store as Eb,DollarSign as Mb,Percent as Lb,Play as Ib,Pause as Rb,VolumeX as Pb,Camera as Wb,Image as Bb,Film as Hb,Headphones as Db,MessageCircle as Fb,MessageSquare as Ob,Bell as Nb,Heart as _b,Star as Vb,Eye as $b,EyeOff as Ub,Bookmark as zb,CalendarDays as qb,History as jb,Timer as Kb,Folder as Gb,FolderOpen as Yb,Files as Xb,Sparkles as Qb,Zap as Jb,Sun as Zb,Moon as ey,Flag as ty,Monitor as ny,Smartphone as oy}from"lucide";var ry={activity:Zf,"arrow-down":eh,"arrow-up":th,"arrow-up-right":nh,bot:oh,"chevron-down":rh,"chevron-up":sh,"chevron-right":ah,"chevron-left":ih,check:lh,clipboard:ch,"clipboard-copy":dh,copy:ph,file:uh,"file-code":mh,"file-spreadsheet":gh,"file-text":fh,"image-plus":hh,loader:bh,"loader-circle":yh,mic:vh,paperclip:xh,"refresh-cw":wh,search:Ch,send:Sh,"shield-alert":Ah,"shield-check":Th,"shield-x":kh,square:Eh,"thumbs-down":Mh,"thumbs-up":Lh,upload:Ih,"volume-2":Rh,x:Ph,user:Wh,mail:Bh,phone:Hh,calendar:Dh,clock:Fh,building:Oh,"map-pin":Nh,lock:_h,key:Vh,"credit-card":$h,"at-sign":Uh,hash:zh,globe:qh,link:jh,"circle-check":Kh,"circle-x":Gh,"triangle-alert":Yh,info:Xh,ban:Qh,shield:Jh,"arrow-left":Zh,"arrow-right":eb,"external-link":tb,ellipsis:nb,"ellipsis-vertical":ob,menu:rb,house:sb,plus:ab,minus:ib,pencil:lb,trash:cb,"trash-2":db,save:pb,download:ub,share:mb,funnel:gb,settings:fb,"rotate-cw":hb,maximize:bb,minimize:yb,"shopping-cart":vb,"shopping-bag":xb,package:wb,truck:Cb,tag:Sb,gift:Ab,receipt:Tb,wallet:kb,store:Eb,"dollar-sign":Mb,percent:Lb,play:Ib,pause:Rb,"volume-x":Pb,camera:Wb,image:Bb,film:Hb,headphones:Db,"message-circle":Fb,"message-square":Ob,bell:Nb,heart:_b,star:Vb,eye:$b,"eye-off":Ub,bookmark:zb,"calendar-days":qb,history:jb,timer:Kb,folder:Gb,"folder-open":Yb,files:Xb,sparkles:Qb,zap:Jb,sun:Zb,moon:ey,flag:ty,monitor:ny,smartphone:oy},Te=(e,t=24,n="currentColor",o=2)=>{let r=ry[e];return r?sy(r,t,n,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function sy(e,t,n,o){if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,p])=>{l!=="stroke"&&d.setAttribute(l,String(p))}),r.appendChild(d)}),r}var ti={allowedTypes:_o,maxFileSize:10*1024*1024,maxFiles:4};function ay(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function iy(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var Ds=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,o,r;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:ti.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:ti.maxFileSize,maxFiles:(r=t.maxFiles)!=null?r:ti.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:ti.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,o,r,s,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(o=(n=this.config).onFileRejected)==null||o.call(n,l,"count");continue}let p=Pu(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let m=(r=p.error)!=null&&r.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,m);continue}try{let m=await Ru(l),f=Qa(l)?URL.createObjectURL(l):null,u={id:ay(),file:l,previewUrl:f,contentPart:m};this.attachments.push(u),this.renderPreview(u)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let o of this.attachments)o.previewUrl&&URL.revokeObjectURL(o.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Qa(t.file),o=b("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let a=b("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=b("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=iy(t.file.type),d=Te(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=b("span");l.textContent=Wu(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),o.appendChild(a)}let r=b("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=Te("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};import{Idiomorph as ly}from"idiomorph";var ni=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;ly.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){var a,i;if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=r.textContent)!=null?a:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var oi={index:-1,draft:""};function Du(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:o}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...oi}}}function Fu(e,t){var n,o,r,s,a,i,d,l,p,m,f,u,w,C,M,I,R,H,D,B,v,x,k,S,E,F,$,j,me,se,ge,ie,be,Fe,ve,J,Le,Y;return[e.id,e.role,(o=(n=e.content)==null?void 0:n.length)!=null?o:0,(s=(r=e.content)==null?void 0:r.slice(-32))!=null?s:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(l=e.llmContent)==null?void 0:l.length)!=null?p:0,(f=(m=e.approval)==null?void 0:m.status)!=null?f:"",(w=(u=e.toolCall)==null?void 0:u.status)!=null?w:"",(M=(C=e.toolCall)==null?void 0:C.name)!=null?M:"",(H=(R=(I=e.toolCall)==null?void 0:I.chunks)==null?void 0:R.length)!=null?H:0,(x=(v=(B=(D=e.toolCall)==null?void 0:D.chunks)==null?void 0:B[e.toolCall.chunks.length-1])==null?void 0:v.slice(-32))!=null?x:"",typeof((k=e.toolCall)==null?void 0:k.args)=="string"?e.toolCall.args.length:(S=e.toolCall)!=null&&S.args?JSON.stringify(e.toolCall.args).length:0,($=(F=(E=e.reasoning)==null?void 0:E.chunks)==null?void 0:F.length)!=null?$:0,(ge=(se=(me=(j=e.reasoning)==null?void 0:j.chunks)==null?void 0:me[e.reasoning.chunks.length-1])==null?void 0:se.length)!=null?ge:0,(ve=(Fe=(be=(ie=e.reasoning)==null?void 0:ie.chunks)==null?void 0:be[e.reasoning.chunks.length-1])==null?void 0:Fe.slice(-32))!=null?ve:"",(Le=(J=e.contentParts)==null?void 0:J.length)!=null?Le:0,(Y=e.stopReason)!=null?Y:"",t].join("\0")}function Ou(){return new Map}function Nu(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function _u(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Vu(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function ri(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Fs(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Os(e,t){return Fs(e)-e.scrollTop<=t}function si(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,p=n-o;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&r&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!r?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function ai(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}var fn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},hn=1e5,or=hn+1;var Ns={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},cy=["pre","code","a","script","style"],ii=e=>{var t,n,o,r,s;return{type:(t=e==null?void 0:e.type)!=null?t:Ns.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:Ns.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:Ns.speed,duration:(r=e==null?void 0:e.duration)!=null?r:Ns.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:Ns.buffer}},dy=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],Uu=new Map;for(let e of dy)Uu.set(e.name,e);var _s=(e,t)=>{var n,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(o=Uu.get(e))!=null?o:null},li=(e,t,n,o,r)=>{if(!r)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
|
|
15
|
-
`);return s<0?"":e.slice(0,s)}return e},
|
|
14
|
+
_Details: ${n.message}_`:o}var Fs=e=>({isError:!0,content:[{type:"text",text:e}]}),Fu=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,ni=class e{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=t=>{var n,o,r,s,a,i,d,l;if(t.type==="message"){this.upsertMessage(t.message);let m=t.message.toolCall;((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&(m!=null&&m.name)&&qr(m.name)&&this.enqueueWebMcpAwait(t.message),(o=t.message.agentMetadata)!=null&&o.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(r=t.message.agentMetadata.agentName)!=null?r:"",status:"running",currentIteration:(s=t.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let m=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":m||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var o,r;this.messages=[...(o=t.initialMessages)!=null?o:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Ws(t),this.wireDefaultWebMcpConfirm();for(let s of(r=t.initialArtifacts)!=null?r:[])this.artifacts.set(s.id,{...s,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return dl((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,o;return(o=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?o:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(t){var n,o,r;try{let s=t||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=Ds(s);let a=(n=this.config.voiceRecognition)!=null?n:{},i=(o=a.processingText)!=null?o:"\u{1F3A4} Processing voice...",d=(r=a.processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let m=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=m.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var m,u,g,p,w,S;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((m=l.transcript)!=null&&m.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(u=l.transcript)!=null&&u.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((g=l.text)!=null&&g.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=l.text)!=null&&p.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let M=(S=this.pendingVoiceAssistantMessageId)!=null?S:(w=[...this.messages].reverse().find(I=>I.role==="assistant"))==null?void 0:w.id;M&&this.ttsSpokenMessageIds.add(M)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var m,u;this.voiceStatus=l,this.voiceActive=l==="listening",(u=(m=this.callbacks).onVoiceStatusChanged)==null||u.call(m,l)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,o,r,s,a,i,d,l,m;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((o=t.runtype)==null?void 0:o.agentId)||"",clientToken:((r=t.runtype)==null?void 0:r.clientToken)||"",host:(s=t.runtype)==null?void 0:s.host,voiceId:(a=t.runtype)==null?void 0:a.voiceId,pauseDuration:(i=t.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=t.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=t.browser)==null?void 0:l.language)||"en-US",continuous:(m=t.browser)==null?void 0:m.continuous}};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let o=await this.client.initSession();return this.setClientSession(o),o}catch(o){return(n=(t=this.callbacks).onError)==null||n.call(t,o instanceof Error?o:new Error(String(o))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let n=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new Ws(this.config),this.wireDefaultWebMcpConfirm(),n&&this.client.setSSEEventCallback(n)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:m,rawContent:u}=t,p={id:a!=null?a:n==="user"?Qa():n==="assistant"?Bs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...m!==void 0&&{voiceProcessing:m},...u!==void 0&&{rawContent:u}};return this.upsertMessage(p),p}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:m,streaming:u=!1,voiceProcessing:g,rawContent:p}=o,S={id:d!=null?d:r==="user"?Qa():r==="assistant"?Bs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:m!=null?m:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...p!==void 0&&{rawContent:p}};n.push(S)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:i,sequence:d}=t,l={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(l),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var l,m,u,g,p;let o=t.trim();if(!o&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let r=Qa(),s=Bs(),a={id:r,role:"user",content:o||Ja,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(w){let S=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));if(!S){let M=Du(w,this.config.errorMessage);if(M){let I={id:s,role:"assistant",createdAt:new Date().toISOString(),content:M,sequence:this.nextSequence()};this.appendMessage(I)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,S||(w instanceof Error?(u=(m=this.callbacks).onError)==null||u.call(m,w):(p=(g=this.callbacks).onError)==null||p.call(g,new Error(String(w))))}}async continueConversation(){var r,s,a,i,d;if(this.streaming)return;(r=this.abortController)==null||r.abort();let t=Bs();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(l){let m=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!m){let u=Du(l,this.config.errorMessage);if(u){let g={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,m||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var r,s,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(r=this.abortController)==null||r.abort();let o=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var r,s,a;try{if(((s=(r=this.config.webmcp)==null?void 0:r.autoApprove)==null?void 0:s.call(r,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(o,i)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r!=null&&r.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n){var d,l,m,u;let o=`approval-${t.id}`,r={...t,status:n,resolvedAt:Date.now()},s={id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:r};this.upsertMessage(s),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let g;if(i?g=await i({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n):g=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),g){let p=null;if(g instanceof Response){if(!g.ok){let w=await g.json().catch(()=>null);throw new Error((l=w==null?void 0:w.error)!=null?l:`Approval request failed: ${g.status}`)}p=g.body}else g instanceof ReadableStream&&(p=g);p?await this.connectStream(p,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(g){let p=g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"));this.setStreaming(!1),this.abortController=null,p||(u=(m=this.callbacks).onError)==null||u.call(m,g instanceof Error?g:new Error(String(g)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var m,u,g,p,w,S,M,I,L,H,D,W;let o=this.messages.find(v=>v.id===t.id);if(((m=o==null?void 0:o.agentMetadata)==null?void 0:m.askUserQuestionAnswered)===!0)return;let r=(u=t.agentMetadata)==null?void 0:u.executionId,s=(g=t.toolCall)==null?void 0:g.name;if(!r||!s){(w=(p=this.callbacks).onError)==null||w.call(p,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let v=(S=t.toolCall)==null?void 0:S.args,x=Array.isArray(v==null?void 0:v.questions)?v.questions:[];if(x.length===1){let k=typeof((M=x[0])==null?void 0:M.question)=="string"?x[0].question:"";k&&(a={[k]:n})}}this.markAskUserQuestionResolved(t,a),(I=this.abortController)==null||I.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(L=t.toolCall)==null?void 0:L.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let v=typeof n=="string"?n:Object.entries(n).map(([x,k])=>`${x}: ${Array.isArray(k)?k.join(", "):k}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:v,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let v=a!=null?a:{};l.forEach((x,k)=>{let C=typeof(x==null?void 0:x.question)=="string"?x.question:"";if(!C)return;let T=v[C],F=Array.isArray(T)?T.join(", "):typeof T=="string"?T:"";this.appendMessage({id:`ask-user-q-${i}-${k}`,role:"assistant",content:C,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${k}`,role:"user",content:F||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let v=await this.client.resumeFlow(r,{[s]:n});if(!v.ok){let x=await v.json().catch(()=>null);throw new Error((H=x==null?void 0:x.error)!=null?H:`Resume failed: ${v.status}`)}v.body?await this.connectStream(v.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,x||(W=(D=this.callbacks).onError)==null||W.call(D,v instanceof Error?v:new Error(String(v)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,o=(a=t.toolCall)==null?void 0:a.id;if(!n||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){var r,s;let n=this.messages.find(a=>a.id===t.id),o=[(r=n==null?void 0:n.toolCall)==null?void 0:r.startedAt,(s=t.toolCall)==null?void 0:s.startedAt];for(let a of o)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now()){this.messages.some(s=>s.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,l,m;let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async u=>{var D,W,v,x,k,C,T;let g=(D=u.toolCall)==null?void 0:D.name,p=(W=u.toolCall)==null?void 0:W.id;if(!g||!p)return null;let w=`${t}:${p}`;if(this.webMcpInflightKeys.has(w)||this.webMcpResolvedKeys.has(w))return null;this.webMcpInflightKeys.add(w),o.push(w);let S=this.markWebMcpToolRunning(u),M=new AbortController;this.webMcpResolveControllers.add(M),r.push(M);let I=(x=(v=u.agentMetadata)==null?void 0:v.webMcpToolCallId)!=null?x:g,L=this.client.executeWebMcpToolCall(g,(k=u.toolCall)==null?void 0:k.args,M.signal),H;if(!L)H={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{H=await L}catch(F){let $=F instanceof Error&&(F.name==="AbortError"||F.message.includes("aborted")||F.message.includes("abort"));return $||(T=(C=this.callbacks).onError)==null||T.call(C,F instanceof Error?F:new Error(String(F))),this.markWebMcpToolComplete(u,Fs($?"Aborted by cancel()":Fu(F)),S),this.webMcpInflightKeys.delete(w),null}return M.signal.aborted?(this.markWebMcpToolComplete(u,Fs("Aborted by cancel()"),S),this.webMcpInflightKeys.delete(w),null):{dedupeKey:w,resumeKey:I,output:H,toolMessage:u,startedAt:S,completedAt:Date.now()}})),i=[];try{if(i=a.filter(p=>p!==null),i.length===0)return;let u={};for(let p of i)u[p.resumeKey]=p.output;let g=await this.client.resumeFlow(t,u,{signal:s.signal});if(!g.ok){let p=await g.json().catch(()=>null);throw new Error((d=p==null?void 0:p.error)!=null?d:`Resume failed: ${g.status}`)}for(let p of i)this.webMcpResolvedKeys.add(p.dedupeKey),this.markWebMcpToolComplete(p.toolMessage,p.output,p.startedAt,p.completedAt);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(u){if(!(u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))))(m=(l=this.callbacks).onError)==null||m.call(l,u instanceof Error?u:new Error(String(u)));else for(let p of i)this.markWebMcpToolComplete(p.toolMessage,Fs("Aborted by cancel()"),p.startedAt)}finally{for(let u of o)this.webMcpInflightKeys.delete(u);for(let u of r)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var p,w,S,M,I,L,H,D,W,v,x,k;let n=(p=t.agentMetadata)==null?void 0:p.executionId,o=(w=t.toolCall)==null?void 0:w.name,r=(S=t.toolCall)==null?void 0:S.id;if(!n){(I=(M=this.callbacks).onError)==null||I.call(M,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!o)return;if(!r){let C=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(C)||this.webMcpResolvedKeys.has(C))return;this.webMcpInflightKeys.add(C);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(C)}catch(T){(H=(L=this.callbacks).onError)==null||H.call(L,T instanceof Error?T:new Error(String(T)))}finally{this.webMcpInflightKeys.delete(C)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let l=(D=t.toolCall)==null?void 0:D.args,m=this.client.executeWebMcpToolCall(o,l,d),u="execute",g=a;try{let C;if(m?C=await m:C={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),d.aborted){this.markWebMcpToolComplete(t,Fs("Aborted by cancel()"),a);return}let T=(v=(W=t.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?v:o;u="resume",await this.resumeWithToolOutput(n,T,C,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,C,a,g)},signal:d})}catch(C){let T=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));(u==="execute"||T||d.aborted)&&this.markWebMcpToolComplete(t,Fs(T||d.aborted?"Aborted by cancel()":Fu(C)),a),T||(k=(x=this.callbacks).onError)==null||k.call(x,C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){var a,i;let s=await this.client.resumeFlow(t,{[n]:o},{signal:r==null?void 0:r.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=r==null?void 0:r.onHttpOk)==null||i.call(r),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var r;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let o={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(r=t.props)!=null?r:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),o}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,o;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let r=this.artifacts.get(t.id);(r==null?void 0:r.artifactType)==="markdown"&&(r.markdown=((o=r.markdown)!=null?o:"")+t.artDelta);break}case"artifact_update":{let r=this.artifacts.get(t.id);(r==null?void 0:r.artifactType)==="component"&&(r.props={...r.props,...t.props},t.component&&(r.component=t.component));break}case"artifact_complete":{let r=this.artifacts.get(t.id);r&&(r.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>{var r;return{...o,streaming:!1,sequence:(r=o.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=o.content;r.trim()&&this.speak(r,t)}speak(t,n){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t),s=o.getVoices();if(n.voice){let a=s.find(i=>i.name===n.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=n.pickVoice?n.pickVoice(s):e.pickBestVoice(s));n.rate!==void 0&&(r.rate=n.rate),n.pitch!==void 0&&(r.pitch=n.pitch),setTimeout(()=>o.speak(r),50)}static pickBestVoice(t){var o;let n=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of n){let s=t.find(a=>a.name===r);if(s)return s}return(o=t.find(r=>r.lang.startsWith("en")))!=null?o:t[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{var m,u,g,p,w,S,M,I,L,H;if(s!==o)return r;let a={...r,...n};((m=r.agentMetadata)==null?void 0:m.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(u=n.toolCall)==null?void 0:u.name,d=(g=n.agentMetadata)==null?void 0:g.executionId,l=(p=n.toolCall)==null?void 0:p.id;if(i&&qr(i)&&d&&l&&((w=n.agentMetadata)==null?void 0:w.awaitingLocalTool)===!0){let D=`${d}:${l}`,W=this.webMcpInflightKeys.has(D),v=this.webMcpResolvedKeys.has(D),x=(S=r.toolCall)==null?void 0:S.name,k=((M=r.agentMetadata)==null?void 0:M.executionId)===d&&((I=r.toolCall)==null?void 0:I.id)===l&&x!==void 0&&qr(x)&&((L=r.toolCall)==null?void 0:L.status)==="complete";(W||v||k)&&(a.agentMetadata={...(H=a.agentMetadata)!=null?H:{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{var d,l;let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=(d=n.sequence)!=null?d:0,i=(l=o.sequence)!=null?l:0;return a!==i?a-i:n.id.localeCompare(o.id)})}};var b=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Eo=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o};import{Activity as th,ArrowDown as nh,ArrowUp as oh,ArrowUpRight as rh,Bot as sh,ChevronDown as ah,ChevronUp as ih,ChevronRight as lh,ChevronLeft as ch,Check as dh,Clipboard as ph,ClipboardCopy as uh,Copy as mh,File as fh,FileCode as gh,FileSpreadsheet as hh,FileText as bh,ImagePlus as yh,Loader as vh,LoaderCircle as xh,Mic as wh,Paperclip as Ch,RefreshCw as Sh,Search as Ah,Send as Th,ShieldAlert as kh,ShieldCheck as Eh,ShieldX as Mh,Square as Lh,ThumbsDown as Ih,ThumbsUp as Rh,Upload as Ph,Volume2 as Wh,X as Bh,User as Hh,Mail as Dh,Phone as Fh,Calendar as Oh,Clock as Nh,Building as _h,MapPin as Vh,Lock as $h,Key as Uh,CreditCard as zh,AtSign as qh,Hash as jh,Globe as Kh,Link as Gh,CircleCheck as Yh,CircleX as Xh,TriangleAlert as Qh,Info as Jh,Ban as Zh,Shield as eb,ArrowLeft as tb,ArrowRight as nb,ExternalLink as ob,Ellipsis as rb,EllipsisVertical as sb,Menu as ab,House as ib,Plus as lb,Minus as cb,Pencil as db,Trash as pb,Trash2 as ub,Save as mb,Download as fb,Share as gb,Funnel as hb,Settings as bb,RotateCw as yb,Maximize as vb,Minimize as xb,ShoppingCart as wb,ShoppingBag as Cb,Package as Sb,Truck as Ab,Tag as Tb,Gift as kb,Receipt as Eb,Wallet as Mb,Store as Lb,DollarSign as Ib,Percent as Rb,Play as Pb,Pause as Wb,VolumeX as Bb,Camera as Hb,Image as Db,Film as Fb,Headphones as Ob,MessageCircle as Nb,MessageSquare as _b,Bell as Vb,Heart as $b,Star as Ub,Eye as zb,EyeOff as qb,Bookmark as jb,CalendarDays as Kb,History as Gb,Timer as Yb,Folder as Xb,FolderOpen as Qb,Files as Jb,Sparkles as Zb,Zap as ey,Sun as ty,Moon as ny,Flag as oy,Monitor as ry,Smartphone as sy}from"lucide";var ay={activity:th,"arrow-down":nh,"arrow-up":oh,"arrow-up-right":rh,bot:sh,"chevron-down":ah,"chevron-up":ih,"chevron-right":lh,"chevron-left":ch,check:dh,clipboard:ph,"clipboard-copy":uh,copy:mh,file:fh,"file-code":gh,"file-spreadsheet":hh,"file-text":bh,"image-plus":yh,loader:vh,"loader-circle":xh,mic:wh,paperclip:Ch,"refresh-cw":Sh,search:Ah,send:Th,"shield-alert":kh,"shield-check":Eh,"shield-x":Mh,square:Lh,"thumbs-down":Ih,"thumbs-up":Rh,upload:Ph,"volume-2":Wh,x:Bh,user:Hh,mail:Dh,phone:Fh,calendar:Oh,clock:Nh,building:_h,"map-pin":Vh,lock:$h,key:Uh,"credit-card":zh,"at-sign":qh,hash:jh,globe:Kh,link:Gh,"circle-check":Yh,"circle-x":Xh,"triangle-alert":Qh,info:Jh,ban:Zh,shield:eb,"arrow-left":tb,"arrow-right":nb,"external-link":ob,ellipsis:rb,"ellipsis-vertical":sb,menu:ab,house:ib,plus:lb,minus:cb,pencil:db,trash:pb,"trash-2":ub,save:mb,download:fb,share:gb,funnel:hb,settings:bb,"rotate-cw":yb,maximize:vb,minimize:xb,"shopping-cart":wb,"shopping-bag":Cb,package:Sb,truck:Ab,tag:Tb,gift:kb,receipt:Eb,wallet:Mb,store:Lb,"dollar-sign":Ib,percent:Rb,play:Pb,pause:Wb,"volume-x":Bb,camera:Hb,image:Db,film:Fb,headphones:Ob,"message-circle":Nb,"message-square":_b,bell:Vb,heart:$b,star:Ub,eye:zb,"eye-off":qb,bookmark:jb,"calendar-days":Kb,history:Gb,timer:Yb,folder:Xb,"folder-open":Qb,files:Jb,sparkles:Zb,zap:ey,sun:ty,moon:ny,flag:oy,monitor:ry,smartphone:sy},Te=(e,t=24,n="currentColor",o=2)=>{let r=ay[e];return r?iy(r,t,n,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function iy(e,t,n,o){if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,m])=>{l!=="stroke"&&d.setAttribute(l,String(m))}),r.appendChild(d)}),r}var oi={allowedTypes:_o,maxFileSize:10*1024*1024,maxFiles:4};function ly(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function cy(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var Os=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,o,r;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:oi.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:oi.maxFileSize,maxFiles:(r=t.maxFiles)!=null?r:oi.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:oi.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,o,r,s,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(o=(n=this.config).onFileRejected)==null||o.call(n,l,"count");continue}let m=Wu(l,this.config.allowedTypes,this.config.maxFileSize);if(!m.valid){let u=(r=m.error)!=null&&r.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,u);continue}try{let u=await Pu(l),g=Za(l)?URL.createObjectURL(l):null,p={id:ly(),file:l,previewUrl:g,contentPart:u};this.attachments.push(p),this.renderPreview(p)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let o of this.attachments)o.previewUrl&&URL.revokeObjectURL(o.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Za(t.file),o=b("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let a=b("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=b("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=cy(t.file.type),d=Te(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=b("span");l.textContent=Bu(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),o.appendChild(a)}let r=b("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=Te("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};import{Idiomorph as dy}from"idiomorph";var ri=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;dy.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){var a,i;if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=r.textContent)!=null?a:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var si={index:-1,draft:""};function Ou(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:o}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...si}}}function Nu(e,t){var n,o,r,s,a,i,d,l,m,u,g,p,w,S,M,I,L,H,D,W,v,x,k,C,T,F,$,j,me,se,fe,ie,be,Oe,ve,Q,Le,Y;return[e.id,e.role,(o=(n=e.content)==null?void 0:n.length)!=null?o:0,(s=(r=e.content)==null?void 0:r.slice(-32))!=null?s:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(m=(l=e.llmContent)==null?void 0:l.length)!=null?m:0,(g=(u=e.approval)==null?void 0:u.status)!=null?g:"",(w=(p=e.toolCall)==null?void 0:p.status)!=null?w:"",(M=(S=e.toolCall)==null?void 0:S.name)!=null?M:"",(H=(L=(I=e.toolCall)==null?void 0:I.chunks)==null?void 0:L.length)!=null?H:0,(x=(v=(W=(D=e.toolCall)==null?void 0:D.chunks)==null?void 0:W[e.toolCall.chunks.length-1])==null?void 0:v.slice(-32))!=null?x:"",typeof((k=e.toolCall)==null?void 0:k.args)=="string"?e.toolCall.args.length:(C=e.toolCall)!=null&&C.args?JSON.stringify(e.toolCall.args).length:0,($=(F=(T=e.reasoning)==null?void 0:T.chunks)==null?void 0:F.length)!=null?$:0,(fe=(se=(me=(j=e.reasoning)==null?void 0:j.chunks)==null?void 0:me[e.reasoning.chunks.length-1])==null?void 0:se.length)!=null?fe:0,(ve=(Oe=(be=(ie=e.reasoning)==null?void 0:ie.chunks)==null?void 0:be[e.reasoning.chunks.length-1])==null?void 0:Oe.slice(-32))!=null?ve:"",(Le=(Q=e.contentParts)==null?void 0:Q.length)!=null?Le:0,(Y=e.stopReason)!=null?Y:"",t].join("\0")}function _u(){return new Map}function Vu(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function $u(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Uu(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function ai(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Ns(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function _s(e,t){return Ns(e)-e.scrollTop<=t}function ii(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,m=n-o;return a||Math.abs(m)<s?{action:"none",delta:m,nextLastScrollTop:n}:!t&&r&&(!l||m>0)?{action:"resume",delta:m,nextLastScrollTop:n}:t&&i&&m<0?{action:"pause",delta:m,nextLastScrollTop:n}:t&&d&&!r?{action:"pause",delta:m,nextLastScrollTop:n}:{action:"none",delta:m,nextLastScrollTop:n}}function li(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}var gn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},hn=1e5,or=hn+1;var Vs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},py=["pre","code","a","script","style"],ci=e=>{var t,n,o,r,s;return{type:(t=e==null?void 0:e.type)!=null?t:Vs.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:Vs.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:Vs.speed,duration:(r=e==null?void 0:e.duration)!=null?r:Vs.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:Vs.buffer}},uy=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],qu=new Map;for(let e of uy)qu.set(e.name,e);var $s=(e,t)=>{var n,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(o=qu.get(e))!=null?o:null},di=(e,t,n,o,r)=>{if(!r)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
|
|
15
|
+
`);return s<0?"":e.slice(0,s)}return e},my=(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},fy=(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},pl=/\s/,gy=(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},hy=(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(pl.test(s[i])){let l=i;for(;l<s.length&&pl.test(s[l]);)l+=1;a.appendChild(o.createTextNode(s.slice(i,l))),i=l}else{let l=o.createElement("span");l.className="persona-stream-word-group";let m=i;for(;m<s.length&&!pl.test(s[m]);)l.appendChild(my(o,s[m],t,n.value)),n.value+=1,m+=1;a.appendChild(l),i=m}r.replaceChild(a,e)},by=(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(fy(o,l,t,n.value)),n.value+=1));r.replaceChild(a,e)},Us=(e,t,n,o)=>{var u,g;if(!e||typeof document=="undefined")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set(((u=o==null?void 0:o.skipTags)!=null?u:py).map(p=>p.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)gy(d,s)||i.push(d),d=a.nextNode();let l={value:(g=o==null?void 0:o.startIndex)!=null?g:0},m=t==="char"?hy:by;for(let p of i)m(p,n,l);return r.innerHTML},pi=(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},zs=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},zu=new WeakMap,yy=(e,t)=>{var s;if(!e.styles)return;let n=zu.get(t);if(n||(n=new Set,zu.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},ul=new WeakMap,vy=(e,t)=>{if(!e.onAttach)return;let n=ul.get(t);if(n||(n=new Map,ul.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},ju=e=>{let t=ul.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},ml=(e,t)=>{yy(e,t),vy(e,t)};function fl(e,t=hn){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var qs=0,rr=null;function gl(e=document){var n;if(qs++,qs===1){let o=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;rr={originalOverflow:o.style.overflow,originalPosition:o.style.position,originalTop:o.style.top,originalWidth:o.style.width,scrollY:s},o.style.overflow="hidden",o.style.position="fixed",o.style.top=`-${s}px`,o.style.width="100%"}let t=!1;return()=>{var o;if(!t&&(t=!0,qs=Math.max(0,qs-1),qs===0&&rr)){let r=e.body,s=(o=e.defaultView)!=null?o:window;r.style.overflow=rr.originalOverflow,r.style.position=rr.originalPosition,r.style.top=rr.originalTop,r.style.width=rr.originalWidth,s.scrollTo(0,rr.scrollY),rr=null}}}var ui={side:"right",width:"420px",animate:!0,reveal:"resize"},pn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},js=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:ui.side,width:(r=t==null?void 0:t.width)!=null?r:ui.width,animate:(s=t==null?void 0:t.animate)!=null?s:ui.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:ui.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 Ks=(e,t)=>{let n=b("button");n.type="button",n.innerHTML=`
|
|
16
16
|
<span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
17
17
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
18
18
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -20,14 +20,14 @@ _Details: ${n.message}_`:o}var ei=class e{constructor(t={},n){this.config=t;this
|
|
|
20
20
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
21
21
|
</span>
|
|
22
22
|
<span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
23
|
-
`,n.addEventListener("click",t);let o=s=>{var H,D,B,v,x,k,S,E,F,$,j,me,se,ge;let a=(H=s.launcher)!=null?H:{},i=pn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let ie=(D=a.title)!=null?D:"Chat Assistant";d.textContent=ie,d.setAttribute("title",ie)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let ie=(B=a.subtitle)!=null?B:"Get answers fast";l.textContent=ie,l.setAttribute("title",ie)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let m=n.querySelector("[data-role='launcher-icon']");if(m)if(a.agentIconHidden)m.style.display="none";else{let ie=(v=a.agentIconSize)!=null?v:"40px";if(m.style.height=ie,m.style.width=ie,m.innerHTML="",a.agentIconName){let be=parseFloat(ie)||24,Fe=Te(a.agentIconName,be*.6,"var(--persona-text-inverse, #ffffff)",2);Fe?(m.appendChild(Fe),m.style.display=""):(m.textContent=(x=a.agentIconText)!=null?x:"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=(k=a.agentIconText)!=null?k:"\u{1F4AC}",m.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let ie=(S=a.agentIconSize)!=null?S:"40px";f.style.height=ie,f.style.width=ie,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let u=n.querySelector("[data-role='launcher-call-to-action-icon']");if(u){let ie=(E=a.callToActionIconSize)!=null?E:"32px";u.style.height=ie,u.style.width=ie,a.callToActionIconBackgroundColor?(u.style.backgroundColor=a.callToActionIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(u.style.color=a.callToActionIconColor,u.classList.remove("persona-text-persona-call-to-action")):(u.style.color="",u.classList.add("persona-text-persona-call-to-action"));let be=0;if(a.callToActionIconPadding?(u.style.boxSizing="border-box",u.style.padding=a.callToActionIconPadding,be=(parseFloat(a.callToActionIconPadding)||0)*2):(u.style.boxSizing="",u.style.padding=""),a.callToActionIconHidden)u.style.display="none";else if(u.style.display=i?"none":"",u.innerHTML="",a.callToActionIconName){let Fe=parseFloat(ie)||24,ve=Math.max(Fe-be,8),J=Te(a.callToActionIconName,ve,"currentColor",2);J?u.appendChild(J):u.textContent=(F=a.callToActionIconText)!=null?F:"\u2197"}else u.textContent=($=a.callToActionIconText)!=null?$:"\u2197"}let w=a.position&&xo[a.position]?xo[a.position]:xo["bottom-right"],C="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",M="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?M:`${C} ${w}`,i||(n.style.zIndex=String((j=a.zIndex)!=null?j:hn));let I="1px solid var(--persona-border, #e5e7eb)",R="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(me=a.border)!=null?me:I,n.style.boxShadow=(se=a.shadow)!=null?se:R,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(ge=a.collapsedMaxWidth)!=null?ge:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}};var yy="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",pi=(e,t={})=>{var C,M,I,R,H,D;let{showClose:n=!0,wrapperClassName:o=yy,buttonSize:r,iconSize:s="28px"}=t,a=(C=e==null?void 0:e.launcher)!=null?C:{},i=(M=r!=null?r:a.closeButtonSize)!=null?M:"32px",d=b("div",o),l=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let p=(I=a.closeButtonTooltipText)!=null?I:"Close chat",m=(R=a.closeButtonShowTooltip)!=null?R:!0;l.setAttribute("aria-label",p),l.style.display=n?"":"none";let f=(H=a.closeButtonIconName)!=null?H:"x",u=(D=a.closeButtonIconText)!=null?D:"\xD7";l.style.color=a.closeButtonColor||Mn.actionIconColor;let w=Te(f,s,"currentColor",1);if(w?(w.style.display="block",l.appendChild(w)):l.textContent=u,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let B=a.closeButtonBorderWidth||"0px",v=a.closeButtonBorderColor||"transparent";l.style.border=`${B} solid ${v}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),m&&p){let B=null,v=()=>{if(B)return;let k=l.ownerDocument,S=k.body;if(!S)return;B=Eo(k,"div","persona-clear-chat-tooltip"),B.textContent=p;let E=Eo(k,"div");E.className="persona-clear-chat-tooltip-arrow",B.appendChild(E);let F=l.getBoundingClientRect();B.style.position="fixed",B.style.zIndex=String(or),B.style.left=`${F.left+F.width/2}px`,B.style.top=`${F.top-8}px`,B.style.transform="translate(-50%, -100%)",S.appendChild(B)},x=()=>{B&&B.parentNode&&(B.parentNode.removeChild(B),B=null)};d.addEventListener("mouseenter",v),d.addEventListener("mouseleave",x),l.addEventListener("focus",v),l.addEventListener("blur",x),d._cleanupTooltip=()=>{x(),d.removeEventListener("mouseenter",v),d.removeEventListener("mouseleave",x),l.removeEventListener("focus",v),l.removeEventListener("blur",x)}}return{button:l,wrapper:d}},vy="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ui=(e,t={})=>{var B,v,x,k,S,E,F,$,j,me,se,ge,ie;let{wrapperClassName:n=vy,buttonSize:o,iconSize:r="20px"}=t,a=(v=((B=e==null?void 0:e.launcher)!=null?B:{}).clearChat)!=null?v:{},i=(x=o!=null?o:a.size)!=null?x:"32px",d=(k=a.iconName)!=null?k:"refresh-cw",l=(S=a.iconColor)!=null?S:"",p=(E=a.backgroundColor)!=null?E:"",m=(F=a.borderWidth)!=null?F:"",f=($=a.borderColor)!=null?$:"",u=(j=a.borderRadius)!=null?j:"",w=(me=a.paddingX)!=null?me:"",C=(se=a.paddingY)!=null?se:"",M=(ge=a.tooltipText)!=null?ge:"Clear chat",I=(ie=a.showTooltip)!=null?ie:!0,R=b("div",n),H=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");H.style.height=i,H.style.width=i,H.type="button",H.setAttribute("aria-label",M),H.style.color=l||Mn.actionIconColor;let D=Te(d,r,"currentColor",1);if(D&&(D.style.display="block",H.appendChild(D)),p&&(H.style.backgroundColor=p,H.classList.remove("hover:persona-bg-gray-100")),m||f){let be=m||"0px",Fe=f||"transparent";H.style.border=`${be} solid ${Fe}`,H.classList.remove("persona-border-none")}if(u&&(H.style.borderRadius=u,H.classList.remove("persona-rounded-full")),w&&(H.style.paddingLeft=w,H.style.paddingRight=w),C&&(H.style.paddingTop=C,H.style.paddingBottom=C),R.appendChild(H),I&&M){let be=null,Fe=()=>{if(be)return;let J=H.ownerDocument,Le=J.body;if(!Le)return;be=Eo(J,"div","persona-clear-chat-tooltip"),be.textContent=M;let Y=Eo(J,"div");Y.className="persona-clear-chat-tooltip-arrow",be.appendChild(Y);let xe=H.getBoundingClientRect();be.style.position="fixed",be.style.zIndex=String(or),be.style.left=`${xe.left+xe.width/2}px`,be.style.top=`${xe.top-8}px`,be.style.transform="translate(-50%, -100%)",Le.appendChild(be)},ve=()=>{be&&be.parentNode&&(be.parentNode.removeChild(be),be=null)};R.addEventListener("mouseenter",Fe),R.addEventListener("mouseleave",ve),H.addEventListener("focus",Fe),H.addEventListener("blur",ve),R._cleanupTooltip=()=>{ve(),R.removeEventListener("mouseenter",Fe),R.removeEventListener("mouseleave",ve),H.removeEventListener("focus",Fe),H.removeEventListener("blur",ve)}}return{button:H,wrapper:R}};var Mn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Ar=e=>{var B,v,x,k,S,E,F,$,j,me,se,ge,ie,be,Fe,ve;let{config:t,showClose:n=!0}=e,o=b("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");o.setAttribute("data-persona-theme-zone","header"),o.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",o.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",o.style.boxShadow="var(--persona-header-shadow, none)",o.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let r=(B=t==null?void 0:t.launcher)!=null?B:{},s=(v=r.headerIconSize)!=null?v:"48px",a=(x=r.closeButtonPlacement)!=null?x:"inline",i=(k=r.headerIconHidden)!=null?k:!1,d=r.headerIconName,l=b("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let J=parseFloat(s)||24,Le=Te(d,J*.6,"currentColor",1);Le?l.replaceChildren(Le):l.textContent=(E=(S=t==null?void 0:t.launcher)==null?void 0:S.agentIconText)!=null?E:"\u{1F4AC}"}else if((F=t==null?void 0:t.launcher)!=null&&F.iconUrl){let J=b("img");J.src=t.launcher.iconUrl,J.alt="",J.className="persona-rounded-xl persona-object-cover",J.style.height=s,J.style.width=s,l.replaceChildren(J)}else l.textContent=(j=($=t==null?void 0:t.launcher)==null?void 0:$.agentIconText)!=null?j:"\u{1F4AC}";let p=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=b("span","persona-text-base persona-font-semibold");m.style.color=Mn.titleColor,m.textContent=(se=(me=t==null?void 0:t.launcher)==null?void 0:me.title)!=null?se:"Chat Assistant";let f=b("span","persona-text-xs");f.style.color=Mn.subtitleColor,f.textContent=(ie=(ge=t==null?void 0:t.launcher)==null?void 0:ge.subtitle)!=null?ie:"Here to help you get answers fast",p.append(m,f),i?o.append(p):o.append(l,p);let u=(be=r.clearChat)!=null?be:{},w=(Fe=u.enabled)!=null?Fe:!0,C=(ve=u.placement)!=null?ve:"inline",M=null,I=null;if(w){let Le=ui(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=Le.button,I=Le.wrapper,C==="top-right"&&(I.style.right="48px"),C==="inline"&&o.appendChild(I)}let R=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":w&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:H,wrapper:D}=pi(t,{showClose:n,wrapperClassName:R});return a!=="top-right"&&o.appendChild(D),{header:o,iconHolder:l,headerTitle:m,headerSubtitle:f,closeButton:H,closeButtonWrapper:D,clearChatButton:M,clearChatButtonWrapper:I}},js=(e,t,n)=>{var a,i,d,l;let o=(a=n==null?void 0:n.launcher)!=null?a:{},r=(i=o.closeButtonPlacement)!=null?i:"inline",s=(l=(d=o.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function jr(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=e,a=b("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(or)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let u of t){if(u.dividerBefore){let M=document.createElement("hr");a.appendChild(M)}let w=document.createElement("button");if(w.type="button",w.setAttribute("role","menuitem"),w.setAttribute("data-dropdown-item-id",u.id),u.destructive&&w.setAttribute("data-destructive",""),u.icon){let M=Te(u.icon,16,"currentColor",1.5);M&&w.appendChild(M)}let C=document.createElement("span");C.textContent=u.label,w.appendChild(C),w.addEventListener("click",M=>{M.stopPropagation(),p(),n(u.id)}),a.appendChild(w)}let i=null;function d(){if(!s)return;let u=o.getBoundingClientRect();a.style.top=`${u.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-u.right}px`,a.style.left="auto"):(a.style.left=`${u.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let u=w=>{!a.contains(w.target)&&!o.contains(w.target)&&p()};document.addEventListener("click",u,!0),i=()=>document.removeEventListener("click",u,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function m(){a.classList.contains("persona-hidden")?l():p()}function f(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:p,toggle:m,destroy:f}}function bn(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:i}=e,d=b("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=Te(t,o!=null?o:16,"currentColor",r!=null?r:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[p,m]of Object.entries(i))d.setAttribute(p,m);return d}function fl(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";o!=="default"&&(l+=" persona-label-btn--"+o),l+=" persona-label-btn--"+r,a&&(l+=" "+a);let p=b("button",l);if(p.type="button",p.setAttribute("aria-label",n),t){let f=Te(t,s!=null?s:14,"currentColor",2);f&&p.appendChild(f)}let m=b("span");if(m.textContent=n,p.appendChild(m),i&&p.addEventListener("click",i),d)for(let[f,u]of Object.entries(d))p.setAttribute(f,u);return p}function qu(e){var u,w;let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:i,hover:d}=e,l=b("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let p=b("span","persona-combo-btn-label");p.textContent=t,l.appendChild(p);let m=Te(n,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",l.appendChild(m)),d&&(l.style.borderRadius=(u=d.borderRadius)!=null?u:"10px",l.style.padding=(w=d.padding)!=null?w:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var C,M;l.style.backgroundColor=(C=d.background)!=null?C:"",l.style.borderColor=(M=d.border)!=null?M:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=jr({items:o,onSelect:C=>{l.setAttribute("aria-expanded","false"),r(C)},anchor:l,position:s,portal:a});return a||l.appendChild(f.element),l.addEventListener("click",C=>{C.stopPropagation();let M=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",M?"false":"true"),f.toggle()}),l.addEventListener("keydown",C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),l.click())}),{element:l,setLabel:C=>{p.textContent=C,l.setAttribute("aria-label",C)},open:()=>{l.setAttribute("aria-expanded","true"),f.show()},close:()=>{l.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let C=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",C?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}var xy=e=>{var o;let t=Ar({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(o=e.layoutHeaderConfig)==null?void 0:o.onTitleClick;if(n){let r=t.headerTitle.parentElement;r&&(r.style.cursor="pointer",r.setAttribute("role","button"),r.setAttribute("tabindex","0"),r.addEventListener("click",()=>n()),r.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function wy(e,t,n){var o,r,s;if(t!=null&&t.length)for(let a of t){let i=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(r=(o=a.ariaLabel)!=null?o:a.label)!=null?r:a.id),a.icon){let d=Te(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=b("div","persona-relative");d.appendChild(i);let l=jr({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var Cy=e=>{var R,H,D,B,v,x,k,S,E;let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=(R=t==null?void 0:t.launcher)!=null?R:{},i=b("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=r==null?void 0:r.titleMenu,l,p;if(d)l=qu({label:(H=a.title)!=null?H:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Mn.titleColor,p=(D=l.querySelector(".persona-combo-btn-label"))!=null?D:l;else{if(l=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=b("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Mn.titleColor,p.textContent=(B=a.title)!=null?B:"Chat Assistant",l.appendChild(p),wy(l,r==null?void 0:r.trailingActions,(v=r==null?void 0:r.onAction)!=null?v:s),r!=null&&r.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let $=r.onTitleClick;l.addEventListener("click",j=>{j.target.closest("button")||$()}),l.addEventListener("keydown",j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),$())})}let F=r==null?void 0:r.titleRowHover;F&&(l.style.borderRadius=(x=F.borderRadius)!=null?x:"10px",l.style.padding=(k=F.padding)!=null?k:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var $,j;l.style.backgroundColor=($=F.background)!=null?$:"",l.style.borderColor=(j=F.border)!=null?j:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let m=(S=a.closeButtonSize)!=null?S:"32px",f=b("div",""),u=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");u.style.height=m,u.style.width=m,u.type="button",u.setAttribute("aria-label","Close chat"),u.style.display=n?"":"none",u.style.color=a.closeButtonColor||Mn.actionIconColor;let w=(E=a.closeButtonIconName)!=null?E:"x",C=Te(w,"28px","currentColor",1);C?u.appendChild(C):u.textContent="\xD7",o&&u.addEventListener("click",o),f.appendChild(u),i.appendChild(f);let M=b("div");M.style.display="none";let I=b("span");return I.style.display="none",{header:i,iconHolder:M,headerTitle:p,headerSubtitle:I,closeButton:u,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},ju={default:xy,minimal:Cy},Sy=e=>{var t;return(t=ju[e])!=null?t:ju.default},mi=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=b("div");p.style.display="none";let m=b("span"),f=b("span"),u=b("button");u.style.display="none";let w=b("div");return w.style.display="none",{header:l,iconHolder:p,headerTitle:m,headerSubtitle:f,closeButton:u,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}}let o=(a=t==null?void 0:t.layout)!=null?a:"default",s=Sy(o)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var gi=e=>{var a,i;let t=b("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;t.style.maxHeight=`${n*o}px`,t.style.overflowY="auto";let r=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*o},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,r());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},fi=e=>{var B,v,x,k,S,E,F,$,j,me,se,ge;let t=(B=e==null?void 0:e.sendButton)!=null?B:{},n=(v=t.useIcon)!=null?v:!1,o=(x=t.iconText)!=null?x:"\u2191",r=t.iconName,s=(k=t.stopIconName)!=null?k:"square",a=(S=t.tooltipText)!=null?S:"Send message",i=(E=t.stopTooltipText)!=null?E:"Stop generating",d=($=(F=e==null?void 0:e.copy)==null?void 0:F.sendButtonLabel)!=null?$:"Send",l=(me=(j=e==null?void 0:e.copy)==null?void 0:j.stopButtonLabel)!=null?me:"Stop",p=(se=t.showTooltip)!=null?se:!1,m=(ge=t.size)!=null?ge:"40px",f=t.backgroundColor,u=t.textColor,w=b("div","persona-send-button-wrapper"),C=b("button",n?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");C.type="submit",C.setAttribute("data-persona-composer-submit","");let M=null,I=null;if(n){C.style.width=m,C.style.height=m,C.style.minWidth=m,C.style.minHeight=m,C.style.fontSize="18px",C.style.lineHeight="1",C.innerHTML="",u?C.style.color=u:C.style.color="var(--persona-button-primary-fg, #ffffff)";let ie=parseFloat(m)||24,be=(u==null?void 0:u.trim())||"currentColor";r?(M=Te(r,ie,be,2),M?C.appendChild(M):C.textContent=o):C.textContent=o,I=Te(s,ie,be,2),f?C.style.backgroundColor=f:C.classList.add("persona-bg-persona-primary")}else C.textContent=d,u?C.style.color=u:C.classList.add("persona-text-white");t.borderWidth&&(C.style.borderWidth=t.borderWidth,C.style.borderStyle="solid"),t.borderColor&&(C.style.borderColor=t.borderColor),t.paddingX?(C.style.paddingLeft=t.paddingX,C.style.paddingRight=t.paddingX):(C.style.paddingLeft="",C.style.paddingRight=""),t.paddingY?(C.style.paddingTop=t.paddingY,C.style.paddingBottom=t.paddingY):(C.style.paddingTop="",C.style.paddingBottom="");let R=null;p&&a&&(R=b("div","persona-send-button-tooltip"),R.textContent=a,w.appendChild(R)),C.setAttribute("aria-label",a),w.appendChild(C);let H="send";return{button:C,wrapper:w,setMode:ie=>{if(ie===H)return;H=ie;let be=ie==="stop"?i:a;if(C.setAttribute("aria-label",be),R&&(R.textContent=be),n){if(M&&I){let Fe=ie==="stop"?I:M;C.replaceChildren(Fe)}}else C.textContent=ie==="stop"?l:d}}},hi=e=>{var R,H,D,B,v,x,k,S,E,F,$,j;let t=(R=e==null?void 0:e.voiceRecognition)!=null?R:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),r=((H=t.provider)==null?void 0:H.type)==="runtype";if(!(o||r))return null;let a=(B=(D=e==null?void 0:e.sendButton)==null?void 0:D.size)!=null?B:"40px",i=b("div","persona-send-button-wrapper"),d=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(v=t.iconName)!=null?v:"mic",p=(x=t.iconSize)!=null?x:a,m=parseFloat(p)||24,f=(S=t.backgroundColor)!=null?S:(k=e==null?void 0:e.sendButton)==null?void 0:k.backgroundColor,u=(F=t.iconColor)!=null?F:(E=e==null?void 0:e.sendButton)==null?void 0:E.textColor;d.style.width=p,d.style.height=p,d.style.minWidth=p,d.style.minHeight=p,d.style.fontSize="18px",d.style.lineHeight="1",u?d.style.color=u:d.style.color="var(--persona-text, #111827)";let C=Te(l,m,u||"currentColor",1.5);C?d.appendChild(C):d.textContent="\u{1F3A4}",f&&(d.style.backgroundColor=f),t.borderWidth&&(d.style.borderWidth=t.borderWidth,d.style.borderStyle="solid"),t.borderColor&&(d.style.borderColor=t.borderColor),t.paddingX&&(d.style.paddingLeft=t.paddingX,d.style.paddingRight=t.paddingX),t.paddingY&&(d.style.paddingTop=t.paddingY,d.style.paddingBottom=t.paddingY),i.appendChild(d);let M=($=t.tooltipText)!=null?$:"Start voice recognition";if(((j=t.showTooltip)!=null?j:!1)&&M){let me=b("div","persona-send-button-tooltip");me.textContent=M,i.appendChild(me)}return{button:d,wrapper:i}},bi=e=>{var w,C,M,I,R,H,D,B;let t=(w=e==null?void 0:e.attachments)!=null?w:{};if(t.enabled!==!0)return null;let n=(M=(C=e==null?void 0:e.sendButton)==null?void 0:C.size)!=null?M:"40px",o=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.style.display="none";let r=b("input");r.type="file",r.accept=((I=t.allowedTypes)!=null?I:_o).join(","),r.multiple=((R=t.maxFiles)!=null?R:4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=b("div","persona-send-button-wrapper"),a=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(H=t.buttonTooltipText)!=null?H:"Attach file");let i=(D=t.buttonIconName)!=null?D:"paperclip",d=n,l=parseFloat(d)||40,p=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let m=Te(i,p,"currentColor",1.5);m?a.appendChild(m):a.textContent="\u{1F4CE}",a.addEventListener("click",v=>{v.preventDefault(),r.click()}),s.appendChild(a);let f=(B=t.buttonTooltipText)!=null?B:"Attach file",u=b("div","persona-send-button-tooltip");return u.textContent=f,s.appendChild(u),{button:a,wrapper:s,input:r,previewsContainer:o}},yi=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=b("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=(i=t.visible)!=null?i:!0;o.style.display=r?"":"none";let s=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let l=b("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=s,l.style.color="inherit",l.style.textDecoration="none",o.appendChild(l)}else o.textContent=s;return o},vi=()=>b("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var xi=e=>{var w,C,M,I,R,H;let{config:t}=e,n=b("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");n.setAttribute("data-persona-theme-zone","composer");let o=vi(),r=b("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");r.setAttribute("data-persona-composer-form",""),r.style.outline="none";let{textarea:s,attachAutoResize:a}=gi(t);a();let i=fi(t),d=hi(t),l=bi(t),p=yi(t);l&&(l.previewsContainer.style.gap="8px",r.append(l.previewsContainer,l.input)),r.append(s);let m=b("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),f=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),u=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&f.append(l.wrapper),d&&u.append(d.wrapper),u.append(i.wrapper),m.append(f,u),r.append(m),r.addEventListener("click",D=>{D.target!==i.button&&D.target!==i.wrapper&&D.target!==(d==null?void 0:d.button)&&D.target!==(d==null?void 0:d.wrapper)&&D.target!==(l==null?void 0:l.button)&&D.target!==(l==null?void 0:l.wrapper)&&s.focus()}),n.append(o,r,p),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(w=d==null?void 0:d.button)!=null?w:null,micButtonWrapper:(C=d==null?void 0:d.wrapper)!=null?C:null,statusText:p,attachmentButton:(M=l==null?void 0:l.button)!=null?M:null,attachmentButtonWrapper:(I=l==null?void 0:l.wrapper)!=null?I:null,attachmentInput:(R=l==null?void 0:l.input)!=null?R:null,attachmentPreviewsContainer:(H=l==null?void 0:l.previewsContainer)!=null?H:null,actionsRow:m,leftActions:f,rightActions:u,setSendButtonMode:i.setMode}};var Ku=()=>{let e=b("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let t=b("span","persona-pill-peek__icon"),n=Te("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=b("span","persona-pill-peek__text"),r=b("span","persona-pill-peek__caret"),s=Te("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},Gu=e=>{var w,C,M,I,R,H;let{config:t}=e,n=b("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let o=vi();o.style.display="none";let r=yi(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=gi(t);s.style.maxHeight="100px",a();let i=fi(t),d=hi(t),l=bi(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=b("form","persona-widget-composer persona-pill-composer");p.setAttribute("data-persona-composer-form",""),p.style.outline="none";let m=b("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&m.append(l.wrapper);let f=b("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),p.addEventListener("click",D=>{D.target!==i.button&&D.target!==i.wrapper&&D.target!==(d==null?void 0:d.button)&&D.target!==(d==null?void 0:d.wrapper)&&D.target!==(l==null?void 0:l.button)&&D.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&p.append(l.input),p.append(m,s,f),l&&n.append(l.previewsContainer),n.append(p,o,r);let u=p;return{footer:n,suggestions:o,composerForm:p,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(w=d==null?void 0:d.button)!=null?w:null,micButtonWrapper:(C=d==null?void 0:d.wrapper)!=null?C:null,statusText:r,attachmentButton:(M=l==null?void 0:l.button)!=null?M:null,attachmentButtonWrapper:(I=l==null?void 0:l.wrapper)!=null?I:null,attachmentInput:(R=l==null?void 0:l.input)!=null?R:null,attachmentPreviewsContainer:(H=l==null?void 0:l.previewsContainer)!=null?H:null,actionsRow:u,leftActions:m,rightActions:f,setSendButtonMode:i.setMode}};var Yu=e=>{var p,m,f,u,w,C,M,I,R,H,D,B,v,x,k,S,E;let t=(m=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?m:!0,n=pn(e);if(zs(e)){let F=(u=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?u:{},$=b("div","persona-widget-wrapper persona-fixed persona-transition");$.setAttribute("data-persona-composer-bar",""),$.dataset.state="collapsed",$.dataset.expandedSize=(w=F.expandedSize)!=null?w:"anchored",$.style.zIndex=String((M=(C=e==null?void 0:e.launcher)==null?void 0:C.zIndex)!=null?M:hn);let j=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");j.style.width="100%",$.appendChild(j);let me=b("div","persona-widget-pill-root");return me.setAttribute("data-persona-composer-bar",""),me.dataset.state="collapsed",me.dataset.expandedSize=(I=F.expandedSize)!=null?I:"anchored",me.style.zIndex=String((H=(R=e==null?void 0:e.launcher)==null?void 0:R.zIndex)!=null?H:hn),{wrapper:$,panel:j,pillRoot:me}}if(n){let F=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),$=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return F.appendChild($),{wrapper:F,panel:$}}if(!t){let F=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),$=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),j=(B=(D=e==null?void 0:e.launcher)==null?void 0:D.width)!=null?B:"100%";return F.style.width=j,$.style.width="100%",F.appendChild($),{wrapper:F,panel:$}}let r=(v=e==null?void 0:e.launcher)!=null?v:{},s=r.position&&xo[r.position]?xo[r.position]:xo["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((k=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?k:hn);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(E=(S=e==null?void 0:e.launcher)==null?void 0:S.width)!=null?E:e==null?void 0:e.launcherWidth,l=d!=null?d:io;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Ay=(e,t)=>{var D,B,v,x,k,S,E,F,$;let n=b("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=pi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=(v=(B=(D=e==null?void 0:e.launcher)==null?void 0:D.clearChat)==null?void 0:B.enabled)!=null?v:!0,a=null,i=null;if(s){let j=ui(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=j.button,i=j.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=b("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=b("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let p=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");p.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",p.setAttribute("data-persona-intro-card","");let m=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");m.textContent=(k=(x=e==null?void 0:e.copy)==null?void 0:x.welcomeTitle)!=null?k:"Hello \u{1F44B}";let f=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(E=(S=e==null?void 0:e.copy)==null?void 0:S.welcomeSubtitle)!=null?E:"Ask anything about your account or products.",p.append(m,f);let u=b("div","persona-flex persona-flex-col persona-gap-3"),w=(F=e==null?void 0:e.layout)==null?void 0:F.contentMaxWidth;w&&(u.style.maxWidth=w,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),(($=e==null?void 0:e.copy)==null?void 0:$.showWelcomeCard)!==!1||(p.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(p,u);let M=b("div","persona-composer-overlay persona-pointer-events-none");M.setAttribute("data-persona-composer-overlay",""),M.style.position="absolute",M.style.left="0",M.style.right="0",M.style.bottom="0",M.style.zIndex="20";let I=Gu({config:e}),{root:R,textNode:H}=Ku();return n.append(d,r,l,M),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:u,composerOverlay:M,suggestions:I.suggestions,textarea:I.textarea,sendButton:I.sendButton,sendButtonWrapper:I.sendButtonWrapper,micButton:I.micButton,micButtonWrapper:I.micButtonWrapper,composerForm:I.composerForm,statusText:I.statusText,introTitle:m,introSubtitle:f,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:d,footer:I.footer,attachmentButton:I.attachmentButton,attachmentButtonWrapper:I.attachmentButtonWrapper,attachmentInput:I.attachmentInput,attachmentPreviewsContainer:I.attachmentPreviewsContainer,actionsRow:I.actionsRow,leftActions:I.leftActions,rightActions:I.rightActions,setSendButtonMode:I.setSendButtonMode,peekBanner:R,peekTextNode:H}},Xu=(e,t=!0)=>{var M,I,R,H,D,B,v,x,k;if(zs(e))return Ay(e,t);let n=b("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");n.setAttribute("data-persona-theme-zone","container");let o=(M=e==null?void 0:e.layout)==null?void 0:M.header,r=((I=e==null?void 0:e.layout)==null?void 0:I.showHeader)!==!1,s=o?mi(e,o,{showClose:t}):Ar({config:e,showClose:t}),a=b("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=pn(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(H=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeTitle)!=null?H:"Hello \u{1F44B}";let l=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(B=(D=e==null?void 0:e.copy)==null?void 0:D.welcomeSubtitle)!=null?B:"Ask anything about your account or products.",i.append(d,l);let p=b("div","persona-flex persona-flex-col persona-gap-3"),m=(v=e==null?void 0:e.layout)==null?void 0:v.contentMaxWidth;m&&(p.style.maxWidth=m,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((x=e==null?void 0:e.copy)==null?void 0:x.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,p);let u=xi({config:e}),w=((k=e==null?void 0:e.layout)==null?void 0:k.showFooter)!==!1;r?js(n,s,e):(s.header.style.display="none",js(n,s,e)),n.append(a);let C=b("div","persona-composer-overlay persona-pointer-events-none");return C.setAttribute("data-persona-composer-overlay",""),C.style.position="absolute",C.style.left="0",C.style.right="0",C.style.bottom="0",C.style.zIndex="20",w||(u.footer.style.display="none"),n.append(u.footer),n.append(C),{container:n,body:a,messagesWrapper:p,composerOverlay:C,suggestions:u.suggestions,textarea:u.textarea,sendButton:u.sendButton,sendButtonWrapper:u.sendButtonWrapper,micButton:u.micButton,micButtonWrapper:u.micButtonWrapper,composerForm:u.composerForm,statusText:u.statusText,introTitle:d,introSubtitle:l,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:u.footer,attachmentButton:u.attachmentButton,attachmentButtonWrapper:u.attachmentButtonWrapper,attachmentInput:u.attachmentInput,attachmentPreviewsContainer:u.attachmentPreviewsContainer,actionsRow:u.actionsRow,leftActions:u.leftActions,rightActions:u.rightActions,setSendButtonMode:u.setSendButtonMode}};var Ty=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},ky=(e,t)=>{if(!e)return null;let n=Ty(e);if(n===null)return null;let o=t==null?void 0:t[e],r=o!==void 0?o:n;return r||null},Ey=(e,t)=>{let n=b("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},My=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},hl=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},bl=320,Ju=320,Ly=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Iy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Ry=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Py=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Wy=(e,t,n)=>{if(e.length===0)return null;try{let o=b("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n==null||n())};return e.forEach((i,d)=>{var m;let l=b("img");l.alt=((m=i.alt)==null?void 0:m.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${bl}px`,l.style.maxHeight=`${Ju}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;r+=1,l.addEventListener("error",()=>{p||(p=!0,r=Math.max(0,r-1),l.remove(),r===0&&a())}),l.addEventListener("load",()=>{p=!0}),My(i.image)?(l.src=i.image,o.appendChild(l)):(p=!0,r=Math.max(0,r-1),l.remove())}),r===0?(a(),null):o}catch{return n==null||n(),null}},By=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!hl(o.audio))return;let r=b("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${bl}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Hy=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!hl(o.video))return;let r=b("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${bl}px`,r.style.maxHeight=`${Ju}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Dy=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!hl(o.data))return;let r=b("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Ks=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},Fy=(e,t,n)=>{let o={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Ks};if(t){let r=t(o);if(r!==null)return r}return Ks()},Oy=(e,t)=>{let n=b("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=b("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Qu=(e,t)=>{let n=b("div","persona-text-xs persona-text-persona-muted"),o=new Date(e.createdAt);return t.format?n.textContent=t.format(o):n.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},Ny=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},_y=(e,t,n)=>{var u,w,C,M,I,R;let o=(u=t.showCopy)!=null?u:!0,r=(w=t.showUpvote)!=null?w:!0,s=(C=t.showDownvote)!=null?C:!0;if(!o&&!r&&!s){let H=b("div");return H.style.display="none",H.id=`actions-${e.id}`,H.setAttribute("data-actions-for",e.id),H}let a=(M=t.visibility)!=null?M:"hover",i=(I=t.align)!=null?I:"right",d=(R=t.layout)!=null?R:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],p={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],m=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);m.id=`actions-${e.id}`,m.setAttribute("data-actions-for",e.id);let f=(H,D,B)=>{let v=bn({icon:H,label:D,size:14,className:"persona-message-action-btn"});return v.setAttribute("data-action",B),v};return o&&m.appendChild(f("copy","Copy message","copy")),r&&m.appendChild(f("thumbs-up","Upvote","upvote")),s&&m.appendChild(f("thumbs-down","Downvote","downvote")),m},yl=(e,t,n,o,r,s)=>{var J,Le,Y,xe,Se,de,we,Ue,te,ne,re,nt,ye,le,$e,Be,ce;let a=n!=null?n:{},i=(J=a.layout)!=null?J:"bubble",d=a.avatar,l=a.timestamp,p=(Le=d==null?void 0:d.show)!=null?Le:!1,m=(Y=l==null?void 0:l.show)!=null?Y:!1,f=(xe=d==null?void 0:d.position)!=null?xe:"left",u=(Se=l==null?void 0:l.position)!=null?Se:"below",w=Ny(e.role,i),C=b("div",w.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let M=Ly(e),I=(we=(de=e.content)==null?void 0:de.trim())!=null?we:"",H=M.length>0&&I===Xa,D=ii((te=(Ue=s==null?void 0:s.widgetConfig)==null?void 0:Ue.features)==null?void 0:te.streamAnimation),B=(nt=(re=(ne=s==null?void 0:s.widgetConfig)==null?void 0:ne.features)==null?void 0:re.streamAnimation)==null?void 0:nt.plugins,v=e.role==="assistant"&&D.type!=="none"?_s(D.type,B):null,x=e.role==="assistant"&&((ye=v==null?void 0:v.isAnimating)==null?void 0:ye.call(v,e))===!0,k=e.role==="assistant"&&v!==null&&(!!e.streaming||x);k&&(v!=null&&v.bubbleClass)&&C.classList.add(v.bubbleClass);let S=document.createElement("div");S.classList.add("persona-message-content"),k&&v&&(v.containerClass&&S.classList.add(v.containerClass),S.style.setProperty("--persona-stream-step",`${D.speed}ms`),S.style.setProperty("--persona-stream-duration",`${D.duration}ms`));let E=k?li((le=e.content)!=null?le:"",D.buffer,v,e,!!e.streaming):($e=e.content)!=null?$e:"",F=t({text:E,message:e,streaming:!!e.streaming,raw:e.rawContent}),$=F;k&&(v==null?void 0:v.wrap)==="char"?$=Vs(F,"char",e.id,{skipTags:v.skipTags}):k&&(v==null?void 0:v.wrap)==="word"&&($=Vs(F,"word",e.id,{skipTags:v.skipTags}));let j=null;if(H?(j=document.createElement("div"),j.innerHTML=$,j.style.display="none",S.appendChild(j)):S.innerHTML=$,k&&(v!=null&&v.useCaret)&&!H&&I){let K=ci(),_e=S.querySelectorAll(".persona-stream-char, .persona-stream-word"),Et=_e[_e.length-1];if(Et!=null&&Et.parentNode)Et.parentNode.insertBefore(K,Et.nextSibling);else{let pe=S.lastElementChild;pe?pe.appendChild(K):S.appendChild(K)}}if(m&&u==="inline"&&e.createdAt){let K=Qu(e,l);K.classList.add("persona-ml-2","persona-inline"),S.appendChild(K)}if(M.length>0){let K=Wy(M,!H&&!!I,()=>{H&&j&&(j.style.display="")});K?C.appendChild(K):H&&j&&(j.style.display="")}let me=Iy(e);if(me.length>0){let K=By(me);K&&C.appendChild(K)}let se=Ry(e);if(se.length>0){let K=Hy(se);K&&C.appendChild(K)}let ge=Py(e);if(ge.length>0){let K=Dy(ge);K&&C.appendChild(K)}if(C.appendChild(S),m&&u==="below"&&e.createdAt){let K=Qu(e,l);K.classList.add("persona-mt-1"),C.appendChild(K)}let ie=e.role==="assistant"?ky(e.stopReason,(ce=(Be=s==null?void 0:s.widgetConfig)==null?void 0:Be.copy)==null?void 0:ce.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let K=!!(E&&E.trim()),_e=D.placeholder==="skeleton",Et=_e&&D.buffer==="line"&&K;if(K)Et&&C.appendChild($s());else if(_e)C.appendChild($s());else{let pe=Fy("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);pe&&C.appendChild(pe)}}if(ie&&e.stopReason&&!e.streaming&&(I||(S.style.display="none"),C.appendChild(Ey(e.stopReason,ie))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let K=_y(e,o,r);C.appendChild(K)}if(!p||e.role==="system")return C;let Fe=b("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ve=Oy(d,e.role);return f==="right"||f==="left"&&e.role==="user"?Fe.append(C,ve):Fe.append(ve,C),C.classList.remove("persona-max-w-[85%]"),C.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Fe};var Kr=new Set,Vy=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),$y=(e,t)=>{var o,r;let n=(r=(o=e.reasoning)==null?void 0:o.chunks.join("").trim())!=null?r:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
|
|
24
|
-
`):""},
|
|
25
|
-
`);let r=
|
|
26
|
-
`):""},qy=(e,t)=>{var p,m,f,u,w;let n=e.toolCall,o=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,r=(m=o==null?void 0:o.collapsedMode)!=null?m:"tool-call",s=zy(e,(f=o==null?void 0:o.previewMaxLines)!=null?f:3),a=n?Au(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(u=t==null?void 0:t.toolCall)!=null?u:{},l=a;return r==="tool-name"?l=((w=n.name)==null?void 0:w.trim())||a:r==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=al(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=al(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},em=(e,t,n)=>{var p;let o=Gr.has(e),r=(p=n==null?void 0:n.toolCall)!=null?p:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let m=r.toggleTextColor||r.headerTextColor||"currentColor",f=Te(o?"chevron-up":"chevron-down",16,m,2);f?l.appendChild(f):l.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},xl=(e,t)=>{var $,j,me,se,ge,ie,be,Fe,ve;let n=e.toolCall,o=($=t==null?void 0:t.toolCall)!=null?$:{},r=b("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),!n)return r;let s=(me=(j=t==null?void 0:t.features)==null?void 0:j.toolCallDisplay)!=null?me:{},a=s.expandable!==!1,i=a&&Gr.has(e.id),{summary:d,previewText:l,isActive:p}=qy(e,t),m=b("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");m.type="button",a&&(m.setAttribute("aria-expanded",i?"true":"false"),m.setAttribute("data-expand-header","true")),m.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(m.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(m.style.paddingLeft=o.headerPaddingX,m.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(m.style.paddingTop=o.headerPaddingY,m.style.paddingBottom=o.headerPaddingY);let f=b("div","persona-flex persona-flex-col persona-text-left"),u=b("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(u.style.color=o.headerTextColor);let w=String((se=n.startedAt)!=null?se:Date.now()),C=()=>{let J=b("span","");return J.setAttribute("data-tool-elapsed",w),J.textContent=Rs(n),J},M=(ie=o.renderCollapsedSummary)==null?void 0:ie.call(o,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(ge=s.collapsedMode)!=null?ge:"tool-call",isActive:p,config:t!=null?t:{},elapsed:Rs(n),createElapsedElement:C});typeof M=="string"&&M.trim()?(u.textContent=M,f.appendChild(u)):M instanceof HTMLElement?f.appendChild(M):(u.textContent=d,f.appendChild(u));let I=(be=s.loadingAnimation)!=null?be:"none",R=o.activeTextTemplate,H=o.completeTextTemplate,D=p?R:H,B=M instanceof HTMLElement,v=(J,Le,Y)=>{let xe=Y;for(let Se of Le){let de=b("span","persona-tool-char");de.style.setProperty("--char-index",String(xe)),de.textContent=Se===" "?"\xA0":Se,J.appendChild(de),xe++}return xe},x=(J,Le)=>{var de;u.textContent="";let Y=((de=n.name)==null?void 0:de.trim())||"tool",xe=ja(J,Y),Se=0;for(let we of xe){let Ue=we.styles.length>0?(()=>{let te=b("span",we.styles.map(ne=>`persona-tool-text-${ne}`).join(" "));return u.appendChild(te),te})():u;if(we.isDuration&&p)Ue.appendChild(C());else{let te=we.isDuration?Rs(n):we.text;Le?Se=v(Ue,te,Se):Ue.appendChild(document.createTextNode(te))}}};if(!B)if(p&&I!=="none"){let J=(Fe=o.loadingAnimationDuration)!=null?Fe:2e3;if(u.setAttribute("data-preserve-animation","true"),I==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${J}ms`),D&&x(D,!1);else if(u.classList.add(`persona-tool-loading-${I}`),u.style.setProperty("--persona-tool-anim-duration",`${J}ms`),I==="shimmer-color"&&(o.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),D)x(D,!0);else{let Le=u.textContent||d;u.textContent="",v(u,Le,0)}}else D&&x(D,!1);let k=null;if(a){k=b("div","persona-flex persona-items-center");let J=o.toggleTextColor||o.headerTextColor||"currentColor",Le=Te(i?"chevron-up":"chevron-down",16,J,2);Le?k.appendChild(Le):k.textContent=i?"Hide":"Show";let Y=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Y.append(k),m.append(f,Y)}else m.append(f);let S=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(S.setAttribute("data-persona-collapsed-preview","tool"),S.style.display="none",S.style.whiteSpace="pre-wrap",!i&&p&&s.activePreview&&l){let J=(ve=o.renderCollapsedPreview)==null?void 0:ve.call(o,{message:e,toolCall:n,defaultPreview:l,isActive:p,config:t!=null?t:{}});Uy(S,J)||(S.textContent=l),S.style.display=""}if(!i&&p&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(m,S),r;let E=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(E.style.display=i?"":"none",o.contentBackgroundColor&&(E.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(E.style.color=o.contentTextColor),o.contentPaddingX&&(E.style.paddingLeft=o.contentPaddingX,E.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(E.style.paddingTop=o.contentPaddingY,E.style.paddingBottom=o.contentPaddingY),n.name){let J=b("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?J.style.color=o.contentTextColor:o.headerTextColor&&(J.style.color=o.headerTextColor),J.textContent=n.name,E.appendChild(J)}if(n.args!==void 0){let J=b("div","persona-space-y-1"),Le=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Le.style.color=o.labelTextColor),Le.textContent="Arguments";let Y=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(Y.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(Y.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(Y.style.color=o.codeBlockTextColor),Y.textContent=qr(n.args),J.append(Le,Y),E.appendChild(J)}if(n.chunks&&n.chunks.length){let J=b("div","persona-space-y-1"),Le=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Le.style.color=o.labelTextColor),Le.textContent="Activity";let Y=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(Y.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(Y.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(Y.style.color=o.codeBlockTextColor),Y.textContent=n.chunks.join(""),J.append(Le,Y),E.appendChild(J)}if(n.status==="complete"&&n.result!==void 0){let J=b("div","persona-space-y-1"),Le=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Le.style.color=o.labelTextColor),Le.textContent="Result";let Y=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(Y.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(Y.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(Y.style.color=o.codeBlockTextColor),Y.textContent=qr(n.result),J.append(Le,Y),E.appendChild(J)}if(n.status==="complete"&&typeof n.duration=="number"){let J=b("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(J.style.color=o.contentTextColor),J.textContent=`Duration: ${n.duration}ms`,E.appendChild(J)}return(()=>{if(m.setAttribute("aria-expanded",i?"true":"false"),k){k.innerHTML="";let J=o.toggleTextColor||o.headerTextColor||"currentColor",Le=Te(i?"chevron-up":"chevron-down",16,J,2);Le?k.appendChild(Le):k.textContent=i?"Hide":"Show"}E.style.display=i?"":"none",S.style.display=i?"none":S.textContent||S.childNodes.length?"":"none"})(),r.append(m,S,E),r};import{parse as jy,ARR as Ky,OBJ as Gy,STR as Yy}from"partial-json";var Xy="ask_user_question",wl=8,Yr="data-persona-ask-sheet-for",Qy="Other",Jy="Other\u2026",nm="Type your own answer here",om="Send",Zy="Next",ev="Back",tv="Submit all",nv="Skip",ov=3,Cl="data-ask-current-index",Sl="data-ask-question-count",rm="data-ask-answers",Al="data-ask-grouped",sm="data-ask-layout",rv=e=>e.layout==="pills"?"pills":"rows",sv=e=>e.getAttribute(sm)==="pills"?"pills":"rows",tm=!1,am=e=>e.replace(/["\\]/g,"\\$&"),Tr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Xy,Tl=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},Xr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=jy(r,Yy|Gy|Ky);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Gs=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>wl&&!tm&&(tm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${wl}.`)),t.slice(0,wl)},av=e=>{var t;return(t=Gs(e)[0])!=null?t:null},iv=(e,t)=>{var n;return(n=Gs(e)[t])!=null?n:null},lv=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},im=(e,t,n)=>{if(e!=="rows")return null;let o=b("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=b("span","persona-ask-row-check");o.appendChild(r)}else{let r=b("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},cv=(e,t,n,o)=>{let s=b("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=b("span","persona-ask-row-content"),i=b("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=b("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}s.appendChild(a);let d=im(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},dv=e=>{let n=b("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},pv=(e,t,n,o)=>{var p,m,f;let s=b("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(u=>u&&typeof u.label=="string"&&u.label.length>0);if(d.length===0&&!n){for(let u=0;u<ov;u++)s.appendChild(dv(o));return s}if(d.forEach((u,w)=>{s.appendChild(cv(u,w,o,a))}),(e==null?void 0:e.allowFreeText)!==!1){let u=o==="rows"?Qy:Jy;if(o==="rows"){let w=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");w.setAttribute("data-ask-user-action","focus-free-text"),w.setAttribute("data-option-index",String(d.length)),w.setAttribute("data-ask-other-row","true");let C=b("span","persona-ask-row-content"),M=document.createElement("input");M.type="text",M.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",M.placeholder=(p=t.freeTextPlaceholder)!=null?p:nm,M.setAttribute("data-ask-free-text-input","true"),M.setAttribute("aria-label",(m=t.freeTextLabel)!=null?m:u),C.appendChild(M),w.appendChild(C);let I=im(o,a,d.length);I&&w.appendChild(I),s.appendChild(w)}else{let w=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");w.type="button",w.setAttribute("data-ask-user-action","open-free-text"),w.textContent=(f=t.freeTextLabel)!=null?f:u,s.appendChild(w)}}return s},lm=(e,t)=>{var s,a;let o=b("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=(s=e.freeTextPlaceholder)!=null?s:nm,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let i=b("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:om,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},uv=e=>{var o;let t=b("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=b("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(o=e.submitLabel)!=null?o:om,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},mv=(e,t,n)=>{var l,p,m,f;let o=b("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=b("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=(l=n.backLabel)!=null?l:ev,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=n.skipLabel)!=null?p:nv,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=b("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(m=n.submitAllLabel)!=null?m:tv:(f=n.nextLabel)!=null?f:Zy,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},kr=e=>{let t=e.getAttribute(rm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},cm=(e,t)=>{e.setAttribute(rm,JSON.stringify(t))},lo=e=>{var n;let t=Number((n=e.getAttribute(Cl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},gv=(e,t)=>{e.setAttribute(Cl,String(Math.max(0,Math.floor(t))))},Qr=e=>{var n;let t=Number((n=e.getAttribute(Sl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},sr=e=>e.getAttribute(Al)==="true",fv=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(o[a]=d)}}),o},hv=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},wi=(e,t)=>{let{payload:n}=Xr(t),o=Gs(n),r=kr(e),s={},a=new Set;return o.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(r,d)&&(s[l]=r[d]))}),s},dm=e=>{let t=kr(e),n=lo(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(d=>r.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var m;let l=(m=d.getAttribute("data-option-label"))!=null?m:"",p=r.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!a.has(o)){i.value=o;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},pm=e=>{if(!sr(e))return;let t=kr(e),n=lo(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},kl=(e,t,n)=>{let o=Tl(n),r=sv(e),{payload:s,complete:a}=Xr(t),i=sr(e),d=lo(e),l=Qr(e),p=i?iv(s,d):av(s),m=!!(p!=null&&p.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let u=e.querySelector('[data-ask-stepper="true"]');u&&u.remove();let w=e.querySelector('[data-ask-question="true"]');if(w){let R=typeof(p==null?void 0:p.question)=="string"?p.question:"";w.textContent=R,w.classList.toggle("persona-ask-question-skeleton",!R&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let R=pv(p,o,a,r);C.replaceWith(R)}if(r!=="rows"){let R=e.querySelector('[data-ask-free-text-row="true"]');R&&R.replaceWith(lm(o,r))}let M=e.querySelector('[data-ask-multi-actions="true"]');!i&&m&&!M?e.appendChild(uv(o)):(!m||i)&&M&&M.remove(),e.setAttribute("data-multi-select",m?"true":"false");let I=e.querySelector('[data-ask-nav-row="true"]');if(i){let R=mv(d,l,o);I?I.replaceWith(R):e.appendChild(R)}else I&&I.remove();dm(e),pm(e)},bv=(e,t,n)=>{let o=Tl(t),r=rv(o),s=e.toolCall.id,a=Gs(n),i=Math.max(1,a.length),d=i>1,l=fv(e,a),p=d?hv(e,i):0,m=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(Yr,s),m.setAttribute("data-tool-call-id",s),m.setAttribute("data-message-id",e.id),m.setAttribute(Sl,String(i)),m.setAttribute(Cl,String(p)),m.setAttribute(Al,d?"true":"false"),m.setAttribute(sm,r),cm(m,l),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),lv(m,o);let f=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),u=b("div","persona-ask-sheet-question persona-flex-1");u.setAttribute("data-ask-question","true"),u.textContent="",f.appendChild(u);let w=b("span","persona-ask-sheet-step-inline");w.setAttribute("data-ask-step-inline","true"),w.textContent="",f.appendChild(w),m.appendChild(f);let M=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),m.appendChild(M),r!=="rows"&&m.appendChild(lm(o,r)),kl(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},yv=(e,t,n)=>{let{payload:o}=Xr(t),r=Math.max(1,Gs(o).length);r>Qr(e)&&(e.setAttribute(Sl,String(r)),r>1&&!sr(e)&&e.setAttribute(Al,"true")),kl(e,t,n)};var Ci=(e,t,n)=>{if(!n||!Tr(e)||Tl(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Yr}]`).forEach(l=>{l.getAttribute(Yr)!==r&&l.remove()});let a=n.querySelector(`[${Yr}="${am(r)}"]`);if(a){yv(a,e,t);return}let{payload:i}=Xr(e),d=bv(e,t,i);n.appendChild(d)},Jr=(e,t)=>{if(!e)return;let n=t?`[${Yr}="${am(t)}"]`:`[${Yr}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},El=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),ar=(e,t)=>{let n=kr(e),o=lo(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,cm(e,n),dm(e),pm(e)},Si=(e,t,n,o)=>{let r=Qr(e),s=Math.max(0,Math.min(r-1,o));gv(e,s),kl(e,t,n)};var Ml=(e,t)=>{var C,M,I,R,H,D,B,v,x,k,S,E;let n=e.approval,o=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,r=(n==null?void 0:n.status)==="pending",s=b("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(C=o==null?void 0:o.backgroundColor)!=null?C:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(M=o==null?void 0:o.borderColor)!=null?M:"var(--persona-approval-border, #fef08a)",!n)return s;let a=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=b("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",l=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(I=o==null?void 0:o.titleColor)!=null?I:"currentColor",p=Te(d,20,l,2);p&&i.appendChild(p);let m=b("div","persona-flex-1 persona-min-w-0"),f=b("div","persona-flex persona-items-center persona-gap-2"),u=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o!=null&&o.titleColor&&(u.style.color=o.titleColor),u.textContent=(R=o==null?void 0:o.title)!=null?R:"Approval Required",f.appendChild(u),!r){let F=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");F.setAttribute("data-approval-status",n.status),n.status==="approved"?(F.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",F.style.color="var(--persona-palette-colors-success-700, #15803d)",F.textContent="Approved"):n.status==="denied"?(F.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",F.style.color="var(--persona-palette-colors-error-700, #b91c1c)",F.textContent="Denied"):n.status==="timeout"&&(F.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",F.style.color="var(--persona-palette-colors-warning-700, #b45309)",F.textContent="Timeout"),f.appendChild(F)}m.appendChild(f);let w=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(o!=null&&o.descriptionColor&&(w.style.color=o.descriptionColor),w.textContent=n.description,m.appendChild(w),n.parameters){let F=b("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o!=null&&o.parameterBackgroundColor&&(F.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(F.style.color=o.parameterTextColor),F.style.fontSize="0.75rem",F.style.lineHeight="1rem",F.textContent=qr(n.parameters),m.appendChild(F)}if(r){let F=b("div","persona-flex persona-gap-2 persona-mt-2");F.setAttribute("data-approval-buttons","true");let $=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");$.type="button",$.style.backgroundColor=(H=o==null?void 0:o.approveButtonColor)!=null?H:"var(--persona-approval-approve-bg, #22c55e)",$.style.color=(D=o==null?void 0:o.approveButtonTextColor)!=null?D:"#ffffff",$.setAttribute("data-approval-action","approve");let j=Te("shield-check",14,(B=o==null?void 0:o.approveButtonTextColor)!=null?B:"#ffffff",2);j&&(j.style.marginRight="4px",$.appendChild(j));let me=document.createTextNode((v=o==null?void 0:o.approveLabel)!=null?v:"Approve");$.appendChild(me);let se=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");se.type="button",se.style.backgroundColor=(x=o==null?void 0:o.denyButtonColor)!=null?x:"transparent",se.style.color=(k=o==null?void 0:o.denyButtonTextColor)!=null?k:"var(--persona-feedback-error, #dc2626)",se.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,se.setAttribute("data-approval-action","deny");let ge=Te("shield-x",14,(S=o==null?void 0:o.denyButtonTextColor)!=null?S:"var(--persona-feedback-error, #dc2626)",2);ge&&(ge.style.marginRight="4px",se.appendChild(ge));let ie=document.createTextNode((E=o==null?void 0:o.denyLabel)!=null?E:"Deny");se.appendChild(ie),F.append($,se),m.appendChild(F)}return a.append(i,m),s.appendChild(a),s};var um=e=>{let t=[];return{buttons:t,render:(o,r,s,a,i)=>{if(e.innerHTML="",t.length=0,!o||!o.length||(a!=null?a:r?r.getMessages():[]).some(u=>u.role==="user"))return;let p=document.createDocumentFragment(),m=r?r.isStreaming():!1,f=u=>{switch(u){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};o.forEach(u=>{let w=b("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");w.type="button",w.textContent=u,w.disabled=m,i!=null&&i.fontFamily&&(w.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(w.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(w.style.paddingLeft=i.paddingX,w.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(w.style.paddingTop=i.paddingY,w.style.paddingBottom=i.paddingY),w.addEventListener("click",()=>{!r||r.isStreaming()||(s.value="",r.sendMessage(u))}),p.appendChild(w),t.push(w)}),e.appendChild(p)}}};var Ys=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Xs=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}};var vv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),xv=new Set(["step_start","execution_start"]),wv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Cv=new Set(["step_complete","agent_turn_complete"]),Sv=new Set(["flow_complete","agent_complete"]),mm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),fm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Er=(e,t)=>{let n=e[t];return fm(n)?n:void 0};function Ll(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Ai(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Av(e,t){return typeof t.type=="string"?t.type:e}function Tv(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function kv(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function gm(e){var o,r,s,a,i;let t=Er(e,"result"),n=[Er(e,"tokens"),Er(e,"totalTokens"),t?Er(t,"tokens"):void 0,Er(e,"usage"),t?Er(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(r=(o=Qn(d.output))!=null?o:Qn(d.outputTokens))!=null?r:Qn(d.completionTokens);if(l!==void 0)return l}return(i=(s=Qn(e.outputTokens))!=null?s:Qn(e.completionTokens))!=null?i:t?(a=Qn(t.outputTokens))!=null?a:Qn(t.completionTokens):void 0}function Ev(e){var n,o,r,s,a;let t=Er(e,"result");return(a=(r=(o=(n=Qn(e.executionTime))!=null?n:Qn(e.executionTimeMs))!=null?o:Qn(e.execution_time))!=null?r:Qn(e.duration))!=null?a:t?(s=Qn(t.executionTime))!=null?s:Qn(t.executionTimeMs):void 0}function Mv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Qs=class{constructor(t=Mv){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:Ai(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var s;if(!fm(n)){mm.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Av(t,n),r=this.now();if(vv.has(o)){this.startRun(r);return}if(xv.has(o)){this.run||this.startRun(r);return}if(wv.has(o)){if(!kv(o,n))return;let a=Tv(n);if(!a)return;this.run||this.startRun(r);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=r),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Ll(i.visibleCharCount),l=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ai(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Cv.has(o)){if(!this.run)return;let a=this.run,i=gm(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Ll(a.visibleCharCount),p=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:Ai(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(Sv.has(o)){if(!this.run)return;let a=this.run,i=gm(n),d=i!=null?i:a.exactOutputTokens+Ll(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:Ai(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(mm.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;if(r!==void 0&&r>=250)return r;let s=Ev(n);return s!=null?s:o-t.startedAt}};function Zr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Lv={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},Iv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Rv=["flowName","stepName","reasoningText","text","name","tool","toolName"],Pv=100;function Wv(e,t){let n={...Lv,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Iv}function Bv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Hv(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function Dv(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Fv(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let o=document.createElement("textarea");o.value=e,o.style.position="fixed",o.style.opacity="0",document.body.appendChild(o),o.select(),document.execCommand("copy"),document.body.removeChild(o),n()})}function Ov(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function Nv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function _v(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function Vv(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(i)return i}return a();function a(){let i=b("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=b("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=o,i.appendChild(d),i}}function Il(e,t,n,o,r,s,a,i){var f;let d=r.has(e.id),l=b("div","persona-border-b persona-border-persona-divider persona-text-xs");Zr(l,(f=o.classNames)==null?void 0:f.eventRow);let p=a.find(u=>u.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let u=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>m(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(u)return l.appendChild(u),l}return l.appendChild(m()),l;function m(){var $,j;let u=b("div",""),w=b("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");w.setAttribute("data-event-id",e.id);let C=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),M=Te(d?"chevron-down":"chevron-right","14px","currentColor",2);M&&C.appendChild(M);let I=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),R=($=o.timestampFormat)!=null?$:"relative";I.textContent=R==="relative"?Bv(e.timestamp,n):Hv(e.timestamp);let H=null;o.showSequenceNumbers!==!1&&(H=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),H.textContent=String(t+1));let D=Wv(e.type,o.badgeColors),B=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");B.style.backgroundColor=D.bg,B.style.color=D.text,B.style.borderColor=D.text+"50",B.textContent=e.type;let v=(j=o.descriptionFields)!=null?j:Rv,x=Dv(e.payload,v),k=null;x&&(k=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),k.textContent=x);let S=b("div","persona-flex-1 persona-min-w-0"),E=b("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),F=Te("clipboard","12px","currentColor",1.5);return F&&E.appendChild(F),E.addEventListener("click",async me=>{me.stopPropagation(),await Fv(Ov(e)),E.innerHTML="";let se=Te("check","12px","currentColor",1.5);se&&E.appendChild(se),setTimeout(()=>{E.innerHTML="";let ge=Te("clipboard","12px","currentColor",1.5);ge&&E.appendChild(ge)},1500)}),w.appendChild(C),w.appendChild(I),H&&w.appendChild(H),w.appendChild(B),k&&w.appendChild(k),w.appendChild(S),w.appendChild(E),u.appendChild(w),d&&u.appendChild(Vv(e,a,i)),u}}function hm(e){var w,C,M,I,R;let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,i=(w=r==null?void 0:r.features)==null?void 0:w.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(C=i==null?void 0:i.iconName)!=null?C:"arrow-down",p=(M=i==null?void 0:i.label)!=null?M:"",m=(R=(I=r==null?void 0:r.features)==null?void 0:I.eventStream)!=null?R:{},f=s.find(H=>H.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&r){let H=f.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>u().element,onClose:o});if(H)return{element:H,update:()=>{},destroy:()=>{}}}return u();function u(){let H=m.classNames,D=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Zr(D,H==null?void 0:H.panel);let B=[],v="",x="",k=null,S=[],E={},F=0,$=ri(),j=0,me=0,se=!1,ge=null,ie=!1,be=0,Fe=new Set,ve=new Map,J="",Le="",Y=null,xe,Se,de,we,Ue,te=null,ne=null,re=null;function nt(){let oe=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),fe=b("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");Zr(fe,H==null?void 0:H.headerBar);let xt=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(xt.textContent="Events",xe=b("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),xe.textContent="0",a){ne=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ne.style.cursor="help";let Fn=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Fn.textContent="Throughput",te=b("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),te.textContent="-- tok/s",re=b("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),re.style.display="none",re.style.pointerEvents="none";let Zn=ne,vn=re,On=()=>{if(!vn.textContent)return;let wo=Zn.getBoundingClientRect(),Nn=oe.getBoundingClientRect();vn.style.left=`${wo.left-Nn.left}px`,vn.style.top=`${wo.bottom-Nn.top+4}px`,vn.style.display="block"},ut=()=>{vn.style.display="none"};ne.addEventListener("mouseenter",On),ne.addEventListener("mouseleave",ut),ne.appendChild(Fn),ne.appendChild(te)}let $t=b("div","persona-flex-1");Se=b("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Jt=b("option","");Jt.value="",Jt.textContent="All events",Se.appendChild(Jt),de=b("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),de.type="button",de.title="Copy All";let Tt=Te("clipboard-copy","12px","currentColor",1.5);Tt&&de.appendChild(Tt);let wt=b("span","persona-text-xs");wt.textContent="Copy All",de.appendChild(wt),fe.appendChild(xt),fe.appendChild(xe),ne&&fe.appendChild(ne),fe.appendChild($t),fe.appendChild(Se),fe.appendChild(de);let ft=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Zr(ft,H==null?void 0:H.searchBar);let bt=Te("search","14px","var(--persona-muted, #9ca3af)",1.5),zt=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");bt&&zt.appendChild(bt),we=b("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Zr(we,H==null?void 0:H.searchInput),we.type="text",we.placeholder="Search event payloads...",Ue=b("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Ue.type="button",Ue.style.display="none";let et=Te("x","12px","currentColor",2);return et&&Ue.appendChild(et),ft.appendChild(zt),ft.appendChild(we),ft.appendChild(Ue),oe.appendChild(fe),oe.appendChild(ft),re&&oe.appendChild(re),oe}let ye,le=s.find(oe=>oe.renderEventStreamToolbar);if(le!=null&&le.renderEventStreamToolbar&&r){let oe=le.renderEventStreamToolbar({config:r,defaultRenderer:()=>nt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:fe=>{v=fe,Dn(),_()},onSearchChange:fe=>{x=fe,Dn(),_()}});ye=oe!=null?oe:nt()}else ye=nt();let $e=b("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");$e.style.display="none";function Be(){if(!a||!te||!ne)return;let oe=a();te.textContent=Nv(oe);let fe=_v(oe);re&&(re.textContent=fe,fe||(re.style.display="none")),fe?ne.setAttribute("aria-label",fe):ne.removeAttribute("aria-label")}let ce=b("div","persona-flex-1 persona-min-h-0 persona-relative"),K=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");K.style.height="100%";let _e=b("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Zr(_e,H==null?void 0:H.scrollIndicator),_e.style.display="none",_e.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let Et=Te(l,"14px","currentColor",2);Et&&_e.appendChild(Et);let pe=b("span","");pe.textContent=p,_e.appendChild(pe);let ae=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ae.style.display="none",ce.appendChild(K),ce.appendChild(ae),ce.appendChild(_e),D.setAttribute("tabindex","0"),D.appendChild(ye),D.appendChild($e),D.appendChild(ce);function Ln(){let oe=t.getAll(),fe={};for(let wt of oe)fe[wt.type]=(fe[wt.type]||0)+1;let xt=Object.keys(fe).sort(),$t=xt.length!==S.length||!xt.every((wt,ft)=>wt===S[ft]),Jt=!$t&&xt.some(wt=>fe[wt]!==E[wt]),yn=oe.length!==Object.values(E).reduce((wt,ft)=>wt+ft,0);if(!$t&&!Jt&&!yn||(S=xt,E=fe,!Se))return;let Tt=Se.value;if(Se.options[0].textContent="All events",$t){for(;Se.options.length>1;)Se.remove(1);for(let wt of xt){let ft=b("option","");ft.value=wt,ft.textContent=`${wt} (${fe[wt]||0})`,Se.appendChild(ft)}Tt&&xt.includes(Tt)?Se.value=Tt:Tt&&(Se.value="",v="")}else for(let wt=1;wt<Se.options.length;wt++){let ft=Se.options[wt];ft.textContent=`${ft.value} (${fe[ft.value]||0})`}}function Nt(){let oe=t.getAll();if(v&&(oe=oe.filter(fe=>fe.type===v)),x){let fe=x.toLowerCase();oe=oe.filter(xt=>xt.type.toLowerCase().includes(fe)||xt.payload.toLowerCase().includes(fe))}return oe}function ln(){return v!==""||x!==""}function Dn(){F=0,j=0,$.resume(),_e.style.display="none"}function Jn(oe){Fe.has(oe)?Fe.delete(oe):Fe.add(oe),Y=oe;let fe=K.scrollTop,xt=$.isFollowing();ie=!0,$.pause(),_(),K.scrollTop=fe,xt&&$.resume(),ie=!1}function ze(){return Os(K,50)}function _(){me=Date.now(),se=!1,Be(),Ln();let oe=t.getEvictedCount();oe>0?($e.textContent=`${oe.toLocaleString()} older events truncated`,$e.style.display=""):$e.style.display="none",B=Nt();let fe=B.length,xt=t.getSize()>0;xe&&(xe.textContent=String(t.getSize())),fe===0&&xt&&ln()?(ae.textContent=x?`No events matching '${x}'`:"No events matching filter",ae.style.display="",K.style.display="none"):(ae.style.display="none",K.style.display=""),de&&(de.title=ln()?`Copy Filtered (${fe})`:"Copy All"),d&&!$.isFollowing()&&fe>F&&(j+=fe-F,pe.textContent=p?`${p}${j>0?` (${j})`:""}`:"",_e.style.display=""),F=fe;let $t=t.getAll(),Jt=$t.length>0?$t[0].timestamp:0,yn=new Set(B.map(ft=>ft.id));for(let ft of Fe)yn.has(ft)||Fe.delete(ft);let Tt=v!==J||x!==Le,wt=ve.size===0&&B.length>0;if(Tt||wt||B.length===0){K.innerHTML="",ve.clear();let ft=document.createDocumentFragment();for(let bt=0;bt<B.length;bt++){let zt=Il(B[bt],bt,Jt,m,Fe,Jn,s,r);ve.set(B[bt].id,zt),ft.appendChild(zt)}K.appendChild(ft),J=v,Le=x,Y=null}else{if(Y!==null){let bt=ve.get(Y);if(bt&&bt.parentNode===K){let zt=B.findIndex(et=>et.id===Y);if(zt>=0){let et=Il(B[zt],zt,Jt,m,Fe,Jn,s,r);K.insertBefore(et,bt),bt.remove(),ve.set(Y,et)}}Y=null}let ft=new Set(B.map(bt=>bt.id));for(let[bt,zt]of ve)ft.has(bt)||(zt.remove(),ve.delete(bt));for(let bt=0;bt<B.length;bt++){let zt=B[bt];if(!ve.has(zt.id)){let et=Il(zt,bt,Jt,m,Fe,Jn,s,r);ve.set(zt.id,et),K.appendChild(et)}}}$.isFollowing()&&(K.scrollTop=K.scrollHeight)}function ke(){if(Date.now()-me>=Pv){ge!==null&&(cancelAnimationFrame(ge),ge=null),_();return}se||(se=!0,ge=requestAnimationFrame(()=>{ge=null,_()}))}let He=(oe,fe)=>{if(!de)return;de.innerHTML="";let xt=Te(oe,"12px","currentColor",1.5);xt&&de.appendChild(xt);let $t=b("span","persona-text-xs");$t.textContent="Copy All",de.appendChild($t),setTimeout(()=>{de.innerHTML="";let Jt=Te("clipboard-copy","12px","currentColor",1.5);Jt&&de.appendChild(Jt);let yn=b("span","persona-text-xs");yn.textContent="Copy All",de.appendChild(yn),de.disabled=!1},fe)},De=async()=>{if(de){de.disabled=!0;try{let oe;ln()?oe=B:n?(oe=await n(),oe.length===0&&(oe=t.getAll())):oe=t.getAll();let fe=oe.map(xt=>{try{return JSON.parse(xt.payload)}catch{return xt.payload}});await navigator.clipboard.writeText(JSON.stringify(fe,null,2)),He("check",1500)}catch{He("x",1500)}}},Ve=()=>{Se&&(v=Se.value,Dn(),_())},dt=()=>{!we||!Ue||(Ue.style.display=we.value?"":"none",k&&clearTimeout(k),k=setTimeout(()=>{x=we.value,Dn(),_()},150))},ot=()=>{!we||!Ue||(we.value="",x="",Ue.style.display="none",k&&clearTimeout(k),Dn(),_())},At=()=>{if(ie)return;let oe=K.scrollTop,{action:fe,nextLastScrollTop:xt}=si({following:$.isFollowing(),currentScrollTop:oe,lastScrollTop:be,nearBottom:ze(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});be=xt,fe==="resume"?($.resume(),j=0,_e.style.display="none"):fe==="pause"&&($.pause(),d&&(pe.textContent=p,_e.style.display=""))},Vt=oe=>{let fe=ai({following:$.isFollowing(),deltaY:oe.deltaY,nearBottom:ze(),resumeWhenNearBottom:!0});fe==="pause"?($.pause(),d&&(pe.textContent=p,_e.style.display="")):fe==="resume"&&($.resume(),j=0,_e.style.display="none")},q=()=>{d&&(K.scrollTop=K.scrollHeight,$.resume(),j=0,_e.style.display="none")},_t=oe=>{let fe=oe.target;if(!fe||fe.closest("button"))return;let xt=fe.closest("[data-event-id]");if(!xt)return;let $t=xt.getAttribute("data-event-id");$t&&Jn($t)},Qe=oe=>{if((oe.metaKey||oe.ctrlKey)&&oe.key==="f"){oe.preventDefault(),we==null||we.focus(),we==null||we.select();return}oe.key==="Escape"&&(we&&document.activeElement===we?(ot(),we.blur(),D.focus()):o&&o())};de&&de.addEventListener("click",De),Se&&Se.addEventListener("change",Ve),we&&we.addEventListener("input",dt),Ue&&Ue.addEventListener("click",ot),K.addEventListener("scroll",At),K.addEventListener("wheel",Vt,{passive:!0}),K.addEventListener("click",_t),_e.addEventListener("click",q),D.addEventListener("keydown",Qe);function Ft(){k&&clearTimeout(k),ge!==null&&(cancelAnimationFrame(ge),ge=null),se=!1,ve.clear(),de&&de.removeEventListener("click",De),Se&&Se.removeEventListener("change",Ve),we&&we.removeEventListener("input",dt),Ue&&Ue.removeEventListener("click",ot),K.removeEventListener("scroll",At),K.removeEventListener("wheel",Vt),K.removeEventListener("click",_t),_e.removeEventListener("click",q),D.removeEventListener("keydown",Qe)}return{element:D,update:ke,destroy:Ft}}}function bm(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",o=typeof e.artifactId=="string"?e.artifactId:"",r=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),o&&i.setAttribute("data-open-artifact",o);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=n;let m=document.createElement("div");if(m.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",m.style.color="var(--persona-muted, #9ca3af)",r==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",m.appendChild(f);let u=document.createElement("span");u.textContent=`Generating ${a.toLowerCase()}...`,m.appendChild(u)}else m.textContent=a;if(l.append(p,m),i.append(d,l),r==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${n}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",o),i.append(f)}return i}var ym=(e,t)=>{var o,r,s;let n=(s=(r=(o=t==null?void 0:t.config)==null?void 0:o.features)==null?void 0:r.artifacts)==null?void 0:s.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>bm(e,t)});if(p)return p}return bm(e,t)};var Rl=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},Mr=new Rl;Mr.register("PersonaArtifactCard",ym);function $v(e){var r;let t=b("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=b("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify((r=e.props)!=null?r:{},null,2),t.appendChild(n),t.appendChild(o),t}function vm(e,t){var Se,de,we,Ue;let n=(de=(Se=e.features)==null?void 0:Se.artifacts)==null?void 0:de.layout,r=((we=n==null?void 0:n.toolbarPreset)!=null?we:"default")==="document",s=(Ue=n==null?void 0:n.panePadding)==null?void 0:Ue.trim(),a=e.markdown?_a(e.markdown):null,i=Va(e.sanitize),d=te=>{let ne=a?a(te):Ls(te);return i?i(ne):ne},l=typeof document!="undefined"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{l==null||l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"),F==null||F.hide()};l&&l.addEventListener("click",()=>{var te;p(),(te=t.onDismiss)==null||te.call(t)});let m=b("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");m.setAttribute("data-persona-theme-zone","artifact-pane"),r&&m.classList.add("persona-artifact-pane-document");let f=b("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&f.classList.add("persona-artifact-toolbar-document");let u=b("span","persona-text-xs persona-font-medium persona-truncate");u.textContent="Artifacts";let w=b("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");w.type="button",w.textContent="Close",w.setAttribute("aria-label","Close artifacts panel"),w.addEventListener("click",()=>{var te;p(),(te=t.onDismiss)==null||te.call(t)});let C="rendered",M=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),I=r?bn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):bn({icon:"eye",label:"Rendered view"}),R=r?bn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):bn({icon:"code-2",label:"Source"}),H=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),D=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,B=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,v=n==null?void 0:n.documentToolbarCopyMenuItems,x=!!(B&&v&&v.length>0),k=null,S,E=null,F=null;if(r&&(D||B)&&!x){if(S=D?fl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):bn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),B){let te=Te("chevron-down",14,"currentColor",2);te&&S.appendChild(te)}}else r&&x?(k=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),S=D?fl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):bn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),E=bn({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),k.append(S,E)):r?S=bn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):S=bn({icon:"copy",label:"Copy"});let $=r?bn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):bn({icon:"refresh-cw",label:"Refresh"}),j=r?bn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):bn({icon:"x",label:"Close"}),me=()=>{var ye,le,$e;let te=(ye=ve.find(Be=>Be.id===J))!=null?ye:ve[ve.length-1],ne=(le=te==null?void 0:te.id)!=null?le:null,re=(te==null?void 0:te.artifactType)==="markdown"&&($e=te.markdown)!=null?$e:"",nt=te?JSON.stringify({component:te.component,props:te.props},null,2):"";return{markdown:re,jsonPayload:nt,id:ne}},se=async()=>{var ye;let{markdown:te,jsonPayload:ne}=me(),re=(ye=ve.find(le=>le.id===J))!=null?ye:ve[ve.length-1],nt=(re==null?void 0:re.artifactType)==="markdown"?te:re?ne:"";try{await navigator.clipboard.writeText(nt)}catch{}};if(S.addEventListener("click",async()=>{let te=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(te&&x){let{markdown:ne,jsonPayload:re,id:nt}=me();try{await te({actionId:"primary",artifactId:nt,markdown:ne,jsonPayload:re})}catch{}return}await se()}),E&&(v!=null&&v.length)){let te=()=>{var re;return(re=m.closest("[data-persona-root]"))!=null?re:document.body},ne=()=>{F=jr({items:v.map(re=>({id:re.id,label:re.label})),onSelect:async re=>{let{markdown:nt,jsonPayload:ye,id:le}=me(),$e=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{$e?await $e({actionId:re,artifactId:le,markdown:nt,jsonPayload:ye}):re==="markdown"||re==="md"?await navigator.clipboard.writeText(nt):re==="json"||re==="source"?await navigator.clipboard.writeText(ye):await navigator.clipboard.writeText(nt||ye)}catch{}},anchor:k!=null?k:E,position:"bottom-right",portal:te()})};m.isConnected?ne():requestAnimationFrame(ne),E.addEventListener("click",re=>{re.stopPropagation(),F==null||F.toggle()})}$.addEventListener("click",async()=>{var te;try{await((te=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:te.call(n))}catch{}Y()}),j.addEventListener("click",()=>{var te;p(),(te=t.onDismiss)==null||te.call(t)});let ge=()=>{r&&(I.setAttribute("aria-pressed",C==="rendered"?"true":"false"),R.setAttribute("aria-pressed",C==="source"?"true":"false"))};I.addEventListener("click",()=>{C="rendered",ge(),Y()}),R.addEventListener("click",()=>{C="source",ge(),Y()});let ie=b("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");r?(f.replaceChildren(),M.append(I,R),k?H.append(k,$,j):H.append(S,$,j),f.append(M,ie,H),ge()):(f.appendChild(u),f.appendChild(w)),s&&(f.style.paddingLeft=s,f.style.paddingRight=s);let be=b("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Fe=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(be.style.paddingLeft=s,be.style.paddingRight=s,Fe.style.padding=s),m.appendChild(f),m.appendChild(be),m.appendChild(Fe);let ve=[],J=null,Le=!1,Y=()=>{var nt,ye,le,$e;let te=r&&ve.length<=1;be.classList.toggle("persona-hidden",te),be.replaceChildren();for(let Be of ve){let ce=b("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");ce.type="button",ce.textContent=Be.title||Be.id.slice(0,8),Be.id===J&&ce.classList.add("persona-bg-persona-container","persona-border-persona-border"),ce.addEventListener("click",()=>t.onSelect(Be.id)),be.appendChild(ce)}Fe.replaceChildren();let ne=J&&ve.find(Be=>Be.id===J)||ve[ve.length-1];if(!ne)return;if(r){let Be=ne.artifactType==="markdown"?"MD":(nt=ne.component)!=null?nt:"Component",K=(ne.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ie.textContent=`${K} \xB7 ${Be}`}else u.textContent="Artifacts";if(ne.artifactType==="markdown"){if(r&&C==="source"){let ce=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ce.textContent=(ye=ne.markdown)!=null?ye:"",Fe.appendChild(ce);return}let Be=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Be.innerHTML=d((le=ne.markdown)!=null?le:""),Fe.appendChild(Be);return}let re=ne.component?Mr.get(ne.component):void 0;if(re){let ce={message:{id:ne.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let K=re(($e=ne.props)!=null?$e:{},ce);if(K){Fe.appendChild(K);return}}catch{}}Fe.appendChild($v(ne))},xe=()=>{var ne;let te=ve.length>0;if(m.classList.toggle("persona-hidden",!te),l){let re=typeof m.closest=="function"?m.closest("[data-persona-root]"):null,ye=((ne=re==null?void 0:re.classList.contains("persona-artifact-narrow-host"))!=null?ne:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;te&&ye&&Le?(l.classList.remove("persona-hidden"),m.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"))}};return{element:m,backdrop:l,update(te){var ne,re,nt;ve=te.artifacts,J=(nt=(re=te.selectedId)!=null?re:(ne=te.artifacts[te.artifacts.length-1])==null?void 0:ne.id)!=null?nt:null,ve.length>0&&(Le=!0),Y(),xe()},setMobileOpen(te){Le=te,!te&&l?(l.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open")):xe()}}}function co(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function xm(e,t){var s,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!co(t))return;let n=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,o=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),r=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function Uv(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function Ti(e,t){var d,l,p,m,f,u,w,C,M,I;if(!co(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),Uv(e),xm(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(p=n==null?void 0:n.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(m=n==null?void 0:n.paneWidth)!=null?m:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=n==null?void 0:n.paneMaxWidth)!=null?f:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=(u=n==null?void 0:n.paneBackground)==null?void 0:u.trim();o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let r=(w=n==null?void 0:n.panePadding)==null?void 0:w.trim();r?e.style.setProperty("--persona-artifact-pane-padding",r):e.style.removeProperty("--persona-artifact-pane-padding");let s=(C=n==null?void 0:n.documentToolbarIconColor)==null?void 0:C.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(M=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:M.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(I=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:I.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),xm(e,t)}var wm=["panel","seamless"];function ki(e,t){var i,d,l,p,m,f;for(let u of wm)e.classList.remove(`persona-artifact-appearance-${u}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!co(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,o=(l=n==null?void 0:n.paneAppearance)!=null?l:"panel",r=wm.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${r}`);let s=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(m=n==null?void 0:n.paneShadow)==null?void 0:m.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let u=((f=n.unifiedSplitOuterRadius)==null?void 0:f.trim())||s;u&&e.style.setProperty("--persona-artifact-unified-outer-radius",u)}}function Cm(e,t){var n,o,r;return!t||!co(e)?!1:((r=(o=(n=e.features)==null?void 0:n.artifacts)==null?void 0:o.layout)==null?void 0:r.expandLauncherPanelWhenOpen)!==!1}function zv(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function qv(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function jv(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Kv(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Sm(e,t){var a;let o=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function Am(e,t,n,o,r,s){let a=zv(r,200),i=Kv(t,n,o,200);i=Math.max(a,i);let d=qv(s);return d!==null&&(i=Math.min(i,d)),jv(e,a,i)}var Tm={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Pl=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var w,C,M;if(s.dataset.enhanced==="true")return;let a=(w=s.dataset.tvForm)!=null?w:"init";s.dataset.enhanced="true";let i=(C=Tm[a])!=null?C:Tm.init;s.classList.add("persona-form-card","persona-space-y-4");let d=b("div","persona-space-y-1"),l=b("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let I=b("p","persona-text-sm persona-text-persona-muted");I.textContent=i.description,d.appendChild(I)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(I=>{var v,x;let R=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");R.htmlFor=`${t.id}-${a}-${I.name}`;let H=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");H.textContent=I.label,R.appendChild(H);let D=(v=I.type)!=null?v:"text",B;D==="textarea"?(B=document.createElement("textarea"),B.rows=3):(B=document.createElement("input"),B.type=D),B.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",B.id=`${t.id}-${a}-${I.name}`,B.name=I.name,B.placeholder=(x=I.placeholder)!=null?x:"",I.required&&(B.required=!0),R.appendChild(B),p.appendChild(R)});let m=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),u=b("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");u.type="submit",u.textContent=(M=i.submitLabel)!=null?M:"Submit",m.appendChild(f),m.appendChild(u),p.appendChild(m),s.replaceChildren(d,p),p.addEventListener("submit",async I=>{var B,v;I.preventDefault();let R=(B=n.formEndpoint)!=null?B:"/form",H=new FormData(p),D={};H.forEach((x,k)=>{D[k]=x}),D.type=a,u.disabled=!0,f.textContent="Submitting\u2026";try{let x=await fetch(R,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D)});if(!x.ok)throw new Error(`Form submission failed (${x.status})`);let k=await x.json();f.textContent=(v=k.message)!=null?v:"Thanks! We'll be in touch soon.",k.success&&k.nextPrompt&&await o.sendMessage(String(k.nextPrompt))}catch(x){f.textContent=x instanceof Error?x.message:"Something went wrong. Please try again."}finally{u.disabled=!1}})})};var Wl=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var o;let n=this.plugins.get(t);n&&((o=n.onUnregister)==null||o.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var o,r;return((o=n.priority)!=null?o:0)-((r=t.priority)!=null?r:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},Bl=new Wl;var km=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{var a;(a=e.get(r))==null||a.delete(s)};return{on:t,off:n,emit:(r,s)=>{var a;(a=e.get(r))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Gv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Yv=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},Dl=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Gv(e),n=Yv(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},Hl=e=>typeof e=="string"?e:e==null?"":String(e),Js={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Hl(e.payload.text)},messageAndClick:(e,t)=>{var r;if(e.type!=="message_and_click")return;let n=e.payload,o=Hl(n.element);if(o&&((r=t.document)!=null&&r.querySelector)){let s=t.document.querySelector(o);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Hl(n.text)}}},Em=e=>Array.isArray(e)?e.map(t=>String(t)):[],Fl=e=>{let t=new Set(Em(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Em(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,p)=>l||(p==null?void 0:p({text:a,message:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),o();let d={action:i,message:s.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let p=()=>{e.emit("action:resubmit",d)},m=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!m)continue;if(m.handled){let f=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:f,resubmit:m.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var Xv=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Qv=e=>e.map(t=>({...t,streaming:!1})),Jv=e=>e.map(t=>({...t,status:"complete"})),Mm=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Xv(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?Qv(n.messages):void 0,artifacts:n.artifacts?Jv(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};import{parse as j0,STR as K0,OBJ as G0}from"partial-json";function Lm(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Mr.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:i=>{r&&r(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Im(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function Rm(e){let t=Im(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Pm(e){let t=Im(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var Zv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Wm(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=Zv}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let m=null,f=document.createElement("div");f.className="persona-feedback-content";let u=document.createElement("div");u.className="persona-feedback-header";let w=document.createElement("h3");w.className="persona-feedback-title",w.textContent=o,u.appendChild(w);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,u.appendChild(C),f.appendChild(u);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let I=[];for(let v=1;v<=5;v++){let x=document.createElement("button");x.type="button",x.className="persona-feedback-rating-btn persona-feedback-star-btn",x.setAttribute("role","radio"),x.setAttribute("aria-checked","false"),x.setAttribute("aria-label",`${v} star${v>1?"s":""}: ${l[v-1]}`),x.title=l[v-1],x.dataset.rating=String(v),x.innerHTML=`
|
|
23
|
+
`,n.addEventListener("click",t);let o=s=>{var H,D,W,v,x,k,C,T,F,$,j,me,se,fe;let a=(H=s.launcher)!=null?H:{},i=pn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let ie=(D=a.title)!=null?D:"Chat Assistant";d.textContent=ie,d.setAttribute("title",ie)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let ie=(W=a.subtitle)!=null?W:"Get answers fast";l.textContent=ie,l.setAttribute("title",ie)}let m=n.querySelector(".persona-flex-col");m&&(a.textHidden||i?m.style.display="none":m.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let ie=(v=a.agentIconSize)!=null?v:"40px";if(u.style.height=ie,u.style.width=ie,u.innerHTML="",a.agentIconName){let be=parseFloat(ie)||24,Oe=Te(a.agentIconName,be*.6,"var(--persona-text-inverse, #ffffff)",2);Oe?(u.appendChild(Oe),u.style.display=""):(u.textContent=(x=a.agentIconText)!=null?x:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(k=a.agentIconText)!=null?k:"\u{1F4AC}",u.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let ie=(C=a.agentIconSize)!=null?C:"40px";g.style.height=ie,g.style.width=ie,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let p=n.querySelector("[data-role='launcher-call-to-action-icon']");if(p){let ie=(T=a.callToActionIconSize)!=null?T:"32px";p.style.height=ie,p.style.width=ie,a.callToActionIconBackgroundColor?(p.style.backgroundColor=a.callToActionIconBackgroundColor,p.classList.remove("persona-bg-persona-primary")):(p.style.backgroundColor="",p.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(p.style.color=a.callToActionIconColor,p.classList.remove("persona-text-persona-call-to-action")):(p.style.color="",p.classList.add("persona-text-persona-call-to-action"));let be=0;if(a.callToActionIconPadding?(p.style.boxSizing="border-box",p.style.padding=a.callToActionIconPadding,be=(parseFloat(a.callToActionIconPadding)||0)*2):(p.style.boxSizing="",p.style.padding=""),a.callToActionIconHidden)p.style.display="none";else if(p.style.display=i?"none":"",p.innerHTML="",a.callToActionIconName){let Oe=parseFloat(ie)||24,ve=Math.max(Oe-be,8),Q=Te(a.callToActionIconName,ve,"currentColor",2);Q?p.appendChild(Q):p.textContent=(F=a.callToActionIconText)!=null?F:"\u2197"}else p.textContent=($=a.callToActionIconText)!=null?$:"\u2197"}let w=a.position&&xo[a.position]?xo[a.position]:xo["bottom-right"],S="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",M="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?M:`${S} ${w}`,i||(n.style.zIndex=String((j=a.zIndex)!=null?j:hn));let I="1px solid var(--persona-border, #e5e7eb)",L="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(me=a.border)!=null?me:I,n.style.boxShadow=(se=a.shadow)!=null?se:L,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(fe=a.collapsedMaxWidth)!=null?fe:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}};var xy="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",mi=(e,t={})=>{var S,M,I,L,H,D;let{showClose:n=!0,wrapperClassName:o=xy,buttonSize:r,iconSize:s="28px"}=t,a=(S=e==null?void 0:e.launcher)!=null?S:{},i=(M=r!=null?r:a.closeButtonSize)!=null?M:"32px",d=b("div",o),l=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let m=(I=a.closeButtonTooltipText)!=null?I:"Close chat",u=(L=a.closeButtonShowTooltip)!=null?L:!0;l.setAttribute("aria-label",m),l.style.display=n?"":"none";let g=(H=a.closeButtonIconName)!=null?H:"x",p=(D=a.closeButtonIconText)!=null?D:"\xD7";l.style.color=a.closeButtonColor||Mn.actionIconColor;let w=Te(g,s,"currentColor",1);if(w?(w.style.display="block",l.appendChild(w)):l.textContent=p,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let W=a.closeButtonBorderWidth||"0px",v=a.closeButtonBorderColor||"transparent";l.style.border=`${W} solid ${v}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),u&&m){let W=null,v=()=>{if(W)return;let k=l.ownerDocument,C=k.body;if(!C)return;W=Eo(k,"div","persona-clear-chat-tooltip"),W.textContent=m;let T=Eo(k,"div");T.className="persona-clear-chat-tooltip-arrow",W.appendChild(T);let F=l.getBoundingClientRect();W.style.position="fixed",W.style.zIndex=String(or),W.style.left=`${F.left+F.width/2}px`,W.style.top=`${F.top-8}px`,W.style.transform="translate(-50%, -100%)",C.appendChild(W)},x=()=>{W&&W.parentNode&&(W.parentNode.removeChild(W),W=null)};d.addEventListener("mouseenter",v),d.addEventListener("mouseleave",x),l.addEventListener("focus",v),l.addEventListener("blur",x),d._cleanupTooltip=()=>{x(),d.removeEventListener("mouseenter",v),d.removeEventListener("mouseleave",x),l.removeEventListener("focus",v),l.removeEventListener("blur",x)}}return{button:l,wrapper:d}},wy="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",fi=(e,t={})=>{var W,v,x,k,C,T,F,$,j,me,se,fe,ie;let{wrapperClassName:n=wy,buttonSize:o,iconSize:r="20px"}=t,a=(v=((W=e==null?void 0:e.launcher)!=null?W:{}).clearChat)!=null?v:{},i=(x=o!=null?o:a.size)!=null?x:"32px",d=(k=a.iconName)!=null?k:"refresh-cw",l=(C=a.iconColor)!=null?C:"",m=(T=a.backgroundColor)!=null?T:"",u=(F=a.borderWidth)!=null?F:"",g=($=a.borderColor)!=null?$:"",p=(j=a.borderRadius)!=null?j:"",w=(me=a.paddingX)!=null?me:"",S=(se=a.paddingY)!=null?se:"",M=(fe=a.tooltipText)!=null?fe:"Clear chat",I=(ie=a.showTooltip)!=null?ie:!0,L=b("div",n),H=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");H.style.height=i,H.style.width=i,H.type="button",H.setAttribute("aria-label",M),H.style.color=l||Mn.actionIconColor;let D=Te(d,r,"currentColor",1);if(D&&(D.style.display="block",H.appendChild(D)),m&&(H.style.backgroundColor=m,H.classList.remove("hover:persona-bg-gray-100")),u||g){let be=u||"0px",Oe=g||"transparent";H.style.border=`${be} solid ${Oe}`,H.classList.remove("persona-border-none")}if(p&&(H.style.borderRadius=p,H.classList.remove("persona-rounded-full")),w&&(H.style.paddingLeft=w,H.style.paddingRight=w),S&&(H.style.paddingTop=S,H.style.paddingBottom=S),L.appendChild(H),I&&M){let be=null,Oe=()=>{if(be)return;let Q=H.ownerDocument,Le=Q.body;if(!Le)return;be=Eo(Q,"div","persona-clear-chat-tooltip"),be.textContent=M;let Y=Eo(Q,"div");Y.className="persona-clear-chat-tooltip-arrow",be.appendChild(Y);let xe=H.getBoundingClientRect();be.style.position="fixed",be.style.zIndex=String(or),be.style.left=`${xe.left+xe.width/2}px`,be.style.top=`${xe.top-8}px`,be.style.transform="translate(-50%, -100%)",Le.appendChild(be)},ve=()=>{be&&be.parentNode&&(be.parentNode.removeChild(be),be=null)};L.addEventListener("mouseenter",Oe),L.addEventListener("mouseleave",ve),H.addEventListener("focus",Oe),H.addEventListener("blur",ve),L._cleanupTooltip=()=>{ve(),L.removeEventListener("mouseenter",Oe),L.removeEventListener("mouseleave",ve),H.removeEventListener("focus",Oe),H.removeEventListener("blur",ve)}}return{button:H,wrapper:L}};var Mn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Ar=e=>{var W,v,x,k,C,T,F,$,j,me,se,fe,ie,be,Oe,ve;let{config:t,showClose:n=!0}=e,o=b("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");o.setAttribute("data-persona-theme-zone","header"),o.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",o.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",o.style.boxShadow="var(--persona-header-shadow, none)",o.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let r=(W=t==null?void 0:t.launcher)!=null?W:{},s=(v=r.headerIconSize)!=null?v:"48px",a=(x=r.closeButtonPlacement)!=null?x:"inline",i=(k=r.headerIconHidden)!=null?k:!1,d=r.headerIconName,l=b("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let Q=parseFloat(s)||24,Le=Te(d,Q*.6,"currentColor",1);Le?l.replaceChildren(Le):l.textContent=(T=(C=t==null?void 0:t.launcher)==null?void 0:C.agentIconText)!=null?T:"\u{1F4AC}"}else if((F=t==null?void 0:t.launcher)!=null&&F.iconUrl){let Q=b("img");Q.src=t.launcher.iconUrl,Q.alt="",Q.className="persona-rounded-xl persona-object-cover",Q.style.height=s,Q.style.width=s,l.replaceChildren(Q)}else l.textContent=(j=($=t==null?void 0:t.launcher)==null?void 0:$.agentIconText)!=null?j:"\u{1F4AC}";let m=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=b("span","persona-text-base persona-font-semibold");u.style.color=Mn.titleColor,u.textContent=(se=(me=t==null?void 0:t.launcher)==null?void 0:me.title)!=null?se:"Chat Assistant";let g=b("span","persona-text-xs");g.style.color=Mn.subtitleColor,g.textContent=(ie=(fe=t==null?void 0:t.launcher)==null?void 0:fe.subtitle)!=null?ie:"Here to help you get answers fast",m.append(u,g),i?o.append(m):o.append(l,m);let p=(be=r.clearChat)!=null?be:{},w=(Oe=p.enabled)!=null?Oe:!0,S=(ve=p.placement)!=null?ve:"inline",M=null,I=null;if(w){let Le=fi(t,{wrapperClassName:S==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=Le.button,I=Le.wrapper,S==="top-right"&&(I.style.right="48px"),S==="inline"&&o.appendChild(I)}let L=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":w&&S==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:H,wrapper:D}=mi(t,{showClose:n,wrapperClassName:L});return a!=="top-right"&&o.appendChild(D),{header:o,iconHolder:l,headerTitle:u,headerSubtitle:g,closeButton:H,closeButtonWrapper:D,clearChatButton:M,clearChatButtonWrapper:I}},Gs=(e,t,n)=>{var a,i,d,l;let o=(a=n==null?void 0:n.launcher)!=null?a:{},r=(i=o.closeButtonPlacement)!=null?i:"inline",s=(l=(d=o.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Kr(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=e,a=b("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(or)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let p of t){if(p.dividerBefore){let M=document.createElement("hr");a.appendChild(M)}let w=document.createElement("button");if(w.type="button",w.setAttribute("role","menuitem"),w.setAttribute("data-dropdown-item-id",p.id),p.destructive&&w.setAttribute("data-destructive",""),p.icon){let M=Te(p.icon,16,"currentColor",1.5);M&&w.appendChild(M)}let S=document.createElement("span");S.textContent=p.label,w.appendChild(S),w.addEventListener("click",M=>{M.stopPropagation(),m(),n(p.id)}),a.appendChild(w)}let i=null;function d(){if(!s)return;let p=o.getBoundingClientRect();a.style.top=`${p.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-p.right}px`,a.style.left="auto"):(a.style.left=`${p.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let p=w=>{!a.contains(w.target)&&!o.contains(w.target)&&m()};document.addEventListener("click",p,!0),i=()=>document.removeEventListener("click",p,!0)})}function m(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?l():m()}function g(){m(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:m,toggle:u,destroy:g}}function bn(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:i}=e,d=b("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=Te(t,o!=null?o:16,"currentColor",r!=null?r:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[m,u]of Object.entries(i))d.setAttribute(m,u);return d}function hl(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";o!=="default"&&(l+=" persona-label-btn--"+o),l+=" persona-label-btn--"+r,a&&(l+=" "+a);let m=b("button",l);if(m.type="button",m.setAttribute("aria-label",n),t){let g=Te(t,s!=null?s:14,"currentColor",2);g&&m.appendChild(g)}let u=b("span");if(u.textContent=n,m.appendChild(u),i&&m.addEventListener("click",i),d)for(let[g,p]of Object.entries(d))m.setAttribute(g,p);return m}function Ku(e){var p,w;let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:i,hover:d}=e,l=b("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let m=b("span","persona-combo-btn-label");m.textContent=t,l.appendChild(m);let u=Te(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",l.appendChild(u)),d&&(l.style.borderRadius=(p=d.borderRadius)!=null?p:"10px",l.style.padding=(w=d.padding)!=null?w:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var S,M;l.style.backgroundColor=(S=d.background)!=null?S:"",l.style.borderColor=(M=d.border)!=null?M:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let g=Kr({items:o,onSelect:S=>{l.setAttribute("aria-expanded","false"),r(S)},anchor:l,position:s,portal:a});return a||l.appendChild(g.element),l.addEventListener("click",S=>{S.stopPropagation();let M=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",M?"false":"true"),g.toggle()}),l.addEventListener("keydown",S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),l.click())}),{element:l,setLabel:S=>{m.textContent=S,l.setAttribute("aria-label",S)},open:()=>{l.setAttribute("aria-expanded","true"),g.show()},close:()=>{l.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let S=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",S?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),l.remove()}}}var Cy=e=>{var o;let t=Ar({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(o=e.layoutHeaderConfig)==null?void 0:o.onTitleClick;if(n){let r=t.headerTitle.parentElement;r&&(r.style.cursor="pointer",r.setAttribute("role","button"),r.setAttribute("tabindex","0"),r.addEventListener("click",()=>n()),r.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function Sy(e,t,n){var o,r,s;if(t!=null&&t.length)for(let a of t){let i=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(r=(o=a.ariaLabel)!=null?o:a.label)!=null?r:a.id),a.icon){let d=Te(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=b("div","persona-relative");d.appendChild(i);let l=Kr({items:a.menuItems,onSelect:m=>n==null?void 0:n(m),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",m=>{m.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var Ay=e=>{var L,H,D,W,v,x,k,C,T;let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=(L=t==null?void 0:t.launcher)!=null?L:{},i=b("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=r==null?void 0:r.titleMenu,l,m;if(d)l=Ku({label:(H=a.title)!=null?H:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Mn.titleColor,m=(D=l.querySelector(".persona-combo-btn-label"))!=null?D:l;else{if(l=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),m=b("span","persona-text-base persona-font-semibold persona-truncate"),m.style.color=Mn.titleColor,m.textContent=(W=a.title)!=null?W:"Chat Assistant",l.appendChild(m),Sy(l,r==null?void 0:r.trailingActions,(v=r==null?void 0:r.onAction)!=null?v:s),r!=null&&r.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let $=r.onTitleClick;l.addEventListener("click",j=>{j.target.closest("button")||$()}),l.addEventListener("keydown",j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),$())})}let F=r==null?void 0:r.titleRowHover;F&&(l.style.borderRadius=(x=F.borderRadius)!=null?x:"10px",l.style.padding=(k=F.padding)!=null?k:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var $,j;l.style.backgroundColor=($=F.background)!=null?$:"",l.style.borderColor=(j=F.border)!=null?j:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let u=(C=a.closeButtonSize)!=null?C:"32px",g=b("div",""),p=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");p.style.height=u,p.style.width=u,p.type="button",p.setAttribute("aria-label","Close chat"),p.style.display=n?"":"none",p.style.color=a.closeButtonColor||Mn.actionIconColor;let w=(T=a.closeButtonIconName)!=null?T:"x",S=Te(w,"28px","currentColor",1);S?p.appendChild(S):p.textContent="\xD7",o&&p.addEventListener("click",o),g.appendChild(p),i.appendChild(g);let M=b("div");M.style.display="none";let I=b("span");return I.style.display="none",{header:i,iconHolder:M,headerTitle:m,headerSubtitle:I,closeButton:p,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},Gu={default:Cy,minimal:Ay},Ty=e=>{var t;return(t=Gu[e])!=null?t:Gu.default},gi=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),m=b("div");m.style.display="none";let u=b("span"),g=b("span"),p=b("button");p.style.display="none";let w=b("div");return w.style.display="none",{header:l,iconHolder:m,headerTitle:u,headerSubtitle:g,closeButton:p,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}}let o=(a=t==null?void 0:t.layout)!=null?a:"default",s=Ty(o)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var hi=e=>{var a,i;let t=b("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;t.style.maxHeight=`${n*o}px`,t.style.overflowY="auto";let r=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*o},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,r());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},bi=e=>{var W,v,x,k,C,T,F,$,j,me,se,fe;let t=(W=e==null?void 0:e.sendButton)!=null?W:{},n=(v=t.useIcon)!=null?v:!1,o=(x=t.iconText)!=null?x:"\u2191",r=t.iconName,s=(k=t.stopIconName)!=null?k:"square",a=(C=t.tooltipText)!=null?C:"Send message",i=(T=t.stopTooltipText)!=null?T:"Stop generating",d=($=(F=e==null?void 0:e.copy)==null?void 0:F.sendButtonLabel)!=null?$:"Send",l=(me=(j=e==null?void 0:e.copy)==null?void 0:j.stopButtonLabel)!=null?me:"Stop",m=(se=t.showTooltip)!=null?se:!1,u=(fe=t.size)!=null?fe:"40px",g=t.backgroundColor,p=t.textColor,w=b("div","persona-send-button-wrapper"),S=b("button",n?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");S.type="submit",S.setAttribute("data-persona-composer-submit","");let M=null,I=null;if(n){S.style.width=u,S.style.height=u,S.style.minWidth=u,S.style.minHeight=u,S.style.fontSize="18px",S.style.lineHeight="1",S.innerHTML="",p?S.style.color=p:S.style.color="var(--persona-button-primary-fg, #ffffff)";let ie=parseFloat(u)||24,be=(p==null?void 0:p.trim())||"currentColor";r?(M=Te(r,ie,be,2),M?S.appendChild(M):S.textContent=o):S.textContent=o,I=Te(s,ie,be,2),g?S.style.backgroundColor=g:S.classList.add("persona-bg-persona-primary")}else S.textContent=d,p?S.style.color=p:S.classList.add("persona-text-white");t.borderWidth&&(S.style.borderWidth=t.borderWidth,S.style.borderStyle="solid"),t.borderColor&&(S.style.borderColor=t.borderColor),t.paddingX?(S.style.paddingLeft=t.paddingX,S.style.paddingRight=t.paddingX):(S.style.paddingLeft="",S.style.paddingRight=""),t.paddingY?(S.style.paddingTop=t.paddingY,S.style.paddingBottom=t.paddingY):(S.style.paddingTop="",S.style.paddingBottom="");let L=null;m&&a&&(L=b("div","persona-send-button-tooltip"),L.textContent=a,w.appendChild(L)),S.setAttribute("aria-label",a),w.appendChild(S);let H="send";return{button:S,wrapper:w,setMode:ie=>{if(ie===H)return;H=ie;let be=ie==="stop"?i:a;if(S.setAttribute("aria-label",be),L&&(L.textContent=be),n){if(M&&I){let Oe=ie==="stop"?I:M;S.replaceChildren(Oe)}}else S.textContent=ie==="stop"?l:d}}},yi=e=>{var L,H,D,W,v,x,k,C,T,F,$,j;let t=(L=e==null?void 0:e.voiceRecognition)!=null?L:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),r=((H=t.provider)==null?void 0:H.type)==="runtype";if(!(o||r))return null;let a=(W=(D=e==null?void 0:e.sendButton)==null?void 0:D.size)!=null?W:"40px",i=b("div","persona-send-button-wrapper"),d=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(v=t.iconName)!=null?v:"mic",m=(x=t.iconSize)!=null?x:a,u=parseFloat(m)||24,g=(C=t.backgroundColor)!=null?C:(k=e==null?void 0:e.sendButton)==null?void 0:k.backgroundColor,p=(F=t.iconColor)!=null?F:(T=e==null?void 0:e.sendButton)==null?void 0:T.textColor;d.style.width=m,d.style.height=m,d.style.minWidth=m,d.style.minHeight=m,d.style.fontSize="18px",d.style.lineHeight="1",p?d.style.color=p:d.style.color="var(--persona-text, #111827)";let S=Te(l,u,p||"currentColor",1.5);S?d.appendChild(S):d.textContent="\u{1F3A4}",g&&(d.style.backgroundColor=g),t.borderWidth&&(d.style.borderWidth=t.borderWidth,d.style.borderStyle="solid"),t.borderColor&&(d.style.borderColor=t.borderColor),t.paddingX&&(d.style.paddingLeft=t.paddingX,d.style.paddingRight=t.paddingX),t.paddingY&&(d.style.paddingTop=t.paddingY,d.style.paddingBottom=t.paddingY),i.appendChild(d);let M=($=t.tooltipText)!=null?$:"Start voice recognition";if(((j=t.showTooltip)!=null?j:!1)&&M){let me=b("div","persona-send-button-tooltip");me.textContent=M,i.appendChild(me)}return{button:d,wrapper:i}},vi=e=>{var w,S,M,I,L,H,D,W;let t=(w=e==null?void 0:e.attachments)!=null?w:{};if(t.enabled!==!0)return null;let n=(M=(S=e==null?void 0:e.sendButton)==null?void 0:S.size)!=null?M:"40px",o=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.style.display="none";let r=b("input");r.type="file",r.accept=((I=t.allowedTypes)!=null?I:_o).join(","),r.multiple=((L=t.maxFiles)!=null?L:4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=b("div","persona-send-button-wrapper"),a=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(H=t.buttonTooltipText)!=null?H:"Attach file");let i=(D=t.buttonIconName)!=null?D:"paperclip",d=n,l=parseFloat(d)||40,m=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let u=Te(i,m,"currentColor",1.5);u?a.appendChild(u):a.textContent="\u{1F4CE}",a.addEventListener("click",v=>{v.preventDefault(),r.click()}),s.appendChild(a);let g=(W=t.buttonTooltipText)!=null?W:"Attach file",p=b("div","persona-send-button-tooltip");return p.textContent=g,s.appendChild(p),{button:a,wrapper:s,input:r,previewsContainer:o}},xi=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=b("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=(i=t.visible)!=null?i:!0;o.style.display=r?"":"none";let s=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let l=b("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=s,l.style.color="inherit",l.style.textDecoration="none",o.appendChild(l)}else o.textContent=s;return o},wi=()=>b("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var Ci=e=>{var w,S,M,I,L,H;let{config:t}=e,n=b("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");n.setAttribute("data-persona-theme-zone","composer");let o=wi(),r=b("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");r.setAttribute("data-persona-composer-form",""),r.style.outline="none";let{textarea:s,attachAutoResize:a}=hi(t);a();let i=bi(t),d=yi(t),l=vi(t),m=xi(t);l&&(l.previewsContainer.style.gap="8px",r.append(l.previewsContainer,l.input)),r.append(s);let u=b("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),g=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),p=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&g.append(l.wrapper),d&&p.append(d.wrapper),p.append(i.wrapper),u.append(g,p),r.append(u),r.addEventListener("click",D=>{D.target!==i.button&&D.target!==i.wrapper&&D.target!==(d==null?void 0:d.button)&&D.target!==(d==null?void 0:d.wrapper)&&D.target!==(l==null?void 0:l.button)&&D.target!==(l==null?void 0:l.wrapper)&&s.focus()}),n.append(o,r,m),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(w=d==null?void 0:d.button)!=null?w:null,micButtonWrapper:(S=d==null?void 0:d.wrapper)!=null?S:null,statusText:m,attachmentButton:(M=l==null?void 0:l.button)!=null?M:null,attachmentButtonWrapper:(I=l==null?void 0:l.wrapper)!=null?I:null,attachmentInput:(L=l==null?void 0:l.input)!=null?L:null,attachmentPreviewsContainer:(H=l==null?void 0:l.previewsContainer)!=null?H:null,actionsRow:u,leftActions:g,rightActions:p,setSendButtonMode:i.setMode}};var Yu=()=>{let e=b("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let t=b("span","persona-pill-peek__icon"),n=Te("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=b("span","persona-pill-peek__text"),r=b("span","persona-pill-peek__caret"),s=Te("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},Xu=e=>{var w,S,M,I,L,H;let{config:t}=e,n=b("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let o=wi();o.style.display="none";let r=xi(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=hi(t);s.style.maxHeight="100px",a();let i=bi(t),d=yi(t),l=vi(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let m=b("form","persona-widget-composer persona-pill-composer");m.setAttribute("data-persona-composer-form",""),m.style.outline="none";let u=b("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&u.append(l.wrapper);let g=b("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),m.addEventListener("click",D=>{D.target!==i.button&&D.target!==i.wrapper&&D.target!==(d==null?void 0:d.button)&&D.target!==(d==null?void 0:d.wrapper)&&D.target!==(l==null?void 0:l.button)&&D.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&m.append(l.input),m.append(u,s,g),l&&n.append(l.previewsContainer),n.append(m,o,r);let p=m;return{footer:n,suggestions:o,composerForm:m,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(w=d==null?void 0:d.button)!=null?w:null,micButtonWrapper:(S=d==null?void 0:d.wrapper)!=null?S:null,statusText:r,attachmentButton:(M=l==null?void 0:l.button)!=null?M:null,attachmentButtonWrapper:(I=l==null?void 0:l.wrapper)!=null?I:null,attachmentInput:(L=l==null?void 0:l.input)!=null?L:null,attachmentPreviewsContainer:(H=l==null?void 0:l.previewsContainer)!=null?H:null,actionsRow:p,leftActions:u,rightActions:g,setSendButtonMode:i.setMode}};var Qu=e=>{var m,u,g,p,w,S,M,I,L,H,D,W,v,x,k,C,T;let t=(u=(m=e==null?void 0:e.launcher)==null?void 0:m.enabled)!=null?u:!0,n=pn(e);if(js(e)){let F=(p=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?p:{},$=b("div","persona-widget-wrapper persona-fixed persona-transition");$.setAttribute("data-persona-composer-bar",""),$.dataset.state="collapsed",$.dataset.expandedSize=(w=F.expandedSize)!=null?w:"anchored",$.style.zIndex=String((M=(S=e==null?void 0:e.launcher)==null?void 0:S.zIndex)!=null?M:hn);let j=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");j.style.width="100%",$.appendChild(j);let me=b("div","persona-widget-pill-root");return me.setAttribute("data-persona-composer-bar",""),me.dataset.state="collapsed",me.dataset.expandedSize=(I=F.expandedSize)!=null?I:"anchored",me.style.zIndex=String((H=(L=e==null?void 0:e.launcher)==null?void 0:L.zIndex)!=null?H:hn),{wrapper:$,panel:j,pillRoot:me}}if(n){let F=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),$=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return F.appendChild($),{wrapper:F,panel:$}}if(!t){let F=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),$=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),j=(W=(D=e==null?void 0:e.launcher)==null?void 0:D.width)!=null?W:"100%";return F.style.width=j,$.style.width="100%",F.appendChild($),{wrapper:F,panel:$}}let r=(v=e==null?void 0:e.launcher)!=null?v:{},s=r.position&&xo[r.position]?xo[r.position]:xo["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((k=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?k:hn);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(T=(C=e==null?void 0:e.launcher)==null?void 0:C.width)!=null?T:e==null?void 0:e.launcherWidth,l=d!=null?d:io;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},ky=(e,t)=>{var D,W,v,x,k,C,T,F,$;let n=b("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=mi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=(v=(W=(D=e==null?void 0:e.launcher)==null?void 0:D.clearChat)==null?void 0:W.enabled)!=null?v:!0,a=null,i=null;if(s){let j=fi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=j.button,i=j.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=b("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=b("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let m=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");m.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",m.setAttribute("data-persona-intro-card","");let u=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");u.textContent=(k=(x=e==null?void 0:e.copy)==null?void 0:x.welcomeTitle)!=null?k:"Hello \u{1F44B}";let g=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");g.textContent=(T=(C=e==null?void 0:e.copy)==null?void 0:C.welcomeSubtitle)!=null?T:"Ask anything about your account or products.",m.append(u,g);let p=b("div","persona-flex persona-flex-col persona-gap-3"),w=(F=e==null?void 0:e.layout)==null?void 0:F.contentMaxWidth;w&&(p.style.maxWidth=w,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),(($=e==null?void 0:e.copy)==null?void 0:$.showWelcomeCard)!==!1||(m.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(m,p);let M=b("div","persona-composer-overlay persona-pointer-events-none");M.setAttribute("data-persona-composer-overlay",""),M.style.position="absolute",M.style.left="0",M.style.right="0",M.style.bottom="0",M.style.zIndex="20";let I=Xu({config:e}),{root:L,textNode:H}=Yu();return n.append(d,r,l,M),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:p,composerOverlay:M,suggestions:I.suggestions,textarea:I.textarea,sendButton:I.sendButton,sendButtonWrapper:I.sendButtonWrapper,micButton:I.micButton,micButtonWrapper:I.micButtonWrapper,composerForm:I.composerForm,statusText:I.statusText,introTitle:u,introSubtitle:g,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:d,footer:I.footer,attachmentButton:I.attachmentButton,attachmentButtonWrapper:I.attachmentButtonWrapper,attachmentInput:I.attachmentInput,attachmentPreviewsContainer:I.attachmentPreviewsContainer,actionsRow:I.actionsRow,leftActions:I.leftActions,rightActions:I.rightActions,setSendButtonMode:I.setSendButtonMode,peekBanner:L,peekTextNode:H}},Ju=(e,t=!0)=>{var M,I,L,H,D,W,v,x,k;if(js(e))return ky(e,t);let n=b("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");n.setAttribute("data-persona-theme-zone","container");let o=(M=e==null?void 0:e.layout)==null?void 0:M.header,r=((I=e==null?void 0:e.layout)==null?void 0:I.showHeader)!==!1,s=o?gi(e,o,{showClose:t}):Ar({config:e,showClose:t}),a=b("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=pn(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(H=(L=e==null?void 0:e.copy)==null?void 0:L.welcomeTitle)!=null?H:"Hello \u{1F44B}";let l=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(W=(D=e==null?void 0:e.copy)==null?void 0:D.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",i.append(d,l);let m=b("div","persona-flex persona-flex-col persona-gap-3"),u=(v=e==null?void 0:e.layout)==null?void 0:v.contentMaxWidth;u&&(m.style.maxWidth=u,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((x=e==null?void 0:e.copy)==null?void 0:x.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,m);let p=Ci({config:e}),w=((k=e==null?void 0:e.layout)==null?void 0:k.showFooter)!==!1;r?Gs(n,s,e):(s.header.style.display="none",Gs(n,s,e)),n.append(a);let S=b("div","persona-composer-overlay persona-pointer-events-none");return S.setAttribute("data-persona-composer-overlay",""),S.style.position="absolute",S.style.left="0",S.style.right="0",S.style.bottom="0",S.style.zIndex="20",w||(p.footer.style.display="none"),n.append(p.footer),n.append(S),{container:n,body:a,messagesWrapper:m,composerOverlay:S,suggestions:p.suggestions,textarea:p.textarea,sendButton:p.sendButton,sendButtonWrapper:p.sendButtonWrapper,micButton:p.micButton,micButtonWrapper:p.micButtonWrapper,composerForm:p.composerForm,statusText:p.statusText,introTitle:d,introSubtitle:l,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:p.footer,attachmentButton:p.attachmentButton,attachmentButtonWrapper:p.attachmentButtonWrapper,attachmentInput:p.attachmentInput,attachmentPreviewsContainer:p.attachmentPreviewsContainer,actionsRow:p.actionsRow,leftActions:p.leftActions,rightActions:p.rightActions,setSendButtonMode:p.setSendButtonMode}};var Ey=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},My=(e,t)=>{if(!e)return null;let n=Ey(e);if(n===null)return null;let o=t==null?void 0:t[e],r=o!==void 0?o:n;return r||null},Ly=(e,t)=>{let n=b("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},Iy=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},bl=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},yl=320,em=320,Ry=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Py=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Wy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),By=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Hy=(e,t,n)=>{if(e.length===0)return null;try{let o=b("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n==null||n())};return e.forEach((i,d)=>{var u;let l=b("img");l.alt=((u=i.alt)==null?void 0:u.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${yl}px`,l.style.maxHeight=`${em}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let m=!1;r+=1,l.addEventListener("error",()=>{m||(m=!0,r=Math.max(0,r-1),l.remove(),r===0&&a())}),l.addEventListener("load",()=>{m=!0}),Iy(i.image)?(l.src=i.image,o.appendChild(l)):(m=!0,r=Math.max(0,r-1),l.remove())}),r===0?(a(),null):o}catch{return n==null||n(),null}},Dy=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!bl(o.audio))return;let r=b("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${yl}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Fy=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!bl(o.video))return;let r=b("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${yl}px`,r.style.maxHeight=`${em}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Oy=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!bl(o.data))return;let r=b("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Ys=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},Ny=(e,t,n)=>{let o={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Ys};if(t){let r=t(o);if(r!==null)return r}return Ys()},_y=(e,t)=>{let n=b("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=b("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Zu=(e,t)=>{let n=b("div","persona-text-xs persona-text-persona-muted"),o=new Date(e.createdAt);return t.format?n.textContent=t.format(o):n.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},Vy=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},$y=(e,t,n)=>{var p,w,S,M,I,L;let o=(p=t.showCopy)!=null?p:!0,r=(w=t.showUpvote)!=null?w:!0,s=(S=t.showDownvote)!=null?S:!0;if(!o&&!r&&!s){let H=b("div");return H.style.display="none",H.id=`actions-${e.id}`,H.setAttribute("data-actions-for",e.id),H}let a=(M=t.visibility)!=null?M:"hover",i=(I=t.align)!=null?I:"right",d=(L=t.layout)!=null?L:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],m={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],u=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${m} ${a==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${e.id}`,u.setAttribute("data-actions-for",e.id);let g=(H,D,W)=>{let v=bn({icon:H,label:D,size:14,className:"persona-message-action-btn"});return v.setAttribute("data-action",W),v};return o&&u.appendChild(g("copy","Copy message","copy")),r&&u.appendChild(g("thumbs-up","Upvote","upvote")),s&&u.appendChild(g("thumbs-down","Downvote","downvote")),u},vl=(e,t,n,o,r,s)=>{var Q,Le,Y,xe,Se,de,we,ze,te,ne,re,nt,ye,le,Ue,He,ce;let a=n!=null?n:{},i=(Q=a.layout)!=null?Q:"bubble",d=a.avatar,l=a.timestamp,m=(Le=d==null?void 0:d.show)!=null?Le:!1,u=(Y=l==null?void 0:l.show)!=null?Y:!1,g=(xe=d==null?void 0:d.position)!=null?xe:"left",p=(Se=l==null?void 0:l.position)!=null?Se:"below",w=Vy(e.role,i),S=b("div",w.join(" "));S.id=`bubble-${e.id}`,S.setAttribute("data-message-id",e.id),S.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(S.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",S.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(S.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",S.style.color="var(--persona-message-assistant-text, var(--persona-text))");let M=Ry(e),I=(we=(de=e.content)==null?void 0:de.trim())!=null?we:"",H=M.length>0&&I===Ja,D=ci((te=(ze=s==null?void 0:s.widgetConfig)==null?void 0:ze.features)==null?void 0:te.streamAnimation),W=(nt=(re=(ne=s==null?void 0:s.widgetConfig)==null?void 0:ne.features)==null?void 0:re.streamAnimation)==null?void 0:nt.plugins,v=e.role==="assistant"&&D.type!=="none"?$s(D.type,W):null,x=e.role==="assistant"&&((ye=v==null?void 0:v.isAnimating)==null?void 0:ye.call(v,e))===!0,k=e.role==="assistant"&&v!==null&&(!!e.streaming||x);k&&(v!=null&&v.bubbleClass)&&S.classList.add(v.bubbleClass);let C=document.createElement("div");C.classList.add("persona-message-content"),k&&v&&(v.containerClass&&C.classList.add(v.containerClass),C.style.setProperty("--persona-stream-step",`${D.speed}ms`),C.style.setProperty("--persona-stream-duration",`${D.duration}ms`));let T=k?di((le=e.content)!=null?le:"",D.buffer,v,e,!!e.streaming):(Ue=e.content)!=null?Ue:"",F=t({text:T,message:e,streaming:!!e.streaming,raw:e.rawContent}),$=F;k&&(v==null?void 0:v.wrap)==="char"?$=Us(F,"char",e.id,{skipTags:v.skipTags}):k&&(v==null?void 0:v.wrap)==="word"&&($=Us(F,"word",e.id,{skipTags:v.skipTags}));let j=null;if(H?(j=document.createElement("div"),j.innerHTML=$,j.style.display="none",C.appendChild(j)):C.innerHTML=$,k&&(v!=null&&v.useCaret)&&!H&&I){let G=pi(),Ve=C.querySelectorAll(".persona-stream-char, .persona-stream-word"),Et=Ve[Ve.length-1];if(Et!=null&&Et.parentNode)Et.parentNode.insertBefore(G,Et.nextSibling);else{let pe=C.lastElementChild;pe?pe.appendChild(G):C.appendChild(G)}}if(u&&p==="inline"&&e.createdAt){let G=Zu(e,l);G.classList.add("persona-ml-2","persona-inline"),C.appendChild(G)}if(M.length>0){let G=Hy(M,!H&&!!I,()=>{H&&j&&(j.style.display="")});G?S.appendChild(G):H&&j&&(j.style.display="")}let me=Py(e);if(me.length>0){let G=Dy(me);G&&S.appendChild(G)}let se=Wy(e);if(se.length>0){let G=Fy(se);G&&S.appendChild(G)}let fe=By(e);if(fe.length>0){let G=Oy(fe);G&&S.appendChild(G)}if(S.appendChild(C),u&&p==="below"&&e.createdAt){let G=Zu(e,l);G.classList.add("persona-mt-1"),S.appendChild(G)}let ie=e.role==="assistant"?My(e.stopReason,(ce=(He=s==null?void 0:s.widgetConfig)==null?void 0:He.copy)==null?void 0:ce.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let G=!!(T&&T.trim()),Ve=D.placeholder==="skeleton",Et=Ve&&D.buffer==="line"&&G;if(G)Et&&S.appendChild(zs());else if(Ve)S.appendChild(zs());else{let pe=Ny("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);pe&&S.appendChild(pe)}}if(ie&&e.stopReason&&!e.streaming&&(I||(C.style.display="none"),S.appendChild(Ly(e.stopReason,ie))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let G=$y(e,o,r);S.appendChild(G)}if(!m||e.role==="system")return S;let Oe=b("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ve=_y(d,e.role);return g==="right"||g==="left"&&e.role==="user"?Oe.append(S,ve):Oe.append(ve,S),S.classList.remove("persona-max-w-[85%]"),S.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Oe};var Gr=new Set,Uy=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),zy=(e,t)=>{var o,r;let n=(r=(o=e.reasoning)==null?void 0:o.chunks.join("").trim())!=null?r:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
|
|
24
|
+
`):""},tm=(e,t)=>{let n=Gr.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let a=o.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=Te(n?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},xl=(e,t)=>{var se,fe,ie,be,Oe,ve,Q,Le,Y,xe,Se;let n=e.reasoning,o=b("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let r=(fe=(se=t==null?void 0:t.features)==null?void 0:se.reasoningDisplay)!=null?fe:{},s=r.expandable!==!1,a=s&&Gr.has(e.id),i=n.status!=="complete",d=zy(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 m=b("div","persona-flex persona-flex-col persona-text-left"),u=b("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",p=(be=t==null?void 0:t.reasoning)!=null?be:{},w=String((Oe=n.startedAt)!=null?Oe:Date.now()),S=()=>{let de=b("span","");return de.setAttribute("data-tool-elapsed",w),de.textContent=Ka(n),de},M=(ve=p.renderCollapsedSummary)==null?void 0:ve.call(p,{message:e,reasoning:n,defaultSummary:g,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Ka(n),createElapsedElement:S});typeof M=="string"&&M.trim()?(u.textContent=M,m.appendChild(u)):M instanceof HTMLElement?m.appendChild(M):(u.textContent=g,m.appendChild(u));let I=b("span","persona-text-xs persona-text-persona-primary");I.textContent=Au(n),m.appendChild(I);let L=(Q=r.loadingAnimation)!=null?Q:"none",H=p.activeTextTemplate,D=p.completeTextTemplate,W=i?H:D,v=M instanceof HTMLElement,x=(de,we,ze)=>{let te=ze;for(let ne of we){let re=b("span","persona-tool-char");re.style.setProperty("--char-index",String(te)),re.textContent=ne===" "?"\xA0":ne,de.appendChild(re),te++}return te},k=(de,we)=>{u.textContent="";let ze=Ga(de,""),te=0;for(let ne of ze){let re=ne.styles.length>0?(()=>{let nt=b("span",ne.styles.map(ye=>`persona-tool-text-${ye}`).join(" "));return u.appendChild(nt),nt})():u;if(ne.isDuration&&i)re.appendChild(S());else{let nt=ne.isDuration?Ka(n):ne.text;we?te=x(re,nt,te):re.appendChild(document.createTextNode(nt))}}};if(!v&&W)if(I.style.display="none",u.style.display="",i&&L!=="none"){let de=(Le=p.loadingAnimationDuration)!=null?Le:2e3;u.setAttribute("data-preserve-animation","true"),L==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${de}ms`),k(W,!1)):(u.classList.add(`persona-tool-loading-${L}`),u.style.setProperty("--persona-tool-anim-duration",`${de}ms`),L==="shimmer-color"&&(p.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",p.loadingAnimationColor),p.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",p.loadingAnimationSecondaryColor)),k(W,!0))}else k(W,!1);else if(!v&&i&&L!=="none"){u.style.display="";let de=(Y=p.loadingAnimationDuration)!=null?Y:2e3;if(u.setAttribute("data-preserve-animation","true"),L==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${de}ms`);else{u.classList.add(`persona-tool-loading-${L}`),u.style.setProperty("--persona-tool-anim-duration",`${de}ms`),L==="shimmer-color"&&(p.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",p.loadingAnimationColor),p.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",p.loadingAnimationSecondaryColor));let we=u.textContent||g;u.textContent="",x(u,we,0)}n.status==="complete"&&(u.style.display="none")}else v||(n.status==="complete"?u.style.display="none":u.style.display="");let C=null;if(s){C=b("div","persona-flex persona-items-center");let we=Te(a?"chevron-up":"chevron-down",16,"currentColor",2);we?C.appendChild(we):C.textContent=a?"Hide":"Show";let ze=b("div","persona-flex persona-items-center persona-ml-auto");ze.append(C),l.append(m,ze)}else l.append(m);let T=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(T.setAttribute("data-persona-collapsed-preview","reasoning"),T.style.display="none",T.style.whiteSpace="pre-wrap",!a&&i&&r.activePreview&&d){let de=(Se=(xe=t==null?void 0:t.reasoning)==null?void 0:xe.renderCollapsedPreview)==null?void 0:Se.call(xe,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});Uy(T,de)||(T.textContent=d),T.style.display=""}if(!a&&i&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(l,T),o;let F=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");F.style.display=a?"":"none";let $=n.chunks.join(""),j=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return j.textContent=$||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),F.appendChild(j),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),C){C.innerHTML="";let we=Te(a?"chevron-up":"chevron-down",16,"currentColor",2);we?C.appendChild(we):C.textContent=a?"Hide":"Show"}F.style.display=a?"":"none",T.style.display=a?"none":T.textContent||T.childNodes.length?"":"none"})(),o.append(l,T,F),o};var Yr=new Set,qy=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),jy=(e,t)=>{var s;let n=e.toolCall;if(!n)return"";let o=((s=n.chunks)!=null?s:[]).join("").trim();if(o)return o.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
|
|
25
|
+
`);let r=jr(n.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
|
|
26
|
+
`):""},Ky=(e,t)=>{var m,u,g,p,w;let n=e.toolCall,o=(m=t==null?void 0:t.features)==null?void 0:m.toolCallDisplay,r=(u=o==null?void 0:o.collapsedMode)!=null?u:"tool-call",s=jy(e,(g=o==null?void 0:o.previewMaxLines)!=null?g:3),a=n?Tu(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(p=t==null?void 0:t.toolCall)!=null?p:{},l=a;return r==="tool-name"?l=((w=n.name)==null?void 0:w.trim())||a:r==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=il(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=il(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},nm=(e,t,n)=>{var m;let o=Yr.has(e),r=(m=n==null?void 0:n.toolCall)!=null?m:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let u=r.toggleTextColor||r.headerTextColor||"currentColor",g=Te(o?"chevron-up":"chevron-down",16,u,2);g?l.appendChild(g):l.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},wl=(e,t)=>{var $,j,me,se,fe,ie,be,Oe,ve;let n=e.toolCall,o=($=t==null?void 0:t.toolCall)!=null?$:{},r=b("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),!n)return r;let s=(me=(j=t==null?void 0:t.features)==null?void 0:j.toolCallDisplay)!=null?me:{},a=s.expandable!==!1,i=a&&Yr.has(e.id),{summary:d,previewText:l,isActive:m}=Ky(e,t),u=b("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");u.type="button",a&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let g=b("div","persona-flex persona-flex-col persona-text-left"),p=b("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(p.style.color=o.headerTextColor);let w=String((se=n.startedAt)!=null?se:Date.now()),S=()=>{let Q=b("span","");return Q.setAttribute("data-tool-elapsed",w),Q.textContent=Ps(n),Q},M=(ie=o.renderCollapsedSummary)==null?void 0:ie.call(o,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(fe=s.collapsedMode)!=null?fe:"tool-call",isActive:m,config:t!=null?t:{},elapsed:Ps(n),createElapsedElement:S});typeof M=="string"&&M.trim()?(p.textContent=M,g.appendChild(p)):M instanceof HTMLElement?g.appendChild(M):(p.textContent=d,g.appendChild(p));let I=(be=s.loadingAnimation)!=null?be:"none",L=o.activeTextTemplate,H=o.completeTextTemplate,D=m?L:H,W=M instanceof HTMLElement,v=(Q,Le,Y)=>{let xe=Y;for(let Se of Le){let de=b("span","persona-tool-char");de.style.setProperty("--char-index",String(xe)),de.textContent=Se===" "?"\xA0":Se,Q.appendChild(de),xe++}return xe},x=(Q,Le)=>{var de;p.textContent="";let Y=((de=n.name)==null?void 0:de.trim())||"tool",xe=Ga(Q,Y),Se=0;for(let we of xe){let ze=we.styles.length>0?(()=>{let te=b("span",we.styles.map(ne=>`persona-tool-text-${ne}`).join(" "));return p.appendChild(te),te})():p;if(we.isDuration&&m)ze.appendChild(S());else{let te=we.isDuration?Ps(n):we.text;Le?Se=v(ze,te,Se):ze.appendChild(document.createTextNode(te))}}};if(!W)if(m&&I!=="none"){let Q=(Oe=o.loadingAnimationDuration)!=null?Oe:2e3;if(p.setAttribute("data-preserve-animation","true"),I==="pulse")p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${Q}ms`),D&&x(D,!1);else if(p.classList.add(`persona-tool-loading-${I}`),p.style.setProperty("--persona-tool-anim-duration",`${Q}ms`),I==="shimmer-color"&&(o.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),D)x(D,!0);else{let Le=p.textContent||d;p.textContent="",v(p,Le,0)}}else D&&x(D,!1);let k=null;if(a){k=b("div","persona-flex persona-items-center");let Q=o.toggleTextColor||o.headerTextColor||"currentColor",Le=Te(i?"chevron-up":"chevron-down",16,Q,2);Le?k.appendChild(Le):k.textContent=i?"Hide":"Show";let Y=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Y.append(k),u.append(g,Y)}else u.append(g);let C=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(C.setAttribute("data-persona-collapsed-preview","tool"),C.style.display="none",C.style.whiteSpace="pre-wrap",!i&&m&&s.activePreview&&l){let Q=(ve=o.renderCollapsedPreview)==null?void 0:ve.call(o,{message:e,toolCall:n,defaultPreview:l,isActive:m,config:t!=null?t:{}});qy(C,Q)||(C.textContent=l),C.style.display=""}if(!i&&m&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(u,C),r;let T=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(T.style.display=i?"":"none",o.contentBackgroundColor&&(T.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(T.style.color=o.contentTextColor),o.contentPaddingX&&(T.style.paddingLeft=o.contentPaddingX,T.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(T.style.paddingTop=o.contentPaddingY,T.style.paddingBottom=o.contentPaddingY),n.name){let Q=b("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?Q.style.color=o.contentTextColor:o.headerTextColor&&(Q.style.color=o.headerTextColor),Q.textContent=n.name,T.appendChild(Q)}if(n.args!==void 0){let Q=b("div","persona-space-y-1"),Le=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Le.style.color=o.labelTextColor),Le.textContent="Arguments";let Y=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(Y.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(Y.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(Y.style.color=o.codeBlockTextColor),Y.textContent=jr(n.args),Q.append(Le,Y),T.appendChild(Q)}if(n.chunks&&n.chunks.length){let Q=b("div","persona-space-y-1"),Le=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Le.style.color=o.labelTextColor),Le.textContent="Activity";let Y=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(Y.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(Y.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(Y.style.color=o.codeBlockTextColor),Y.textContent=n.chunks.join(""),Q.append(Le,Y),T.appendChild(Q)}if(n.status==="complete"&&n.result!==void 0){let Q=b("div","persona-space-y-1"),Le=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Le.style.color=o.labelTextColor),Le.textContent="Result";let Y=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(Y.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(Y.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(Y.style.color=o.codeBlockTextColor),Y.textContent=jr(n.result),Q.append(Le,Y),T.appendChild(Q)}if(n.status==="complete"&&typeof n.duration=="number"){let Q=b("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(Q.style.color=o.contentTextColor),Q.textContent=`Duration: ${n.duration}ms`,T.appendChild(Q)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),k){k.innerHTML="";let Q=o.toggleTextColor||o.headerTextColor||"currentColor",Le=Te(i?"chevron-up":"chevron-down",16,Q,2);Le?k.appendChild(Le):k.textContent=i?"Hide":"Show"}T.style.display=i?"":"none",C.style.display=i?"none":C.textContent||C.childNodes.length?"":"none"})(),r.append(u,C,T),r};import{parse as Gy,ARR as Yy,OBJ as Xy,STR as Qy}from"partial-json";var Jy="ask_user_question",Cl=8,Xr="data-persona-ask-sheet-for",Zy="Other",ev="Other\u2026",rm="Type your own answer here",sm="Send",tv="Next",nv="Back",ov="Submit all",rv="Skip",sv=3,Sl="data-ask-current-index",Al="data-ask-question-count",am="data-ask-answers",Tl="data-ask-grouped",im="data-ask-layout",av=e=>e.layout==="pills"?"pills":"rows",iv=e=>e.getAttribute(im)==="pills"?"pills":"rows",om=!1,lm=e=>e.replace(/["\\]/g,"\\$&"),Tr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Jy,kl=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},Qr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=Gy(r,Qy|Xy|Yy);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Xs=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>Cl&&!om&&(om=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Cl}.`)),t.slice(0,Cl)},lv=e=>{var t;return(t=Xs(e)[0])!=null?t:null},cv=(e,t)=>{var n;return(n=Xs(e)[t])!=null?n:null},dv=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},cm=(e,t,n)=>{if(e!=="rows")return null;let o=b("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=b("span","persona-ask-row-check");o.appendChild(r)}else{let r=b("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},pv=(e,t,n,o)=>{let s=b("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=b("span","persona-ask-row-content"),i=b("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=b("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}s.appendChild(a);let d=cm(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},uv=e=>{let n=b("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},mv=(e,t,n,o)=>{var m,u,g;let s=b("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(p=>p&&typeof p.label=="string"&&p.label.length>0);if(d.length===0&&!n){for(let p=0;p<sv;p++)s.appendChild(uv(o));return s}if(d.forEach((p,w)=>{s.appendChild(pv(p,w,o,a))}),(e==null?void 0:e.allowFreeText)!==!1){let p=o==="rows"?Zy:ev;if(o==="rows"){let w=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");w.setAttribute("data-ask-user-action","focus-free-text"),w.setAttribute("data-option-index",String(d.length)),w.setAttribute("data-ask-other-row","true");let S=b("span","persona-ask-row-content"),M=document.createElement("input");M.type="text",M.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",M.placeholder=(m=t.freeTextPlaceholder)!=null?m:rm,M.setAttribute("data-ask-free-text-input","true"),M.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:p),S.appendChild(M),w.appendChild(S);let I=cm(o,a,d.length);I&&w.appendChild(I),s.appendChild(w)}else{let w=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");w.type="button",w.setAttribute("data-ask-user-action","open-free-text"),w.textContent=(g=t.freeTextLabel)!=null?g:p,s.appendChild(w)}}return s},dm=(e,t)=>{var s,a;let o=b("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=(s=e.freeTextPlaceholder)!=null?s:rm,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let i=b("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:sm,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},fv=e=>{var o;let t=b("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=b("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(o=e.submitLabel)!=null?o:sm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},gv=(e,t,n)=>{var l,m,u,g;let o=b("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=b("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=(l=n.backLabel)!=null?l:nv,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(m=n.skipLabel)!=null?m:rv,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=b("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(u=n.submitAllLabel)!=null?u:ov:(g=n.nextLabel)!=null?g:tv,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},kr=e=>{let t=e.getAttribute(am);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},pm=(e,t)=>{e.setAttribute(am,JSON.stringify(t))},lo=e=>{var n;let t=Number((n=e.getAttribute(Sl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},hv=(e,t)=>{e.setAttribute(Sl,String(Math.max(0,Math.floor(t))))},Jr=e=>{var n;let t=Number((n=e.getAttribute(Al))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},sr=e=>e.getAttribute(Tl)==="true",bv=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(o[a]=d)}}),o},yv=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Si=(e,t)=>{let{payload:n}=Qr(t),o=Xs(n),r=kr(e),s={},a=new Set;return o.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(r,d)&&(s[l]=r[d]))}),s},um=e=>{let t=kr(e),n=lo(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(d=>r.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var u;let l=(u=d.getAttribute("data-option-label"))!=null?u:"",m=r.has(l);d.setAttribute("aria-pressed",m?"true":"false"),d.classList.toggle("persona-ask-pill-selected",m)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!a.has(o)){i.value=o;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},mm=e=>{if(!sr(e))return;let t=kr(e),n=lo(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},El=(e,t,n)=>{let o=kl(n),r=iv(e),{payload:s,complete:a}=Qr(t),i=sr(e),d=lo(e),l=Jr(e),m=i?cv(s,d):lv(s),u=!!(m!=null&&m.multiSelect),g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${l}`:"");let p=e.querySelector('[data-ask-stepper="true"]');p&&p.remove();let w=e.querySelector('[data-ask-question="true"]');if(w){let L=typeof(m==null?void 0:m.question)=="string"?m.question:"";w.textContent=L,w.classList.toggle("persona-ask-question-skeleton",!L&&!a)}let S=e.querySelector('[data-ask-pill-list="true"]');if(S){let L=mv(m,o,a,r);S.replaceWith(L)}if(r!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(dm(o,r))}let M=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!M?e.appendChild(fv(o)):(!u||i)&&M&&M.remove(),e.setAttribute("data-multi-select",u?"true":"false");let I=e.querySelector('[data-ask-nav-row="true"]');if(i){let L=gv(d,l,o);I?I.replaceWith(L):e.appendChild(L)}else I&&I.remove();um(e),mm(e)},vv=(e,t,n)=>{let o=kl(t),r=av(o),s=e.toolCall.id,a=Xs(n),i=Math.max(1,a.length),d=i>1,l=bv(e,a),m=d?yv(e,i):0,u=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Xr,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(Al,String(i)),u.setAttribute(Sl,String(m)),u.setAttribute(Tl,d?"true":"false"),u.setAttribute(im,r),pm(u,l),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),dv(u,o);let g=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),p=b("div","persona-ask-sheet-question persona-flex-1");p.setAttribute("data-ask-question","true"),p.textContent="",g.appendChild(p);let w=b("span","persona-ask-sheet-step-inline");w.setAttribute("data-ask-step-inline","true"),w.textContent="",g.appendChild(w),u.appendChild(g);let M=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),u.appendChild(M),r!=="rows"&&u.appendChild(dm(o,r)),El(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},xv=(e,t,n)=>{let{payload:o}=Qr(t),r=Math.max(1,Xs(o).length);r>Jr(e)&&(e.setAttribute(Al,String(r)),r>1&&!sr(e)&&e.setAttribute(Tl,"true")),El(e,t,n)};var Ai=(e,t,n)=>{if(!n||!Tr(e)||kl(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Xr}]`).forEach(l=>{l.getAttribute(Xr)!==r&&l.remove()});let a=n.querySelector(`[${Xr}="${lm(r)}"]`);if(a){xv(a,e,t);return}let{payload:i}=Qr(e),d=vv(e,t,i);n.appendChild(d)},Zr=(e,t)=>{if(!e)return;let n=t?`[${Xr}="${lm(t)}"]`:`[${Xr}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},Ml=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),ar=(e,t)=>{let n=kr(e),o=lo(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,pm(e,n),um(e),mm(e)},Ti=(e,t,n,o)=>{let r=Jr(e),s=Math.max(0,Math.min(r-1,o));hv(e,s),El(e,t,n)};var Ll=(e,t)=>{var S,M,I,L,H,D,W,v,x,k,C,T;let n=e.approval,o=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,r=(n==null?void 0:n.status)==="pending",s=b("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(S=o==null?void 0:o.backgroundColor)!=null?S:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(M=o==null?void 0:o.borderColor)!=null?M:"var(--persona-approval-border, #fef08a)",!n)return s;let a=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=b("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",l=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(I=o==null?void 0:o.titleColor)!=null?I:"currentColor",m=Te(d,20,l,2);m&&i.appendChild(m);let u=b("div","persona-flex-1 persona-min-w-0"),g=b("div","persona-flex persona-items-center persona-gap-2"),p=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o!=null&&o.titleColor&&(p.style.color=o.titleColor),p.textContent=(L=o==null?void 0:o.title)!=null?L:"Approval Required",g.appendChild(p),!r){let F=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");F.setAttribute("data-approval-status",n.status),n.status==="approved"?(F.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",F.style.color="var(--persona-palette-colors-success-700, #15803d)",F.textContent="Approved"):n.status==="denied"?(F.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",F.style.color="var(--persona-palette-colors-error-700, #b91c1c)",F.textContent="Denied"):n.status==="timeout"&&(F.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",F.style.color="var(--persona-palette-colors-warning-700, #b45309)",F.textContent="Timeout"),g.appendChild(F)}u.appendChild(g);let w=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(o!=null&&o.descriptionColor&&(w.style.color=o.descriptionColor),w.textContent=n.description,u.appendChild(w),n.parameters){let F=b("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o!=null&&o.parameterBackgroundColor&&(F.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(F.style.color=o.parameterTextColor),F.style.fontSize="0.75rem",F.style.lineHeight="1rem",F.textContent=jr(n.parameters),u.appendChild(F)}if(r){let F=b("div","persona-flex persona-gap-2 persona-mt-2");F.setAttribute("data-approval-buttons","true");let $=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");$.type="button",$.style.backgroundColor=(H=o==null?void 0:o.approveButtonColor)!=null?H:"var(--persona-approval-approve-bg, #22c55e)",$.style.color=(D=o==null?void 0:o.approveButtonTextColor)!=null?D:"#ffffff",$.setAttribute("data-approval-action","approve");let j=Te("shield-check",14,(W=o==null?void 0:o.approveButtonTextColor)!=null?W:"#ffffff",2);j&&(j.style.marginRight="4px",$.appendChild(j));let me=document.createTextNode((v=o==null?void 0:o.approveLabel)!=null?v:"Approve");$.appendChild(me);let se=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");se.type="button",se.style.backgroundColor=(x=o==null?void 0:o.denyButtonColor)!=null?x:"transparent",se.style.color=(k=o==null?void 0:o.denyButtonTextColor)!=null?k:"var(--persona-feedback-error, #dc2626)",se.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,se.setAttribute("data-approval-action","deny");let fe=Te("shield-x",14,(C=o==null?void 0:o.denyButtonTextColor)!=null?C:"var(--persona-feedback-error, #dc2626)",2);fe&&(fe.style.marginRight="4px",se.appendChild(fe));let ie=document.createTextNode((T=o==null?void 0:o.denyLabel)!=null?T:"Deny");se.appendChild(ie),F.append($,se),u.appendChild(F)}return a.append(i,u),s.appendChild(a),s};var fm=e=>{let t=[];return{buttons:t,render:(o,r,s,a,i)=>{if(e.innerHTML="",t.length=0,!o||!o.length||(a!=null?a:r?r.getMessages():[]).some(p=>p.role==="user"))return;let m=document.createDocumentFragment(),u=r?r.isStreaming():!1,g=p=>{switch(p){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};o.forEach(p=>{let w=b("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");w.type="button",w.textContent=p,w.disabled=u,i!=null&&i.fontFamily&&(w.style.fontFamily=g(i.fontFamily)),i!=null&&i.fontWeight&&(w.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(w.style.paddingLeft=i.paddingX,w.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(w.style.paddingTop=i.paddingY,w.style.paddingBottom=i.paddingY),w.addEventListener("click",()=>{!r||r.isStreaming()||(s.value="",r.sendMessage(p))}),m.appendChild(w),t.push(w)}),e.appendChild(m)}}};var Qs=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Js=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}};var wv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Cv=new Set(["step_start","execution_start"]),Sv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Av=new Set(["step_complete","agent_turn_complete"]),Tv=new Set(["flow_complete","agent_complete"]),gm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),bm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Er=(e,t)=>{let n=e[t];return bm(n)?n:void 0};function Il(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function ki(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function kv(e,t){return typeof t.type=="string"?t.type:e}function Ev(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function Mv(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function hm(e){var o,r,s,a,i;let t=Er(e,"result"),n=[Er(e,"tokens"),Er(e,"totalTokens"),t?Er(t,"tokens"):void 0,Er(e,"usage"),t?Er(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(r=(o=Qn(d.output))!=null?o:Qn(d.outputTokens))!=null?r:Qn(d.completionTokens);if(l!==void 0)return l}return(i=(s=Qn(e.outputTokens))!=null?s:Qn(e.completionTokens))!=null?i:t?(a=Qn(t.outputTokens))!=null?a:Qn(t.completionTokens):void 0}function Lv(e){var n,o,r,s,a;let t=Er(e,"result");return(a=(r=(o=(n=Qn(e.executionTime))!=null?n:Qn(e.executionTimeMs))!=null?o:Qn(e.execution_time))!=null?r:Qn(e.duration))!=null?a:t?(s=Qn(t.executionTime))!=null?s:Qn(t.executionTimeMs):void 0}function Iv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Zs=class{constructor(t=Iv){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:ki(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var s;if(!bm(n)){gm.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=kv(t,n),r=this.now();if(wv.has(o)){this.startRun(r);return}if(Cv.has(o)){this.run||this.startRun(r);return}if(Sv.has(o)){if(!Mv(o,n))return;let a=Ev(n);if(!a)return;this.run||this.startRun(r);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=r),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Il(i.visibleCharCount),l=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:ki(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Av.has(o)){if(!this.run)return;let a=this.run,i=hm(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Il(a.visibleCharCount),m=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:ki(l,m),outputTokens:l,durationMs:m,source:d?"usage":"estimate"};return}if(Tv.has(o)){if(!this.run)return;let a=this.run,i=hm(n),d=i!=null?i:a.exactOutputTokens+Il(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",m=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:ki(d,m),outputTokens:d,durationMs:m,source:l},this.run=null;return}if(gm.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;if(r!==void 0&&r>=250)return r;let s=Lv(n);return s!=null?s:o-t.startedAt}};function es(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Rv={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},Pv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Wv=["flowName","stepName","reasoningText","text","name","tool","toolName"],Bv=100;function Hv(e,t){let n={...Rv,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Pv}function Dv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Fv(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function Ov(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Nv(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let o=document.createElement("textarea");o.value=e,o.style.position="fixed",o.style.opacity="0",document.body.appendChild(o),o.select(),document.execCommand("copy"),document.body.removeChild(o),n()})}function _v(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function Vv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function $v(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function Uv(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(i)return i}return a();function a(){let i=b("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=b("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=o,i.appendChild(d),i}}function Rl(e,t,n,o,r,s,a,i){var g;let d=r.has(e.id),l=b("div","persona-border-b persona-border-persona-divider persona-text-xs");es(l,(g=o.classNames)==null?void 0:g.eventRow);let m=a.find(p=>p.renderEventStreamRow);if(m!=null&&m.renderEventStreamRow&&i){let p=m.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(p)return l.appendChild(p),l}return l.appendChild(u()),l;function u(){var $,j;let p=b("div",""),w=b("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");w.setAttribute("data-event-id",e.id);let S=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),M=Te(d?"chevron-down":"chevron-right","14px","currentColor",2);M&&S.appendChild(M);let I=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=($=o.timestampFormat)!=null?$:"relative";I.textContent=L==="relative"?Dv(e.timestamp,n):Fv(e.timestamp);let H=null;o.showSequenceNumbers!==!1&&(H=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),H.textContent=String(t+1));let D=Hv(e.type,o.badgeColors),W=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");W.style.backgroundColor=D.bg,W.style.color=D.text,W.style.borderColor=D.text+"50",W.textContent=e.type;let v=(j=o.descriptionFields)!=null?j:Wv,x=Ov(e.payload,v),k=null;x&&(k=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),k.textContent=x);let C=b("div","persona-flex-1 persona-min-w-0"),T=b("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),F=Te("clipboard","12px","currentColor",1.5);return F&&T.appendChild(F),T.addEventListener("click",async me=>{me.stopPropagation(),await Nv(_v(e)),T.innerHTML="";let se=Te("check","12px","currentColor",1.5);se&&T.appendChild(se),setTimeout(()=>{T.innerHTML="";let fe=Te("clipboard","12px","currentColor",1.5);fe&&T.appendChild(fe)},1500)}),w.appendChild(S),w.appendChild(I),H&&w.appendChild(H),w.appendChild(W),k&&w.appendChild(k),w.appendChild(C),w.appendChild(T),p.appendChild(w),d&&p.appendChild(Uv(e,a,i)),p}}function ym(e){var w,S,M,I,L;let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,i=(w=r==null?void 0:r.features)==null?void 0:w.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(S=i==null?void 0:i.iconName)!=null?S:"arrow-down",m=(M=i==null?void 0:i.label)!=null?M:"",u=(L=(I=r==null?void 0:r.features)==null?void 0:I.eventStream)!=null?L:{},g=s.find(H=>H.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&r){let H=g.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>p().element,onClose:o});if(H)return{element:H,update:()=>{},destroy:()=>{}}}return p();function p(){let H=u.classNames,D=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");es(D,H==null?void 0:H.panel);let W=[],v="",x="",k=null,C=[],T={},F=0,$=ai(),j=0,me=0,se=!1,fe=null,ie=!1,be=0,Oe=new Set,ve=new Map,Q="",Le="",Y=null,xe,Se,de,we,ze,te=null,ne=null,re=null;function nt(){let oe=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ge=b("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");es(ge,H==null?void 0:H.headerBar);let xt=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(xt.textContent="Events",xe=b("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),xe.textContent="0",a){ne=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ne.style.cursor="help";let Fn=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Fn.textContent="Throughput",te=b("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),te.textContent="-- tok/s",re=b("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),re.style.display="none",re.style.pointerEvents="none";let Zn=ne,vn=re,On=()=>{if(!vn.textContent)return;let wo=Zn.getBoundingClientRect(),Nn=oe.getBoundingClientRect();vn.style.left=`${wo.left-Nn.left}px`,vn.style.top=`${wo.bottom-Nn.top+4}px`,vn.style.display="block"},ut=()=>{vn.style.display="none"};ne.addEventListener("mouseenter",On),ne.addEventListener("mouseleave",ut),ne.appendChild(Fn),ne.appendChild(te)}let $t=b("div","persona-flex-1");Se=b("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Jt=b("option","");Jt.value="",Jt.textContent="All events",Se.appendChild(Jt),de=b("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),de.type="button",de.title="Copy All";let Tt=Te("clipboard-copy","12px","currentColor",1.5);Tt&&de.appendChild(Tt);let wt=b("span","persona-text-xs");wt.textContent="Copy All",de.appendChild(wt),ge.appendChild(xt),ge.appendChild(xe),ne&&ge.appendChild(ne),ge.appendChild($t),ge.appendChild(Se),ge.appendChild(de);let gt=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");es(gt,H==null?void 0:H.searchBar);let bt=Te("search","14px","var(--persona-muted, #9ca3af)",1.5),zt=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");bt&&zt.appendChild(bt),we=b("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),es(we,H==null?void 0:H.searchInput),we.type="text",we.placeholder="Search event payloads...",ze=b("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),ze.type="button",ze.style.display="none";let et=Te("x","12px","currentColor",2);return et&&ze.appendChild(et),gt.appendChild(zt),gt.appendChild(we),gt.appendChild(ze),oe.appendChild(ge),oe.appendChild(gt),re&&oe.appendChild(re),oe}let ye,le=s.find(oe=>oe.renderEventStreamToolbar);if(le!=null&&le.renderEventStreamToolbar&&r){let oe=le.renderEventStreamToolbar({config:r,defaultRenderer:()=>nt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:ge=>{v=ge,Dn(),_()},onSearchChange:ge=>{x=ge,Dn(),_()}});ye=oe!=null?oe:nt()}else ye=nt();let Ue=b("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Ue.style.display="none";function He(){if(!a||!te||!ne)return;let oe=a();te.textContent=Vv(oe);let ge=$v(oe);re&&(re.textContent=ge,ge||(re.style.display="none")),ge?ne.setAttribute("aria-label",ge):ne.removeAttribute("aria-label")}let ce=b("div","persona-flex-1 persona-min-h-0 persona-relative"),G=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");G.style.height="100%";let Ve=b("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");es(Ve,H==null?void 0:H.scrollIndicator),Ve.style.display="none",Ve.setAttribute("data-persona-scroll-to-bottom-has-label",m?"true":"false");let Et=Te(l,"14px","currentColor",2);Et&&Ve.appendChild(Et);let pe=b("span","");pe.textContent=m,Ve.appendChild(pe);let ae=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ae.style.display="none",ce.appendChild(G),ce.appendChild(ae),ce.appendChild(Ve),D.setAttribute("tabindex","0"),D.appendChild(ye),D.appendChild(Ue),D.appendChild(ce);function Ln(){let oe=t.getAll(),ge={};for(let wt of oe)ge[wt.type]=(ge[wt.type]||0)+1;let xt=Object.keys(ge).sort(),$t=xt.length!==C.length||!xt.every((wt,gt)=>wt===C[gt]),Jt=!$t&&xt.some(wt=>ge[wt]!==T[wt]),yn=oe.length!==Object.values(T).reduce((wt,gt)=>wt+gt,0);if(!$t&&!Jt&&!yn||(C=xt,T=ge,!Se))return;let Tt=Se.value;if(Se.options[0].textContent="All events",$t){for(;Se.options.length>1;)Se.remove(1);for(let wt of xt){let gt=b("option","");gt.value=wt,gt.textContent=`${wt} (${ge[wt]||0})`,Se.appendChild(gt)}Tt&&xt.includes(Tt)?Se.value=Tt:Tt&&(Se.value="",v="")}else for(let wt=1;wt<Se.options.length;wt++){let gt=Se.options[wt];gt.textContent=`${gt.value} (${ge[gt.value]||0})`}}function Nt(){let oe=t.getAll();if(v&&(oe=oe.filter(ge=>ge.type===v)),x){let ge=x.toLowerCase();oe=oe.filter(xt=>xt.type.toLowerCase().includes(ge)||xt.payload.toLowerCase().includes(ge))}return oe}function ln(){return v!==""||x!==""}function Dn(){F=0,j=0,$.resume(),Ve.style.display="none"}function Jn(oe){Oe.has(oe)?Oe.delete(oe):Oe.add(oe),Y=oe;let ge=G.scrollTop,xt=$.isFollowing();ie=!0,$.pause(),_(),G.scrollTop=ge,xt&&$.resume(),ie=!1}function qe(){return _s(G,50)}function _(){me=Date.now(),se=!1,He(),Ln();let oe=t.getEvictedCount();oe>0?(Ue.textContent=`${oe.toLocaleString()} older events truncated`,Ue.style.display=""):Ue.style.display="none",W=Nt();let ge=W.length,xt=t.getSize()>0;xe&&(xe.textContent=String(t.getSize())),ge===0&&xt&&ln()?(ae.textContent=x?`No events matching '${x}'`:"No events matching filter",ae.style.display="",G.style.display="none"):(ae.style.display="none",G.style.display=""),de&&(de.title=ln()?`Copy Filtered (${ge})`:"Copy All"),d&&!$.isFollowing()&&ge>F&&(j+=ge-F,pe.textContent=m?`${m}${j>0?` (${j})`:""}`:"",Ve.style.display=""),F=ge;let $t=t.getAll(),Jt=$t.length>0?$t[0].timestamp:0,yn=new Set(W.map(gt=>gt.id));for(let gt of Oe)yn.has(gt)||Oe.delete(gt);let Tt=v!==Q||x!==Le,wt=ve.size===0&&W.length>0;if(Tt||wt||W.length===0){G.innerHTML="",ve.clear();let gt=document.createDocumentFragment();for(let bt=0;bt<W.length;bt++){let zt=Rl(W[bt],bt,Jt,u,Oe,Jn,s,r);ve.set(W[bt].id,zt),gt.appendChild(zt)}G.appendChild(gt),Q=v,Le=x,Y=null}else{if(Y!==null){let bt=ve.get(Y);if(bt&&bt.parentNode===G){let zt=W.findIndex(et=>et.id===Y);if(zt>=0){let et=Rl(W[zt],zt,Jt,u,Oe,Jn,s,r);G.insertBefore(et,bt),bt.remove(),ve.set(Y,et)}}Y=null}let gt=new Set(W.map(bt=>bt.id));for(let[bt,zt]of ve)gt.has(bt)||(zt.remove(),ve.delete(bt));for(let bt=0;bt<W.length;bt++){let zt=W[bt];if(!ve.has(zt.id)){let et=Rl(zt,bt,Jt,u,Oe,Jn,s,r);ve.set(zt.id,et),G.appendChild(et)}}}$.isFollowing()&&(G.scrollTop=G.scrollHeight)}function ke(){if(Date.now()-me>=Bv){fe!==null&&(cancelAnimationFrame(fe),fe=null),_();return}se||(se=!0,fe=requestAnimationFrame(()=>{fe=null,_()}))}let De=(oe,ge)=>{if(!de)return;de.innerHTML="";let xt=Te(oe,"12px","currentColor",1.5);xt&&de.appendChild(xt);let $t=b("span","persona-text-xs");$t.textContent="Copy All",de.appendChild($t),setTimeout(()=>{de.innerHTML="";let Jt=Te("clipboard-copy","12px","currentColor",1.5);Jt&&de.appendChild(Jt);let yn=b("span","persona-text-xs");yn.textContent="Copy All",de.appendChild(yn),de.disabled=!1},ge)},Fe=async()=>{if(de){de.disabled=!0;try{let oe;ln()?oe=W:n?(oe=await n(),oe.length===0&&(oe=t.getAll())):oe=t.getAll();let ge=oe.map(xt=>{try{return JSON.parse(xt.payload)}catch{return xt.payload}});await navigator.clipboard.writeText(JSON.stringify(ge,null,2)),De("check",1500)}catch{De("x",1500)}}},$e=()=>{Se&&(v=Se.value,Dn(),_())},dt=()=>{!we||!ze||(ze.style.display=we.value?"":"none",k&&clearTimeout(k),k=setTimeout(()=>{x=we.value,Dn(),_()},150))},ot=()=>{!we||!ze||(we.value="",x="",ze.style.display="none",k&&clearTimeout(k),Dn(),_())},At=()=>{if(ie)return;let oe=G.scrollTop,{action:ge,nextLastScrollTop:xt}=ii({following:$.isFollowing(),currentScrollTop:oe,lastScrollTop:be,nearBottom:qe(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});be=xt,ge==="resume"?($.resume(),j=0,Ve.style.display="none"):ge==="pause"&&($.pause(),d&&(pe.textContent=m,Ve.style.display=""))},Vt=oe=>{let ge=li({following:$.isFollowing(),deltaY:oe.deltaY,nearBottom:qe(),resumeWhenNearBottom:!0});ge==="pause"?($.pause(),d&&(pe.textContent=m,Ve.style.display="")):ge==="resume"&&($.resume(),j=0,Ve.style.display="none")},q=()=>{d&&(G.scrollTop=G.scrollHeight,$.resume(),j=0,Ve.style.display="none")},_t=oe=>{let ge=oe.target;if(!ge||ge.closest("button"))return;let xt=ge.closest("[data-event-id]");if(!xt)return;let $t=xt.getAttribute("data-event-id");$t&&Jn($t)},Qe=oe=>{if((oe.metaKey||oe.ctrlKey)&&oe.key==="f"){oe.preventDefault(),we==null||we.focus(),we==null||we.select();return}oe.key==="Escape"&&(we&&document.activeElement===we?(ot(),we.blur(),D.focus()):o&&o())};de&&de.addEventListener("click",Fe),Se&&Se.addEventListener("change",$e),we&&we.addEventListener("input",dt),ze&&ze.addEventListener("click",ot),G.addEventListener("scroll",At),G.addEventListener("wheel",Vt,{passive:!0}),G.addEventListener("click",_t),Ve.addEventListener("click",q),D.addEventListener("keydown",Qe);function Ft(){k&&clearTimeout(k),fe!==null&&(cancelAnimationFrame(fe),fe=null),se=!1,ve.clear(),de&&de.removeEventListener("click",Fe),Se&&Se.removeEventListener("change",$e),we&&we.removeEventListener("input",dt),ze&&ze.removeEventListener("click",ot),G.removeEventListener("scroll",At),G.removeEventListener("wheel",Vt),G.removeEventListener("click",_t),Ve.removeEventListener("click",q),D.removeEventListener("keydown",Qe)}return{element:D,update:ke,destroy:Ft}}}function vm(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",o=typeof e.artifactId=="string"?e.artifactId:"",r=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),o&&i.setAttribute("data-open-artifact",o);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let m=document.createElement("div");m.className="persona-truncate persona-text-sm persona-font-medium",m.style.color="var(--persona-text, #1f2937)",m.textContent=n;let u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.style.color="var(--persona-muted, #9ca3af)",r==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(g);let p=document.createElement("span");p.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(p)}else u.textContent=a;if(l.append(m,u),i.append(d,l),r==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${n}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",o),i.append(g)}return i}var xm=(e,t)=>{var o,r,s;let n=(s=(r=(o=t==null?void 0:t.config)==null?void 0:o.features)==null?void 0:r.artifacts)==null?void 0:s.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",m=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>vm(e,t)});if(m)return m}return vm(e,t)};var Pl=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},Mr=new Pl;Mr.register("PersonaArtifactCard",xm);function zv(e){var r;let t=b("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=b("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify((r=e.props)!=null?r:{},null,2),t.appendChild(n),t.appendChild(o),t}function wm(e,t){var Se,de,we,ze;let n=(de=(Se=e.features)==null?void 0:Se.artifacts)==null?void 0:de.layout,r=((we=n==null?void 0:n.toolbarPreset)!=null?we:"default")==="document",s=(ze=n==null?void 0:n.panePadding)==null?void 0:ze.trim(),a=e.markdown?$a(e.markdown):null,i=Ua(e.sanitize),d=te=>{let ne=a?a(te):Is(te);return i?i(ne):ne},l=typeof document!="undefined"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,m=()=>{l==null||l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),F==null||F.hide()};l&&l.addEventListener("click",()=>{var te;m(),(te=t.onDismiss)==null||te.call(t)});let u=b("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");u.setAttribute("data-persona-theme-zone","artifact-pane"),r&&u.classList.add("persona-artifact-pane-document");let g=b("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&g.classList.add("persona-artifact-toolbar-document");let p=b("span","persona-text-xs persona-font-medium persona-truncate");p.textContent="Artifacts";let w=b("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");w.type="button",w.textContent="Close",w.setAttribute("aria-label","Close artifacts panel"),w.addEventListener("click",()=>{var te;m(),(te=t.onDismiss)==null||te.call(t)});let S="rendered",M=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),I=r?bn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):bn({icon:"eye",label:"Rendered view"}),L=r?bn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):bn({icon:"code-2",label:"Source"}),H=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),D=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,W=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,v=n==null?void 0:n.documentToolbarCopyMenuItems,x=!!(W&&v&&v.length>0),k=null,C,T=null,F=null;if(r&&(D||W)&&!x){if(C=D?hl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):bn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W){let te=Te("chevron-down",14,"currentColor",2);te&&C.appendChild(te)}}else r&&x?(k=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),C=D?hl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):bn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),T=bn({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),k.append(C,T)):r?C=bn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):C=bn({icon:"copy",label:"Copy"});let $=r?bn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):bn({icon:"refresh-cw",label:"Refresh"}),j=r?bn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):bn({icon:"x",label:"Close"}),me=()=>{var ye,le,Ue;let te=(ye=ve.find(He=>He.id===Q))!=null?ye:ve[ve.length-1],ne=(le=te==null?void 0:te.id)!=null?le:null,re=(te==null?void 0:te.artifactType)==="markdown"&&(Ue=te.markdown)!=null?Ue:"",nt=te?JSON.stringify({component:te.component,props:te.props},null,2):"";return{markdown:re,jsonPayload:nt,id:ne}},se=async()=>{var ye;let{markdown:te,jsonPayload:ne}=me(),re=(ye=ve.find(le=>le.id===Q))!=null?ye:ve[ve.length-1],nt=(re==null?void 0:re.artifactType)==="markdown"?te:re?ne:"";try{await navigator.clipboard.writeText(nt)}catch{}};if(C.addEventListener("click",async()=>{let te=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(te&&x){let{markdown:ne,jsonPayload:re,id:nt}=me();try{await te({actionId:"primary",artifactId:nt,markdown:ne,jsonPayload:re})}catch{}return}await se()}),T&&(v!=null&&v.length)){let te=()=>{var re;return(re=u.closest("[data-persona-root]"))!=null?re:document.body},ne=()=>{F=Kr({items:v.map(re=>({id:re.id,label:re.label})),onSelect:async re=>{let{markdown:nt,jsonPayload:ye,id:le}=me(),Ue=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Ue?await Ue({actionId:re,artifactId:le,markdown:nt,jsonPayload:ye}):re==="markdown"||re==="md"?await navigator.clipboard.writeText(nt):re==="json"||re==="source"?await navigator.clipboard.writeText(ye):await navigator.clipboard.writeText(nt||ye)}catch{}},anchor:k!=null?k:T,position:"bottom-right",portal:te()})};u.isConnected?ne():requestAnimationFrame(ne),T.addEventListener("click",re=>{re.stopPropagation(),F==null||F.toggle()})}$.addEventListener("click",async()=>{var te;try{await((te=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:te.call(n))}catch{}Y()}),j.addEventListener("click",()=>{var te;m(),(te=t.onDismiss)==null||te.call(t)});let fe=()=>{r&&(I.setAttribute("aria-pressed",S==="rendered"?"true":"false"),L.setAttribute("aria-pressed",S==="source"?"true":"false"))};I.addEventListener("click",()=>{S="rendered",fe(),Y()}),L.addEventListener("click",()=>{S="source",fe(),Y()});let ie=b("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");r?(g.replaceChildren(),M.append(I,L),k?H.append(k,$,j):H.append(C,$,j),g.append(M,ie,H),fe()):(g.appendChild(p),g.appendChild(w)),s&&(g.style.paddingLeft=s,g.style.paddingRight=s);let be=b("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Oe=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(be.style.paddingLeft=s,be.style.paddingRight=s,Oe.style.padding=s),u.appendChild(g),u.appendChild(be),u.appendChild(Oe);let ve=[],Q=null,Le=!1,Y=()=>{var nt,ye,le,Ue;let te=r&&ve.length<=1;be.classList.toggle("persona-hidden",te),be.replaceChildren();for(let He of ve){let ce=b("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");ce.type="button",ce.textContent=He.title||He.id.slice(0,8),He.id===Q&&ce.classList.add("persona-bg-persona-container","persona-border-persona-border"),ce.addEventListener("click",()=>t.onSelect(He.id)),be.appendChild(ce)}Oe.replaceChildren();let ne=Q&&ve.find(He=>He.id===Q)||ve[ve.length-1];if(!ne)return;if(r){let He=ne.artifactType==="markdown"?"MD":(nt=ne.component)!=null?nt:"Component",G=(ne.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ie.textContent=`${G} \xB7 ${He}`}else p.textContent="Artifacts";if(ne.artifactType==="markdown"){if(r&&S==="source"){let ce=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ce.textContent=(ye=ne.markdown)!=null?ye:"",Oe.appendChild(ce);return}let He=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");He.innerHTML=d((le=ne.markdown)!=null?le:""),Oe.appendChild(He);return}let re=ne.component?Mr.get(ne.component):void 0;if(re){let ce={message:{id:ne.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let G=re((Ue=ne.props)!=null?Ue:{},ce);if(G){Oe.appendChild(G);return}}catch{}}Oe.appendChild(zv(ne))},xe=()=>{var ne;let te=ve.length>0;if(u.classList.toggle("persona-hidden",!te),l){let re=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,ye=((ne=re==null?void 0:re.classList.contains("persona-artifact-narrow-host"))!=null?ne:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;te&&ye&&Le?(l.classList.remove("persona-hidden"),u.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:l,update(te){var ne,re,nt;ve=te.artifacts,Q=(nt=(re=te.selectedId)!=null?re:(ne=te.artifacts[te.artifacts.length-1])==null?void 0:ne.id)!=null?nt:null,ve.length>0&&(Le=!0),Y(),xe()},setMobileOpen(te){Le=te,!te&&l?(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):xe()}}}function co(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function Cm(e,t){var s,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!co(t))return;let n=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,o=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),r=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function qv(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function Ei(e,t){var d,l,m,u,g,p,w,S,M,I;if(!co(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),qv(e),Cm(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(m=n==null?void 0:n.splitGap)!=null?m:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(u=n==null?void 0:n.paneWidth)!=null?u:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(g=n==null?void 0:n.paneMaxWidth)!=null?g:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=(p=n==null?void 0:n.paneBackground)==null?void 0:p.trim();o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let r=(w=n==null?void 0:n.panePadding)==null?void 0:w.trim();r?e.style.setProperty("--persona-artifact-pane-padding",r):e.style.removeProperty("--persona-artifact-pane-padding");let s=(S=n==null?void 0:n.documentToolbarIconColor)==null?void 0:S.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(M=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:M.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(I=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:I.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Cm(e,t)}var Sm=["panel","seamless"];function Mi(e,t){var i,d,l,m,u,g;for(let p of Sm)e.classList.remove(`persona-artifact-appearance-${p}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!co(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,o=(l=n==null?void 0:n.paneAppearance)!=null?l:"panel",r=Sm.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${r}`);let s=(m=n==null?void 0:n.paneBorderRadius)==null?void 0:m.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(u=n==null?void 0:n.paneShadow)==null?void 0:u.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let p=((g=n.unifiedSplitOuterRadius)==null?void 0:g.trim())||s;p&&e.style.setProperty("--persona-artifact-unified-outer-radius",p)}}function Am(e,t){var n,o,r;return!t||!co(e)?!1:((r=(o=(n=e.features)==null?void 0:n.artifacts)==null?void 0:o.layout)==null?void 0:r.expandLauncherPanelWhenOpen)!==!1}function jv(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function Kv(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function Gv(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Yv(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Tm(e,t){var a;let o=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function km(e,t,n,o,r,s){let a=jv(r,200),i=Yv(t,n,o,200);i=Math.max(a,i);let d=Kv(s);return d!==null&&(i=Math.min(i,d)),Gv(e,a,i)}var Em={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Wl=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var w,S,M;if(s.dataset.enhanced==="true")return;let a=(w=s.dataset.tvForm)!=null?w:"init";s.dataset.enhanced="true";let i=(S=Em[a])!=null?S:Em.init;s.classList.add("persona-form-card","persona-space-y-4");let d=b("div","persona-space-y-1"),l=b("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let I=b("p","persona-text-sm persona-text-persona-muted");I.textContent=i.description,d.appendChild(I)}let m=document.createElement("form");m.className="persona-form-grid persona-space-y-3",i.fields.forEach(I=>{var v,x;let L=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");L.htmlFor=`${t.id}-${a}-${I.name}`;let H=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");H.textContent=I.label,L.appendChild(H);let D=(v=I.type)!=null?v:"text",W;D==="textarea"?(W=document.createElement("textarea"),W.rows=3):(W=document.createElement("input"),W.type=D),W.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",W.id=`${t.id}-${a}-${I.name}`,W.name=I.name,W.placeholder=(x=I.placeholder)!=null?x:"",I.required&&(W.required=!0),L.appendChild(W),m.appendChild(L)});let u=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),p=b("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");p.type="submit",p.textContent=(M=i.submitLabel)!=null?M:"Submit",u.appendChild(g),u.appendChild(p),m.appendChild(u),s.replaceChildren(d,m),m.addEventListener("submit",async I=>{var W,v;I.preventDefault();let L=(W=n.formEndpoint)!=null?W:"/form",H=new FormData(m),D={};H.forEach((x,k)=>{D[k]=x}),D.type=a,p.disabled=!0,g.textContent="Submitting\u2026";try{let x=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D)});if(!x.ok)throw new Error(`Form submission failed (${x.status})`);let k=await x.json();g.textContent=(v=k.message)!=null?v:"Thanks! We'll be in touch soon.",k.success&&k.nextPrompt&&await o.sendMessage(String(k.nextPrompt))}catch(x){g.textContent=x instanceof Error?x.message:"Something went wrong. Please try again."}finally{p.disabled=!1}})})};var Bl=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var o;let n=this.plugins.get(t);n&&((o=n.onUnregister)==null||o.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var o,r;return((o=n.priority)!=null?o:0)-((r=t.priority)!=null?r:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},Hl=new Bl;var Mm=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{var a;(a=e.get(r))==null||a.delete(s)};return{on:t,off:n,emit:(r,s)=>{var a;(a=e.get(r))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Xv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Qv=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},Fl=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Xv(e),n=Qv(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},Dl=e=>typeof e=="string"?e:e==null?"":String(e),ea={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Dl(e.payload.text)},messageAndClick:(e,t)=>{var r;if(e.type!=="message_and_click")return;let n=e.payload,o=Dl(n.element);if(o&&((r=t.document)!=null&&r.querySelector)){let s=t.document.querySelector(o);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Dl(n.text)}}},Lm=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ol=e=>{let t=new Set(Lm(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Lm(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,m)=>l||(m==null?void 0:m({text:a,message:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),o();let d={action:i,message:s.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let m=()=>{e.emit("action:resubmit",d)},u=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:m});if(!u)continue;if(u.handled){let g=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:g,resubmit:u.resubmit}}}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",m)}return{text:"",persist:!0}},syncFromMetadata:n}};var Jv=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Zv=e=>e.map(t=>({...t,streaming:!1})),ex=e=>e.map(t=>({...t,status:"complete"})),Im=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Jv(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?Zv(n.messages):void 0,artifacts:n.artifacts?ex(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};import{parse as G0,STR as Y0,OBJ as X0}from"partial-json";function Rm(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Mr.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:i=>{r&&r(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Pm(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function Wm(e){let t=Pm(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Bm(e){let t=Pm(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var tx=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Hm(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=tx}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-csat",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Customer satisfaction feedback");let u=null,g=document.createElement("div");g.className="persona-feedback-content";let p=document.createElement("div");p.className="persona-feedback-header";let w=document.createElement("h3");w.className="persona-feedback-title",w.textContent=o,p.appendChild(w);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=r,p.appendChild(S),g.appendChild(p);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let I=[];for(let v=1;v<=5;v++){let x=document.createElement("button");x.type="button",x.className="persona-feedback-rating-btn persona-feedback-star-btn",x.setAttribute("role","radio"),x.setAttribute("aria-checked","false"),x.setAttribute("aria-label",`${v} star${v>1?"s":""}: ${l[v-1]}`),x.title=l[v-1],x.dataset.rating=String(v),x.innerHTML=`
|
|
27
27
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
28
28
|
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
|
|
29
29
|
</svg>
|
|
30
|
-
`,x.addEventListener("click",()=>{m=v,I.forEach((k,S)=>{let E=S<v;k.classList.toggle("selected",E),k.setAttribute("aria-checked",S===v-1?"true":"false")})}),I.push(x),M.appendChild(x)}f.appendChild(M);let R=null;if(d){let v=document.createElement("div");v.className="persona-feedback-comment-container",R=document.createElement("textarea"),R.className="persona-feedback-comment",R.placeholder=s,R.rows=3,R.setAttribute("aria-label","Additional comments"),v.appendChild(R),f.appendChild(v)}let H=document.createElement("div");H.className="persona-feedback-actions";let D=document.createElement("button");D.type="button",D.className="persona-feedback-btn persona-feedback-btn-skip",D.textContent=i,D.addEventListener("click",()=>{n==null||n(),p.remove()});let B=document.createElement("button");return B.type="button",B.className="persona-feedback-btn persona-feedback-btn-submit",B.textContent=a,B.addEventListener("click",async()=>{if(m===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}B.disabled=!0,B.textContent="Submitting...";try{let v=(R==null?void 0:R.value.trim())||void 0;await t(m,v),p.remove()}catch(v){B.disabled=!1,B.textContent=a,console.error("[CSAT Feedback] Failed to submit:",v)}}),H.appendChild(D),H.appendChild(B),f.appendChild(H),p.appendChild(f),p}function Bm(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:p="Very likely"}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let f=null,u=document.createElement("div");u.className="persona-feedback-content";let w=document.createElement("div");w.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,w.appendChild(C);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=r,w.appendChild(M),u.appendChild(w);let I=document.createElement("div");I.className="persona-feedback-rating persona-feedback-rating-nps",I.setAttribute("role","radiogroup"),I.setAttribute("aria-label","Likelihood rating from 0 to 10");let R=document.createElement("div");R.className="persona-feedback-labels";let H=document.createElement("span");H.className="persona-feedback-label-low",H.textContent=l;let D=document.createElement("span");D.className="persona-feedback-label-high",D.textContent=p,R.appendChild(H),R.appendChild(D);let B=document.createElement("div");B.className="persona-feedback-numbers";let v=[];for(let F=0;F<=10;F++){let $=document.createElement("button");$.type="button",$.className="persona-feedback-rating-btn persona-feedback-number-btn",$.setAttribute("role","radio"),$.setAttribute("aria-checked","false"),$.setAttribute("aria-label",`Rating ${F} out of 10`),$.textContent=String(F),$.dataset.rating=String(F),F<=6?$.classList.add("persona-feedback-detractor"):F<=8?$.classList.add("persona-feedback-passive"):$.classList.add("persona-feedback-promoter"),$.addEventListener("click",()=>{f=F,v.forEach((j,me)=>{j.classList.toggle("selected",me===F),j.setAttribute("aria-checked",me===F?"true":"false")})}),v.push($),B.appendChild($)}I.appendChild(R),I.appendChild(B),u.appendChild(I);let x=null;if(d){let F=document.createElement("div");F.className="persona-feedback-comment-container",x=document.createElement("textarea"),x.className="persona-feedback-comment",x.placeholder=s,x.rows=3,x.setAttribute("aria-label","Additional comments"),F.appendChild(x),u.appendChild(F)}let k=document.createElement("div");k.className="persona-feedback-actions";let S=document.createElement("button");S.type="button",S.className="persona-feedback-btn persona-feedback-btn-skip",S.textContent=i,S.addEventListener("click",()=>{n==null||n(),m.remove()});let E=document.createElement("button");return E.type="button",E.className="persona-feedback-btn persona-feedback-btn-submit",E.textContent=a,E.addEventListener("click",async()=>{if(f===null){B.classList.add("persona-feedback-shake"),setTimeout(()=>B.classList.remove("persona-feedback-shake"),500);return}E.disabled=!0,E.textContent="Submitting...";try{let F=(x==null?void 0:x.value.trim())||void 0;await t(f,F),m.remove()}catch(F){E.disabled=!1,E.textContent=a,console.error("[NPS Feedback] Failed to submit:",F)}}),k.appendChild(S),k.appendChild(E),u.appendChild(k),m.appendChild(u),m}var es="persona-chat-history",ex=30*1e3,tx={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function nx(e){var o,r,s;if(!e)return[];let t=[],n=Array.from((o=e.items)!=null?o:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(r=tx[i.type])!=null?r:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((s=e.files)!=null?s:[]))a.type.startsWith("image/")&&t.push(a);return t}function Ei(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function ox(e){var t,n,o,r,s,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(r=(o=e.persist)==null?void 0:o.openState)!=null?r:!0,voiceState:(a=(s=e.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function rx(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Ol=e=>!e||typeof e!="object"?{}:{...e},Hm=e=>e.map(t=>({...t,streaming:!1})),Dm=(e,t,n)=>{let o=e!=null&&e.markdown?_a(e.markdown):null,r=Va(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&r&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var l,p,m;let a=(l=s.text)!=null?l:"",i=(p=s.message.rawContent)!=null?p:null;if(t){let f=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});f!==null&&(a=f.text,f.persist||(s.message.__skipPersist=!0),f.resubmit&&!s.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...s,text:a,raw:(m=i!=null?i:s.text)!=null?m:""}):o?d=o(a):d=Ls(a),r?r(d):d}};function Fm(e){var i,d,l,p;let t=b("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",o=(d=e==null?void 0:e.iconSize)!=null?d:"48px",r=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=Te(n,o,r,s);if(a&&t.appendChild(a),e!=null&&e.label){let m=b("span","persona-drop-overlay-label");m.textContent=e.label,t.appendChild(m)}return t}var Om=(e,t,n)=>{var sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,bc,yc,vc,xc,wc,Cc,Sc,Ac,Tc,kc,Ec,Mc,Lc,Ic,Rc,Pc,Wc,Bc,Hc,Dc,Fc,Oc,Nc,_c,Vc,$c,Uc,zc,qc,jc,Kc,Gc,Yc,Xc,Qc,Jc;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=Qp(t),r=Bl.getForInstance(o.plugins);o.components&&Mr.registerAll(o.components);let s=km(),i=o.persistState===!1?null:(sc=o.storageAdapter)!=null?sc:Mm(),d={},l=null,p=!1,m=c=>{if(o.onStateLoaded)try{let g=o.onStateLoaded(c);if(g&&typeof g=="object"&&"state"in g){let{state:h,open:y}=g;return y&&(p=!0),h}return g}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(g=>{let h=g!=null?g:{messages:[],metadata:{}};return m(h)});else{let g=c!=null?c:{messages:[],metadata:{}},h=m(g);h.metadata&&(d=Ol(h.metadata)),(ac=h.messages)!=null&&ac.length&&(o={...o,initialMessages:h.messages}),(ic=h.artifacts)!=null&&ic.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(lc=h.selectedArtifactId)!=null?lc:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(o.onStateLoaded)try{let c=m({messages:[],metadata:{}});(cc=c.messages)!=null&&cc.length&&(o={...o,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let f=()=>d,u=c=>{var h;d=(h=c({...d}))!=null?h:{},Wr()},w=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Dl],C=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Js.message,Js.messageAndClick],M=Fl({parsers:w,handlers:C,getSessionMetadata:f,updateSessionMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let I=(pc=(dc=o.launcher)==null?void 0:dc.enabled)!=null?pc:!0,R=(mc=(uc=o.launcher)==null?void 0:uc.autoExpand)!=null?mc:!1,H=(gc=o.autoFocusInput)!=null?gc:!1,D=R,B=I,v=(hc=(fc=o.layout)==null?void 0:fc.header)==null?void 0:hc.layout,x=!1,k=()=>zs(o),S=()=>I||k(),E=k()?!1:I?R:!0,F=!1,$=null,j=()=>{F=!0,$&&clearTimeout($),$=setTimeout(()=>{F&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),F=!1)},1e4)},me=Dm(o,M,j),se=(yc=(bc=o.features)==null?void 0:bc.showReasoning)!=null?yc:!0,ge=(xc=(vc=o.features)==null?void 0:vc.showToolCalls)!=null?xc:!0,ie=(Cc=(wc=o.features)==null?void 0:wc.showEventStreamToggle)!=null?Cc:!1,be=(Ac=(Sc=o.features)==null?void 0:Sc.scrollToBottom)!=null?Ac:{},ve=`${(kc=typeof o.persistState=="object"?(Tc=o.persistState)==null?void 0:Tc.keyPrefix:void 0)!=null?kc:"persona-"}event-stream`,J=ie?new Xs(ve):null,Le=(Lc=(Mc=(Ec=o.features)==null?void 0:Ec.eventStream)==null?void 0:Mc.maxEvents)!=null?Lc:2e3,Y=ie?new Ys(Le,J):null,xe=ie?new Qs:null,Se=null,de=!1,we=null,Ue=0;J==null||J.open().then(()=>Y==null?void 0:Y.restore()).catch(c=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let te={onCopy:c=>{var g,h;s.emit("message:copy",c),T!=null&&T.isClientTokenMode()&&T.submitMessageFeedback(c.id,"copy").catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",y)}),(h=(g=o.messageActions)==null?void 0:g.onCopy)==null||h.call(g,c)},onFeedback:c=>{var g,h;s.emit("message:feedback",c),T!=null&&T.isClientTokenMode()&&T.submitMessageFeedback(c.messageId,c.type).catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",y)}),(h=(g=o.messageActions)==null?void 0:g.onFeedback)==null||h.call(g,c)}},ne=(Ic=o.statusIndicator)!=null?Ic:{},re=c=>{var g,h,y,P;return c==="idle"?(g=ne.idleText)!=null?g:fn.idle:c==="connecting"?(h=ne.connectingText)!=null?h:fn.connecting:c==="connected"?(y=ne.connectedText)!=null?y:fn.connected:c==="error"?(P=ne.errorText)!=null?P:fn.error:fn[c]};function nt(c,g,h,y){if(y==="idle"&&h.idleLink){c.textContent="";let P=document.createElement("a");P.href=h.idleLink,P.target="_blank",P.rel="noopener noreferrer",P.textContent=g,P.style.color="inherit",P.style.textDecoration="none",c.appendChild(P)}else c.textContent=g}let{wrapper:ye,panel:le,pillRoot:$e}=Yu(o),Be=Xu(o,S()),{container:ce,body:K,messagesWrapper:_e,suggestions:Et,textarea:pe,sendButton:ae,sendButtonWrapper:Ln,composerForm:Nt,statusText:ln,introTitle:Dn,introSubtitle:Jn,closeButton:ze,iconHolder:_,headerTitle:ke,headerSubtitle:He,header:De,footer:Ve,actionsRow:dt,leftActions:ot,rightActions:At}=Be,Vt=Be.setSendButtonMode,q=Be.micButton,_t=Be.micButtonWrapper,Qe=Be.attachmentButton,Ft=Be.attachmentButtonWrapper,oe=Be.attachmentInput,fe=Be.attachmentPreviewsContainer;ce.classList.add("persona-relative"),K.classList.add("persona-relative");let xt=12,$t=()=>{var c;return(c=be.label)!=null?c:""},Jt=()=>{var c;return(c=be.iconName)!=null?c:"arrow-down"},yn=()=>be.enabled!==!1,Tt=b("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Tt.type="button",Tt.style.display="none",Tt.setAttribute("data-persona-scroll-to-bottom","true");let wt=b("span","persona-flex persona-items-center"),ft=b("span","");Tt.append(wt,ft),ce.appendChild(Tt);let bt=()=>{let g=Ve.style.display==="none"?0:Ve.offsetHeight;Tt.style.bottom=`${g+xt}px`};bt();let zt=()=>{let c=!!$t();Tt.setAttribute("aria-label",$t()||"Jump to latest"),Tt.title=$t(),Tt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),wt.innerHTML="";let g=Te(Jt(),"14px","currentColor",2);g?(wt.appendChild(g),wt.style.display=""):wt.style.display="none",ft.textContent=$t(),ft.style.display=c?"":"none"};zt();let et=null,Fn=null,Zn=r.find(c=>c.renderHeader);if(Zn!=null&&Zn.renderHeader){let c=Zn.renderHeader({config:o,defaultRenderer:()=>{let g=Ar({config:o,showClose:S()});return js(ce,g,o),g.header},onClose:()=>Bt(!1,"user")});if(c){let g=ce.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),De=c)}}let vn=()=>{var g,h,y,P;if(!Y)return;if(de=!0,!Se&&Y&&(Se=hm({buffer:Y,getFullHistory:()=>Y.getAllFromStore(),onClose:()=>On(),config:o,plugins:r,getThroughput:()=>{var N;return(N=xe==null?void 0:xe.getMetric())!=null?N:{status:"idle"}}})),Se&&(K.style.display="none",(g=Ve.parentNode)==null||g.insertBefore(Se.element,Ve),Se.update()),ut){ut.style.boxShadow=`inset 0 0 0 1.5px ${Mn.actionIconColor}`;let N=(P=(y=(h=o.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:P.toggleButtonActive;N&&N.split(/\s+/).forEach(V=>V&&ut.classList.add(V))}let c=()=>{if(!de)return;let N=Date.now();N-Ue>=200&&(Se==null||Se.update(),Ue=N),we=requestAnimationFrame(c)};Ue=0,we=requestAnimationFrame(c),Ho(),s.emit("eventStream:opened",{timestamp:Date.now()})},On=()=>{var c,g,h;if(de){if(de=!1,Se&&Se.element.remove(),K.style.display="",ut){ut.style.boxShadow="";let y=(h=(g=(c=o.features)==null?void 0:c.eventStream)==null?void 0:g.classNames)==null?void 0:h.toggleButtonActive;y&&y.split(/\s+/).forEach(P=>P&&ut.classList.remove(P))}we!==null&&(cancelAnimationFrame(we),we=null),Ho(),s.emit("eventStream:closed",{timestamp:Date.now()})}},ut=null;if(ie){let c=(Pc=(Rc=o.features)==null?void 0:Rc.eventStream)==null?void 0:Pc.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");ut=b("button",g),ut.style.width="28px",ut.style.height="28px",ut.style.color=Mn.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let h=Te("activity","18px","currentColor",1.5);h&&ut.appendChild(h);let y=Be.clearChatButtonWrapper,P=Be.closeButtonWrapper,N=y||P;N&&N.parentNode===De?De.insertBefore(ut,N):De.appendChild(ut),ut.addEventListener("click",()=>{de?On():vn()})}let wo=c=>{var y,P,N;let g=o.attachments;if(!(g!=null&&g.enabled))return;let h=c.querySelector(".persona-attachment-previews");if(!h){h=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.style.display="none";let V=c.querySelector("[data-persona-composer-form]");V!=null&&V.parentNode?V.parentNode.insertBefore(h,V):c.insertBefore(h,c.firstChild)}if(!c.querySelector('input[type="file"]')){let V=b("input");V.type="file",V.accept=((y=g.allowedTypes)!=null?y:_o).join(","),V.multiple=((P=g.maxFiles)!=null?P:4)>1,V.style.display="none",V.setAttribute("aria-label",(N=g.buttonTooltipText)!=null?N:"Attach files"),c.appendChild(V)}},Nn=r.find(c=>c.renderComposer);if(Nn!=null&&Nn.renderComposer){let c=o.composer,g=Nn.renderComposer({config:o,defaultRenderer:()=>xi({config:o}).footer,onSubmit:h=>{var V;if(!T||T.isStreaming())return;let y=h.trim(),P=(V=et==null?void 0:et.hasAttachments())!=null?V:!1;if(!y&&!P)return;gs();let N;P&&(N=[],N.push(...et.getContentParts()),y&&N.push(ll(y))),T.sendMessage(y,{contentParts:N}),P&&et.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{oe==null||oe.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:((Wc=o.voiceRecognition)==null?void 0:Wc.enabled)===!0?()=>{Fn==null||Fn()}:void 0});g&&(Ve.replaceWith(g),Ve=g)}let ir=c=>{let g=c.querySelector("[data-persona-composer-form]"),h=c.querySelector("[data-persona-composer-input]"),y=c.querySelector("[data-persona-composer-submit]"),P=c.querySelector("[data-persona-composer-mic]"),N=c.querySelector("[data-persona-composer-status]");g&&(Nt=g),h&&(pe=h),y&&(ae=y),P&&(q=P,_t=P.parentElement),N&&(ln=N);let V=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");V&&(Et=V);let z=c.querySelector(".persona-attachment-button");z&&(Qe=z,Ft=z.parentElement),oe=c.querySelector('input[type="file"]'),fe=c.querySelector(".persona-attachment-previews");let O=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");O&&(dt=O)};wo(Ve),ir(Ve);let In=(Oc=(Bc=o.layout)==null?void 0:Bc.contentMaxWidth)!=null?Oc:k()?(Fc=(Dc=(Hc=o.launcher)==null?void 0:Hc.composerBar)==null?void 0:Dc.contentMaxWidth)!=null?Fc:"720px":void 0;if(In&&(_e.style.maxWidth=In,_e.style.marginLeft="auto",_e.style.marginRight="auto",_e.style.width="100%"),In&&Nt&&!k()&&(Nt.style.maxWidth=In,Nt.style.marginLeft="auto",Nt.style.marginRight="auto"),In&&Et&&!k()&&(Et.style.maxWidth=In,Et.style.marginLeft="auto",Et.style.marginRight="auto"),In&&fe&&!k()&&(fe.style.maxWidth=In,fe.style.marginLeft="auto",fe.style.marginRight="auto"),(Nc=o.attachments)!=null&&Nc.enabled&&oe&&fe){et=Ds.fromConfig(o.attachments),et.setPreviewsContainer(fe),oe.addEventListener("change",h=>{let y=h.target;et==null||et.handleFileSelect(y.files),y.value=""});let c=o.attachments.dropOverlay,g=Fm(c);ce.appendChild(g)}(()=>{var y,P;let c=(P=(y=o.layout)==null?void 0:y.slots)!=null?P:{},g=N=>{switch(N){case"body-top":return ce.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return _e;case"footer-top":return Et;case"composer":return Nt;case"footer-bottom":return ln;default:return null}},h=(N,V)=>{var z;switch(N){case"header-left":case"header-center":case"header-right":if(N==="header-left")De.insertBefore(V,De.firstChild);else if(N==="header-right")De.appendChild(V);else{let O=De.querySelector(".persona-flex-col");O?(z=O.parentNode)==null||z.insertBefore(V,O.nextSibling):De.appendChild(V)}break;case"body-top":{let O=K.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");O?O.replaceWith(V):K.insertBefore(V,K.firstChild);break}case"body-bottom":K.appendChild(V);break;case"footer-top":Et.replaceWith(V);break;case"footer-bottom":ln.replaceWith(V);break;default:break}};for(let[N,V]of Object.entries(c))if(V)try{let z=V({config:o,defaultContent:()=>g(N)});z&&h(N,z)}catch(z){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${N}":`,z)}})();let $o=c=>{let h=c.target.closest('button[data-expand-header="true"]');if(!h)return;let y=h.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!y)return;let P=y.getAttribute("data-message-id");if(!P)return;let N=h.getAttribute("data-bubble-type");N==="reasoning"?(Kr.has(P)?Kr.delete(P):Kr.add(P),Zu(P,y)):N==="tool"&&(Gr.has(P)?Gr.delete(P):Gr.add(P),em(P,y,o)),mo.delete(P)};_e.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),$o(c))}),_e.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),$o(c))});let Lo=new Map;_e.addEventListener("click",c=>{var V;let h=c.target.closest(".persona-message-action-btn[data-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.closest("[data-actions-for]");if(!y)return;let P=y.getAttribute("data-actions-for");if(!P)return;let N=h.getAttribute("data-action");if(N==="copy"){let O=T.getMessages().find(Ae=>Ae.id===P);if(O&&te.onCopy){let Ae=O.content||"";navigator.clipboard.writeText(Ae).then(()=>{h.classList.add("persona-message-action-success");let ue=Te("check",14,"currentColor",2);ue&&(h.innerHTML="",h.appendChild(ue)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let ee=Te("copy",14,"currentColor",2);ee&&(h.innerHTML="",h.appendChild(ee))},2e3)}).catch(ue=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ue)}),te.onCopy(O)}}else if(N==="upvote"||N==="downvote"){let O=((V=Lo.get(P))!=null?V:null)===N,Ae=N==="upvote"?"thumbs-up":"thumbs-down";if(O){Lo.delete(P),h.classList.remove("persona-message-action-active");let ue=Te(Ae,14,"currentColor",2);ue&&(h.innerHTML="",h.appendChild(ue))}else{let ue=N==="upvote"?"downvote":"upvote",ee=y.querySelector(`[data-action="${ue}"]`);if(ee){ee.classList.remove("persona-message-action-active");let Ye=Te(ue==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ye&&(ee.innerHTML="",ee.appendChild(Ye))}Lo.set(P,N),h.classList.add("persona-message-action-active");let he=Te(Ae,14,"currentColor",2);he&&(he.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(he)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Oe=T.getMessages().find(tt=>tt.id===P);Oe&&te.onFeedback&&te.onFeedback({type:N,messageId:Oe.id,message:Oe})}}}),_e.addEventListener("click",c=>{let h=c.target.closest("button[data-approval-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.closest(".persona-approval-bubble");if(!y)return;let P=y.getAttribute("data-message-id");if(!P)return;let N=h.getAttribute("data-approval-action");if(!N)return;let V=N==="approve"?"approved":"denied",O=T.getMessages().find(ue=>ue.id===P);if(!(O!=null&&O.approval))return;let Ae=y.querySelector("[data-approval-buttons]");Ae&&Ae.querySelectorAll("button").forEach(ee=>{ee.disabled=!0,ee.style.opacity="0.5",ee.style.cursor="not-allowed"}),O.approval.toolType==="webmcp"?T.resolveWebMcpApproval(P,V):T.resolveApproval(O.approval,V)});let yt=null,_n=null,Vn={artifacts:[],selectedId:null},xn=!1,It={current:null};_e.addEventListener("click",c=>{var ee,he,Ee,Oe,tt;let h=c.target.closest("[data-download-artifact]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||((Ee=(he=(ee=o.features)==null?void 0:ee.artifacts)==null?void 0:he.onArtifactAction)==null?void 0:Ee.call(he,{type:"download",artifactId:y}))===!0)return;let N=T.getArtifactById(y),V=N==null?void 0:N.markdown,z=(N==null?void 0:N.title)||"artifact";if(!V){let Ye=h.closest("[data-open-artifact]"),at=Ye==null?void 0:Ye.closest("[data-message-id]"),it=at==null?void 0:at.getAttribute("data-message-id");if(it){let Re=T.getMessages().find(qe=>qe.id===it);if(Re!=null&&Re.rawContent)try{let qe=JSON.parse(Re.rawContent);V=(Oe=qe==null?void 0:qe.props)==null?void 0:Oe.markdown,z=((tt=qe==null?void 0:qe.props)==null?void 0:tt.title)||z}catch{}}}if(!V)return;let O=new Blob([V],{type:"text/markdown"}),Ae=URL.createObjectURL(O),ue=document.createElement("a");ue.href=Ae,ue.download=`${z}.md`,ue.click(),URL.revokeObjectURL(Ae)}),_e.addEventListener("click",c=>{var N,V,z;let h=c.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||((z=(V=(N=o.features)==null?void 0:N.artifacts)==null?void 0:V.onArtifactAction)==null?void 0:z.call(V,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),xn=!1,T.selectArtifact(y),zn())}),_e.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let eo=Be.composerOverlay,to=(c,g,h)=>{var z,O,Ae,ue;let y=g.trim();if(!y||!It.current)return;let P=(z=c.getAttribute("data-tool-call-id"))!=null?z:"",N=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:P,answer:y,answers:h.structured,values:(O=h.values)!=null?O:h.source==="multi"?y.split(", "):[y],isFreeText:N,source:h.source},bubbles:!0,composed:!0})),Jr(eo,P);let V=It.current.getMessages().find(ee=>{var he;return((he=ee.toolCall)==null?void 0:he.id)===P});(Ae=V==null?void 0:V.agentMetadata)!=null&&Ae.awaitingLocalTool?It.current.resolveAskUserQuestion(V,(ue=h.structured)!=null?ue:y):It.current.sendMessage(y)},$n=c=>{var P;let g=It.current;if(!g)return;let h=(P=c.getAttribute("data-tool-call-id"))!=null?P:"",y=g.getMessages().find(N=>{var V;return((V=N.toolCall)==null?void 0:V.id)===h});y&&g.persistAskUserQuestionProgress(y,{answers:wi(c,y),currentIndex:lo(c)})},Uo=c=>Object.entries(c).map(([g,h])=>`${g}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Io=c=>{var P,N,V;if(((N=(P=o.features)==null?void 0:P.askUserQuestion)==null?void 0:N.groupedAutoAdvance)===!1)return;let g=lo(c),h=Qr(c);if(g>=h-1)return;let y=(V=It.current)==null?void 0:V.getMessages().find(z=>{var O;return((O=z.toolCall)==null?void 0:O.id)===c.getAttribute("data-tool-call-id")});y&&(Si(c,y,o,g+1),$n(c))};eo.addEventListener("click",c=>{var N,V,z,O,Ae,ue,ee,he,Ee,Oe,tt,Ye,at,it;let h=c.target.closest("[data-ask-user-action]");if(!h)return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;let P=h.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),P==="dismiss"){let Pe=(N=y.getAttribute("data-tool-call-id"))!=null?N:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),Jr(eo,Pe);let Re=(V=It.current)==null?void 0:V.getMessages().find(qe=>{var L;return((L=qe.toolCall)==null?void 0:L.id)===Pe});(z=Re==null?void 0:Re.agentMetadata)!=null&&z.awaitingLocalTool&&((O=It.current)==null||O.markAskUserQuestionResolved(Re),(Ae=It.current)==null||Ae.resolveAskUserQuestion(Re,"(dismissed)"));return}if(P==="pick"){let Pe=h.getAttribute("data-option-label");if(!Pe)return;let Re=y.getAttribute("data-multi-select")==="true",qe=sr(y);if(qe&&Re){let L=kr(y)[lo(y)],Me=new Set(Array.isArray(L)?L:[]);Me.has(Pe)?Me.delete(Pe):Me.add(Pe),ar(y,Array.from(Me)),$n(y);return}if(qe){ar(y,Pe),$n(y),Io(y);return}if(Re){let L=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",L?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!L);let Me=y.querySelector('[data-ask-user-action="submit-multi"]');Me&&(Me.disabled=El(y).length===0);return}to(y,Pe,{source:"pick",values:[Pe]});return}if(P==="submit-multi"){let Pe=El(y);if(Pe.length===0)return;to(y,Pe.join(", "),{source:"multi",values:Pe});return}if(P==="open-free-text"){let Pe=y.querySelector('[data-ask-free-text-row="true"]');if(Pe){Pe.classList.remove("persona-hidden");let Re=Pe.querySelector('[data-ask-free-text-input="true"]');Re==null||Re.focus()}return}if(P==="focus-free-text"){let Pe=y.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus();return}if(P==="submit-free-text"){let Pe=y.querySelector('[data-ask-free-text-input="true"]'),Re=(ue=Pe==null?void 0:Pe.value)!=null?ue:"";if(!Re.trim())return;if(sr(y)){ar(y,Re.trim()),$n(y),Io(y);return}to(y,Re,{source:"free-text"});return}if(P==="next"||P==="back"){if(!It.current)return;let Pe=(ee=y.getAttribute("data-tool-call-id"))!=null?ee:"",Re=It.current.getMessages().find(Ke=>{var Ce;return((Ce=Ke.toolCall)==null?void 0:Ce.id)===Pe});if(!Re)return;let qe=y.querySelector('[data-ask-free-text-input="true"]'),L=(Ee=(he=qe==null?void 0:qe.value)==null?void 0:he.trim())!=null?Ee:"";if(L){let Ke=kr(y)[lo(y)];(typeof Ke!="string"||Ke!==L)&&ar(y,L)}let Me=P==="next"?1:-1,We=lo(y)+Me;Si(y,Re,o,We),$n(y);return}if(P==="submit-all"){if(!It.current)return;let Pe=(Oe=y.getAttribute("data-tool-call-id"))!=null?Oe:"",Re=It.current.getMessages().find(Ke=>{var Ce;return((Ce=Ke.toolCall)==null?void 0:Ce.id)===Pe});if(!Re)return;let qe=y.querySelector('[data-ask-free-text-input="true"]'),L=(Ye=(tt=qe==null?void 0:qe.value)==null?void 0:tt.trim())!=null?Ye:"";L&&ar(y,L);let Me=wi(y,Re);It.current.persistAskUserQuestionProgress(Re,{answers:Me,currentIndex:lo(y)});let We=Uo(Me);to(y,We||"(submitted)",{source:"submit-all",structured:Me});return}if(P==="skip"){if(!It.current)return;let Pe=(at=y.getAttribute("data-tool-call-id"))!=null?at:"",Re=It.current.getMessages().find(Ce=>{var Lt;return((Lt=Ce.toolCall)==null?void 0:Lt.id)===Pe});if(!Re)return;let qe=sr(y),L=lo(y),Me=Qr(y),We=L>=Me-1;if(!qe){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),Jr(eo,Pe),(it=Re.agentMetadata)!=null&&it.awaitingLocalTool&&(It.current.markAskUserQuestionResolved(Re),It.current.resolveAskUserQuestion(Re,"(dismissed)"));return}ar(y,"");let Ke=y.querySelector('[data-ask-free-text-input="true"]');if(Ke&&(Ke.value=""),We){let Ce=wi(y,Re),Lt=Uo(Ce);to(y,Lt||"(skipped)",{source:"submit-all",structured:Ce});return}Si(y,Re,o,L+1),$n(y);return}}),eo.addEventListener("keydown",c=>{var N;if(c.key!=="Enter")return;let h=c.target;if(!((N=h.matches)!=null&&N.call(h,'[data-ask-free-text-input="true"]')))return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;c.preventDefault();let P=h.value;if(P.trim()){if(sr(y)){ar(y,P.trim()),$n(y),Io(y);return}to(y,P,{source:"free-text"})}});let zo=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let g=c.target;if((g==null?void 0:g.tagName)==="INPUT"||(g==null?void 0:g.tagName)==="TEXTAREA"||g!=null&&g.isContentEditable)return;let h=eo.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let y=Number(c.key),N=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];N&&(c.preventDefault(),N.click())};document.addEventListener("keydown",zo);let Un=null,Wt=null,wn=null,no=null,qo=()=>{};function Ro(){no==null||no(),no=null}let jo=()=>{var V;if(!Un||!Wt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),h=((V=e.ownerDocument.defaultView)!=null?V:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||h){Wt.style.removeProperty("position"),Wt.style.removeProperty("left"),Wt.style.removeProperty("top"),Wt.style.removeProperty("bottom"),Wt.style.removeProperty("width"),Wt.style.removeProperty("z-index");return}let y=Un.firstElementChild;if(!y||y===Wt)return;let P=10;Wt.style.position="absolute",Wt.style.top="0",Wt.style.bottom="0",Wt.style.width=`${P}px`,Wt.style.zIndex="5";let N=y.offsetWidth-P/2;Wt.style.left=`${Math.max(0,N)}px`},Co=()=>{},zn=()=>{var h,y,P,N,V;if(!yt||!co(o))return;Ti(e,o),ki(e,o),Co();let c=(N=(P=(y=(h=o.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:P.narrowHostMaxWidth)!=null?N:520,g=le.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),yt.update(Vn),xn?(yt.setMobileOpen(!1),yt.element.classList.add("persona-hidden"),(V=yt.backdrop)==null||V.classList.add("persona-hidden")):Vn.artifacts.length>0&&(yt.element.classList.remove("persona-hidden"),yt.setMobileOpen(!0)),qo()};if(co(o)){le.style.position="relative";let c=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(ce),yt=vm(o,{onSelect:h=>{var y;return(y=It.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{xn=!0,zn()}}),yt.element.classList.add("persona-hidden"),Un=g,g.appendChild(c),g.appendChild(yt.element),yt.backdrop&&le.appendChild(yt.backdrop),le.appendChild(g),qo=()=>{var y,P,N,V;if(!Un||!yt)return;if(!(((N=(P=(y=o.features)==null?void 0:y.artifacts)==null?void 0:P.layout)==null?void 0:N.resizable)===!0)){wn==null||wn(),wn=null,Ro(),Wt&&(Wt.remove(),Wt=null),yt.element.style.removeProperty("width"),yt.element.style.removeProperty("maxWidth");return}if(!Wt){let z=b("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");z.setAttribute("role","separator"),z.setAttribute("aria-orientation","vertical"),z.setAttribute("aria-label","Resize artifacts panel"),z.tabIndex=0;let O=e.ownerDocument,Ae=(V=O.defaultView)!=null?V:window,ue=ee=>{var at,it;if(!yt||ee.button!==0||e.classList.contains("persona-artifact-narrow-host")||Ae.innerWidth<=640)return;ee.preventDefault(),Ro();let he=ee.clientX,Ee=yt.element.getBoundingClientRect().width,Oe=(it=(at=o.features)==null?void 0:at.artifacts)==null?void 0:it.layout,tt=Pe=>{let Re=Un.getBoundingClientRect().width,qe=e.classList.contains("persona-artifact-appearance-seamless"),L=qe?0:Sm(Un,Ae),Me=qe?0:z.getBoundingClientRect().width||6,We=Ee-(Pe.clientX-he),Ke=Am(We,Re,L,Me,Oe==null?void 0:Oe.resizableMinWidth,Oe==null?void 0:Oe.resizableMaxWidth);yt.element.style.width=`${Ke}px`,yt.element.style.maxWidth="none",jo()},Ye=()=>{O.removeEventListener("pointermove",tt),O.removeEventListener("pointerup",Ye),O.removeEventListener("pointercancel",Ye),no=null;try{z.releasePointerCapture(ee.pointerId)}catch{}};no=Ye,O.addEventListener("pointermove",tt),O.addEventListener("pointerup",Ye),O.addEventListener("pointercancel",Ye);try{z.setPointerCapture(ee.pointerId)}catch{}};z.addEventListener("pointerdown",ue),Wt=z,Un.insertBefore(z,yt.element),wn=()=>{z.removeEventListener("pointerdown",ue)}}if(Wt){let z=Vn.artifacts.length>0&&!xn;Wt.classList.toggle("persona-hidden",!z),jo()}},Co=()=>{var Ae,ue,ee,he,Ee,Oe,tt,Ye,at,it,Pe,Re,qe,L;if(!I||!yt||((ue=(Ae=o.launcher)==null?void 0:Ae.sidebarMode)!=null?ue:!1)||pn(o)&&Mo(o).reveal==="emerge")return;let y=(ee=e.ownerDocument.defaultView)!=null?ee:window,P=(Ee=(he=o.launcher)==null?void 0:he.mobileFullscreen)!=null?Ee:!0,N=(tt=(Oe=o.launcher)==null?void 0:Oe.mobileBreakpoint)!=null?tt:640;if(P&&y.innerWidth<=N||!Cm(o,I))return;let V=(it=(at=(Ye=o.launcher)==null?void 0:Ye.width)!=null?at:o.launcherWidth)!=null?it:io,z=(L=(qe=(Re=(Pe=o.features)==null?void 0:Pe.artifacts)==null?void 0:Re.layout)==null?void 0:qe.expandedPanelWidth)!=null?L:"min(720px, calc(100vw - 24px))";Vn.artifacts.length>0&&!xn?(le.style.width=z,le.style.maxWidth=z):(le.style.width=V,le.style.maxWidth=V)},typeof ResizeObserver!="undefined"&&(_n=new ResizeObserver(()=>{zn()}),_n.observe(le))}else le.appendChild(ce),k()&&$e&&(Be.peekBanner&&$e.appendChild(Be.peekBanner),$e.appendChild(Ve));e.appendChild(ye),$e&&e.appendChild($e);let po=()=>{var Ke,Ce,Lt,st,Xt,cn,Pt,An,dn,Je,lt,Tn,mn,mr,gr,fr,Nr,_r,qt,hr,nr,ht,Pn,Oo,kn,Wn,Ht,Ut;if(k()){le.style.width="100%",le.style.maxWidth="100%";let Dt=(Ce=(Ke=o.launcher)==null?void 0:Ke.composerBar)!=null?Ce:{},jt=ye.dataset.state==="expanded",Bn=(Lt=Dt.expandedSize)!=null?Lt:"anchored";if(!(jt&&Bn!=="fullscreen")){ce.style.background="",ce.style.border="",ce.style.borderRadius="",ce.style.overflow="",ce.style.boxShadow="";return}let en=(Xt=(st=o.theme)==null?void 0:st.components)==null?void 0:Xt.panel,To=ka(o),No=(br,Aa)=>{var Cs;return br==null||br===""?Aa:(Cs=Vr(To,br))!=null?Cs:br},wa="1px solid var(--persona-border)",Ca="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Sa="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ce.style.background="var(--persona-surface, #ffffff)",ce.style.border=No(en==null?void 0:en.border,wa),ce.style.borderRadius=No(en==null?void 0:en.borderRadius,Sa),ce.style.boxShadow=No(en==null?void 0:en.shadow,Ca),ce.style.overflow="hidden";return}let c=pn(o),g=(Pt=(cn=o.launcher)==null?void 0:cn.sidebarMode)!=null?Pt:!1,h=c||g||((dn=(An=o.launcher)==null?void 0:An.fullHeight)!=null?dn:!1),y=((Je=o.launcher)==null?void 0:Je.enabled)===!1,P=(Tn=(lt=o.theme)==null?void 0:lt.components)==null?void 0:Tn.panel,N=ka(o),V=(Dt,jt)=>{var Bn;return Dt==null||Dt===""?jt:(Bn=Vr(N,Dt))!=null?Bn:Dt},z=(mn=e.ownerDocument.defaultView)!=null?mn:window,O=(gr=(mr=o.launcher)==null?void 0:mr.mobileFullscreen)!=null?gr:!0,Ae=(Nr=(fr=o.launcher)==null?void 0:fr.mobileBreakpoint)!=null?Nr:640,ue=z.innerWidth<=Ae,ee=O&&ue&&I,he=(qt=(_r=o.launcher)==null?void 0:_r.position)!=null?qt:"bottom-left",Ee=he==="bottom-left"||he==="top-left",Oe=(nr=(hr=o.launcher)==null?void 0:hr.zIndex)!=null?nr:hn,tt=g||ee?"none":"1px solid var(--persona-border)",Ye=ee?"none":g?Ee?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!ee&&(Ye="none",tt="none");let at=g||ee?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",it=V(P==null?void 0:P.border,tt),Pe=V(P==null?void 0:P.shadow,Ye),Re=V(P==null?void 0:P.borderRadius,at),qe=K.scrollTop;e.style.cssText="",ye.style.cssText="",le.style.cssText="",ce.style.cssText="",K.style.cssText="",Ve.style.cssText="";let L=()=>{var jt;if(qe<=0)return;((jt=K.ownerDocument.defaultView)!=null?jt:window).requestAnimationFrame(()=>{if(K.scrollTop===qe)return;let Bn=K.scrollHeight-K.clientHeight;Bn<=0||(K.scrollTop=Math.min(qe,Bn))})};if(ee){ye.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),ye.style.cssText=`
|
|
30
|
+
`,x.addEventListener("click",()=>{u=v,I.forEach((k,C)=>{let T=C<v;k.classList.toggle("selected",T),k.setAttribute("aria-checked",C===v-1?"true":"false")})}),I.push(x),M.appendChild(x)}g.appendChild(M);let L=null;if(d){let v=document.createElement("div");v.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),v.appendChild(L),g.appendChild(v)}let H=document.createElement("div");H.className="persona-feedback-actions";let D=document.createElement("button");D.type="button",D.className="persona-feedback-btn persona-feedback-btn-skip",D.textContent=i,D.addEventListener("click",()=>{n==null||n(),m.remove()});let W=document.createElement("button");return W.type="button",W.className="persona-feedback-btn persona-feedback-btn-submit",W.textContent=a,W.addEventListener("click",async()=>{if(u===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}W.disabled=!0,W.textContent="Submitting...";try{let v=(L==null?void 0:L.value.trim())||void 0;await t(u,v),m.remove()}catch(v){W.disabled=!1,W.textContent=a,console.error("[CSAT Feedback] Failed to submit:",v)}}),H.appendChild(D),H.appendChild(W),g.appendChild(H),m.appendChild(g),m}function Dm(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:m="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let g=null,p=document.createElement("div");p.className="persona-feedback-content";let w=document.createElement("div");w.className="persona-feedback-header";let S=document.createElement("h3");S.className="persona-feedback-title",S.textContent=o,w.appendChild(S);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=r,w.appendChild(M),p.appendChild(w);let I=document.createElement("div");I.className="persona-feedback-rating persona-feedback-rating-nps",I.setAttribute("role","radiogroup"),I.setAttribute("aria-label","Likelihood rating from 0 to 10");let L=document.createElement("div");L.className="persona-feedback-labels";let H=document.createElement("span");H.className="persona-feedback-label-low",H.textContent=l;let D=document.createElement("span");D.className="persona-feedback-label-high",D.textContent=m,L.appendChild(H),L.appendChild(D);let W=document.createElement("div");W.className="persona-feedback-numbers";let v=[];for(let F=0;F<=10;F++){let $=document.createElement("button");$.type="button",$.className="persona-feedback-rating-btn persona-feedback-number-btn",$.setAttribute("role","radio"),$.setAttribute("aria-checked","false"),$.setAttribute("aria-label",`Rating ${F} out of 10`),$.textContent=String(F),$.dataset.rating=String(F),F<=6?$.classList.add("persona-feedback-detractor"):F<=8?$.classList.add("persona-feedback-passive"):$.classList.add("persona-feedback-promoter"),$.addEventListener("click",()=>{g=F,v.forEach((j,me)=>{j.classList.toggle("selected",me===F),j.setAttribute("aria-checked",me===F?"true":"false")})}),v.push($),W.appendChild($)}I.appendChild(L),I.appendChild(W),p.appendChild(I);let x=null;if(d){let F=document.createElement("div");F.className="persona-feedback-comment-container",x=document.createElement("textarea"),x.className="persona-feedback-comment",x.placeholder=s,x.rows=3,x.setAttribute("aria-label","Additional comments"),F.appendChild(x),p.appendChild(F)}let k=document.createElement("div");k.className="persona-feedback-actions";let C=document.createElement("button");C.type="button",C.className="persona-feedback-btn persona-feedback-btn-skip",C.textContent=i,C.addEventListener("click",()=>{n==null||n(),u.remove()});let T=document.createElement("button");return T.type="button",T.className="persona-feedback-btn persona-feedback-btn-submit",T.textContent=a,T.addEventListener("click",async()=>{if(g===null){W.classList.add("persona-feedback-shake"),setTimeout(()=>W.classList.remove("persona-feedback-shake"),500);return}T.disabled=!0,T.textContent="Submitting...";try{let F=(x==null?void 0:x.value.trim())||void 0;await t(g,F),u.remove()}catch(F){T.disabled=!1,T.textContent=a,console.error("[NPS Feedback] Failed to submit:",F)}}),k.appendChild(C),k.appendChild(T),p.appendChild(k),u.appendChild(p),u}var ts="persona-chat-history",nx=30*1e3,ox={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function rx(e){var o,r,s;if(!e)return[];let t=[],n=Array.from((o=e.items)!=null?o:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(r=ox[i.type])!=null?r:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((s=e.files)!=null?s:[]))a.type.startsWith("image/")&&t.push(a);return t}function Li(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function sx(e){var t,n,o,r,s,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(r=(o=e.persist)==null?void 0:o.openState)!=null?r:!0,voiceState:(a=(s=e.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function ax(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Nl=e=>!e||typeof e!="object"?{}:{...e},Fm=e=>e.map(t=>({...t,streaming:!1})),Om=(e,t,n)=>{let o=e!=null&&e.markdown?$a(e.markdown):null,r=Ua(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&r&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var l,m,u;let a=(l=s.text)!=null?l:"",i=(m=s.message.rawContent)!=null?m:null;if(t){let g=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});g!==null&&(a=g.text,g.persist||(s.message.__skipPersist=!0),g.resubmit&&!s.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...s,text:a,raw:(u=i!=null?i:s.text)!=null?u:""}):o?d=o(a):d=Is(a),r?r(d):d}};function Nm(e){var i,d,l,m;let t=b("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",o=(d=e==null?void 0:e.iconSize)!=null?d:"48px",r=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(m=e==null?void 0:e.iconStrokeWidth)!=null?m:.5,a=Te(n,o,r,s);if(a&&t.appendChild(a),e!=null&&e.label){let u=b("span","persona-drop-overlay-label");u.textContent=e.label,t.appendChild(u)}return t}var _m=(e,t,n)=>{var ac,ic,lc,cc,dc,pc,uc,mc,fc,gc,hc,bc,yc,vc,xc,wc,Cc,Sc,Ac,Tc,kc,Ec,Mc,Lc,Ic,Rc,Pc,Wc,Bc,Hc,Dc,Fc,Oc,Nc,_c,Vc,$c,Uc,zc,qc,jc,Kc,Gc,Yc,Xc,Qc,Jc,Zc;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=Jp(t),r=Hl.getForInstance(o.plugins);o.components&&Mr.registerAll(o.components);let s=Mm(),i=o.persistState===!1?null:(ac=o.storageAdapter)!=null?ac:Im(),d={},l=null,m=!1,u=c=>{if(o.onStateLoaded)try{let f=o.onStateLoaded(c);if(f&&typeof f=="object"&&"state"in f){let{state:h,open:y}=f;return y&&(m=!0),h}return f}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",f)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(f=>{let h=f!=null?f:{messages:[],metadata:{}};return u(h)});else{let f=c!=null?c:{messages:[],metadata:{}},h=u(f);h.metadata&&(d=Nl(h.metadata)),(ic=h.messages)!=null&&ic.length&&(o={...o,initialMessages:h.messages}),(lc=h.artifacts)!=null&&lc.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(cc=h.selectedArtifactId)!=null?cc:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(o.onStateLoaded)try{let c=u({messages:[],metadata:{}});(dc=c.messages)!=null&&dc.length&&(o={...o,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let g=()=>d,p=c=>{var h;d=(h=c({...d}))!=null?h:{},Wr()},w=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Fl],S=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ea.message,ea.messageAndClick],M=Ol({parsers:w,handlers:S,getSessionMetadata:g,updateSessionMetadata:p,emit:s.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let I=(uc=(pc=o.launcher)==null?void 0:pc.enabled)!=null?uc:!0,L=(fc=(mc=o.launcher)==null?void 0:mc.autoExpand)!=null?fc:!1,H=(gc=o.autoFocusInput)!=null?gc:!1,D=L,W=I,v=(bc=(hc=o.layout)==null?void 0:hc.header)==null?void 0:bc.layout,x=!1,k=()=>js(o),C=()=>I||k(),T=k()?!1:I?L:!0,F=!1,$=null,j=()=>{F=!0,$&&clearTimeout($),$=setTimeout(()=>{F&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),F=!1)},1e4)},me=Om(o,M,j),se=(vc=(yc=o.features)==null?void 0:yc.showReasoning)!=null?vc:!0,fe=(wc=(xc=o.features)==null?void 0:xc.showToolCalls)!=null?wc:!0,ie=(Sc=(Cc=o.features)==null?void 0:Cc.showEventStreamToggle)!=null?Sc:!1,be=(Tc=(Ac=o.features)==null?void 0:Ac.scrollToBottom)!=null?Tc:{},ve=`${(Ec=typeof o.persistState=="object"?(kc=o.persistState)==null?void 0:kc.keyPrefix:void 0)!=null?Ec:"persona-"}event-stream`,Q=ie?new Js(ve):null,Le=(Ic=(Lc=(Mc=o.features)==null?void 0:Mc.eventStream)==null?void 0:Lc.maxEvents)!=null?Ic:2e3,Y=ie?new Qs(Le,Q):null,xe=ie?new Zs:null,Se=null,de=!1,we=null,ze=0;Q==null||Q.open().then(()=>Y==null?void 0:Y.restore()).catch(c=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let te={onCopy:c=>{var f,h;s.emit("message:copy",c),E!=null&&E.isClientTokenMode()&&E.submitMessageFeedback(c.id,"copy").catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",y)}),(h=(f=o.messageActions)==null?void 0:f.onCopy)==null||h.call(f,c)},onFeedback:c=>{var f,h;s.emit("message:feedback",c),E!=null&&E.isClientTokenMode()&&E.submitMessageFeedback(c.messageId,c.type).catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",y)}),(h=(f=o.messageActions)==null?void 0:f.onFeedback)==null||h.call(f,c)}},ne=(Rc=o.statusIndicator)!=null?Rc:{},re=c=>{var f,h,y,P;return c==="idle"?(f=ne.idleText)!=null?f:gn.idle:c==="connecting"?(h=ne.connectingText)!=null?h:gn.connecting:c==="connected"?(y=ne.connectedText)!=null?y:gn.connected:c==="error"?(P=ne.errorText)!=null?P:gn.error:gn[c]};function nt(c,f,h,y){if(y==="idle"&&h.idleLink){c.textContent="";let P=document.createElement("a");P.href=h.idleLink,P.target="_blank",P.rel="noopener noreferrer",P.textContent=f,P.style.color="inherit",P.style.textDecoration="none",c.appendChild(P)}else c.textContent=f}let{wrapper:ye,panel:le,pillRoot:Ue}=Qu(o),He=Ju(o,C()),{container:ce,body:G,messagesWrapper:Ve,suggestions:Et,textarea:pe,sendButton:ae,sendButtonWrapper:Ln,composerForm:Nt,statusText:ln,introTitle:Dn,introSubtitle:Jn,closeButton:qe,iconHolder:_,headerTitle:ke,headerSubtitle:De,header:Fe,footer:$e,actionsRow:dt,leftActions:ot,rightActions:At}=He,Vt=He.setSendButtonMode,q=He.micButton,_t=He.micButtonWrapper,Qe=He.attachmentButton,Ft=He.attachmentButtonWrapper,oe=He.attachmentInput,ge=He.attachmentPreviewsContainer;ce.classList.add("persona-relative"),G.classList.add("persona-relative");let xt=12,$t=()=>{var c;return(c=be.label)!=null?c:""},Jt=()=>{var c;return(c=be.iconName)!=null?c:"arrow-down"},yn=()=>be.enabled!==!1,Tt=b("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Tt.type="button",Tt.style.display="none",Tt.setAttribute("data-persona-scroll-to-bottom","true");let wt=b("span","persona-flex persona-items-center"),gt=b("span","");Tt.append(wt,gt),ce.appendChild(Tt);let bt=()=>{let f=$e.style.display==="none"?0:$e.offsetHeight;Tt.style.bottom=`${f+xt}px`};bt();let zt=()=>{let c=!!$t();Tt.setAttribute("aria-label",$t()||"Jump to latest"),Tt.title=$t(),Tt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),wt.innerHTML="";let f=Te(Jt(),"14px","currentColor",2);f?(wt.appendChild(f),wt.style.display=""):wt.style.display="none",gt.textContent=$t(),gt.style.display=c?"":"none"};zt();let et=null,Fn=null,Zn=r.find(c=>c.renderHeader);if(Zn!=null&&Zn.renderHeader){let c=Zn.renderHeader({config:o,defaultRenderer:()=>{let f=Ar({config:o,showClose:C()});return Gs(ce,f,o),f.header},onClose:()=>Bt(!1,"user")});if(c){let f=ce.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(c),Fe=c)}}let vn=()=>{var f,h,y,P;if(!Y)return;if(de=!0,!Se&&Y&&(Se=ym({buffer:Y,getFullHistory:()=>Y.getAllFromStore(),onClose:()=>On(),config:o,plugins:r,getThroughput:()=>{var N;return(N=xe==null?void 0:xe.getMetric())!=null?N:{status:"idle"}}})),Se&&(G.style.display="none",(f=$e.parentNode)==null||f.insertBefore(Se.element,$e),Se.update()),ut){ut.style.boxShadow=`inset 0 0 0 1.5px ${Mn.actionIconColor}`;let N=(P=(y=(h=o.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:P.toggleButtonActive;N&&N.split(/\s+/).forEach(V=>V&&ut.classList.add(V))}let c=()=>{if(!de)return;let N=Date.now();N-ze>=200&&(Se==null||Se.update(),ze=N),we=requestAnimationFrame(c)};ze=0,we=requestAnimationFrame(c),Ho(),s.emit("eventStream:opened",{timestamp:Date.now()})},On=()=>{var c,f,h;if(de){if(de=!1,Se&&Se.element.remove(),G.style.display="",ut){ut.style.boxShadow="";let y=(h=(f=(c=o.features)==null?void 0:c.eventStream)==null?void 0:f.classNames)==null?void 0:h.toggleButtonActive;y&&y.split(/\s+/).forEach(P=>P&&ut.classList.remove(P))}we!==null&&(cancelAnimationFrame(we),we=null),Ho(),s.emit("eventStream:closed",{timestamp:Date.now()})}},ut=null;if(ie){let c=(Wc=(Pc=o.features)==null?void 0:Pc.eventStream)==null?void 0:Wc.classNames,f="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");ut=b("button",f),ut.style.width="28px",ut.style.height="28px",ut.style.color=Mn.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let h=Te("activity","18px","currentColor",1.5);h&&ut.appendChild(h);let y=He.clearChatButtonWrapper,P=He.closeButtonWrapper,N=y||P;N&&N.parentNode===Fe?Fe.insertBefore(ut,N):Fe.appendChild(ut),ut.addEventListener("click",()=>{de?On():vn()})}let wo=c=>{var y,P,N;let f=o.attachments;if(!(f!=null&&f.enabled))return;let h=c.querySelector(".persona-attachment-previews");if(!h){h=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.style.display="none";let V=c.querySelector("[data-persona-composer-form]");V!=null&&V.parentNode?V.parentNode.insertBefore(h,V):c.insertBefore(h,c.firstChild)}if(!c.querySelector('input[type="file"]')){let V=b("input");V.type="file",V.accept=((y=f.allowedTypes)!=null?y:_o).join(","),V.multiple=((P=f.maxFiles)!=null?P:4)>1,V.style.display="none",V.setAttribute("aria-label",(N=f.buttonTooltipText)!=null?N:"Attach files"),c.appendChild(V)}},Nn=r.find(c=>c.renderComposer);if(Nn!=null&&Nn.renderComposer){let c=o.composer,f=Nn.renderComposer({config:o,defaultRenderer:()=>Ci({config:o}).footer,onSubmit:h=>{var V;if(!E||E.isStreaming())return;let y=h.trim(),P=(V=et==null?void 0:et.hasAttachments())!=null?V:!1;if(!y&&!P)return;gs();let N;P&&(N=[],N.push(...et.getContentParts()),y&&N.push(cl(y))),E.sendMessage(y,{contentParts:N}),P&&et.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{oe==null||oe.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:((Bc=o.voiceRecognition)==null?void 0:Bc.enabled)===!0?()=>{Fn==null||Fn()}:void 0});f&&($e.replaceWith(f),$e=f)}let ir=c=>{let f=c.querySelector("[data-persona-composer-form]"),h=c.querySelector("[data-persona-composer-input]"),y=c.querySelector("[data-persona-composer-submit]"),P=c.querySelector("[data-persona-composer-mic]"),N=c.querySelector("[data-persona-composer-status]");f&&(Nt=f),h&&(pe=h),y&&(ae=y),P&&(q=P,_t=P.parentElement),N&&(ln=N);let V=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");V&&(Et=V);let z=c.querySelector(".persona-attachment-button");z&&(Qe=z,Ft=z.parentElement),oe=c.querySelector('input[type="file"]'),ge=c.querySelector(".persona-attachment-previews");let O=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");O&&(dt=O)};wo($e),ir($e);let In=(Nc=(Hc=o.layout)==null?void 0:Hc.contentMaxWidth)!=null?Nc:k()?(Oc=(Fc=(Dc=o.launcher)==null?void 0:Dc.composerBar)==null?void 0:Fc.contentMaxWidth)!=null?Oc:"720px":void 0;if(In&&(Ve.style.maxWidth=In,Ve.style.marginLeft="auto",Ve.style.marginRight="auto",Ve.style.width="100%"),In&&Nt&&!k()&&(Nt.style.maxWidth=In,Nt.style.marginLeft="auto",Nt.style.marginRight="auto"),In&&Et&&!k()&&(Et.style.maxWidth=In,Et.style.marginLeft="auto",Et.style.marginRight="auto"),In&&ge&&!k()&&(ge.style.maxWidth=In,ge.style.marginLeft="auto",ge.style.marginRight="auto"),(_c=o.attachments)!=null&&_c.enabled&&oe&&ge){et=Os.fromConfig(o.attachments),et.setPreviewsContainer(ge),oe.addEventListener("change",h=>{let y=h.target;et==null||et.handleFileSelect(y.files),y.value=""});let c=o.attachments.dropOverlay,f=Nm(c);ce.appendChild(f)}(()=>{var y,P;let c=(P=(y=o.layout)==null?void 0:y.slots)!=null?P:{},f=N=>{switch(N){case"body-top":return ce.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ve;case"footer-top":return Et;case"composer":return Nt;case"footer-bottom":return ln;default:return null}},h=(N,V)=>{var z;switch(N){case"header-left":case"header-center":case"header-right":if(N==="header-left")Fe.insertBefore(V,Fe.firstChild);else if(N==="header-right")Fe.appendChild(V);else{let O=Fe.querySelector(".persona-flex-col");O?(z=O.parentNode)==null||z.insertBefore(V,O.nextSibling):Fe.appendChild(V)}break;case"body-top":{let O=G.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");O?O.replaceWith(V):G.insertBefore(V,G.firstChild);break}case"body-bottom":G.appendChild(V);break;case"footer-top":Et.replaceWith(V);break;case"footer-bottom":ln.replaceWith(V);break;default:break}};for(let[N,V]of Object.entries(c))if(V)try{let z=V({config:o,defaultContent:()=>f(N)});z&&h(N,z)}catch(z){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${N}":`,z)}})();let $o=c=>{let h=c.target.closest('button[data-expand-header="true"]');if(!h)return;let y=h.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!y)return;let P=y.getAttribute("data-message-id");if(!P)return;let N=h.getAttribute("data-bubble-type");N==="reasoning"?(Gr.has(P)?Gr.delete(P):Gr.add(P),tm(P,y)):N==="tool"&&(Yr.has(P)?Yr.delete(P):Yr.add(P),nm(P,y,o)),mo.delete(P)};Ve.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),$o(c))}),Ve.addEventListener("keydown",c=>{let f=c.target;(c.key==="Enter"||c.key===" ")&&f.closest('button[data-expand-header="true"]')&&(c.preventDefault(),$o(c))});let Lo=new Map;Ve.addEventListener("click",c=>{var V;let h=c.target.closest(".persona-message-action-btn[data-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.closest("[data-actions-for]");if(!y)return;let P=y.getAttribute("data-actions-for");if(!P)return;let N=h.getAttribute("data-action");if(N==="copy"){let O=E.getMessages().find(Ae=>Ae.id===P);if(O&&te.onCopy){let Ae=O.content||"";navigator.clipboard.writeText(Ae).then(()=>{h.classList.add("persona-message-action-success");let ue=Te("check",14,"currentColor",2);ue&&(h.innerHTML="",h.appendChild(ue)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Z=Te("copy",14,"currentColor",2);Z&&(h.innerHTML="",h.appendChild(Z))},2e3)}).catch(ue=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ue)}),te.onCopy(O)}}else if(N==="upvote"||N==="downvote"){let O=((V=Lo.get(P))!=null?V:null)===N,Ae=N==="upvote"?"thumbs-up":"thumbs-down";if(O){Lo.delete(P),h.classList.remove("persona-message-action-active");let ue=Te(Ae,14,"currentColor",2);ue&&(h.innerHTML="",h.appendChild(ue))}else{let ue=N==="upvote"?"downvote":"upvote",Z=y.querySelector(`[data-action="${ue}"]`);if(Z){Z.classList.remove("persona-message-action-active");let Xe=Te(ue==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Xe&&(Z.innerHTML="",Z.appendChild(Xe))}Lo.set(P,N),h.classList.add("persona-message-action-active");let he=Te(Ae,14,"currentColor",2);he&&(he.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(he)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ne=E.getMessages().find(tt=>tt.id===P);Ne&&te.onFeedback&&te.onFeedback({type:N,messageId:Ne.id,message:Ne})}}}),Ve.addEventListener("click",c=>{let h=c.target.closest("button[data-approval-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.closest(".persona-approval-bubble");if(!y)return;let P=y.getAttribute("data-message-id");if(!P)return;let N=h.getAttribute("data-approval-action");if(!N)return;let V=N==="approve"?"approved":"denied",O=E.getMessages().find(ue=>ue.id===P);if(!(O!=null&&O.approval))return;let Ae=y.querySelector("[data-approval-buttons]");Ae&&Ae.querySelectorAll("button").forEach(Z=>{Z.disabled=!0,Z.style.opacity="0.5",Z.style.cursor="not-allowed"}),O.approval.toolType==="webmcp"?E.resolveWebMcpApproval(P,V):E.resolveApproval(O.approval,V)});let yt=null,_n=null,Vn={artifacts:[],selectedId:null},xn=!1,It={current:null};Ve.addEventListener("click",c=>{var Z,he,Ee,Ne,tt;let h=c.target.closest("[data-download-artifact]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||((Ee=(he=(Z=o.features)==null?void 0:Z.artifacts)==null?void 0:he.onArtifactAction)==null?void 0:Ee.call(he,{type:"download",artifactId:y}))===!0)return;let N=E.getArtifactById(y),V=N==null?void 0:N.markdown,z=(N==null?void 0:N.title)||"artifact";if(!V){let Xe=h.closest("[data-open-artifact]"),at=Xe==null?void 0:Xe.closest("[data-message-id]"),it=at==null?void 0:at.getAttribute("data-message-id");if(it){let Re=E.getMessages().find(je=>je.id===it);if(Re!=null&&Re.rawContent)try{let je=JSON.parse(Re.rawContent);V=(Ne=je==null?void 0:je.props)==null?void 0:Ne.markdown,z=((tt=je==null?void 0:je.props)==null?void 0:tt.title)||z}catch{}}}if(!V)return;let O=new Blob([V],{type:"text/markdown"}),Ae=URL.createObjectURL(O),ue=document.createElement("a");ue.href=Ae,ue.download=`${z}.md`,ue.click(),URL.revokeObjectURL(Ae)}),Ve.addEventListener("click",c=>{var N,V,z;let h=c.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||((z=(V=(N=o.features)==null?void 0:N.artifacts)==null?void 0:V.onArtifactAction)==null?void 0:z.call(V,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),xn=!1,E.selectArtifact(y),zn())}),Ve.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let f=c.target;f.hasAttribute("data-open-artifact")&&(c.preventDefault(),f.click())});let eo=He.composerOverlay,to=(c,f,h)=>{var z,O,Ae,ue;let y=f.trim();if(!y||!It.current)return;let P=(z=c.getAttribute("data-tool-call-id"))!=null?z:"",N=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:P,answer:y,answers:h.structured,values:(O=h.values)!=null?O:h.source==="multi"?y.split(", "):[y],isFreeText:N,source:h.source},bubbles:!0,composed:!0})),Zr(eo,P);let V=It.current.getMessages().find(Z=>{var he;return((he=Z.toolCall)==null?void 0:he.id)===P});(Ae=V==null?void 0:V.agentMetadata)!=null&&Ae.awaitingLocalTool?It.current.resolveAskUserQuestion(V,(ue=h.structured)!=null?ue:y):It.current.sendMessage(y)},$n=c=>{var P;let f=It.current;if(!f)return;let h=(P=c.getAttribute("data-tool-call-id"))!=null?P:"",y=f.getMessages().find(N=>{var V;return((V=N.toolCall)==null?void 0:V.id)===h});y&&f.persistAskUserQuestionProgress(y,{answers:Si(c,y),currentIndex:lo(c)})},Uo=c=>Object.entries(c).map(([f,h])=>`${f}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Io=c=>{var P,N,V;if(((N=(P=o.features)==null?void 0:P.askUserQuestion)==null?void 0:N.groupedAutoAdvance)===!1)return;let f=lo(c),h=Jr(c);if(f>=h-1)return;let y=(V=It.current)==null?void 0:V.getMessages().find(z=>{var O;return((O=z.toolCall)==null?void 0:O.id)===c.getAttribute("data-tool-call-id")});y&&(Ti(c,y,o,f+1),$n(c))};eo.addEventListener("click",c=>{var N,V,z,O,Ae,ue,Z,he,Ee,Ne,tt,Xe,at,it;let h=c.target.closest("[data-ask-user-action]");if(!h)return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;let P=h.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),P==="dismiss"){let Pe=(N=y.getAttribute("data-tool-call-id"))!=null?N:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),Zr(eo,Pe);let Re=(V=It.current)==null?void 0:V.getMessages().find(je=>{var R;return((R=je.toolCall)==null?void 0:R.id)===Pe});(z=Re==null?void 0:Re.agentMetadata)!=null&&z.awaitingLocalTool&&((O=It.current)==null||O.markAskUserQuestionResolved(Re),(Ae=It.current)==null||Ae.resolveAskUserQuestion(Re,"(dismissed)"));return}if(P==="pick"){let Pe=h.getAttribute("data-option-label");if(!Pe)return;let Re=y.getAttribute("data-multi-select")==="true",je=sr(y);if(je&&Re){let R=kr(y)[lo(y)],Me=new Set(Array.isArray(R)?R:[]);Me.has(Pe)?Me.delete(Pe):Me.add(Pe),ar(y,Array.from(Me)),$n(y);return}if(je){ar(y,Pe),$n(y),Io(y);return}if(Re){let R=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",R?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!R);let Me=y.querySelector('[data-ask-user-action="submit-multi"]');Me&&(Me.disabled=Ml(y).length===0);return}to(y,Pe,{source:"pick",values:[Pe]});return}if(P==="submit-multi"){let Pe=Ml(y);if(Pe.length===0)return;to(y,Pe.join(", "),{source:"multi",values:Pe});return}if(P==="open-free-text"){let Pe=y.querySelector('[data-ask-free-text-row="true"]');if(Pe){Pe.classList.remove("persona-hidden");let Re=Pe.querySelector('[data-ask-free-text-input="true"]');Re==null||Re.focus()}return}if(P==="focus-free-text"){let Pe=y.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus();return}if(P==="submit-free-text"){let Pe=y.querySelector('[data-ask-free-text-input="true"]'),Re=(ue=Pe==null?void 0:Pe.value)!=null?ue:"";if(!Re.trim())return;if(sr(y)){ar(y,Re.trim()),$n(y),Io(y);return}to(y,Re,{source:"free-text"});return}if(P==="next"||P==="back"){if(!It.current)return;let Pe=(Z=y.getAttribute("data-tool-call-id"))!=null?Z:"",Re=It.current.getMessages().find(Ge=>{var Ce;return((Ce=Ge.toolCall)==null?void 0:Ce.id)===Pe});if(!Re)return;let je=y.querySelector('[data-ask-free-text-input="true"]'),R=(Ee=(he=je==null?void 0:je.value)==null?void 0:he.trim())!=null?Ee:"";if(R){let Ge=kr(y)[lo(y)];(typeof Ge!="string"||Ge!==R)&&ar(y,R)}let Me=P==="next"?1:-1,Be=lo(y)+Me;Ti(y,Re,o,Be),$n(y);return}if(P==="submit-all"){if(!It.current)return;let Pe=(Ne=y.getAttribute("data-tool-call-id"))!=null?Ne:"",Re=It.current.getMessages().find(Ge=>{var Ce;return((Ce=Ge.toolCall)==null?void 0:Ce.id)===Pe});if(!Re)return;let je=y.querySelector('[data-ask-free-text-input="true"]'),R=(Xe=(tt=je==null?void 0:je.value)==null?void 0:tt.trim())!=null?Xe:"";R&&ar(y,R);let Me=Si(y,Re);It.current.persistAskUserQuestionProgress(Re,{answers:Me,currentIndex:lo(y)});let Be=Uo(Me);to(y,Be||"(submitted)",{source:"submit-all",structured:Me});return}if(P==="skip"){if(!It.current)return;let Pe=(at=y.getAttribute("data-tool-call-id"))!=null?at:"",Re=It.current.getMessages().find(Ce=>{var Lt;return((Lt=Ce.toolCall)==null?void 0:Lt.id)===Pe});if(!Re)return;let je=sr(y),R=lo(y),Me=Jr(y),Be=R>=Me-1;if(!je){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),Zr(eo,Pe),(it=Re.agentMetadata)!=null&&it.awaitingLocalTool&&(It.current.markAskUserQuestionResolved(Re),It.current.resolveAskUserQuestion(Re,"(dismissed)"));return}ar(y,"");let Ge=y.querySelector('[data-ask-free-text-input="true"]');if(Ge&&(Ge.value=""),Be){let Ce=Si(y,Re),Lt=Uo(Ce);to(y,Lt||"(skipped)",{source:"submit-all",structured:Ce});return}Ti(y,Re,o,R+1),$n(y);return}}),eo.addEventListener("keydown",c=>{var N;if(c.key!=="Enter")return;let h=c.target;if(!((N=h.matches)!=null&&N.call(h,'[data-ask-free-text-input="true"]')))return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;c.preventDefault();let P=h.value;if(P.trim()){if(sr(y)){ar(y,P.trim()),$n(y),Io(y);return}to(y,P,{source:"free-text"})}});let zo=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let f=c.target;if((f==null?void 0:f.tagName)==="INPUT"||(f==null?void 0:f.tagName)==="TEXTAREA"||f!=null&&f.isContentEditable)return;let h=eo.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let y=Number(c.key),N=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];N&&(c.preventDefault(),N.click())};document.addEventListener("keydown",zo);let Un=null,Wt=null,wn=null,no=null,qo=()=>{};function Ro(){no==null||no(),no=null}let jo=()=>{var V;if(!Un||!Wt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),h=((V=e.ownerDocument.defaultView)!=null?V:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||h){Wt.style.removeProperty("position"),Wt.style.removeProperty("left"),Wt.style.removeProperty("top"),Wt.style.removeProperty("bottom"),Wt.style.removeProperty("width"),Wt.style.removeProperty("z-index");return}let y=Un.firstElementChild;if(!y||y===Wt)return;let P=10;Wt.style.position="absolute",Wt.style.top="0",Wt.style.bottom="0",Wt.style.width=`${P}px`,Wt.style.zIndex="5";let N=y.offsetWidth-P/2;Wt.style.left=`${Math.max(0,N)}px`},Co=()=>{},zn=()=>{var h,y,P,N,V;if(!yt||!co(o))return;Ei(e,o),Mi(e,o),Co();let c=(N=(P=(y=(h=o.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:P.narrowHostMaxWidth)!=null?N:520,f=le.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",f>0&&f<=c),yt.update(Vn),xn?(yt.setMobileOpen(!1),yt.element.classList.add("persona-hidden"),(V=yt.backdrop)==null||V.classList.add("persona-hidden")):Vn.artifacts.length>0&&(yt.element.classList.remove("persona-hidden"),yt.setMobileOpen(!0)),qo()};if(co(o)){le.style.position="relative";let c=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),f=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(ce),yt=wm(o,{onSelect:h=>{var y;return(y=It.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{xn=!0,zn()}}),yt.element.classList.add("persona-hidden"),Un=f,f.appendChild(c),f.appendChild(yt.element),yt.backdrop&&le.appendChild(yt.backdrop),le.appendChild(f),qo=()=>{var y,P,N,V;if(!Un||!yt)return;if(!(((N=(P=(y=o.features)==null?void 0:y.artifacts)==null?void 0:P.layout)==null?void 0:N.resizable)===!0)){wn==null||wn(),wn=null,Ro(),Wt&&(Wt.remove(),Wt=null),yt.element.style.removeProperty("width"),yt.element.style.removeProperty("maxWidth");return}if(!Wt){let z=b("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");z.setAttribute("role","separator"),z.setAttribute("aria-orientation","vertical"),z.setAttribute("aria-label","Resize artifacts panel"),z.tabIndex=0;let O=e.ownerDocument,Ae=(V=O.defaultView)!=null?V:window,ue=Z=>{var at,it;if(!yt||Z.button!==0||e.classList.contains("persona-artifact-narrow-host")||Ae.innerWidth<=640)return;Z.preventDefault(),Ro();let he=Z.clientX,Ee=yt.element.getBoundingClientRect().width,Ne=(it=(at=o.features)==null?void 0:at.artifacts)==null?void 0:it.layout,tt=Pe=>{let Re=Un.getBoundingClientRect().width,je=e.classList.contains("persona-artifact-appearance-seamless"),R=je?0:Tm(Un,Ae),Me=je?0:z.getBoundingClientRect().width||6,Be=Ee-(Pe.clientX-he),Ge=km(Be,Re,R,Me,Ne==null?void 0:Ne.resizableMinWidth,Ne==null?void 0:Ne.resizableMaxWidth);yt.element.style.width=`${Ge}px`,yt.element.style.maxWidth="none",jo()},Xe=()=>{O.removeEventListener("pointermove",tt),O.removeEventListener("pointerup",Xe),O.removeEventListener("pointercancel",Xe),no=null;try{z.releasePointerCapture(Z.pointerId)}catch{}};no=Xe,O.addEventListener("pointermove",tt),O.addEventListener("pointerup",Xe),O.addEventListener("pointercancel",Xe);try{z.setPointerCapture(Z.pointerId)}catch{}};z.addEventListener("pointerdown",ue),Wt=z,Un.insertBefore(z,yt.element),wn=()=>{z.removeEventListener("pointerdown",ue)}}if(Wt){let z=Vn.artifacts.length>0&&!xn;Wt.classList.toggle("persona-hidden",!z),jo()}},Co=()=>{var Ae,ue,Z,he,Ee,Ne,tt,Xe,at,it,Pe,Re,je,R;if(!I||!yt||((ue=(Ae=o.launcher)==null?void 0:Ae.sidebarMode)!=null?ue:!1)||pn(o)&&Mo(o).reveal==="emerge")return;let y=(Z=e.ownerDocument.defaultView)!=null?Z:window,P=(Ee=(he=o.launcher)==null?void 0:he.mobileFullscreen)!=null?Ee:!0,N=(tt=(Ne=o.launcher)==null?void 0:Ne.mobileBreakpoint)!=null?tt:640;if(P&&y.innerWidth<=N||!Am(o,I))return;let V=(it=(at=(Xe=o.launcher)==null?void 0:Xe.width)!=null?at:o.launcherWidth)!=null?it:io,z=(R=(je=(Re=(Pe=o.features)==null?void 0:Pe.artifacts)==null?void 0:Re.layout)==null?void 0:je.expandedPanelWidth)!=null?R:"min(720px, calc(100vw - 24px))";Vn.artifacts.length>0&&!xn?(le.style.width=z,le.style.maxWidth=z):(le.style.width=V,le.style.maxWidth=V)},typeof ResizeObserver!="undefined"&&(_n=new ResizeObserver(()=>{zn()}),_n.observe(le))}else le.appendChild(ce),k()&&Ue&&(He.peekBanner&&Ue.appendChild(He.peekBanner),Ue.appendChild($e));e.appendChild(ye),Ue&&e.appendChild(Ue);let po=()=>{var Ge,Ce,Lt,st,Xt,cn,Pt,An,dn,Je,lt,Tn,mn,mr,fr,gr,Nr,_r,qt,hr,nr,ht,Pn,Oo,kn,Wn,Ht,Ut;if(k()){le.style.width="100%",le.style.maxWidth="100%";let Dt=(Ce=(Ge=o.launcher)==null?void 0:Ge.composerBar)!=null?Ce:{},jt=ye.dataset.state==="expanded",Bn=(Lt=Dt.expandedSize)!=null?Lt:"anchored";if(!(jt&&Bn!=="fullscreen")){ce.style.background="",ce.style.border="",ce.style.borderRadius="",ce.style.overflow="",ce.style.boxShadow="";return}let en=(Xt=(st=o.theme)==null?void 0:st.components)==null?void 0:Xt.panel,To=Ma(o),No=(br,ka)=>{var Ss;return br==null||br===""?ka:(Ss=Vr(To,br))!=null?Ss:br},Sa="1px solid var(--persona-border)",Aa="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Ta="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ce.style.background="var(--persona-surface, #ffffff)",ce.style.border=No(en==null?void 0:en.border,Sa),ce.style.borderRadius=No(en==null?void 0:en.borderRadius,Ta),ce.style.boxShadow=No(en==null?void 0:en.shadow,Aa),ce.style.overflow="hidden";return}let c=pn(o),f=(Pt=(cn=o.launcher)==null?void 0:cn.sidebarMode)!=null?Pt:!1,h=c||f||((dn=(An=o.launcher)==null?void 0:An.fullHeight)!=null?dn:!1),y=((Je=o.launcher)==null?void 0:Je.enabled)===!1,P=(Tn=(lt=o.theme)==null?void 0:lt.components)==null?void 0:Tn.panel,N=Ma(o),V=(Dt,jt)=>{var Bn;return Dt==null||Dt===""?jt:(Bn=Vr(N,Dt))!=null?Bn:Dt},z=(mn=e.ownerDocument.defaultView)!=null?mn:window,O=(fr=(mr=o.launcher)==null?void 0:mr.mobileFullscreen)!=null?fr:!0,Ae=(Nr=(gr=o.launcher)==null?void 0:gr.mobileBreakpoint)!=null?Nr:640,ue=z.innerWidth<=Ae,Z=O&&ue&&I,he=(qt=(_r=o.launcher)==null?void 0:_r.position)!=null?qt:"bottom-left",Ee=he==="bottom-left"||he==="top-left",Ne=(nr=(hr=o.launcher)==null?void 0:hr.zIndex)!=null?nr:hn,tt=f||Z?"none":"1px solid var(--persona-border)",Xe=Z?"none":f?Ee?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!Z&&(Xe="none",tt="none");let at=f||Z?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",it=V(P==null?void 0:P.border,tt),Pe=V(P==null?void 0:P.shadow,Xe),Re=V(P==null?void 0:P.borderRadius,at),je=G.scrollTop;e.style.cssText="",ye.style.cssText="",le.style.cssText="",ce.style.cssText="",G.style.cssText="",$e.style.cssText="";let R=()=>{var jt;if(je<=0)return;((jt=G.ownerDocument.defaultView)!=null?jt:window).requestAnimationFrame(()=>{if(G.scrollTop===je)return;let Bn=G.scrollHeight-G.clientHeight;Bn<=0||(G.scrollTop=Math.min(je,Bn))})};if(Z){ye.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),ye.style.cssText=`
|
|
31
31
|
position: fixed !important;
|
|
32
32
|
inset: 0 !important;
|
|
33
33
|
width: 100% !important;
|
|
@@ -37,7 +37,7 @@ _Details: ${n.message}_`:o}var ei=class e{constructor(t={},n){this.config=t;this
|
|
|
37
37
|
padding: 0 !important;
|
|
38
38
|
display: flex !important;
|
|
39
39
|
flex-direction: column !important;
|
|
40
|
-
z-index: ${
|
|
40
|
+
z-index: ${Ne} !important;
|
|
41
41
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
42
42
|
`,le.style.cssText=`
|
|
43
43
|
position: relative !important;
|
|
@@ -63,7 +63,7 @@ _Details: ${n.message}_`:o}var ei=class e{constructor(t={},n){this.config=t;this
|
|
|
63
63
|
overflow: hidden !important;
|
|
64
64
|
border-radius: 0 !important;
|
|
65
65
|
border: none !important;
|
|
66
|
-
`,
|
|
66
|
+
`,G.style.flex="1 1 0%",G.style.minHeight="0",G.style.overflowY="auto",$e.style.flexShrink="0",x=!0,R();return}let Me=(Pn=(ht=o==null?void 0:o.launcher)==null?void 0:ht.width)!=null?Pn:o==null?void 0:o.launcherWidth,Be=Me!=null?Me:io;if(!f&&!c)y&&h?(le.style.width="100%",le.style.maxWidth="100%"):(le.style.width=Be,le.style.maxWidth=Be);else if(c)if(Mo(o).reveal==="emerge"){let jt=Mo(o).width;le.style.width=jt,le.style.maxWidth=jt}else le.style.width="100%",le.style.maxWidth="100%";if(Co(),le.style.boxShadow=Pe,le.style.borderRadius=Re,ce.style.border=it,ce.style.borderRadius=Re,c&&!Z&&(P==null?void 0:P.border)===void 0&&(ce.style.border="none",Mo(o).side==="right"?ce.style.borderLeft="1px solid var(--persona-border)":ce.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",y&&(e.style.width="100%"),ye.style.display="flex",ye.style.flexDirection="column",ye.style.flex="1 1 0%",ye.style.minHeight="0",ye.style.maxHeight="100%",ye.style.height="100%",y&&(ye.style.overflow="hidden"),le.style.display="flex",le.style.flexDirection="column",le.style.flex="1 1 0%",le.style.minHeight="0",le.style.maxHeight="100%",le.style.height="100%",le.style.overflow="hidden",ce.style.display="flex",ce.style.flexDirection="column",ce.style.flex="1 1 0%",ce.style.minHeight="0",ce.style.maxHeight="100%",ce.style.overflow="hidden",G.style.flex="1 1 0%",G.style.minHeight="0",G.style.overflowY="auto",$e.style.flexShrink="0"),ye.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!f&&!y&&!c&&((Oo=xo[he])!=null?Oo:xo["bottom-right"]).split(" ").forEach(jt=>ye.classList.add(jt)),f){let Dt=(Wn=(kn=o.launcher)==null?void 0:kn.sidebarWidth)!=null?Wn:"420px";ye.style.cssText=`
|
|
67
67
|
position: fixed !important;
|
|
68
68
|
top: 0 !important;
|
|
69
69
|
bottom: 0 !important;
|
|
@@ -74,7 +74,7 @@ _Details: ${n.message}_`:o}var ei=class e{constructor(t={},n){this.config=t;this
|
|
|
74
74
|
padding: 0 !important;
|
|
75
75
|
display: flex !important;
|
|
76
76
|
flex-direction: column !important;
|
|
77
|
-
z-index: ${
|
|
77
|
+
z-index: ${Ne} !important;
|
|
78
78
|
${Ee?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
79
79
|
`,le.style.cssText=`
|
|
80
80
|
position: relative !important;
|
|
@@ -100,11 +100,11 @@ _Details: ${n.message}_`:o}var ei=class e{constructor(t={},n){this.config=t;this
|
|
|
100
100
|
overflow: hidden !important;
|
|
101
101
|
border-radius: ${Re} !important;
|
|
102
102
|
border: ${it} !important;
|
|
103
|
-
|
|
103
|
+
`,$e.style.cssText=`
|
|
104
104
|
flex-shrink: 0 !important;
|
|
105
105
|
border-top: none !important;
|
|
106
106
|
padding: 8px 16px 12px 16px !important;
|
|
107
|
-
`}if(!y&&!c){let Dt="max-height: -moz-available !important; max-height: stretch !important;",jt=g?"":"padding-top: 1.25em !important;",Bn=g?"":`z-index: ${(Ut=(Ht=o.launcher)==null?void 0:Ht.zIndex)!=null?Ut:hn} !important;`;ye.style.cssText+=Dt+jt+Bn}L()};po(),$r(e,o),Ti(e,o),ki(e,o);let gt=[];gt.push(()=>{document.removeEventListener("keydown",zo)});let Kt=null,Gt=null;gt.push(()=>{Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null}),_n&>.push(()=>{_n==null||_n.disconnect(),_n=null}),gt.push(()=>{wn==null||wn(),wn=null,Ro(),Wt&&(Wt.remove(),Wt=null),yt==null||yt.element.style.removeProperty("width"),yt==null||yt.element.style.removeProperty("maxWidth")}),ie&>.push(()=>{we!==null&&(cancelAnimationFrame(we),we=null),Se==null||Se.destroy(),Se=null,Y==null||Y.destroy(),Y=null,J=null});let qn=null,Ko=()=>{qn&&(qn(),qn=null),o.colorScheme==="auto"&&(qn=nu(()=>{$r(e,o)}))};Ko(),gt.push(()=>{qn&&(qn(),qn=null)});let oo=(_c=o.features)==null?void 0:_c.streamAnimation;if(oo!=null&&oo.type&&oo.type!=="none"){let c=_s(oo.type,oo.plugins);c&&(ul(c,e),gt.push(()=>zu(e)))}let uo=um(Et),jn=null,T,Kn=!1,mo=Ou(),Po=new Map,So=new Map,ss=0,go=ri(),fo=0,ho=null,Wo=!1,lr=!1,ra=4,as=24,sa=80,Pr=new Map,mt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},is=($c=(Vc=o.voiceRecognition)==null?void 0:Vc.autoResume)!=null?$c:!1,ro=c=>{s.emit("voice:state",{active:mt.active,source:c,timestamp:Date.now()})},Rn=()=>{u(c=>({...c,voiceState:{active:mt.active,timestamp:Date.now(),manuallyDeactivated:mt.manuallyDeactivated}}))},aa=()=>{var y,P;if(((y=o.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=Ol(d.voiceState),g=!!c.active,h=Number((P=c.timestamp)!=null?P:0);mt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-h<ex&&setTimeout(()=>{var N,V;mt.active||(mt.manuallyDeactivated=!1,((V=(N=o.voiceRecognition)==null?void 0:N.provider)==null?void 0:V.type)==="runtype"?T.toggleVoice().then(()=>{mt.active=T.isVoiceActive(),ro("restore"),T.isVoiceActive()&&U()}):ur("restore"))},1e3)},ia=()=>T?Hm(T.getMessages()).filter(c=>!c.__skipPersist):[];function Wr(c){if(!(i!=null&&i.save))return;let h={messages:c?Hm(c):T?ia():[],metadata:d,artifacts:Vn.artifacts,selectedArtifactId:Vn.selectedId};try{let y=i.save(h);y instanceof Promise&&y.catch(P=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",P)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let Bo=null,la=()=>ye.querySelector("#persona-scroll-container")||K,cr=()=>{Bo!==null&&(cancelAnimationFrame(Bo),Bo=null),Wo=!1},ls=()=>{ho!==null&&(cancelAnimationFrame(ho),ho=null),lr=!1,cr()},Ho=()=>{if(!yn()||de){Tt.parentNode&&Tt.remove(),Tt.style.display="none";return}Tt.parentNode!==ce&&ce.appendChild(Tt),bt();let c=Fs(K)>0;Tt.style.display=go.isFollowing()||!c?"none":""},cs=()=>{go.pause()&&(ls(),Ho())},Go=()=>{go.resume(),Ho()},Yo=(c=!1)=>{go.isFollowing()&&(!c&&!Kn||(ho!==null&&(cancelAnimationFrame(ho),ho=null),lr=!0,ho=requestAnimationFrame(()=>{ho=null,lr=!1,go.isFollowing()&&ca(la(),c?220:140)})))},ca=(c,g=500)=>{let h=c.scrollTop,y=Fs(c),P=y-h;if(Math.abs(P)<1){fo=c.scrollTop;return}if(Math.abs(P)>=sa){cr(),Wo=!0,c.scrollTop=y,fo=c.scrollTop,Wo=!1;return}cr();let N=performance.now();Wo=!0;let V=O=>1-Math.pow(1-O,3),z=O=>{if(!go.isFollowing()){cr();return}let Ae=Fs(c);Ae!==y&&(y=Ae,P=y-h);let ue=O-N,ee=Math.min(ue/g,1),he=V(ee),Ee=h+P*he;c.scrollTop=Ee,fo=c.scrollTop,ee<1?Bo=requestAnimationFrame(z):(c.scrollTop=y,fo=c.scrollTop,Bo=null,Wo=!1)};Bo=requestAnimationFrame(z)},da=c=>{let g=new Map;c.forEach(h=>{let y=Pr.get(h.id);g.set(h.id,{streaming:h.streaming,role:h.role}),!y&&h.role==="assistant"&&s.emit("assistant:message",h),h.role==="assistant"&&(y!=null&&y.streaming)&&h.streaming===!1&&s.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(y?h.approval.status!=="pending"&&s.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):s.emit("approval:requested",{approval:h.approval,message:h}))}),Pr.clear(),g.forEach((h,y)=>{Pr.set(y,h)})},dr=(c,g,h)=>{var Ye,at,it,Pe,Re,qe;let y=document.createElement("div"),N=(()=>{var Me;let L=r.find(We=>We.renderLoadingIndicator);if(L!=null&&L.renderLoadingIndicator)return L.renderLoadingIndicator;if((Me=o.loadingIndicator)!=null&&Me.render)return o.loadingIndicator.render})(),V=(L,Me)=>Me==null?!1:typeof Me=="string"?(L.textContent=Me,!0):(L.appendChild(Me),!0),z=new Set,O=new Set,Ae=r.some(L=>L.renderAskUserQuestion),ue=[],ee=[],he=o.enableComponentStreaming!==!1;if(g.forEach(L=>{var An,dn,Je,lt,Tn,mn,mr,gr,fr,Nr,_r,qt,hr,nr;z.add(L.id);let Me=Ae&&Tr(L),We=!Me&&L.role==="assistant"&&!L.variant&&he&&Rm(L);if(!We&&So.has(L.id)){let ht=c.querySelector(`#wrapper-${L.id}`);ht==null||ht.removeAttribute("data-preserve-runtime"),So.delete(L.id)}let Ke=Tr(L)?`:${(An=L.agentMetadata)!=null&&An.askUserQuestionAnswered?"a":"u"}:${(dn=L.agentMetadata)!=null&&dn.askUserQuestionAnswers?Object.keys(L.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ce=Fu(L,ss)+Ke,Lt=Me||We?null:Nu(mo,L.id,Ce);if(Lt){y.appendChild(Lt.cloneNode(!0)),Tr(L)&&((Je=L.toolCall)!=null&&Je.id)&&((lt=L.agentMetadata)==null?void 0:lt.awaitingLocalTool)===!0&&!((Tn=L.agentMetadata)!=null&&Tn.askUserQuestionAnswered)&&(O.add(L.toolCall.id),Ci(L,o,Be.composerOverlay));return}let st=null,Xt=r.find(ht=>!!(L.variant==="reasoning"&&ht.renderReasoning||L.variant==="tool"&&ht.renderToolCall||L.variant==="approval"&&ht.renderApproval||!L.variant&&ht.renderMessage)),cn=(mn=o.layout)==null?void 0:mn.messages;if(Tr(L)&&((mr=L.agentMetadata)==null?void 0:mr.askUserQuestionAnswered)===!0){Po.delete(L.id);let ht=c.querySelector(`#wrapper-${L.id}`);ht==null||ht.removeAttribute("data-preserve-runtime");return}if(Tr(L)&&((fr=(gr=o.features)==null?void 0:gr.askUserQuestion)==null?void 0:fr.enabled)!==!1){let ht=r.find(Pn=>typeof Pn.renderAskUserQuestion=="function");if(ht&&It.current){let Pn=Po.get(L.id),Oo=Pn!==Ce,kn=null;if(Oo){let{payload:Ut,complete:Dt}=Xr(L),jt=L.id,Bn=()=>{var Yn;return(Yn=It.current)==null?void 0:Yn.getMessages().find(en=>en.id===jt)};kn=ht.renderAskUserQuestion({message:L,payload:Ut,complete:Dt,resolve:Yn=>{var To;let en=Bn();en&&((To=It.current)==null||To.resolveAskUserQuestion(en,Yn))},dismiss:()=>{var en,To,No;let Yn=Bn();(en=Yn==null?void 0:Yn.agentMetadata)!=null&&en.awaitingLocalTool&&((To=It.current)==null||To.markAskUserQuestionResolved(Yn),(No=It.current)==null||No.resolveAskUserQuestion(Yn,"(dismissed)"))},config:o})}let Wn=Pn!=null;if(Oo&&kn===null&&!Wn){((Nr=L.agentMetadata)==null?void 0:Nr.awaitingLocalTool)===!0&&!((_r=L.agentMetadata)!=null&&_r.askUserQuestionAnswered)&&(O.add(L.toolCall.id),Ci(L,o,Be.composerOverlay));return}let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${L.id}`,Ht.setAttribute("data-wrapper-id",L.id),Ht.setAttribute("data-ask-plugin-stub","true"),Ht.setAttribute("data-preserve-runtime","true"),y.appendChild(Ht),ue.push({messageId:L.id,fingerprint:Ce,bubble:kn});return}else{((qt=L.agentMetadata)==null?void 0:qt.awaitingLocalTool)===!0&&!((hr=L.agentMetadata)!=null&&hr.askUserQuestionAnswered)&&(O.add(L.toolCall.id),Ci(L,o,Be.composerOverlay));return}}else if(Xt)if(L.variant==="reasoning"&&L.reasoning&&Xt.renderReasoning){if(!se)return;st=Xt.renderReasoning({message:L,defaultRenderer:()=>vl(L,o),config:o})}else if(L.variant==="tool"&&L.toolCall&&Xt.renderToolCall){if(!ge)return;st=Xt.renderToolCall({message:L,defaultRenderer:()=>xl(L,o),config:o})}else if(L.variant==="approval"&&L.approval&&Xt.renderApproval){if(o.approval===!1)return;st=Xt.renderApproval({message:L,defaultRenderer:()=>Ml(L,o),config:o})}else Xt.renderMessage&&(st=Xt.renderMessage({message:L,defaultRenderer:()=>{let ht=yl(L,h,cn,o.messageActions,te,{loadingIndicatorRenderer:N,widgetConfig:o});return L.role!=="user"&&Pl(ht,L,o,T),ht},config:o}));if(!st&&We){let ht=Pm(L);if(ht){let Pn=So.get(L.id),Oo=Pn!==Ce,kn=o.wrapComponentDirectiveInBubble!==!1,Wn=null;if(Oo){let Ht=Lm(ht,{config:o,message:L,transform:h});if(Ht)if(kn){let Ut=document.createElement("div");if(Ut.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ut.id=`bubble-${L.id}`,Ut.setAttribute("data-message-id",L.id),L.content&&L.content.trim()){let Dt=document.createElement("div");Dt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Dt.innerHTML=h({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),Ut.appendChild(Dt)}Ut.appendChild(Ht),Wn=Ut}else{let Ut=document.createElement("div");if(Ut.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ut.id=`bubble-${L.id}`,Ut.setAttribute("data-message-id",L.id),Ut.setAttribute("data-persona-component-directive","true"),L.content&&L.content.trim()){let Dt=document.createElement("div");Dt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Dt.innerHTML=h({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),Ut.appendChild(Dt)}Ut.appendChild(Ht),Wn=Ut}}if(Wn||Pn!=null){let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${L.id}`,Ht.setAttribute("data-wrapper-id",L.id),Ht.setAttribute("data-component-directive-stub","true"),Ht.setAttribute("data-preserve-runtime","true"),kn||Ht.classList.add("persona-w-full"),y.appendChild(Ht),ee.push({messageId:L.id,fingerprint:Ce,bubble:Wn});return}}}if(!st)if(L.variant==="reasoning"&&L.reasoning){if(!se)return;st=vl(L,o)}else if(L.variant==="tool"&&L.toolCall){if(!ge)return;st=xl(L,o)}else if(L.variant==="approval"&&L.approval){if(o.approval===!1)return;st=Ml(L,o)}else{let ht=(nr=o.layout)==null?void 0:nr.messages;ht!=null&&ht.renderUserMessage&&L.role==="user"?st=ht.renderUserMessage({message:L,config:o,streaming:!!L.streaming}):ht!=null&&ht.renderAssistantMessage&&L.role==="assistant"?st=ht.renderAssistantMessage({message:L,config:o,streaming:!!L.streaming}):st=yl(L,h,ht,o.messageActions,te,{loadingIndicatorRenderer:N,widgetConfig:o}),L.role!=="user"&&st&&Pl(st,L,o,T)}let Pt=document.createElement("div");Pt.className="persona-flex",Pt.id=`wrapper-${L.id}`,Pt.setAttribute("data-wrapper-id",L.id),L.role==="user"&&Pt.classList.add("persona-justify-end"),(st==null?void 0:st.getAttribute("data-persona-component-directive"))==="true"&&Pt.classList.add("persona-w-full"),Pt.appendChild(st),_u(mo,L.id,Ce,Pt),y.appendChild(Pt)}),Be.composerOverlay&&Be.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Me=>{let We=Me.getAttribute("data-persona-ask-sheet-for");We&&!O.has(We)&&Jr(Be.composerOverlay,We)}),(at=(Ye=o.features)==null?void 0:Ye.toolCallDisplay)!=null&&at.grouped){let L=[],Me=[];g.forEach(We=>{if(We.variant==="tool"&&We.toolCall&&ge){Me.push(We);return}Me.length>1&&L.push(Me),Me=[]}),Me.length>1&&L.push(Me),L.forEach((We,Ke)=>{var dn,Je;let Ce=We.map(lt=>Array.from(y.children).find(Tn=>Tn instanceof HTMLElement&&Tn.getAttribute("data-wrapper-id")===lt.id)).filter(lt=>!!lt);if(Ce.length<2)return;let Lt=document.createElement("div");Lt.className="persona-flex",Lt.id=`wrapper-tool-group-${Ke}-${We[0].id}`,Lt.setAttribute("data-wrapper-id",`tool-group-${Ke}-${We[0].id}`);let st=document.createElement("div");st.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",st.setAttribute("data-persona-tool-group","true");let Xt=document.createElement("div");Xt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let cn=`Called ${We.length} tools`,Pt=(Je=(dn=o.toolCall)==null?void 0:dn.renderGroupedSummary)==null?void 0:Je.call(dn,{messages:We,toolCalls:We.map(lt=>lt.toolCall).filter(lt=>!!lt),defaultSummary:cn,config:o});V(Xt,Pt)||(Xt.textContent=cn);let An=document.createElement("div");An.className="persona-tool-group-stack persona-flex persona-flex-col",st.append(Xt,An),Lt.appendChild(st),Ce[0].before(Lt),Ce.forEach((lt,Tn)=>{let mn=document.createElement("div");mn.className="persona-tool-group-item persona-relative",mn.setAttribute("data-persona-tool-group-item","true"),Tn<Ce.length-1&&mn.setAttribute("data-persona-tool-group-connector","true"),mn.appendChild(lt),An.appendChild(mn)})})}Vu(mo,z);let Ee=g.some(L=>L.role==="assistant"&&L.streaming),Oe=g[g.length-1],tt=(Oe==null?void 0:Oe.role)==="assistant"&&!Oe.streaming&&Oe.variant!=="approval";if(Kn&&g.some(L=>L.role==="user")&&!Ee&&!tt){let L={config:o,streaming:!0,location:"standalone",defaultRenderer:Ks},Me=r.find(Ke=>Ke.renderLoadingIndicator),We=null;if(Me!=null&&Me.renderLoadingIndicator&&(We=Me.renderLoadingIndicator(L)),We===null&&((it=o.loadingIndicator)!=null&&it.render)&&(We=o.loadingIndicator.render(L)),We===null&&(We=Ks()),We){let Ke=document.createElement("div"),Ce=((Pe=o.loadingIndicator)==null?void 0:Pe.showBubble)!==!1;Ke.className=Ce?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ke.setAttribute("data-typing-indicator","true"),Ke.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ke.appendChild(We);let Lt=document.createElement("div");Lt.className="persona-flex",Lt.id="wrapper-typing-indicator",Lt.setAttribute("data-wrapper-id","typing-indicator"),Lt.appendChild(Ke),y.appendChild(Lt)}}if(!Kn&&g.length>0){let L=g[g.length-1],Me={config:o,lastMessage:L,messageCount:g.length},We=r.find(Ce=>Ce.renderIdleIndicator),Ke=null;if(We!=null&&We.renderIdleIndicator&&(Ke=We.renderIdleIndicator(Me)),Ke===null&&((Re=o.loadingIndicator)!=null&&Re.renderIdle)&&(Ke=o.loadingIndicator.renderIdle(Me)),Ke){let Ce=document.createElement("div"),Lt=((qe=o.loadingIndicator)==null?void 0:qe.showBubble)!==!1;Ce.className=Lt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ce.setAttribute("data-idle-indicator","true"),Ce.appendChild(Ke);let st=document.createElement("div");st.className="persona-flex",st.id="wrapper-idle-indicator",st.setAttribute("data-wrapper-id","idle-indicator"),st.appendChild(Ce),y.appendChild(st)}}if(ni(c,y),ue.length>0)for(let{messageId:L,fingerprint:Me,bubble:We}of ue){let Ke=c.querySelector(`#wrapper-${L}`);Ke&&We!==null&&(Ke.replaceChildren(We),Ke.setAttribute("data-bubble-fp",Me),Po.set(L,Me))}if(Po.size>0)for(let L of Po.keys())z.has(L)||Po.delete(L);if(ee.length>0)for(let{messageId:L,fingerprint:Me,bubble:We}of ee){let Ke=c.querySelector(`#wrapper-${L}`);Ke&&We!==null&&(Ke.replaceChildren(We),Ke.setAttribute("data-bubble-fp",Me),So.set(L,Me))}if(So.size>0)for(let L of So.keys())z.has(L)||So.delete(L)},Xo=null,pa=()=>{var h;if(Xo)return;let c=y=>{let P=y.composedPath();P.includes(ye)||$e&&P.includes($e)||Bt(!1,"user")};Xo=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},ds=()=>{var g;if(!Xo)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("pointerdown",Xo,!0),Xo=null};gt.push(()=>ds());let Qo=null,ua=()=>{var h;if(Qo)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Bt(!1,"user"))};Qo=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},ps=()=>{var g;if(!Qo)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("keydown",Qo,!0),Qo=null};gt.push(()=>ps());let Jo=!1,us=new Set,ma=()=>{var g,h,y,P;let c=(y=(h=(g=o.launcher)==null?void 0:g.composerBar)==null?void 0:h.peek)==null?void 0:y.streamAnimation;return c||((P=o.features)==null?void 0:P.streamAnimation)},Do=()=>{var at,it,Pe,Re;if(!k())return;let c=Be.peekBanner,g=Be.peekTextNode;if(!c||!g)return;if(E){c.classList.remove("persona-pill-peek--visible");return}let h=(at=T==null?void 0:T.getMessages())!=null?at:[],y;for(let qe=h.length-1;qe>=0;qe--){let L=h[qe];if(L.role==="assistant"&&L.content){y=L;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let P=y.content,N=!!y.streaming,V=ma(),z=ii(V),O=z.type!=="none"?_s(z.type,V==null?void 0:V.plugins):null,Ae=((it=O==null?void 0:O.isAnimating)==null?void 0:it.call(O,y))===!0,ue=O!==null&&(N||Ae);ue&&O&&!us.has(O.name)&&(ul(O,e),us.add(O.name));let ee=ue&&(O!=null&&O.containerClass)?O.containerClass:null,he=(Pe=g.dataset.personaPeekStreamClass)!=null?Pe:null;he&&he!==ee&&(g.classList.remove(he),delete g.dataset.personaPeekStreamClass),ee&&he!==ee&&(g.classList.add(ee),g.dataset.personaPeekStreamClass=ee),ue?(g.style.setProperty("--persona-stream-step",`${z.speed}ms`),g.style.setProperty("--persona-stream-duration",`${z.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ee=ue?li(P,z.buffer,O,y,N):P;if(ue&&z.placeholder==="skeleton"&&N&&(!Ee||!Ee.trim())){let qe=document.createElement("div"),L=$s();L.classList.add("persona-pill-peek__skeleton"),qe.appendChild(L),ni(g,qe)}else{let qe=Math.max(0,Ee.length-100),L=Ee.length>100?Ee.slice(-100):Ee,Me=Ls(L);if(!ue||!O){let We=Ee.length>100?`\u2026${L}`:L;g.textContent!==We&&(g.textContent=We)}else{let We=Me;(O.wrap==="char"||O.wrap==="word")&&(We=Vs(Me,O.wrap,`peek-${y.id}`,{skipTags:O.skipTags,startIndex:qe}));let Ke=document.createElement("div");if(Ke.innerHTML=We,O.useCaret&&L.length>0){let Ce=ci(),Lt=Ke.querySelectorAll(".persona-stream-char, .persona-stream-word"),st=Lt[Lt.length-1];st!=null&&st.parentNode?st.parentNode.insertBefore(Ce,st.nextSibling):Ke.appendChild(Ce)}ni(g,Ke),(Re=O.onAfterRender)==null||Re.call(O,{container:g,bubble:c,messageId:y.id,message:y,speed:z.speed,duration:z.duration})}}let Ye=Kn||Jo;c.classList.toggle("persona-pill-peek--visible",Ye)};if(k()){let c=Be.peekBanner;if(c){let y=P=>{P.preventDefault(),P.stopPropagation(),Bt(!0,"user")};c.addEventListener("pointerdown",y),gt.push(()=>{c.removeEventListener("pointerdown",y)})}let g=()=>{Jo||(Jo=!0,Do())},h=()=>{Jo&&(Jo=!1,Do())};le.addEventListener("pointerenter",g),le.addEventListener("pointerleave",h),gt.push(()=>{le.removeEventListener("pointerenter",g),le.removeEventListener("pointerleave",h)}),$e&&($e.addEventListener("pointerenter",g),$e.addEventListener("pointerleave",h),gt.push(()=>{$e.removeEventListener("pointerenter",g),$e.removeEventListener("pointerleave",h)}))}let ga=c=>{var he,Ee,Oe,tt,Ye,at,it,Pe;let g=(Ee=(he=o.launcher)==null?void 0:he.composerBar)!=null?Ee:{},h=(Oe=g.expandedSize)!=null?Oe:"anchored",y=(tt=g.bottomOffset)!=null?tt:"16px",P=g.collapsedMaxWidth,N=(Ye=g.expandedMaxWidth)!=null?Ye:"880px",V=(at=g.expandedTopOffset)!=null?at:"5vh",z=(it=g.modalMaxWidth)!=null?it:"880px",O=(Pe=g.modalMaxHeight)!=null?Pe:"min(90vh, 800px)",Ae="calc(100vw - 32px)",ue="var(--persona-pill-area-height, 80px)",ee=ye.style;if(ee.left="",ee.right="",ee.top="",ee.bottom="",ee.transform="",ee.width="",ee.maxWidth="",ee.height="",ee.maxHeight="",$e){let Re=$e.style;Re.bottom=y,Re.width=P!=null?P:""}if(c&&h!=="fullscreen"){if(h==="modal"){ee.top="50%",ee.left="50%",ee.transform="translate(-50%, -50%)",ee.bottom="auto",ee.right="auto",ee.width=z,ee.maxWidth=Ae,ee.maxHeight=O,ee.height=O;return}ee.left="50%",ee.transform="translateX(-50%)",ee.bottom=`calc(${y} + ${ue})`,ee.top=V,ee.width=N,ee.maxWidth=Ae}},Zo=()=>{var O,Ae,ue,ee,he,Ee,Oe,tt;if(!S())return;if(k()){let at=(ue=((Ae=(O=o.launcher)==null?void 0:O.composerBar)!=null?Ae:{}).expandedSize)!=null?ue:"anchored",it=E?"expanded":"collapsed";ye.dataset.state=it,ye.dataset.expandedSize=at,$e&&($e.dataset.state=it,$e.dataset.expandedSize=at),ye.style.removeProperty("display"),ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ga(E),ce.style.display=E?"flex":"none",po(),E?(pa(),ua()):(ds(),ps()),Do();return}let c=pn(o),g=(ee=e.ownerDocument.defaultView)!=null?ee:window,h=(Ee=(he=o.launcher)==null?void 0:he.mobileBreakpoint)!=null?Ee:640,y=(tt=(Oe=o.launcher)==null?void 0:Oe.mobileFullscreen)!=null?tt:!0,P=g.innerWidth<=h,N=y&&P&&I,V=Mo(o).reveal;E?(ye.style.removeProperty("display"),ye.style.display=c?"flex":"",ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-95","persona-opacity-0"),le.classList.add("persona-scale-100","persona-opacity-100"),Ie?Ie.element.style.display="none":Ge&&(Ge.style.display="none")):(c?c&&(V==="overlay"||V==="push")&&!N?(ye.style.removeProperty("display"),ye.style.display="flex",ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ye.style.setProperty("display","none","important"),ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ye.style.display="",ye.classList.add("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100"),le.classList.add("persona-scale-95","persona-opacity-0")),Ie?Ie.element.style.display=c?"none":"":Ge&&(Ge.style.display=c?"none":""))},Bt=(c,g="user")=>{var N,V;if(!S()||E===c)return;let h=E;E=c,Zo();let y=(()=>{var Oe,tt,Ye,at,it,Pe,Re,qe,L,Me;let z=(tt=(Oe=o.launcher)==null?void 0:Oe.sidebarMode)!=null?tt:!1,O=(Ye=e.ownerDocument.defaultView)!=null?Ye:window,Ae=(it=(at=o.launcher)==null?void 0:at.mobileFullscreen)!=null?it:!0,ue=(Re=(Pe=o.launcher)==null?void 0:Pe.mobileBreakpoint)!=null?Re:640,ee=O.innerWidth<=ue,he=pn(o)&&Ae&&ee,Ee=k()&&((Me=(L=(qe=o.launcher)==null?void 0:qe.composerBar)==null?void 0:L.expandedSize)!=null?Me:"fullscreen")==="fullscreen";return z||Ae&&ee&&I||he||Ee})();if(E&&y){if(!Kt){let z=e.getRootNode(),O=z instanceof ShadowRoot?z.host:e.closest(".persona-host");O&&(Kt=ml(O,(V=(N=o.launcher)==null?void 0:N.zIndex)!=null?V:hn))}Gt||(Gt=gl(e.ownerDocument))}else E||(Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null);E&&(Rt(),Yo(!0));let P={open:E,source:g,timestamp:Date.now()};E&&!h?s.emit("widget:opened",P):!E&&h&&s.emit("widget:closed",P),s.emit("widget:state",{open:E,launcherEnabled:I,voiceActive:mt.active,streaming:T.isStreaming()})},Br=c=>{Vt(c?"stop":"send"),q&&(q.disabled=c),uo.buttons.forEach(g=>{g.disabled=c}),Ve.dataset.personaComposerStreaming=c?"true":"false",Ve.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=c)})},Hr=()=>{mt.active||pe&&pe.focus()};s.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Hr(),200)});let ms=()=>{var h,y,P,N,V,z,O,Ae,ue,ee,he;Dn.textContent=(y=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",Jn.textContent=(N=(P=o.copy)==null?void 0:P.welcomeSubtitle)!=null?N:"Ask anything about your account or products.",pe.placeholder=(z=(V=o.copy)==null?void 0:V.inputPlaceholder)!=null?z:"How can I help...";let c=K.querySelector("[data-persona-intro-card]");if(c){let Ee=((O=o.copy)==null?void 0:O.showWelcomeCard)!==!1;c.style.display=Ee?"":"none",Ee?(K.classList.remove("persona-gap-3"),K.classList.add("persona-gap-6")):(K.classList.remove("persona-gap-6"),K.classList.add("persona-gap-3"))}!((ue=(Ae=o.sendButton)==null?void 0:Ae.useIcon)!=null&&ue)&&!(T!=null&&T.isStreaming())&&(ae.textContent=(he=(ee=o.copy)==null?void 0:ee.sendButtonLabel)!=null?he:"Send"),pe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',pe.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{u(g=>({...g,sessionId:c}))}});let Ao=null,fa=()=>{Ao==null&&(Ao=setInterval(()=>{let c=_e.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Ao),Ao=null;return}let g=Date.now();c.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=za(g-y))})},100))};if(T=new ei(o,{onMessagesChanged(c){dr(_e,c,me),fa(),T&&(c.some(P=>P.role==="user")?uo.render([],T,pe,c):uo.render(o.suggestionChips,T,pe,c,o.suggestionChipsConfig)),Yo(!Kn),da(c);let g=[...c].reverse().find(y=>y.role==="user"),h=mt.lastUserMessageId;g&&g.id!==h&&(mt.lastUserMessageId=g.id,s.emit("user:message",g)),mt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),Wr(c),Do()},onStatusChanged(c){var y;let g=(y=o.statusIndicator)!=null?y:{};nt(ln,(P=>{var N,V,z,O;return P==="idle"?(N=g.idleText)!=null?N:fn.idle:P==="connecting"?(V=g.connectingText)!=null?V:fn.connecting:P==="connected"?(z=g.connectedText)!=null?z:fn.connected:P==="error"?(O=g.errorText)!=null?O:fn.error:fn[P]})(c),g,c)},onStreamingChanged(c){Kn=c,Br(c),T&&dr(_e,T.getMessages(),me),c||Yo(!0),Do()},onVoiceStatusChanged(c){var g,h;if(((h=(g=o.voiceRecognition)==null?void 0:g.provider)==null?void 0:h.type)==="runtype")switch(c){case"listening":break;case"processing":G(),W();break;case"speaking":G(),Z();break;default:c==="idle"&&T.isBargeInActive()?(G(),U(),q==null||q.setAttribute("aria-label","End voice session")):(mt.active=!1,G(),ro("system"),Rn());break}},onArtifactsState(c){Vn=c,zn(),Wr()}}),It.current=T,((zc=(Uc=o.voiceRecognition)==null?void 0:Uc.provider)==null?void 0:zc.type)==="runtype")try{T.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}o.clientToken&&T.initClientSession().catch(c=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(Y||o.onSSEEvent)&&T.setSSEEventCallback((c,g)=>{var h;(h=o.onSSEEvent)==null||h.call(o,c,g),xe==null||xe.processEvent(c,g),Y==null||Y.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(g)})}),l&&l.then(c=>{var g,h,y;c&&(c.metadata&&(d=Ol(c.metadata),M.syncFromMetadata()),(g=c.messages)!=null&&g.length&&T.hydrateMessages(c.messages),(h=c.artifacts)!=null&&h.length&&T.hydrateArtifacts(c.artifacts,(y=c.selectedArtifactId)!=null?y:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let gs=()=>{var g,h,y;!k()||E||!((y=(h=(g=o.launcher)==null?void 0:g.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||Bt(!0,"auto")},fs=c=>{var P;if(c.preventDefault(),T.isStreaming()){T.cancel(),xe==null||xe.reset(),Se==null||Se.update();return}let g=pe.value.trim(),h=(P=et==null?void 0:et.hasAttachments())!=null?P:!1;if(!g&&!h)return;gs();let y;h&&(y=[],y.push(...et.getContentParts()),g&&y.push(ll(g))),pe.value="",pe.style.height="auto",pr(),T.sendMessage(g,{contentParts:y}),h&&et.clearAttachments()},ha=()=>{var c;return((c=o.features)==null?void 0:c.composerHistory)!==!1},Dr={...oi},Fr=!1,pr=()=>{Dr={...oi}},ba=()=>T.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),ya=c=>{if(!pe)return;Fr=!0,pe.value=c,pe.dispatchEvent(new Event("input",{bubbles:!0})),Fr=!1;let g=pe.value.length;pe.setSelectionRange(g,g)},hs=()=>{Fr||pr()},bs=c=>{if(pe){if(ha()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=pe.selectionStart===0&&pe.selectionEnd===0,h=Du({direction:c.key==="ArrowUp"?"up":"down",history:ba(),currentValue:pe.value,atStart:g,state:Dr});if(Dr=h.state,h.handled){c.preventDefault(),h.value!==void 0&&ya(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(T.isStreaming()){c.preventDefault();return}pr(),c.preventDefault(),ae.click()}}},ys=c=>{c.key!=="Escape"||c.isComposing||T.isStreaming()&&c.composedPath().includes(ce)&&(T.cancel(),xe==null||xe.reset(),Se==null||Se.update(),pr(),c.preventDefault(),c.stopImmediatePropagation())},vs=async c=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!et)return;let g=nx(c.clipboardData);g.length!==0&&(c.preventDefault(),await et.handleFiles(g))},Cn=null,Gn=!1,Fo=null,rt=null,xs=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ur=(c="user")=>{var N,V,z,O,Ae,ue,ee;if(Gn||T.isStreaming())return;let g=xs();if(!g)return;Cn=new g;let y=(V=((N=o.voiceRecognition)!=null?N:{}).pauseDuration)!=null?V:2e3;Cn.continuous=!0,Cn.interimResults=!0,Cn.lang="en-US";let P=pe.value;Cn.onresult=he=>{let Ee="",Oe="";for(let Ye=0;Ye<he.results.length;Ye++){let at=he.results[Ye],it=at[0].transcript;at.isFinal?Ee+=it+" ":Oe=it}let tt=P+Ee+Oe;pe.value=tt,Fo&&clearTimeout(Fo),(Ee||Oe)&&(Fo=window.setTimeout(()=>{let Ye=pe.value.trim();Ye&&Cn&&Gn&&(bo(),pe.value="",pe.style.height="auto",T.sendMessage(Ye,{viaVoice:!0}))},y))},Cn.onerror=he=>{he.error!=="no-speech"&&bo()},Cn.onend=()=>{if(Gn){let he=pe.value.trim();he&&he!==P.trim()&&(pe.value="",pe.style.height="auto",T.sendMessage(he,{viaVoice:!0})),bo()}};try{if(Cn.start(),Gn=!0,mt.active=!0,c!=="system"&&(mt.manuallyDeactivated=!1),ro(c),Rn(),q){let he=(z=o.voiceRecognition)!=null?z:{};rt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(O=he.iconName)!=null?O:"mic",iconSize:parseFloat((ee=(ue=he.iconSize)!=null?ue:(Ae=o.sendButton)==null?void 0:Ae.size)!=null?ee:"40")||24};let Ee=he.recordingBackgroundColor,Oe=he.recordingIconColor,tt=he.recordingBorderColor;if(q.classList.add("persona-voice-recording"),q.style.backgroundColor=Ee!=null?Ee:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=Oe!=null?Oe:"var(--persona-voice-recording-indicator, #ffffff)",Oe){let Ye=q.querySelector("svg");Ye&&Ye.setAttribute("stroke",Oe)}tt&&(q.style.borderColor=tt),q.setAttribute("aria-label","Stop voice recognition")}}catch{bo("system")}},bo=(c="user")=>{if(Gn){if(Gn=!1,Fo&&(clearTimeout(Fo),Fo=null),Cn){try{Cn.stop()}catch{}Cn=null}if(mt.active=!1,ro(c),Rn(),q){if(q.classList.remove("persona-voice-recording"),rt){q.style.backgroundColor=rt.backgroundColor,q.style.color=rt.color,q.style.borderColor=rt.borderColor;let g=q.querySelector("svg");g&&g.setAttribute("stroke",rt.color||"currentColor"),rt=null}q.setAttribute("aria-label","Start voice recognition")}}},va=(c,g)=>{var at,it,Pe,Re,qe,L,Me,We;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((at=c==null?void 0:c.provider)==null?void 0:at.type)==="runtype";if(!(h||y))return null;let N=b("div","persona-send-button-wrapper"),V=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");V.type="button",V.setAttribute("aria-label","Start voice recognition");let z=(it=c==null?void 0:c.iconName)!=null?it:"mic",O=(Pe=g==null?void 0:g.size)!=null?Pe:"40px",Ae=(Re=c==null?void 0:c.iconSize)!=null?Re:O,ue=parseFloat(Ae)||24,ee=(qe=c==null?void 0:c.backgroundColor)!=null?qe:g==null?void 0:g.backgroundColor,he=(L=c==null?void 0:c.iconColor)!=null?L:g==null?void 0:g.textColor;V.style.width=Ae,V.style.height=Ae,V.style.minWidth=Ae,V.style.minHeight=Ae,V.style.fontSize="18px",V.style.lineHeight="1",he?V.style.color=he:V.style.color="var(--persona-text, #111827)";let Oe=Te(z,ue,he||"currentColor",1.5);Oe?V.appendChild(Oe):V.textContent="\u{1F3A4}",ee?V.style.backgroundColor=ee:V.style.backgroundColor="",c!=null&&c.borderWidth&&(V.style.borderWidth=c.borderWidth,V.style.borderStyle="solid"),c!=null&&c.borderColor&&(V.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(V.style.paddingLeft=c.paddingX,V.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(V.style.paddingTop=c.paddingY,V.style.paddingBottom=c.paddingY),N.appendChild(V);let tt=(Me=c==null?void 0:c.tooltipText)!=null?Me:"Start voice recognition";if(((We=c==null?void 0:c.showTooltip)!=null?We:!1)&&tt){let Ke=b("div","persona-send-button-tooltip");Ke.textContent=tt,N.appendChild(Ke)}return{micButton:V,micButtonWrapper:N}},er=()=>{var g,h,y,P,N;if(!q||rt)return;let c=(g=o.voiceRecognition)!=null?g:{};rt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(h=c.iconName)!=null?h:"mic",iconSize:parseFloat((N=(P=c.iconSize)!=null?P:(y=o.sendButton)==null?void 0:y.size)!=null?N:"40")||24}},je=(c,g)=>{var N,V,z,O,Ae;if(!q)return;let h=q.querySelector("svg");h&&h.remove();let y=(Ae=rt==null?void 0:rt.iconSize)!=null?Ae:parseFloat((O=(z=(N=o.voiceRecognition)==null?void 0:N.iconSize)!=null?z:(V=o.sendButton)==null?void 0:V.size)!=null?O:"40")||24,P=Te(c,y,g,1.5);P&&q.appendChild(P)},A=()=>{q&&q.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},U=()=>{var P;if(!q)return;er();let c=(P=o.voiceRecognition)!=null?P:{},g=c.recordingBackgroundColor,h=c.recordingIconColor,y=c.recordingBorderColor;if(A(),q.classList.add("persona-voice-recording"),q.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let N=q.querySelector("svg");N&&N.setAttribute("stroke",h)}y&&(q.style.borderColor=y),q.setAttribute("aria-label","Stop voice recognition")},W=()=>{var z,O,Ae,ue,ee,he,Ee,Oe;if(!q)return;er();let c=(z=o.voiceRecognition)!=null?z:{},g=T.getVoiceInterruptionMode(),h=(O=c.processingIconName)!=null?O:"loader",y=(ue=(Ae=c.processingIconColor)!=null?Ae:rt==null?void 0:rt.color)!=null?ue:"",P=(he=(ee=c.processingBackgroundColor)!=null?ee:rt==null?void 0:rt.backgroundColor)!=null?he:"",N=(Oe=(Ee=c.processingBorderColor)!=null?Ee:rt==null?void 0:rt.borderColor)!=null?Oe:"";A(),q.classList.add("persona-voice-processing"),q.style.backgroundColor=P,q.style.borderColor=N;let V=y||"currentColor";q.style.color=V,je(h,V),q.setAttribute("aria-label","Processing voice input"),g==="none"&&(q.style.cursor="default")},Z=()=>{var Ae,ue,ee,he,Ee,Oe,tt,Ye,at,it,Pe,Re;if(!q)return;er();let c=(Ae=o.voiceRecognition)!=null?Ae:{},g=T.getVoiceInterruptionMode(),h=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",y=(ue=c.speakingIconName)!=null?ue:h,P=(Oe=c.speakingIconColor)!=null?Oe:g==="barge-in"?(he=(ee=c.recordingIconColor)!=null?ee:rt==null?void 0:rt.color)!=null?he:"":(Ee=rt==null?void 0:rt.color)!=null?Ee:"",N=(at=c.speakingBackgroundColor)!=null?at:g==="barge-in"?(tt=c.recordingBackgroundColor)!=null?tt:"var(--persona-voice-recording-bg, #ef4444)":(Ye=rt==null?void 0:rt.backgroundColor)!=null?Ye:"",V=(Re=c.speakingBorderColor)!=null?Re:g==="barge-in"?(it=c.recordingBorderColor)!=null?it:"":(Pe=rt==null?void 0:rt.borderColor)!=null?Pe:"";A(),q.classList.add("persona-voice-speaking"),q.style.backgroundColor=N,q.style.borderColor=V;let z=P||"currentColor";q.style.color=z,je(y,z);let O=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";q.setAttribute("aria-label",O),g==="none"&&(q.style.cursor="default"),g==="barge-in"&&q.classList.add("persona-voice-recording")},G=()=>{var c,g,h;q&&(A(),rt&&(q.style.backgroundColor=(c=rt.backgroundColor)!=null?c:"",q.style.color=(g=rt.color)!=null?g:"",q.style.borderColor=(h=rt.borderColor)!=null?h:"",je(rt.iconName,rt.color||"currentColor"),rt=null),q.style.cursor="",q.setAttribute("aria-label","Start voice recognition"))},X=()=>{var c,g;if(((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let h=T.getVoiceStatus(),y=T.getVoiceInterruptionMode();if(y==="none"&&(h==="processing"||h==="speaking"))return;if(y==="cancel"&&(h==="processing"||h==="speaking")){T.stopVoicePlayback();return}if(T.isBargeInActive()){T.stopVoicePlayback(),T.deactivateBargeIn().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Rn(),ro("user"),G()});return}T.toggleVoice().then(()=>{mt.active=T.isVoiceActive(),mt.manuallyDeactivated=!T.isVoiceActive(),Rn(),ro("user"),T.isVoiceActive()?U():G()});return}if(Gn){let h=pe.value.trim();mt.manuallyDeactivated=!0,Rn(),bo("user"),h&&(pe.value="",pe.style.height="auto",T.sendMessage(h))}else mt.manuallyDeactivated=!1,Rn(),ur("user")};Fn=X,q&&(q.addEventListener("click",X),gt.push(()=>{var c,g;((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(T.isVoiceActive()&&T.toggleVoice(),G()):bo("system"),q&&q.removeEventListener("click",X)}));let Xe=s.on("assistant:complete",()=>{is&&(mt.active||mt.manuallyDeactivated||is==="assistant"&&!mt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!mt.active&&!mt.manuallyDeactivated&&(((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?T.toggleVoice().then(()=>{mt.active=T.isVoiceActive(),ro("auto"),T.isVoiceActive()&&U()}):ur("auto"))},600))});gt.push(Xe);let Ne=s.on("action:resubmit",()=>{setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)});gt.push(Ne);let Ze=()=>{Bt(!E,"user")},Ie=null,Ge=null;if(I&&!k()){let c=r.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:o,defaultRenderer:()=>qs(o,Ze).element,onToggle:Ze});g&&(Ge=g)}Ge||(Ie=qs(o,Ze))}Ie?e.appendChild(Ie.element):Ge&&e.appendChild(Ge),Zo(),uo.render(o.suggestionChips,T,pe,void 0,o.suggestionChipsConfig),ms(),Br(T.isStreaming()),Yo(!0),aa(),H&&(!I||k()?setTimeout(()=>Hr(),0):E&&setTimeout(()=>Hr(),200));let Rt=()=>{var O,Ae,ue,ee,he,Ee,Oe,tt,Ye,at,it,Pe,Re,qe,L,Me,We,Ke,Ce,Lt,st,Xt;if(k()){bt(),Zo();return}let c=pn(o),g=(Ae=(O=o.launcher)==null?void 0:O.sidebarMode)!=null?Ae:!1,h=c||g||((ee=(ue=o.launcher)==null?void 0:ue.fullHeight)!=null?ee:!1),y=(he=e.ownerDocument.defaultView)!=null?he:window,P=(Oe=(Ee=o.launcher)==null?void 0:Ee.mobileFullscreen)!=null?Oe:!0,N=(Ye=(tt=o.launcher)==null?void 0:tt.mobileBreakpoint)!=null?Ye:640,V=y.innerWidth<=N,z=P&&V&&I;try{if(z){po(),$r(e,o);return}if(x&&(x=!1,po(),$r(e,o)),!I&&!c){le.style.height="",le.style.width="";return}if(!g&&!c){let cn=(it=(at=o==null?void 0:o.launcher)==null?void 0:at.width)!=null?it:o==null?void 0:o.launcherWidth,Pt=cn!=null?cn:io;le.style.width=Pt,le.style.maxWidth=Pt}if(Co(),!h){let cn=y.innerHeight,Pt=64,An=(Re=(Pe=o.launcher)==null?void 0:Pe.heightOffset)!=null?Re:0,dn=Math.max(200,cn-Pt),Je=Math.min(640,dn),lt=Math.max(200,Je-An);le.style.height=`${lt}px`}}finally{if(bt(),Zo(),E&&I){let Pt=((qe=e.ownerDocument.defaultView)!=null?qe:window).innerWidth<=((Me=(L=o.launcher)==null?void 0:L.mobileBreakpoint)!=null?Me:640),An=(Ke=(We=o.launcher)==null?void 0:We.sidebarMode)!=null?Ke:!1,dn=(Lt=(Ce=o.launcher)==null?void 0:Ce.mobileFullscreen)!=null?Lt:!0,Je=pn(o)&&dn&&Pt,lt=An||dn&&Pt&&I||Je;if(lt&&!Gt){let Tn=e.getRootNode(),mn=Tn instanceof ShadowRoot?Tn.host:e.closest(".persona-host");mn&&!Kt&&(Kt=ml(mn,(Xt=(st=o.launcher)==null?void 0:st.zIndex)!=null?Xt:hn)),Gt=gl(e.ownerDocument)}else lt||(Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null)}}};Rt();let nn=(qc=e.ownerDocument.defaultView)!=null?qc:window;if(nn.addEventListener("resize",Rt),gt.push(()=>nn.removeEventListener("resize",Rt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{bt()});c.observe(Ve),gt.push(()=>c.disconnect())}fo=K.scrollTop;let Ct=K.scrollHeight,Mt=()=>{let c=K.scrollTop,g=K.scrollHeight,h=g<Ct;Ct=g;let{action:y,nextLastScrollTop:P}=si({following:go.isFollowing(),currentScrollTop:c,lastScrollTop:fo,nearBottom:Os(K,as),userScrollThreshold:ra,isAutoScrolling:Wo||lr||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(fo=P,y==="resume"){Go();return}y==="pause"&&cs()};K.addEventListener("scroll",Mt,{passive:!0}),gt.push(()=>K.removeEventListener("scroll",Mt));let on=c=>{let g=ai({following:go.isFollowing(),deltaY:c.deltaY,nearBottom:Os(K,as),resumeWhenNearBottom:!0});g==="pause"?cs():g==="resume"&&Go()};K.addEventListener("wheel",on,{passive:!0}),gt.push(()=>K.removeEventListener("wheel",on)),Tt.addEventListener("click",()=>{K.scrollTop=K.scrollHeight,fo=K.scrollTop,Go(),Yo(!0)}),gt.push(()=>Tt.remove()),gt.push(()=>{ls()});let un=()=>{ze&&(jn&&(ze.removeEventListener("click",jn),jn=null),S()?(ze.style.display="",jn=()=>{Bt(!1,"user")},ze.addEventListener("click",jn)):ze.style.display="none")};un(),(()=>{let{clearChatButton:c}=Be;c&&c.addEventListener("click",()=>{T.clearMessages(),mo.clear(),Go(),Jr(Be.composerOverlay);try{localStorage.removeItem(es),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${es}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==es)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}d={},M.syncFromMetadata(),Y==null||Y.clear(),xe==null||xe.reset(),Se==null||Se.update()})})(),Nt&&Nt.addEventListener("submit",fs),pe==null||pe.addEventListener("keydown",bs),pe==null||pe.addEventListener("input",hs),pe==null||pe.addEventListener("paste",vs);let Yt=(jc=e.ownerDocument)!=null?jc:document;Yt.addEventListener("keydown",ys,!0);let so="persona-attachment-drop-active",ws=0,Ui=()=>{ws=0,ce.classList.remove(so)},Or=()=>{var c;return((c=o.attachments)==null?void 0:c.enabled)===!0&&et!==null},Zl=c=>{!Ei(c.dataTransfer)||!Or()||(ws++,ws===1&&ce.classList.add(so))},ec=c=>{!Ei(c.dataTransfer)||!Or()||(ws--,ws<=0&&Ui())},tc=c=>{!Ei(c.dataTransfer)||!Or()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},nc=c=>{var h;if(!Ei(c.dataTransfer)||!Or())return;c.preventDefault(),c.stopPropagation(),Ui();let g=Array.from((h=c.dataTransfer.files)!=null?h:[]);g.length!==0&&et.handleFiles(g)},tr=!0;ce.addEventListener("dragenter",Zl,tr),ce.addEventListener("dragleave",ec,tr),e.addEventListener("dragover",tc,tr),e.addEventListener("drop",nc,tr);let xa=e.ownerDocument,oc=c=>{Or()&&c.preventDefault()},rc=c=>{Or()&&c.preventDefault()};xa.addEventListener("dragover",oc),xa.addEventListener("drop",rc),gt.push(()=>{Nt&&Nt.removeEventListener("submit",fs),pe==null||pe.removeEventListener("keydown",bs),pe==null||pe.removeEventListener("input",hs),pe==null||pe.removeEventListener("paste",vs),Yt.removeEventListener("keydown",ys,!0)}),gt.push(()=>{ce.removeEventListener("dragenter",Zl,tr),ce.removeEventListener("dragleave",ec,tr),e.removeEventListener("dragover",tc,tr),e.removeEventListener("drop",nc,tr),xa.removeEventListener("dragover",oc),xa.removeEventListener("drop",rc),Ui()}),gt.push(()=>{T.cancel()}),Ie?gt.push(()=>{Ie==null||Ie.destroy()}):Ge&>.push(()=>{Ge==null||Ge.remove()});let Zt={update(c){var en,To,No,wa,Ca,Sa,br,Aa,Cs,Zc,ed,td,nd,od,rd,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,bd,yd,vd,xd,wd,Cd,Sd,Ad,Td,kd,Ed,Md,Ld,Id,Rd,Pd,Wd,Bd,Hd,Dd,Fd,Od,Nd,_d,Vd,$d,Ud,zd,qd,jd,Kd,Gd,Yd,Xd,Qd,Jd,Zd,ep,tp,np,op,rp,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,bp,yp,vp,xp,wp,Cp,Sp,Ap,Tp,kp,Ep,Mp,Lp,Ip,Rp,Pp,Wp,Bp,Hp,Dp,Fp,Op,Np,_p,Vp,$p,Up,zp,qp,jp,Kp,Gp;let g=o.toolCall,h=o.messageActions,y=(en=o.layout)==null?void 0:en.messages,P=o.colorScheme,N=o.loadingIndicator,V=o.iterationDisplay,z=(To=o.features)==null?void 0:To.showReasoning,O=(No=o.features)==null?void 0:No.showToolCalls,Ae=(wa=o.features)==null?void 0:wa.toolCallDisplay,ue=(Ca=o.features)==null?void 0:Ca.reasoningDisplay;o={...o,...c},po(),$r(e,o),Ti(e,o),ki(e,o),zn(),o.colorScheme!==P&&Ko();let ee=Bl.getForInstance(o.plugins);r.length=0,r.push(...ee),I=(br=(Sa=o.launcher)==null?void 0:Sa.enabled)!=null?br:!0,R=(Cs=(Aa=o.launcher)==null?void 0:Aa.autoExpand)!=null?Cs:!1,se=(ed=(Zc=o.features)==null?void 0:Zc.showReasoning)!=null?ed:!0,ge=(nd=(td=o.features)==null?void 0:td.showToolCalls)!=null?nd:!0,be=(rd=(od=o.features)==null?void 0:od.scrollToBottom)!=null?rd:{},zt(),Ho();let he=ie;if(ie=(ad=(sd=o.features)==null?void 0:sd.showEventStreamToggle)!=null?ad:!1,ie&&!he){if(Y||(J=new Xs(ve),Y=new Ys(Le,J),xe=xe!=null?xe:new Qs,J.open().then(()=>Y==null?void 0:Y.restore()).catch(()=>{}),T.setSSEEventCallback((Q,vt)=>{var Ot;(Ot=o.onSSEEvent)==null||Ot.call(o,Q,vt),xe==null||xe.processEvent(Q,vt),Y.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Q,timestamp:Date.now(),payload:JSON.stringify(vt)})})),!ut&&De){let Q=(ld=(id=o.features)==null?void 0:id.eventStream)==null?void 0:ld.classNames,vt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(Q!=null&&Q.toggleButton?" "+Q.toggleButton:"");ut=b("button",vt),ut.style.width="28px",ut.style.height="28px",ut.style.color=Mn.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let Ot=Te("activity","18px","currentColor",1.5);Ot&&ut.appendChild(Ot);let ct=Be.clearChatButtonWrapper,kt=Be.closeButtonWrapper,rn=ct||kt;rn&&rn.parentNode===De?De.insertBefore(ut,rn):De.appendChild(ut),ut.addEventListener("click",()=>{de?On():vn()})}}else!ie&&he&&(On(),ut&&(ut.remove(),ut=null),Y==null||Y.clear(),J==null||J.destroy(),Y=null,J=null,xe==null||xe.reset(),xe=null);if(((cd=o.launcher)==null?void 0:cd.enabled)===!1&&Ie&&(Ie.destroy(),Ie=null),((dd=o.launcher)==null?void 0:dd.enabled)===!1&&Ge&&(Ge.remove(),Ge=null),((pd=o.launcher)==null?void 0:pd.enabled)!==!1&&!Ie&&!Ge){let Q=r.find(vt=>vt.renderLauncher);if(Q!=null&&Q.renderLauncher){let vt=Q.renderLauncher({config:o,defaultRenderer:()=>qs(o,Ze).element,onToggle:Ze});vt&&(Ge=vt,e.appendChild(Ge))}Ge||(Ie=qs(o,Ze),e.appendChild(Ie.element))}Ie&&Ie.update(o),ke&&((ud=o.launcher)==null?void 0:ud.title)!==void 0&&(ke.textContent=o.launcher.title),He&&((md=o.launcher)==null?void 0:md.subtitle)!==void 0&&(He.textContent=o.launcher.subtitle);let Ee=(gd=o.layout)==null?void 0:gd.header;if((Ee==null?void 0:Ee.layout)!==v&&De){let Q=Ee?mi(o,Ee,{showClose:S(),onClose:()=>Bt(!1,"user")}):Ar({config:o,showClose:S(),onClose:()=>Bt(!1,"user")});De.replaceWith(Q.header),De=Q.header,_=Q.iconHolder,ke=Q.headerTitle,He=Q.headerSubtitle,ze=Q.closeButton,v=Ee==null?void 0:Ee.layout}else if(Ee&&(_&&(_.style.display=Ee.showIcon===!1?"none":""),ke&&(ke.style.display=Ee.showTitle===!1?"none":""),He&&(He.style.display=Ee.showSubtitle===!1?"none":""),ze&&(ze.style.display=Ee.showCloseButton===!1?"none":""),Be.clearChatButtonWrapper)){let Q=Ee.showClearChat;if(Q!==void 0){Be.clearChatButtonWrapper.style.display=Q?"":"none";let{closeButtonWrapper:vt}=Be;vt&&!vt.classList.contains("persona-absolute")&&(Q?vt.classList.remove("persona-ml-auto"):vt.classList.add("persona-ml-auto"))}}let tt=((fd=o.layout)==null?void 0:fd.showHeader)!==!1;De&&(De.style.display=tt?"":"none");let Ye=((hd=o.layout)==null?void 0:hd.showFooter)!==!1;Ve&&(Ve.style.display=Ye?"":"none"),bt(),Ho(),I!==B?I?Bt(R,"auto"):(E=!0,Zo()):R!==D&&Bt(R,"auto"),D=R,B=I,Rt(),un();let Pe=JSON.stringify(c.toolCall)!==JSON.stringify(g),Re=JSON.stringify(o.messageActions)!==JSON.stringify(h),qe=JSON.stringify((bd=o.layout)==null?void 0:bd.messages)!==JSON.stringify(y),L=((yd=o.loadingIndicator)==null?void 0:yd.render)!==(N==null?void 0:N.render)||((vd=o.loadingIndicator)==null?void 0:vd.renderIdle)!==(N==null?void 0:N.renderIdle)||((xd=o.loadingIndicator)==null?void 0:xd.showBubble)!==(N==null?void 0:N.showBubble),Me=o.iterationDisplay!==V,We=((Cd=(wd=o.features)==null?void 0:wd.showReasoning)!=null?Cd:!0)!==(z!=null?z:!0)||((Ad=(Sd=o.features)==null?void 0:Sd.showToolCalls)!=null?Ad:!0)!==(O!=null?O:!0)||JSON.stringify((Td=o.features)==null?void 0:Td.toolCallDisplay)!==JSON.stringify(Ae)||JSON.stringify((kd=o.features)==null?void 0:kd.reasoningDisplay)!==JSON.stringify(ue);(Pe||Re||qe||L||Me||We)&&T&&(ss++,dr(_e,T.getMessages(),me));let Ce=(Ed=o.launcher)!=null?Ed:{},Lt=(Md=Ce.headerIconHidden)!=null?Md:!1,st=(Id=(Ld=o.layout)==null?void 0:Ld.header)==null?void 0:Id.showIcon,Xt=Lt||st===!1,cn=Ce.headerIconName,Pt=(Rd=Ce.headerIconSize)!=null?Rd:"48px";if(_){let Q=ce.querySelector(".persona-border-b-persona-divider"),vt=Q==null?void 0:Q.querySelector(".persona-flex-col");if(Xt)_.style.display="none",Q&&vt&&!Q.contains(vt)&&Q.insertBefore(vt,Q.firstChild);else{if(_.style.display="",_.style.height=Pt,_.style.width=Pt,Q&&vt&&(Q.contains(_)?_.nextSibling!==vt&&(_.remove(),Q.insertBefore(_,vt)):Q.insertBefore(_,vt)),cn){let ct=parseFloat(Pt)||24,kt=Te(cn,ct*.6,"#ffffff",2);kt?_.replaceChildren(kt):_.textContent=(Pd=Ce.agentIconText)!=null?Pd:"\u{1F4AC}"}else if(Ce.iconUrl){let ct=_.querySelector("img");if(ct)ct.src=Ce.iconUrl,ct.style.height=Pt,ct.style.width=Pt;else{let kt=document.createElement("img");kt.src=Ce.iconUrl,kt.alt="",kt.className="persona-rounded-xl persona-object-cover",kt.style.height=Pt,kt.style.width=Pt,_.replaceChildren(kt)}}else{let ct=_.querySelector("svg"),kt=_.querySelector("img");(ct||kt)&&_.replaceChildren(),_.textContent=(Wd=Ce.agentIconText)!=null?Wd:"\u{1F4AC}"}let Ot=_.querySelector("img");Ot&&(Ot.style.height=Pt,Ot.style.width=Pt)}}let An=(Hd=(Bd=o.layout)==null?void 0:Bd.header)==null?void 0:Hd.showTitle,dn=(Fd=(Dd=o.layout)==null?void 0:Dd.header)==null?void 0:Fd.showSubtitle;if(ke&&(ke.style.display=An===!1?"none":""),He&&(He.style.display=dn===!1?"none":""),ze){((Nd=(Od=o.layout)==null?void 0:Od.header)==null?void 0:Nd.showCloseButton)===!1?ze.style.display="none":ze.style.display="";let vt=(_d=Ce.closeButtonSize)!=null?_d:"32px",Ot=(Vd=Ce.closeButtonPlacement)!=null?Vd:"inline";ze.style.height=vt,ze.style.width=vt;let{closeButtonWrapper:ct}=Be,kt=Ot==="top-right",rn=ct==null?void 0:ct.classList.contains("persona-absolute");if(ct&&kt!==rn)if(ct.remove(),kt)ct.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ce.style.position="relative",ce.appendChild(ct);else{let pt=(Ud=($d=Ce.clearChat)==null?void 0:$d.placement)!=null?Ud:"inline",sn=(qd=(zd=Ce.clearChat)==null?void 0:zd.enabled)!=null?qd:!0;ct.className=sn&&pt==="inline"?"":"persona-ml-auto";let Hn=ce.querySelector(".persona-border-b-persona-divider");Hn&&Hn.appendChild(ct)}if(ze.style.color=Ce.closeButtonColor||Mn.actionIconColor,Ce.closeButtonBackgroundColor?(ze.style.backgroundColor=Ce.closeButtonBackgroundColor,ze.classList.remove("hover:persona-bg-gray-100")):(ze.style.backgroundColor="",ze.classList.add("hover:persona-bg-gray-100")),Ce.closeButtonBorderWidth||Ce.closeButtonBorderColor){let pt=Ce.closeButtonBorderWidth||"0px",sn=Ce.closeButtonBorderColor||"transparent";ze.style.border=`${pt} solid ${sn}`,ze.classList.remove("persona-border-none")}else ze.style.border="",ze.classList.add("persona-border-none");Ce.closeButtonBorderRadius?(ze.style.borderRadius=Ce.closeButtonBorderRadius,ze.classList.remove("persona-rounded-full")):(ze.style.borderRadius="",ze.classList.add("persona-rounded-full")),Ce.closeButtonPaddingX?(ze.style.paddingLeft=Ce.closeButtonPaddingX,ze.style.paddingRight=Ce.closeButtonPaddingX):(ze.style.paddingLeft="",ze.style.paddingRight=""),Ce.closeButtonPaddingY?(ze.style.paddingTop=Ce.closeButtonPaddingY,ze.style.paddingBottom=Ce.closeButtonPaddingY):(ze.style.paddingTop="",ze.style.paddingBottom="");let gn=(jd=Ce.closeButtonIconName)!=null?jd:"x",yo=(Kd=Ce.closeButtonIconText)!=null?Kd:"\xD7";ze.innerHTML="";let En=Te(gn,"28px","currentColor",1);En?ze.appendChild(En):ze.textContent=yo;let Qt=(Gd=Ce.closeButtonTooltipText)!=null?Gd:"Close chat",Xn=(Yd=Ce.closeButtonShowTooltip)!=null?Yd:!0;if(ze.setAttribute("aria-label",Qt),ct&&(ct._cleanupTooltip&&(ct._cleanupTooltip(),delete ct._cleanupTooltip),Xn&&Qt)){let pt=null,sn=()=>{if(pt||!ze)return;let yr=ze.ownerDocument,Ss=yr.body;if(!Ss)return;pt=Eo(yr,"div","persona-clear-chat-tooltip"),pt.textContent=Qt;let As=Eo(yr,"div");As.className="persona-clear-chat-tooltip-arrow",pt.appendChild(As);let vr=ze.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(or),pt.style.left=`${vr.left+vr.width/2}px`,pt.style.top=`${vr.top-8}px`,pt.style.transform="translate(-50%, -100%)",Ss.appendChild(pt)},Hn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};ct.addEventListener("mouseenter",sn),ct.addEventListener("mouseleave",Hn),ze.addEventListener("focus",sn),ze.addEventListener("blur",Hn),ct._cleanupTooltip=()=>{Hn(),ct&&(ct.removeEventListener("mouseenter",sn),ct.removeEventListener("mouseleave",Hn)),ze&&(ze.removeEventListener("focus",sn),ze.removeEventListener("blur",Hn))}}}let{clearChatButton:Je,clearChatButtonWrapper:lt}=Be;if(Je){let Q=(Xd=Ce.clearChat)!=null?Xd:{},vt=(Qd=Q.enabled)!=null?Qd:!0,Ot=(Zd=(Jd=o.layout)==null?void 0:Jd.header)==null?void 0:Zd.showClearChat,ct=Ot!==void 0?Ot:vt,kt=(ep=Q.placement)!=null?ep:"inline";if(lt){lt.style.display=ct?"":"none";let{closeButtonWrapper:rn}=Be;!k()&&rn&&!rn.classList.contains("persona-absolute")&&(ct?rn.classList.remove("persona-ml-auto"):rn.classList.add("persona-ml-auto"));let gn=kt==="top-right",yo=lt.classList.contains("persona-absolute");if(!k()&&gn!==yo&&ct){if(lt.remove(),gn)lt.className="persona-absolute persona-top-4 persona-z-50",lt.style.right="48px",ce.style.position="relative",ce.appendChild(lt);else{lt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",lt.style.right="";let Qt=ce.querySelector(".persona-border-b-persona-divider"),Xn=Be.closeButtonWrapper;Qt&&Xn&&Xn.parentElement===Qt?Qt.insertBefore(lt,Xn):Qt&&Qt.appendChild(lt)}let En=Be.closeButtonWrapper;En&&!En.classList.contains("persona-absolute")&&(gn?En.classList.add("persona-ml-auto"):En.classList.remove("persona-ml-auto"))}}if(ct){if(!k()){let pt=(tp=Q.size)!=null?tp:"32px";Je.style.height=pt,Je.style.width=pt}let rn=(np=Q.iconName)!=null?np:"refresh-cw",gn=(op=Q.iconColor)!=null?op:"";Je.style.color=gn||Mn.actionIconColor,Je.innerHTML="";let yo=k()?"14px":"20px",En=Te(rn,yo,"currentColor",2);if(En&&Je.appendChild(En),Q.backgroundColor?(Je.style.backgroundColor=Q.backgroundColor,Je.classList.remove("hover:persona-bg-gray-100")):(Je.style.backgroundColor="",Je.classList.add("hover:persona-bg-gray-100")),Q.borderWidth||Q.borderColor){let pt=Q.borderWidth||"0px",sn=Q.borderColor||"transparent";Je.style.border=`${pt} solid ${sn}`,Je.classList.remove("persona-border-none")}else Je.style.border="",Je.classList.add("persona-border-none");Q.borderRadius?(Je.style.borderRadius=Q.borderRadius,Je.classList.remove("persona-rounded-full")):(Je.style.borderRadius="",Je.classList.add("persona-rounded-full")),Q.paddingX?(Je.style.paddingLeft=Q.paddingX,Je.style.paddingRight=Q.paddingX):(Je.style.paddingLeft="",Je.style.paddingRight=""),Q.paddingY?(Je.style.paddingTop=Q.paddingY,Je.style.paddingBottom=Q.paddingY):(Je.style.paddingTop="",Je.style.paddingBottom="");let Qt=(rp=Q.tooltipText)!=null?rp:"Clear chat",Xn=(sp=Q.showTooltip)!=null?sp:!0;if(Je.setAttribute("aria-label",Qt),lt&&(lt._cleanupTooltip&&(lt._cleanupTooltip(),delete lt._cleanupTooltip),Xn&&Qt)){let pt=null,sn=()=>{if(pt||!Je)return;let yr=Je.ownerDocument,Ss=yr.body;if(!Ss)return;pt=Eo(yr,"div","persona-clear-chat-tooltip"),pt.textContent=Qt;let As=Eo(yr,"div");As.className="persona-clear-chat-tooltip-arrow",pt.appendChild(As);let vr=Je.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(or),pt.style.left=`${vr.left+vr.width/2}px`,pt.style.top=`${vr.top-8}px`,pt.style.transform="translate(-50%, -100%)",Ss.appendChild(pt)},Hn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};lt.addEventListener("mouseenter",sn),lt.addEventListener("mouseleave",Hn),Je.addEventListener("focus",sn),Je.addEventListener("blur",Hn),lt._cleanupTooltip=()=>{Hn(),lt&&(lt.removeEventListener("mouseenter",sn),lt.removeEventListener("mouseleave",Hn)),Je&&(Je.removeEventListener("focus",sn),Je.removeEventListener("blur",Hn))}}}}let Tn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Dl],mn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Js.message,Js.messageAndClick];M=Fl({parsers:Tn,handlers:mn,getSessionMetadata:f,updateSessionMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),me=Dm(o,M,j),T.updateConfig(o),dr(_e,T.getMessages(),me),uo.render(o.suggestionChips,T,pe,void 0,o.suggestionChipsConfig),ms(),Br(T.isStreaming());let mr=((ap=o.voiceRecognition)==null?void 0:ap.enabled)===!0,gr=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),fr=((lp=(ip=o.voiceRecognition)==null?void 0:ip.provider)==null?void 0:lp.type)==="runtype";if(mr&&(gr||fr))if(!q||!_t){let Q=va(o.voiceRecognition,o.sendButton);Q&&(q=Q.micButton,_t=Q.micButtonWrapper,At.insertBefore(_t,Ln),q.addEventListener("click",X),q.disabled=T.isStreaming())}else{let Q=(cp=o.voiceRecognition)!=null?cp:{},vt=(dp=o.sendButton)!=null?dp:{},Ot=(pp=Q.iconName)!=null?pp:"mic",ct=(up=vt.size)!=null?up:"40px",kt=(mp=Q.iconSize)!=null?mp:ct,rn=parseFloat(kt)||24;q.style.width=kt,q.style.height=kt,q.style.minWidth=kt,q.style.minHeight=kt;let gn=(fp=(gp=Q.iconColor)!=null?gp:vt.textColor)!=null?fp:"currentColor";q.innerHTML="";let yo=Te(Ot,rn,gn,2);yo?q.appendChild(yo):q.textContent="\u{1F3A4}";let En=(hp=Q.backgroundColor)!=null?hp:vt.backgroundColor;En?q.style.backgroundColor=En:q.style.backgroundColor="",gn?q.style.color=gn:q.style.color="var(--persona-text, #111827)",Q.borderWidth?(q.style.borderWidth=Q.borderWidth,q.style.borderStyle="solid"):(q.style.borderWidth="",q.style.borderStyle=""),Q.borderColor?q.style.borderColor=Q.borderColor:q.style.borderColor="",Q.paddingX?(q.style.paddingLeft=Q.paddingX,q.style.paddingRight=Q.paddingX):(q.style.paddingLeft="",q.style.paddingRight=""),Q.paddingY?(q.style.paddingTop=Q.paddingY,q.style.paddingBottom=Q.paddingY):(q.style.paddingTop="",q.style.paddingBottom="");let Qt=_t==null?void 0:_t.querySelector(".persona-send-button-tooltip"),Xn=(bp=Q.tooltipText)!=null?bp:"Start voice recognition";if(((yp=Q.showTooltip)!=null?yp:!1)&&Xn)if(Qt)Qt.textContent=Xn,Qt.style.display="";else{let sn=document.createElement("div");sn.className="persona-send-button-tooltip",sn.textContent=Xn,_t==null||_t.insertBefore(sn,q)}else Qt&&(Qt.style.display="none");_t.style.display="",q.disabled=T.isStreaming()}else q&&_t&&(_t.style.display="none",((xp=(vp=o.voiceRecognition)==null?void 0:vp.provider)==null?void 0:xp.type)==="runtype"?T.isVoiceActive()&&T.toggleVoice():Gn&&bo());if(((wp=o.attachments)==null?void 0:wp.enabled)===!0)if(!Ft||!Qe){let Q=(Cp=o.attachments)!=null?Cp:{},Ot=(Ap=((Sp=o.sendButton)!=null?Sp:{}).size)!=null?Ap:"40px";fe||(fe=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),fe.style.display="none",Nt.insertBefore(fe,pe)),oe||(oe=document.createElement("input"),oe.type="file",oe.accept=((Tp=Q.allowedTypes)!=null?Tp:_o).join(","),oe.multiple=((kp=Q.maxFiles)!=null?kp:4)>1,oe.style.display="none",oe.setAttribute("aria-label","Attach files"),Nt.insertBefore(oe,pe)),Ft=b("div","persona-send-button-wrapper"),Qe=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Qe.type="button",Qe.setAttribute("aria-label",(Ep=Q.buttonTooltipText)!=null?Ep:"Attach file");let ct=(Mp=Q.buttonIconName)!=null?Mp:"paperclip",kt=Ot,rn=parseFloat(kt)||40,gn=Math.round(rn*.6);Qe.style.width=kt,Qe.style.height=kt,Qe.style.minWidth=kt,Qe.style.minHeight=kt,Qe.style.fontSize="18px",Qe.style.lineHeight="1",Qe.style.backgroundColor="transparent",Qe.style.color="var(--persona-primary, #111827)",Qe.style.border="none",Qe.style.borderRadius="6px",Qe.style.transition="background-color 0.15s ease",Qe.addEventListener("mouseenter",()=>{Qe.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Qe.addEventListener("mouseleave",()=>{Qe.style.backgroundColor="transparent"});let yo=Te(ct,gn,"currentColor",1.5);yo?Qe.appendChild(yo):Qe.textContent="\u{1F4CE}",Qe.addEventListener("click",Xn=>{Xn.preventDefault(),oe==null||oe.click()}),Ft.appendChild(Qe);let En=(Lp=Q.buttonTooltipText)!=null?Lp:"Attach file",Qt=b("div","persona-send-button-tooltip");Qt.textContent=En,Ft.appendChild(Qt),ot.append(Ft),!et&&oe&&fe&&(et=Ds.fromConfig(Q),et.setPreviewsContainer(fe),oe.addEventListener("change",async()=>{et&&(oe!=null&&oe.files)&&(await et.handleFileSelect(oe.files),oe.value="")})),ce.querySelector(".persona-attachment-drop-overlay")||ce.appendChild(Fm(Q.dropOverlay))}else{Ft.style.display="";let Q=(Ip=o.attachments)!=null?Ip:{};oe&&(oe.accept=((Rp=Q.allowedTypes)!=null?Rp:_o).join(","),oe.multiple=((Pp=Q.maxFiles)!=null?Pp:4)>1),et&&et.updateConfig({allowedTypes:Q.allowedTypes,maxFileSize:Q.maxFileSize,maxFiles:Q.maxFiles})}else Ft&&(Ft.style.display="none"),et&&et.clearAttachments(),(Wp=ce.querySelector(".persona-attachment-drop-overlay"))==null||Wp.remove();let qt=(Bp=o.sendButton)!=null?Bp:{},hr=(Hp=qt.useIcon)!=null?Hp:!1,nr=(Dp=qt.iconText)!=null?Dp:"\u2191",ht=qt.iconName,Pn=(Fp=qt.tooltipText)!=null?Fp:"Send message",Oo=(Op=qt.showTooltip)!=null?Op:!1,kn=(Np=qt.size)!=null?Np:"40px",Wn=qt.backgroundColor,Ht=qt.textColor;if(hr){if(ae.style.width=kn,ae.style.height=kn,ae.style.minWidth=kn,ae.style.minHeight=kn,ae.style.fontSize="18px",ae.style.lineHeight="1",ae.innerHTML="",Ht?ae.style.color=Ht:ae.style.color="var(--persona-button-primary-fg, #ffffff)",ht){let Q=parseFloat(kn)||24,vt=(Ht==null?void 0:Ht.trim())||"currentColor",Ot=Te(ht,Q,vt,2);Ot?ae.appendChild(Ot):ae.textContent=nr}else ae.textContent=nr;ae.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Wn?(ae.style.backgroundColor=Wn,ae.classList.remove("persona-bg-persona-primary")):(ae.style.backgroundColor="",ae.classList.add("persona-bg-persona-primary"))}else ae.textContent=(Vp=(_p=o.copy)==null?void 0:_p.sendButtonLabel)!=null?Vp:"Send",ae.style.width="",ae.style.height="",ae.style.minWidth="",ae.style.minHeight="",ae.style.fontSize="",ae.style.lineHeight="",ae.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Wn?(ae.style.backgroundColor=Wn,ae.classList.remove("persona-bg-persona-accent")):ae.classList.add("persona-bg-persona-accent"),Ht?ae.style.color=Ht:ae.classList.add("persona-text-white");qt.borderWidth?(ae.style.borderWidth=qt.borderWidth,ae.style.borderStyle="solid"):(ae.style.borderWidth="",ae.style.borderStyle=""),qt.borderColor?ae.style.borderColor=qt.borderColor:ae.style.borderColor="",qt.paddingX?(ae.style.paddingLeft=qt.paddingX,ae.style.paddingRight=qt.paddingX):(ae.style.paddingLeft="",ae.style.paddingRight=""),qt.paddingY?(ae.style.paddingTop=qt.paddingY,ae.style.paddingBottom=qt.paddingY):(ae.style.paddingTop="",ae.style.paddingBottom="");let Ut=Ln==null?void 0:Ln.querySelector(".persona-send-button-tooltip");if(Oo&&Pn)if(Ut)Ut.textContent=Pn,Ut.style.display="";else{let Q=document.createElement("div");Q.className="persona-send-button-tooltip",Q.textContent=Pn,Ln==null||Ln.insertBefore(Q,ae)}else Ut&&(Ut.style.display="none");let Dt=(jp=($p=o.layout)==null?void 0:$p.contentMaxWidth)!=null?jp:k()?(qp=(zp=(Up=o.launcher)==null?void 0:Up.composerBar)==null?void 0:zp.contentMaxWidth)!=null?qp:"720px":void 0;Dt?(_e.style.maxWidth=Dt,_e.style.marginLeft="auto",_e.style.marginRight="auto",_e.style.width="100%",Nt&&(Nt.style.maxWidth=Dt,Nt.style.marginLeft="auto",Nt.style.marginRight="auto"),Et&&(Et.style.maxWidth=Dt,Et.style.marginLeft="auto",Et.style.marginRight="auto")):(_e.style.maxWidth="",_e.style.marginLeft="",_e.style.marginRight="",_e.style.width="",Nt&&(Nt.style.maxWidth="",Nt.style.marginLeft="",Nt.style.marginRight=""),Et&&(Et.style.maxWidth="",Et.style.marginLeft="",Et.style.marginRight=""));let jt=(Kp=o.statusIndicator)!=null?Kp:{},Bn=(Gp=jt.visible)!=null?Gp:!0;if(ln.style.display=Bn?"":"none",T){let Q=T.getStatus();nt(ln,(Ot=>{var ct,kt,rn,gn;return Ot==="idle"?(ct=jt.idleText)!=null?ct:fn.idle:Ot==="connecting"?(kt=jt.connectingText)!=null?kt:fn.connecting:Ot==="connected"?(rn=jt.connectedText)!=null?rn:fn.connected:Ot==="error"?(gn=jt.errorText)!=null?gn:fn.error:fn[Ot]})(Q),jt,Q)}ln.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Yn=jt.align==="left"?"persona-text-left":jt.align==="center"?"persona-text-center":"persona-text-right";ln.classList.add(Yn)},open(){S()&&Bt(!0,"api")},close(){S()&&Bt(!1,"api")},toggle(){S()&&Bt(!E,"api")},clearChat(){xn=!1,T.clearMessages(),mo.clear(),Go();try{localStorage.removeItem(es),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${es}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==es)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let g=i.clear();g instanceof Promise&&g.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}d={},M.syncFromMetadata(),Y==null||Y.clear(),xe==null||xe.reset(),Se==null||Se.update()},setMessage(c){return!pe||T.isStreaming()?!1:(!E&&S()&&Bt(!0,"system"),pe.value=c,pe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(T.isStreaming())return!1;let g=(c==null?void 0:c.trim())||pe.value.trim();return g?(!E&&S()&&Bt(!0,"system"),pe.value="",pe.style.height="auto",T.sendMessage(g),!0):!1},startVoiceRecognition(){var g,h;return T.isStreaming()?!1:((h=(g=o.voiceRecognition)==null?void 0:g.provider)==null?void 0:h.type)==="runtype"?(T.isVoiceActive()||(!E&&S()&&Bt(!0,"system"),mt.manuallyDeactivated=!1,Rn(),T.toggleVoice().then(()=>{mt.active=T.isVoiceActive(),ro("user"),T.isVoiceActive()&&U()})),!0):Gn?!0:xs()?(!E&&S()&&Bt(!0,"system"),mt.manuallyDeactivated=!1,Rn(),ur("user"),!0):!1},stopVoiceRecognition(){var c,g;return((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?T.isVoiceActive()?(T.toggleVoice().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Rn(),ro("user"),G()}),!0):!1:Gn?(mt.manuallyDeactivated=!0,Rn(),bo("user"),!0):!1},injectMessage(c){return!E&&S()&&Bt(!0,"system"),T.injectMessage(c)},injectAssistantMessage(c){!E&&S()&&Bt(!0,"system");let g=T.injectAssistantMessage(c);return F&&(F=!1,$&&(clearTimeout($),$=null),setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)),g},injectUserMessage(c){return!E&&S()&&Bt(!0,"system"),T.injectUserMessage(c)},injectSystemMessage(c){return!E&&S()&&Bt(!0,"system"),T.injectSystemMessage(c)},injectMessageBatch(c){return!E&&S()&&Bt(!0,"system"),T.injectMessageBatch(c)},injectComponentDirective(c){return!E&&S()&&Bt(!0,"system"),T.injectComponentDirective(c)},injectTestMessage(c){!E&&S()&&Bt(!0,"system"),T.injectTestEvent(c)},async connectStream(c,g){return T.connectStream(c,g)},__pushEventStreamEvent(c){Y&&(xe==null||xe.processEvent(c.type,c.payload),Y.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!ie||!Y||vn()},hideEventStream(){de&&On()},isEventStreamVisible(){return de},showArtifacts(){co(o)&&(xn=!1,zn(),yt==null||yt.setMobileOpen(!0))},hideArtifacts(){co(o)&&(xn=!0,zn())},upsertArtifact(c){return co(o)?(xn=!1,T.upsertArtifact(c)):null},selectArtifact(c){co(o)&&T.selectArtifact(c)},clearArtifacts(){co(o)&&T.clearArtifacts()},getArtifacts(){var c;return(c=T==null?void 0:T.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=T==null?void 0:T.getSelectedArtifactId())!=null?c:null},focusInput(){return I&&!E&&!k()||!pe?!1:(pe.focus(),!0)},async resolveApproval(c,g){let y=T.getMessages().find(P=>{var N;return P.variant==="approval"&&((N=P.approval)==null?void 0:N.id)===c});if(!(y!=null&&y.approval))throw new Error(`Approval not found: ${c}`);if(y.approval.toolType==="webmcp"){T.resolveWebMcpApproval(y.id,g);return}return T.resolveApproval(y.approval,g)},getMessages(){return T.getMessages()},getStatus(){return T.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){u(c)},on(c,g){return s.on(c,g)},off(c,g){s.off(c,g)},isOpen(){return S()&&E},isVoiceActive(){return mt.active},getState(){return{open:S()&&E,launcherEnabled:I,voiceActive:mt.active,streaming:T.isStreaming()}},showCSATFeedback(c){!E&&S()&&Bt(!0,"system");let g=_e.querySelector(".persona-feedback-container");g&&g.remove();let h=Wm({onSubmit:async(y,P)=>{var N;T.isClientTokenMode()&&await T.submitCSATFeedback(y,P),(N=c==null?void 0:c.onSubmit)==null||N.call(c,y,P)},onDismiss:c==null?void 0:c.onDismiss,...c});_e.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!E&&S()&&Bt(!0,"system");let g=_e.querySelector(".persona-feedback-container");g&&g.remove();let h=Bm({onSubmit:async(y,P)=>{var N;T.isClientTokenMode()&&await T.submitNPSFeedback(y,P),(N=c==null?void 0:c.onSubmit)==null||N.call(c,y,P)},onDismiss:c==null?void 0:c.onDismiss,...c});_e.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,g){return T.submitCSATFeedback(c,g)},async submitNPSFeedback(c,g){return T.submitNPSFeedback(c,g)},destroy(){Ao!=null&&(clearInterval(Ao),Ao=null),gt.forEach(c=>c()),ye.remove(),$e==null||$e.remove(),Ie==null||Ie.destroy(),Ge==null||Ge.remove(),jn&&ze.removeEventListener("click",jn)}};if((((Kc=n==null?void 0:n.debugTools)!=null?Kc:!1)||!!o.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:Zt,getMessages:Zt.getMessages,getStatus:Zt.getStatus,getMetadata:Zt.getPersistentMetadata,updateMetadata:Zt.updatePersistentMetadata,clearHistory:()=>Zt.clearChat(),setVoiceActive:h=>h?Zt.startVoiceRecognition():Zt.stopVoiceRecognition()};window.AgentWidgetBrowser=g,gt.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&Zt.focusInput()};if(window.addEventListener("persona:focusInput",g),gt.push(()=>{window.removeEventListener("persona:focusInput",g)}),ie){let z=Ae=>{let ue=Ae.detail;(!(ue!=null&&ue.instanceId)||ue.instanceId===c)&&Zt.showEventStream()},O=Ae=>{let ue=Ae.detail;(!(ue!=null&&ue.instanceId)||ue.instanceId===c)&&Zt.hideEventStream()};window.addEventListener("persona:showEventStream",z),window.addEventListener("persona:hideEventStream",O),gt.push(()=>{window.removeEventListener("persona:showEventStream",z),window.removeEventListener("persona:hideEventStream",O)})}let h=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&Zt.showArtifacts()},y=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&Zt.hideArtifacts()},P=z=>{let O=z.detail;O!=null&&O.instanceId&&O.instanceId!==c||O!=null&&O.artifact&&Zt.upsertArtifact(O.artifact)},N=z=>{let O=z.detail;O!=null&&O.instanceId&&O.instanceId!==c||typeof(O==null?void 0:O.id)=="string"&&Zt.selectArtifact(O.id)},V=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&Zt.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",P),window.addEventListener("persona:selectArtifact",N),window.addEventListener("persona:clearArtifacts",V),gt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",P),window.removeEventListener("persona:selectArtifact",N),window.removeEventListener("persona:clearArtifacts",V)})}let ao=ox(o.persistState);if(ao&&S()){let c=rx(ao.storage),g=`${ao.keyPrefix}widget-open`,h=`${ao.keyPrefix}widget-voice`,y=`${ao.keyPrefix}widget-voice-mode`;if(c){let P=((Gc=ao.persist)==null?void 0:Gc.openState)&&c.getItem(g)==="true",N=((Yc=ao.persist)==null?void 0:Yc.voiceState)&&c.getItem(h)==="true",V=((Xc=ao.persist)==null?void 0:Xc.voiceState)&&c.getItem(y)==="true";if(P&&setTimeout(()=>{Zt.open(),setTimeout(()=>{var z;if(N||V)Zt.startVoiceRecognition();else if((z=ao.persist)!=null&&z.focusInput){let O=e.querySelector("textarea");O&&O.focus()}},100)},0),(Qc=ao.persist)!=null&&Qc.openState&&(s.on("widget:opened",()=>{c.setItem(g,"true")}),s.on("widget:closed",()=>{c.setItem(g,"false")})),(Jc=ao.persist)!=null&&Jc.voiceState&&(s.on("voice:state",z=>{c.setItem(h,z.active?"true":"false")}),s.on("user:message",z=>{c.setItem(y,z.viaVoice?"true":"false")})),ao.clearOnChatClear){let z=()=>{c.removeItem(g),c.removeItem(h),c.removeItem(y)},O=()=>z();window.addEventListener("persona:clear-chat",O),gt.push(()=>{window.removeEventListener("persona:clear-chat",O)})}}}return p&&S()&&setTimeout(()=>{Zt.open()},0),Do(),Zt};var sx=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},Nm=(e,t)=>{var o,r;let n=(r=(o=t==null?void 0:t.launcher)==null?void 0:o.enabled)!=null?r:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},$l=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},_m=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",$l(e)},Nl=e=>{e.style.transition=""},_l=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform=""},Vl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Mi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},ax=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},ix=(e,t,n,o,r,s)=>{let a=s?t:e;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},Vm=(e,t,n,o,r,s,a)=>{var w,C,M,I,R,H;let i=Mo(s),d=i.reveal==="push";ax(e,t,n,o,d),ix(e,t,n,o,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,p=(C=(w=s==null?void 0:s.launcher)==null?void 0:w.mobileFullscreen)!=null?C:!0,m=(I=(M=s==null?void 0:s.launcher)==null?void 0:M.mobileBreakpoint)!=null?I:640,f=l!=null?l.innerWidth<=m:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),_l(t),Nl(o),_m(o),Vl(n),Mi(r,o),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String((H=(R=s==null?void 0:s.launcher)==null?void 0:R.zIndex)!=null?H:hn),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),_m(o),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",_l(t),Nl(o),Vl(n),Mi(r,o);let D=i.animate?"transform 180ms ease":"none",B=i.side==="right"?"translateX(100%)":"translateX(-100%)",v=a?"translateX(0)":B;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=D,o.style.transform=v,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",i.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Nl(o),$l(o),Mi(r,o);let D=sx(i.width,e.clientWidth),B=Math.max(0,e.clientWidth),v=i.animate?"transform 180ms ease":"none",x=i.side==="right"?a?`translateX(-${D}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${D}px)`;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${B+D}px`,t.style.transition=v,t.style.transform=x,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${B}px`,n.style.maxWidth=`${B}px`,n.style.minWidth=`${B}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.position="relative",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",_l(t),$l(o),Vl(n),Mi(r,o);let D=i.reveal==="emerge";D?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let B=a?i.width:"0px",v=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",x=!a;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${B}`,o.style.width=B,o.style.maxWidth=B,o.style.minWidth=B,o.style.minHeight="0",o.style.position="relative",o.style.overflow=D||x?"hidden":"visible",o.style.transition=v,D&&(o.style.alignItems=i.side==="right"?"flex-start":"flex-end",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.boxSizing="border-box")}},lx=(e,t)=>{let n=e.ownerDocument.createElement("div");return Nm(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Nm(n,o)},destroy(){n.remove()}}},cx=(e,t)=>{var R,H,D,B;let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),p=n.createElement("div"),m=(H=(R=t==null?void 0:t.launcher)==null?void 0:R.enabled)==null||H?(B=(D=t==null?void 0:t.launcher)==null?void 0:D.autoExpand)!=null?B:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",l.appendChild(p),o.insertBefore(a,e),d.appendChild(e);let f=null,u=()=>{f==null||f.disconnect(),f=null},w=()=>{u(),Mo(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Vm(a,i,d,l,p,t,m)}),f.observe(a))},C=()=>{Vm(a,i,d,l,p,t,m),w()},M=a.ownerDocument.defaultView,I=()=>{C()};return M==null||M.addEventListener("resize",I),Mo(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),C(),{mode:"docked",host:p,shell:a,syncWidgetState(v){let x=v.launcherEnabled?v.open:!0;m!==x&&(m=x,C())},updateConfig(v){var x,k;t=v,((k=(x=t==null?void 0:t.launcher)==null?void 0:x.enabled)!=null?k:!0)===!1&&(m=!0),C()},destroy(){M==null||M.removeEventListener("resize",I),u(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},$m=(e,t)=>pn(t)?cx(e,t):lx(e,t);var ts={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Ul=.15,zl=1.5,Li="persona-preview-shell-theme",Um={load:()=>null,save:()=>{},clear:()=>{}},zm=["How do I get started?","Pricing & plans","Talk to support"];function Ii(e){return e.replace(/&/g,"&").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 ql(e){let t=qm(e);return`* { box-sizing: border-box; }
|
|
107
|
+
`}if(!y&&!c){let Dt="max-height: -moz-available !important; max-height: stretch !important;",jt=f?"":"padding-top: 1.25em !important;",Bn=f?"":`z-index: ${(Ut=(Ht=o.launcher)==null?void 0:Ht.zIndex)!=null?Ut:hn} !important;`;ye.style.cssText+=Dt+jt+Bn}R()};po(),$r(e,o),Ei(e,o),Mi(e,o);let ft=[];ft.push(()=>{document.removeEventListener("keydown",zo)});let Kt=null,Gt=null;ft.push(()=>{Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null}),_n&&ft.push(()=>{_n==null||_n.disconnect(),_n=null}),ft.push(()=>{wn==null||wn(),wn=null,Ro(),Wt&&(Wt.remove(),Wt=null),yt==null||yt.element.style.removeProperty("width"),yt==null||yt.element.style.removeProperty("maxWidth")}),ie&&ft.push(()=>{we!==null&&(cancelAnimationFrame(we),we=null),Se==null||Se.destroy(),Se=null,Y==null||Y.destroy(),Y=null,Q=null});let qn=null,Ko=()=>{qn&&(qn(),qn=null),o.colorScheme==="auto"&&(qn=ou(()=>{$r(e,o)}))};Ko(),ft.push(()=>{qn&&(qn(),qn=null)});let oo=(Vc=o.features)==null?void 0:Vc.streamAnimation;if(oo!=null&&oo.type&&oo.type!=="none"){let c=$s(oo.type,oo.plugins);c&&(ml(c,e),ft.push(()=>ju(e)))}let uo=fm(Et),jn=null,E,Kn=!1,mo=_u(),Po=new Map,So=new Map,as=0,fo=ai(),go=0,ho=null,Wo=!1,lr=!1,aa=4,is=24,ia=80,Pr=new Map,mt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ls=(Uc=($c=o.voiceRecognition)==null?void 0:$c.autoResume)!=null?Uc:!1,ro=c=>{s.emit("voice:state",{active:mt.active,source:c,timestamp:Date.now()})},Rn=()=>{p(c=>({...c,voiceState:{active:mt.active,timestamp:Date.now(),manuallyDeactivated:mt.manuallyDeactivated}}))},la=()=>{var y,P;if(((y=o.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=Nl(d.voiceState),f=!!c.active,h=Number((P=c.timestamp)!=null?P:0);mt.manuallyDeactivated=!!c.manuallyDeactivated,f&&Date.now()-h<nx&&setTimeout(()=>{var N,V;mt.active||(mt.manuallyDeactivated=!1,((V=(N=o.voiceRecognition)==null?void 0:N.provider)==null?void 0:V.type)==="runtype"?E.toggleVoice().then(()=>{mt.active=E.isVoiceActive(),ro("restore"),E.isVoiceActive()&&U()}):ur("restore"))},1e3)},ca=()=>E?Fm(E.getMessages()).filter(c=>!c.__skipPersist):[];function Wr(c){if(!(i!=null&&i.save))return;let h={messages:c?Fm(c):E?ca():[],metadata:d,artifacts:Vn.artifacts,selectedArtifactId:Vn.selectedId};try{let y=i.save(h);y instanceof Promise&&y.catch(P=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",P)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let Bo=null,da=()=>ye.querySelector("#persona-scroll-container")||G,cr=()=>{Bo!==null&&(cancelAnimationFrame(Bo),Bo=null),Wo=!1},cs=()=>{ho!==null&&(cancelAnimationFrame(ho),ho=null),lr=!1,cr()},Ho=()=>{if(!yn()||de){Tt.parentNode&&Tt.remove(),Tt.style.display="none";return}Tt.parentNode!==ce&&ce.appendChild(Tt),bt();let c=Ns(G)>0;Tt.style.display=fo.isFollowing()||!c?"none":""},ds=()=>{fo.pause()&&(cs(),Ho())},Go=()=>{fo.resume(),Ho()},Yo=(c=!1)=>{fo.isFollowing()&&(!c&&!Kn||(ho!==null&&(cancelAnimationFrame(ho),ho=null),lr=!0,ho=requestAnimationFrame(()=>{ho=null,lr=!1,fo.isFollowing()&&pa(da(),c?220:140)})))},pa=(c,f=500)=>{let h=c.scrollTop,y=Ns(c),P=y-h;if(Math.abs(P)<1){go=c.scrollTop;return}if(Math.abs(P)>=ia){cr(),Wo=!0,c.scrollTop=y,go=c.scrollTop,Wo=!1;return}cr();let N=performance.now();Wo=!0;let V=O=>1-Math.pow(1-O,3),z=O=>{if(!fo.isFollowing()){cr();return}let Ae=Ns(c);Ae!==y&&(y=Ae,P=y-h);let ue=O-N,Z=Math.min(ue/f,1),he=V(Z),Ee=h+P*he;c.scrollTop=Ee,go=c.scrollTop,Z<1?Bo=requestAnimationFrame(z):(c.scrollTop=y,go=c.scrollTop,Bo=null,Wo=!1)};Bo=requestAnimationFrame(z)},ua=c=>{let f=new Map;c.forEach(h=>{let y=Pr.get(h.id);f.set(h.id,{streaming:h.streaming,role:h.role}),!y&&h.role==="assistant"&&s.emit("assistant:message",h),h.role==="assistant"&&(y!=null&&y.streaming)&&h.streaming===!1&&s.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(y?h.approval.status!=="pending"&&s.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):s.emit("approval:requested",{approval:h.approval,message:h}))}),Pr.clear(),f.forEach((h,y)=>{Pr.set(y,h)})},dr=(c,f,h)=>{var Xe,at,it,Pe,Re,je;let y=document.createElement("div"),N=(()=>{var Me;let R=r.find(Be=>Be.renderLoadingIndicator);if(R!=null&&R.renderLoadingIndicator)return R.renderLoadingIndicator;if((Me=o.loadingIndicator)!=null&&Me.render)return o.loadingIndicator.render})(),V=(R,Me)=>Me==null?!1:typeof Me=="string"?(R.textContent=Me,!0):(R.appendChild(Me),!0),z=new Set,O=new Set,Ae=r.some(R=>R.renderAskUserQuestion),ue=[],Z=[],he=o.enableComponentStreaming!==!1;if(f.forEach(R=>{var An,dn,Je,lt,Tn,mn,mr,fr,gr,Nr,_r,qt,hr,nr;z.add(R.id);let Me=Ae&&Tr(R),Be=!Me&&R.role==="assistant"&&!R.variant&&he&&Wm(R);if(!Be&&So.has(R.id)){let ht=c.querySelector(`#wrapper-${R.id}`);ht==null||ht.removeAttribute("data-preserve-runtime"),So.delete(R.id)}let Ge=Tr(R)?`:${(An=R.agentMetadata)!=null&&An.askUserQuestionAnswered?"a":"u"}:${(dn=R.agentMetadata)!=null&&dn.askUserQuestionAnswers?Object.keys(R.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ce=Nu(R,as)+Ge,Lt=Me||Be?null:Vu(mo,R.id,Ce);if(Lt){y.appendChild(Lt.cloneNode(!0)),Tr(R)&&((Je=R.toolCall)!=null&&Je.id)&&((lt=R.agentMetadata)==null?void 0:lt.awaitingLocalTool)===!0&&!((Tn=R.agentMetadata)!=null&&Tn.askUserQuestionAnswered)&&(O.add(R.toolCall.id),Ai(R,o,He.composerOverlay));return}let st=null,Xt=r.find(ht=>!!(R.variant==="reasoning"&&ht.renderReasoning||R.variant==="tool"&&ht.renderToolCall||R.variant==="approval"&&ht.renderApproval||!R.variant&&ht.renderMessage)),cn=(mn=o.layout)==null?void 0:mn.messages;if(Tr(R)&&((mr=R.agentMetadata)==null?void 0:mr.askUserQuestionAnswered)===!0){Po.delete(R.id);let ht=c.querySelector(`#wrapper-${R.id}`);ht==null||ht.removeAttribute("data-preserve-runtime");return}if(Tr(R)&&((gr=(fr=o.features)==null?void 0:fr.askUserQuestion)==null?void 0:gr.enabled)!==!1){let ht=r.find(Pn=>typeof Pn.renderAskUserQuestion=="function");if(ht&&It.current){let Pn=Po.get(R.id),Oo=Pn!==Ce,kn=null;if(Oo){let{payload:Ut,complete:Dt}=Qr(R),jt=R.id,Bn=()=>{var Yn;return(Yn=It.current)==null?void 0:Yn.getMessages().find(en=>en.id===jt)};kn=ht.renderAskUserQuestion({message:R,payload:Ut,complete:Dt,resolve:Yn=>{var To;let en=Bn();en&&((To=It.current)==null||To.resolveAskUserQuestion(en,Yn))},dismiss:()=>{var en,To,No;let Yn=Bn();(en=Yn==null?void 0:Yn.agentMetadata)!=null&&en.awaitingLocalTool&&((To=It.current)==null||To.markAskUserQuestionResolved(Yn),(No=It.current)==null||No.resolveAskUserQuestion(Yn,"(dismissed)"))},config:o})}let Wn=Pn!=null;if(Oo&&kn===null&&!Wn){((Nr=R.agentMetadata)==null?void 0:Nr.awaitingLocalTool)===!0&&!((_r=R.agentMetadata)!=null&&_r.askUserQuestionAnswered)&&(O.add(R.toolCall.id),Ai(R,o,He.composerOverlay));return}let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${R.id}`,Ht.setAttribute("data-wrapper-id",R.id),Ht.setAttribute("data-ask-plugin-stub","true"),Ht.setAttribute("data-preserve-runtime","true"),y.appendChild(Ht),ue.push({messageId:R.id,fingerprint:Ce,bubble:kn});return}else{((qt=R.agentMetadata)==null?void 0:qt.awaitingLocalTool)===!0&&!((hr=R.agentMetadata)!=null&&hr.askUserQuestionAnswered)&&(O.add(R.toolCall.id),Ai(R,o,He.composerOverlay));return}}else if(Xt)if(R.variant==="reasoning"&&R.reasoning&&Xt.renderReasoning){if(!se)return;st=Xt.renderReasoning({message:R,defaultRenderer:()=>xl(R,o),config:o})}else if(R.variant==="tool"&&R.toolCall&&Xt.renderToolCall){if(!fe)return;st=Xt.renderToolCall({message:R,defaultRenderer:()=>wl(R,o),config:o})}else if(R.variant==="approval"&&R.approval&&Xt.renderApproval){if(o.approval===!1)return;st=Xt.renderApproval({message:R,defaultRenderer:()=>Ll(R,o),config:o})}else Xt.renderMessage&&(st=Xt.renderMessage({message:R,defaultRenderer:()=>{let ht=vl(R,h,cn,o.messageActions,te,{loadingIndicatorRenderer:N,widgetConfig:o});return R.role!=="user"&&Wl(ht,R,o,E),ht},config:o}));if(!st&&Be){let ht=Bm(R);if(ht){let Pn=So.get(R.id),Oo=Pn!==Ce,kn=o.wrapComponentDirectiveInBubble!==!1,Wn=null;if(Oo){let Ht=Rm(ht,{config:o,message:R,transform:h});if(Ht)if(kn){let Ut=document.createElement("div");if(Ut.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ut.id=`bubble-${R.id}`,Ut.setAttribute("data-message-id",R.id),R.content&&R.content.trim()){let Dt=document.createElement("div");Dt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Dt.innerHTML=h({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),Ut.appendChild(Dt)}Ut.appendChild(Ht),Wn=Ut}else{let Ut=document.createElement("div");if(Ut.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ut.id=`bubble-${R.id}`,Ut.setAttribute("data-message-id",R.id),Ut.setAttribute("data-persona-component-directive","true"),R.content&&R.content.trim()){let Dt=document.createElement("div");Dt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Dt.innerHTML=h({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),Ut.appendChild(Dt)}Ut.appendChild(Ht),Wn=Ut}}if(Wn||Pn!=null){let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${R.id}`,Ht.setAttribute("data-wrapper-id",R.id),Ht.setAttribute("data-component-directive-stub","true"),Ht.setAttribute("data-preserve-runtime","true"),kn||Ht.classList.add("persona-w-full"),y.appendChild(Ht),Z.push({messageId:R.id,fingerprint:Ce,bubble:Wn});return}}}if(!st)if(R.variant==="reasoning"&&R.reasoning){if(!se)return;st=xl(R,o)}else if(R.variant==="tool"&&R.toolCall){if(!fe)return;st=wl(R,o)}else if(R.variant==="approval"&&R.approval){if(o.approval===!1)return;st=Ll(R,o)}else{let ht=(nr=o.layout)==null?void 0:nr.messages;ht!=null&&ht.renderUserMessage&&R.role==="user"?st=ht.renderUserMessage({message:R,config:o,streaming:!!R.streaming}):ht!=null&&ht.renderAssistantMessage&&R.role==="assistant"?st=ht.renderAssistantMessage({message:R,config:o,streaming:!!R.streaming}):st=vl(R,h,ht,o.messageActions,te,{loadingIndicatorRenderer:N,widgetConfig:o}),R.role!=="user"&&st&&Wl(st,R,o,E)}let Pt=document.createElement("div");Pt.className="persona-flex",Pt.id=`wrapper-${R.id}`,Pt.setAttribute("data-wrapper-id",R.id),R.role==="user"&&Pt.classList.add("persona-justify-end"),(st==null?void 0:st.getAttribute("data-persona-component-directive"))==="true"&&Pt.classList.add("persona-w-full"),Pt.appendChild(st),$u(mo,R.id,Ce,Pt),y.appendChild(Pt)}),He.composerOverlay&&He.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Me=>{let Be=Me.getAttribute("data-persona-ask-sheet-for");Be&&!O.has(Be)&&Zr(He.composerOverlay,Be)}),(at=(Xe=o.features)==null?void 0:Xe.toolCallDisplay)!=null&&at.grouped){let R=[],Me=[];f.forEach(Be=>{if(Be.variant==="tool"&&Be.toolCall&&fe){Me.push(Be);return}Me.length>1&&R.push(Me),Me=[]}),Me.length>1&&R.push(Me),R.forEach((Be,Ge)=>{var dn,Je;let Ce=Be.map(lt=>Array.from(y.children).find(Tn=>Tn instanceof HTMLElement&&Tn.getAttribute("data-wrapper-id")===lt.id)).filter(lt=>!!lt);if(Ce.length<2)return;let Lt=document.createElement("div");Lt.className="persona-flex",Lt.id=`wrapper-tool-group-${Ge}-${Be[0].id}`,Lt.setAttribute("data-wrapper-id",`tool-group-${Ge}-${Be[0].id}`);let st=document.createElement("div");st.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",st.setAttribute("data-persona-tool-group","true");let Xt=document.createElement("div");Xt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let cn=`Called ${Be.length} tools`,Pt=(Je=(dn=o.toolCall)==null?void 0:dn.renderGroupedSummary)==null?void 0:Je.call(dn,{messages:Be,toolCalls:Be.map(lt=>lt.toolCall).filter(lt=>!!lt),defaultSummary:cn,config:o});V(Xt,Pt)||(Xt.textContent=cn);let An=document.createElement("div");An.className="persona-tool-group-stack persona-flex persona-flex-col",st.append(Xt,An),Lt.appendChild(st),Ce[0].before(Lt),Ce.forEach((lt,Tn)=>{let mn=document.createElement("div");mn.className="persona-tool-group-item persona-relative",mn.setAttribute("data-persona-tool-group-item","true"),Tn<Ce.length-1&&mn.setAttribute("data-persona-tool-group-connector","true"),mn.appendChild(lt),An.appendChild(mn)})})}Uu(mo,z);let Ee=f.some(R=>R.role==="assistant"&&R.streaming),Ne=f[f.length-1],tt=(Ne==null?void 0:Ne.role)==="assistant"&&!Ne.streaming&&Ne.variant!=="approval";if(Kn&&f.some(R=>R.role==="user")&&!Ee&&!tt){let R={config:o,streaming:!0,location:"standalone",defaultRenderer:Ys},Me=r.find(Ge=>Ge.renderLoadingIndicator),Be=null;if(Me!=null&&Me.renderLoadingIndicator&&(Be=Me.renderLoadingIndicator(R)),Be===null&&((it=o.loadingIndicator)!=null&&it.render)&&(Be=o.loadingIndicator.render(R)),Be===null&&(Be=Ys()),Be){let Ge=document.createElement("div"),Ce=((Pe=o.loadingIndicator)==null?void 0:Pe.showBubble)!==!1;Ge.className=Ce?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ge.setAttribute("data-typing-indicator","true"),Ge.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ge.appendChild(Be);let Lt=document.createElement("div");Lt.className="persona-flex",Lt.id="wrapper-typing-indicator",Lt.setAttribute("data-wrapper-id","typing-indicator"),Lt.appendChild(Ge),y.appendChild(Lt)}}if(!Kn&&f.length>0){let R=f[f.length-1],Me={config:o,lastMessage:R,messageCount:f.length},Be=r.find(Ce=>Ce.renderIdleIndicator),Ge=null;if(Be!=null&&Be.renderIdleIndicator&&(Ge=Be.renderIdleIndicator(Me)),Ge===null&&((Re=o.loadingIndicator)!=null&&Re.renderIdle)&&(Ge=o.loadingIndicator.renderIdle(Me)),Ge){let Ce=document.createElement("div"),Lt=((je=o.loadingIndicator)==null?void 0:je.showBubble)!==!1;Ce.className=Lt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ce.setAttribute("data-idle-indicator","true"),Ce.appendChild(Ge);let st=document.createElement("div");st.className="persona-flex",st.id="wrapper-idle-indicator",st.setAttribute("data-wrapper-id","idle-indicator"),st.appendChild(Ce),y.appendChild(st)}}if(ri(c,y),ue.length>0)for(let{messageId:R,fingerprint:Me,bubble:Be}of ue){let Ge=c.querySelector(`#wrapper-${R}`);Ge&&Be!==null&&(Ge.replaceChildren(Be),Ge.setAttribute("data-bubble-fp",Me),Po.set(R,Me))}if(Po.size>0)for(let R of Po.keys())z.has(R)||Po.delete(R);if(Z.length>0)for(let{messageId:R,fingerprint:Me,bubble:Be}of Z){let Ge=c.querySelector(`#wrapper-${R}`);Ge&&Be!==null&&(Ge.replaceChildren(Be),Ge.setAttribute("data-bubble-fp",Me),So.set(R,Me))}if(So.size>0)for(let R of So.keys())z.has(R)||So.delete(R)},Xo=null,ma=()=>{var h;if(Xo)return;let c=y=>{let P=y.composedPath();P.includes(ye)||Ue&&P.includes(Ue)||Bt(!1,"user")};Xo=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},ps=()=>{var f;if(!Xo)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("pointerdown",Xo,!0),Xo=null};ft.push(()=>ps());let Qo=null,fa=()=>{var h;if(Qo)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Bt(!1,"user"))};Qo=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},us=()=>{var f;if(!Qo)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("keydown",Qo,!0),Qo=null};ft.push(()=>us());let Jo=!1,ms=new Set,ga=()=>{var f,h,y,P;let c=(y=(h=(f=o.launcher)==null?void 0:f.composerBar)==null?void 0:h.peek)==null?void 0:y.streamAnimation;return c||((P=o.features)==null?void 0:P.streamAnimation)},Do=()=>{var at,it,Pe,Re;if(!k())return;let c=He.peekBanner,f=He.peekTextNode;if(!c||!f)return;if(T){c.classList.remove("persona-pill-peek--visible");return}let h=(at=E==null?void 0:E.getMessages())!=null?at:[],y;for(let je=h.length-1;je>=0;je--){let R=h[je];if(R.role==="assistant"&&R.content){y=R;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let P=y.content,N=!!y.streaming,V=ga(),z=ci(V),O=z.type!=="none"?$s(z.type,V==null?void 0:V.plugins):null,Ae=((it=O==null?void 0:O.isAnimating)==null?void 0:it.call(O,y))===!0,ue=O!==null&&(N||Ae);ue&&O&&!ms.has(O.name)&&(ml(O,e),ms.add(O.name));let Z=ue&&(O!=null&&O.containerClass)?O.containerClass:null,he=(Pe=f.dataset.personaPeekStreamClass)!=null?Pe:null;he&&he!==Z&&(f.classList.remove(he),delete f.dataset.personaPeekStreamClass),Z&&he!==Z&&(f.classList.add(Z),f.dataset.personaPeekStreamClass=Z),ue?(f.style.setProperty("--persona-stream-step",`${z.speed}ms`),f.style.setProperty("--persona-stream-duration",`${z.duration}ms`)):(f.style.removeProperty("--persona-stream-step"),f.style.removeProperty("--persona-stream-duration"));let Ee=ue?di(P,z.buffer,O,y,N):P;if(ue&&z.placeholder==="skeleton"&&N&&(!Ee||!Ee.trim())){let je=document.createElement("div"),R=zs();R.classList.add("persona-pill-peek__skeleton"),je.appendChild(R),ri(f,je)}else{let je=Math.max(0,Ee.length-100),R=Ee.length>100?Ee.slice(-100):Ee,Me=Is(R);if(!ue||!O){let Be=Ee.length>100?`\u2026${R}`:R;f.textContent!==Be&&(f.textContent=Be)}else{let Be=Me;(O.wrap==="char"||O.wrap==="word")&&(Be=Us(Me,O.wrap,`peek-${y.id}`,{skipTags:O.skipTags,startIndex:je}));let Ge=document.createElement("div");if(Ge.innerHTML=Be,O.useCaret&&R.length>0){let Ce=pi(),Lt=Ge.querySelectorAll(".persona-stream-char, .persona-stream-word"),st=Lt[Lt.length-1];st!=null&&st.parentNode?st.parentNode.insertBefore(Ce,st.nextSibling):Ge.appendChild(Ce)}ri(f,Ge),(Re=O.onAfterRender)==null||Re.call(O,{container:f,bubble:c,messageId:y.id,message:y,speed:z.speed,duration:z.duration})}}let Xe=Kn||Jo;c.classList.toggle("persona-pill-peek--visible",Xe)};if(k()){let c=He.peekBanner;if(c){let y=P=>{P.preventDefault(),P.stopPropagation(),Bt(!0,"user")};c.addEventListener("pointerdown",y),ft.push(()=>{c.removeEventListener("pointerdown",y)})}let f=()=>{Jo||(Jo=!0,Do())},h=()=>{Jo&&(Jo=!1,Do())};le.addEventListener("pointerenter",f),le.addEventListener("pointerleave",h),ft.push(()=>{le.removeEventListener("pointerenter",f),le.removeEventListener("pointerleave",h)}),Ue&&(Ue.addEventListener("pointerenter",f),Ue.addEventListener("pointerleave",h),ft.push(()=>{Ue.removeEventListener("pointerenter",f),Ue.removeEventListener("pointerleave",h)}))}let ha=c=>{var he,Ee,Ne,tt,Xe,at,it,Pe;let f=(Ee=(he=o.launcher)==null?void 0:he.composerBar)!=null?Ee:{},h=(Ne=f.expandedSize)!=null?Ne:"anchored",y=(tt=f.bottomOffset)!=null?tt:"16px",P=f.collapsedMaxWidth,N=(Xe=f.expandedMaxWidth)!=null?Xe:"880px",V=(at=f.expandedTopOffset)!=null?at:"5vh",z=(it=f.modalMaxWidth)!=null?it:"880px",O=(Pe=f.modalMaxHeight)!=null?Pe:"min(90vh, 800px)",Ae="calc(100vw - 32px)",ue="var(--persona-pill-area-height, 80px)",Z=ye.style;if(Z.left="",Z.right="",Z.top="",Z.bottom="",Z.transform="",Z.width="",Z.maxWidth="",Z.height="",Z.maxHeight="",Ue){let Re=Ue.style;Re.bottom=y,Re.width=P!=null?P:""}if(c&&h!=="fullscreen"){if(h==="modal"){Z.top="50%",Z.left="50%",Z.transform="translate(-50%, -50%)",Z.bottom="auto",Z.right="auto",Z.width=z,Z.maxWidth=Ae,Z.maxHeight=O,Z.height=O;return}Z.left="50%",Z.transform="translateX(-50%)",Z.bottom=`calc(${y} + ${ue})`,Z.top=V,Z.width=N,Z.maxWidth=Ae}},Zo=()=>{var O,Ae,ue,Z,he,Ee,Ne,tt;if(!C())return;if(k()){let at=(ue=((Ae=(O=o.launcher)==null?void 0:O.composerBar)!=null?Ae:{}).expandedSize)!=null?ue:"anchored",it=T?"expanded":"collapsed";ye.dataset.state=it,ye.dataset.expandedSize=at,Ue&&(Ue.dataset.state=it,Ue.dataset.expandedSize=at),ye.style.removeProperty("display"),ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ha(T),ce.style.display=T?"flex":"none",po(),T?(ma(),fa()):(ps(),us()),Do();return}let c=pn(o),f=(Z=e.ownerDocument.defaultView)!=null?Z:window,h=(Ee=(he=o.launcher)==null?void 0:he.mobileBreakpoint)!=null?Ee:640,y=(tt=(Ne=o.launcher)==null?void 0:Ne.mobileFullscreen)!=null?tt:!0,P=f.innerWidth<=h,N=y&&P&&I,V=Mo(o).reveal;T?(ye.style.removeProperty("display"),ye.style.display=c?"flex":"",ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-95","persona-opacity-0"),le.classList.add("persona-scale-100","persona-opacity-100"),Ie?Ie.element.style.display="none":Ye&&(Ye.style.display="none")):(c?c&&(V==="overlay"||V==="push")&&!N?(ye.style.removeProperty("display"),ye.style.display="flex",ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ye.style.setProperty("display","none","important"),ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ye.style.display="",ye.classList.add("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100"),le.classList.add("persona-scale-95","persona-opacity-0")),Ie?Ie.element.style.display=c?"none":"":Ye&&(Ye.style.display=c?"none":""))},Bt=(c,f="user")=>{var N,V;if(!C()||T===c)return;let h=T;T=c,Zo();let y=(()=>{var Ne,tt,Xe,at,it,Pe,Re,je,R,Me;let z=(tt=(Ne=o.launcher)==null?void 0:Ne.sidebarMode)!=null?tt:!1,O=(Xe=e.ownerDocument.defaultView)!=null?Xe:window,Ae=(it=(at=o.launcher)==null?void 0:at.mobileFullscreen)!=null?it:!0,ue=(Re=(Pe=o.launcher)==null?void 0:Pe.mobileBreakpoint)!=null?Re:640,Z=O.innerWidth<=ue,he=pn(o)&&Ae&&Z,Ee=k()&&((Me=(R=(je=o.launcher)==null?void 0:je.composerBar)==null?void 0:R.expandedSize)!=null?Me:"fullscreen")==="fullscreen";return z||Ae&&Z&&I||he||Ee})();if(T&&y){if(!Kt){let z=e.getRootNode(),O=z instanceof ShadowRoot?z.host:e.closest(".persona-host");O&&(Kt=fl(O,(V=(N=o.launcher)==null?void 0:N.zIndex)!=null?V:hn))}Gt||(Gt=gl(e.ownerDocument))}else T||(Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null);T&&(Rt(),Yo(!0));let P={open:T,source:f,timestamp:Date.now()};T&&!h?s.emit("widget:opened",P):!T&&h&&s.emit("widget:closed",P),s.emit("widget:state",{open:T,launcherEnabled:I,voiceActive:mt.active,streaming:E.isStreaming()})},Br=c=>{Vt(c?"stop":"send"),q&&(q.disabled=c),uo.buttons.forEach(f=>{f.disabled=c}),$e.dataset.personaComposerStreaming=c?"true":"false",$e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=c)})},Hr=()=>{mt.active||pe&&pe.focus()};s.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Hr(),200)});let fs=()=>{var h,y,P,N,V,z,O,Ae,ue,Z,he;Dn.textContent=(y=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",Jn.textContent=(N=(P=o.copy)==null?void 0:P.welcomeSubtitle)!=null?N:"Ask anything about your account or products.",pe.placeholder=(z=(V=o.copy)==null?void 0:V.inputPlaceholder)!=null?z:"How can I help...";let c=G.querySelector("[data-persona-intro-card]");if(c){let Ee=((O=o.copy)==null?void 0:O.showWelcomeCard)!==!1;c.style.display=Ee?"":"none",Ee?(G.classList.remove("persona-gap-3"),G.classList.add("persona-gap-6")):(G.classList.remove("persona-gap-6"),G.classList.add("persona-gap-3"))}!((ue=(Ae=o.sendButton)==null?void 0:Ae.useIcon)!=null&&ue)&&!(E!=null&&E.isStreaming())&&(ae.textContent=(he=(Z=o.copy)==null?void 0:Z.sendButtonLabel)!=null?he:"Send"),pe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',pe.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{p(f=>({...f,sessionId:c}))}});let Ao=null,ba=()=>{Ao==null&&(Ao=setInterval(()=>{let c=Ve.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Ao),Ao=null;return}let f=Date.now();c.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=ja(f-y))})},100))};if(E=new ni(o,{onMessagesChanged(c){dr(Ve,c,me),ba(),E&&(c.some(P=>P.role==="user")?uo.render([],E,pe,c):uo.render(o.suggestionChips,E,pe,c,o.suggestionChipsConfig)),Yo(!Kn),ua(c);let f=[...c].reverse().find(y=>y.role==="user"),h=mt.lastUserMessageId;f&&f.id!==h&&(mt.lastUserMessageId=f.id,s.emit("user:message",f)),mt.lastUserMessageWasVoice=!!(f!=null&&f.viaVoice),Wr(c),Do()},onStatusChanged(c){var y;let f=(y=o.statusIndicator)!=null?y:{};nt(ln,(P=>{var N,V,z,O;return P==="idle"?(N=f.idleText)!=null?N:gn.idle:P==="connecting"?(V=f.connectingText)!=null?V:gn.connecting:P==="connected"?(z=f.connectedText)!=null?z:gn.connected:P==="error"?(O=f.errorText)!=null?O:gn.error:gn[P]})(c),f,c)},onStreamingChanged(c){Kn=c,Br(c),E&&dr(Ve,E.getMessages(),me),c||Yo(!0),Do()},onVoiceStatusChanged(c){var f,h;if(((h=(f=o.voiceRecognition)==null?void 0:f.provider)==null?void 0:h.type)==="runtype")switch(c){case"listening":break;case"processing":ee(),B();break;case"speaking":ee(),J();break;default:c==="idle"&&E.isBargeInActive()?(ee(),U(),q==null||q.setAttribute("aria-label","End voice session")):(mt.active=!1,ee(),ro("system"),Rn());break}},onArtifactsState(c){Vn=c,zn(),Wr()}}),It.current=E,((qc=(zc=o.voiceRecognition)==null?void 0:zc.provider)==null?void 0:qc.type)==="runtype")try{E.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}o.clientToken&&E.initClientSession().catch(c=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(Y||o.onSSEEvent)&&E.setSSEEventCallback((c,f)=>{var h;(h=o.onSSEEvent)==null||h.call(o,c,f),xe==null||xe.processEvent(c,f),Y==null||Y.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(f)})}),l&&l.then(c=>{var f,h,y;c&&(c.metadata&&(d=Nl(c.metadata),M.syncFromMetadata()),(f=c.messages)!=null&&f.length&&E.hydrateMessages(c.messages),(h=c.artifacts)!=null&&h.length&&E.hydrateArtifacts(c.artifacts,(y=c.selectedArtifactId)!=null?y:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let gs=()=>{var f,h,y;!k()||T||!((y=(h=(f=o.launcher)==null?void 0:f.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||Bt(!0,"auto")},hs=c=>{var P;if(c.preventDefault(),E.isStreaming()){E.cancel(),xe==null||xe.reset(),Se==null||Se.update();return}let f=pe.value.trim(),h=(P=et==null?void 0:et.hasAttachments())!=null?P:!1;if(!f&&!h)return;gs();let y;h&&(y=[],y.push(...et.getContentParts()),f&&y.push(cl(f))),pe.value="",pe.style.height="auto",pr(),E.sendMessage(f,{contentParts:y}),h&&et.clearAttachments()},ya=()=>{var c;return((c=o.features)==null?void 0:c.composerHistory)!==!1},Dr={...si},Fr=!1,pr=()=>{Dr={...si}},va=()=>E.getMessages().filter(c=>c.role==="user").map(c=>{var f;return(f=c.content)!=null?f:""}).filter(c=>c.length>0),xa=c=>{if(!pe)return;Fr=!0,pe.value=c,pe.dispatchEvent(new Event("input",{bubbles:!0})),Fr=!1;let f=pe.value.length;pe.setSelectionRange(f,f)},bs=()=>{Fr||pr()},ys=c=>{if(pe){if(ya()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let f=pe.selectionStart===0&&pe.selectionEnd===0,h=Ou({direction:c.key==="ArrowUp"?"up":"down",history:va(),currentValue:pe.value,atStart:f,state:Dr});if(Dr=h.state,h.handled){c.preventDefault(),h.value!==void 0&&xa(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(E.isStreaming()){c.preventDefault();return}pr(),c.preventDefault(),ae.click()}}},vs=c=>{c.key!=="Escape"||c.isComposing||E.isStreaming()&&c.composedPath().includes(ce)&&(E.cancel(),xe==null||xe.reset(),Se==null||Se.update(),pr(),c.preventDefault(),c.stopImmediatePropagation())},xs=async c=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!et)return;let f=rx(c.clipboardData);f.length!==0&&(c.preventDefault(),await et.handleFiles(f))},Cn=null,Gn=!1,Fo=null,rt=null,ws=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ur=(c="user")=>{var N,V,z,O,Ae,ue,Z;if(Gn||E.isStreaming())return;let f=ws();if(!f)return;Cn=new f;let y=(V=((N=o.voiceRecognition)!=null?N:{}).pauseDuration)!=null?V:2e3;Cn.continuous=!0,Cn.interimResults=!0,Cn.lang="en-US";let P=pe.value;Cn.onresult=he=>{let Ee="",Ne="";for(let Xe=0;Xe<he.results.length;Xe++){let at=he.results[Xe],it=at[0].transcript;at.isFinal?Ee+=it+" ":Ne=it}let tt=P+Ee+Ne;pe.value=tt,Fo&&clearTimeout(Fo),(Ee||Ne)&&(Fo=window.setTimeout(()=>{let Xe=pe.value.trim();Xe&&Cn&&Gn&&(bo(),pe.value="",pe.style.height="auto",E.sendMessage(Xe,{viaVoice:!0}))},y))},Cn.onerror=he=>{he.error!=="no-speech"&&bo()},Cn.onend=()=>{if(Gn){let he=pe.value.trim();he&&he!==P.trim()&&(pe.value="",pe.style.height="auto",E.sendMessage(he,{viaVoice:!0})),bo()}};try{if(Cn.start(),Gn=!0,mt.active=!0,c!=="system"&&(mt.manuallyDeactivated=!1),ro(c),Rn(),q){let he=(z=o.voiceRecognition)!=null?z:{};rt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(O=he.iconName)!=null?O:"mic",iconSize:parseFloat((Z=(ue=he.iconSize)!=null?ue:(Ae=o.sendButton)==null?void 0:Ae.size)!=null?Z:"40")||24};let Ee=he.recordingBackgroundColor,Ne=he.recordingIconColor,tt=he.recordingBorderColor;if(q.classList.add("persona-voice-recording"),q.style.backgroundColor=Ee!=null?Ee:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=Ne!=null?Ne:"var(--persona-voice-recording-indicator, #ffffff)",Ne){let Xe=q.querySelector("svg");Xe&&Xe.setAttribute("stroke",Ne)}tt&&(q.style.borderColor=tt),q.setAttribute("aria-label","Stop voice recognition")}}catch{bo("system")}},bo=(c="user")=>{if(Gn){if(Gn=!1,Fo&&(clearTimeout(Fo),Fo=null),Cn){try{Cn.stop()}catch{}Cn=null}if(mt.active=!1,ro(c),Rn(),q){if(q.classList.remove("persona-voice-recording"),rt){q.style.backgroundColor=rt.backgroundColor,q.style.color=rt.color,q.style.borderColor=rt.borderColor;let f=q.querySelector("svg");f&&f.setAttribute("stroke",rt.color||"currentColor"),rt=null}q.setAttribute("aria-label","Start voice recognition")}}},wa=(c,f)=>{var at,it,Pe,Re,je,R,Me,Be;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((at=c==null?void 0:c.provider)==null?void 0:at.type)==="runtype";if(!(h||y))return null;let N=b("div","persona-send-button-wrapper"),V=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");V.type="button",V.setAttribute("aria-label","Start voice recognition");let z=(it=c==null?void 0:c.iconName)!=null?it:"mic",O=(Pe=f==null?void 0:f.size)!=null?Pe:"40px",Ae=(Re=c==null?void 0:c.iconSize)!=null?Re:O,ue=parseFloat(Ae)||24,Z=(je=c==null?void 0:c.backgroundColor)!=null?je:f==null?void 0:f.backgroundColor,he=(R=c==null?void 0:c.iconColor)!=null?R:f==null?void 0:f.textColor;V.style.width=Ae,V.style.height=Ae,V.style.minWidth=Ae,V.style.minHeight=Ae,V.style.fontSize="18px",V.style.lineHeight="1",he?V.style.color=he:V.style.color="var(--persona-text, #111827)";let Ne=Te(z,ue,he||"currentColor",1.5);Ne?V.appendChild(Ne):V.textContent="\u{1F3A4}",Z?V.style.backgroundColor=Z:V.style.backgroundColor="",c!=null&&c.borderWidth&&(V.style.borderWidth=c.borderWidth,V.style.borderStyle="solid"),c!=null&&c.borderColor&&(V.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(V.style.paddingLeft=c.paddingX,V.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(V.style.paddingTop=c.paddingY,V.style.paddingBottom=c.paddingY),N.appendChild(V);let tt=(Me=c==null?void 0:c.tooltipText)!=null?Me:"Start voice recognition";if(((Be=c==null?void 0:c.showTooltip)!=null?Be:!1)&&tt){let Ge=b("div","persona-send-button-tooltip");Ge.textContent=tt,N.appendChild(Ge)}return{micButton:V,micButtonWrapper:N}},er=()=>{var f,h,y,P,N;if(!q||rt)return;let c=(f=o.voiceRecognition)!=null?f:{};rt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(h=c.iconName)!=null?h:"mic",iconSize:parseFloat((N=(P=c.iconSize)!=null?P:(y=o.sendButton)==null?void 0:y.size)!=null?N:"40")||24}},Ke=(c,f)=>{var N,V,z,O,Ae;if(!q)return;let h=q.querySelector("svg");h&&h.remove();let y=(Ae=rt==null?void 0:rt.iconSize)!=null?Ae:parseFloat((O=(z=(N=o.voiceRecognition)==null?void 0:N.iconSize)!=null?z:(V=o.sendButton)==null?void 0:V.size)!=null?O:"40")||24,P=Te(c,y,f,1.5);P&&q.appendChild(P)},A=()=>{q&&q.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},U=()=>{var P;if(!q)return;er();let c=(P=o.voiceRecognition)!=null?P:{},f=c.recordingBackgroundColor,h=c.recordingIconColor,y=c.recordingBorderColor;if(A(),q.classList.add("persona-voice-recording"),q.style.backgroundColor=f!=null?f:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let N=q.querySelector("svg");N&&N.setAttribute("stroke",h)}y&&(q.style.borderColor=y),q.setAttribute("aria-label","Stop voice recognition")},B=()=>{var z,O,Ae,ue,Z,he,Ee,Ne;if(!q)return;er();let c=(z=o.voiceRecognition)!=null?z:{},f=E.getVoiceInterruptionMode(),h=(O=c.processingIconName)!=null?O:"loader",y=(ue=(Ae=c.processingIconColor)!=null?Ae:rt==null?void 0:rt.color)!=null?ue:"",P=(he=(Z=c.processingBackgroundColor)!=null?Z:rt==null?void 0:rt.backgroundColor)!=null?he:"",N=(Ne=(Ee=c.processingBorderColor)!=null?Ee:rt==null?void 0:rt.borderColor)!=null?Ne:"";A(),q.classList.add("persona-voice-processing"),q.style.backgroundColor=P,q.style.borderColor=N;let V=y||"currentColor";q.style.color=V,Ke(h,V),q.setAttribute("aria-label","Processing voice input"),f==="none"&&(q.style.cursor="default")},J=()=>{var Ae,ue,Z,he,Ee,Ne,tt,Xe,at,it,Pe,Re;if(!q)return;er();let c=(Ae=o.voiceRecognition)!=null?Ae:{},f=E.getVoiceInterruptionMode(),h=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",y=(ue=c.speakingIconName)!=null?ue:h,P=(Ne=c.speakingIconColor)!=null?Ne:f==="barge-in"?(he=(Z=c.recordingIconColor)!=null?Z:rt==null?void 0:rt.color)!=null?he:"":(Ee=rt==null?void 0:rt.color)!=null?Ee:"",N=(at=c.speakingBackgroundColor)!=null?at:f==="barge-in"?(tt=c.recordingBackgroundColor)!=null?tt:"var(--persona-voice-recording-bg, #ef4444)":(Xe=rt==null?void 0:rt.backgroundColor)!=null?Xe:"",V=(Re=c.speakingBorderColor)!=null?Re:f==="barge-in"?(it=c.recordingBorderColor)!=null?it:"":(Pe=rt==null?void 0:rt.borderColor)!=null?Pe:"";A(),q.classList.add("persona-voice-speaking"),q.style.backgroundColor=N,q.style.borderColor=V;let z=P||"currentColor";q.style.color=z,Ke(y,z);let O=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";q.setAttribute("aria-label",O),f==="none"&&(q.style.cursor="default"),f==="barge-in"&&q.classList.add("persona-voice-recording")},ee=()=>{var c,f,h;q&&(A(),rt&&(q.style.backgroundColor=(c=rt.backgroundColor)!=null?c:"",q.style.color=(f=rt.color)!=null?f:"",q.style.borderColor=(h=rt.borderColor)!=null?h:"",Ke(rt.iconName,rt.color||"currentColor"),rt=null),q.style.cursor="",q.setAttribute("aria-label","Start voice recognition"))},K=()=>{var c,f;if(((f=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"){let h=E.getVoiceStatus(),y=E.getVoiceInterruptionMode();if(y==="none"&&(h==="processing"||h==="speaking"))return;if(y==="cancel"&&(h==="processing"||h==="speaking")){E.stopVoicePlayback();return}if(E.isBargeInActive()){E.stopVoicePlayback(),E.deactivateBargeIn().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Rn(),ro("user"),ee()});return}E.toggleVoice().then(()=>{mt.active=E.isVoiceActive(),mt.manuallyDeactivated=!E.isVoiceActive(),Rn(),ro("user"),E.isVoiceActive()?U():ee()});return}if(Gn){let h=pe.value.trim();mt.manuallyDeactivated=!0,Rn(),bo("user"),h&&(pe.value="",pe.style.height="auto",E.sendMessage(h))}else mt.manuallyDeactivated=!1,Rn(),ur("user")};Fn=K,q&&(q.addEventListener("click",K),ft.push(()=>{var c,f;((f=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?(E.isVoiceActive()&&E.toggleVoice(),ee()):bo("system"),q&&q.removeEventListener("click",K)}));let We=s.on("assistant:complete",()=>{ls&&(mt.active||mt.manuallyDeactivated||ls==="assistant"&&!mt.lastUserMessageWasVoice||setTimeout(()=>{var c,f;!mt.active&&!mt.manuallyDeactivated&&(((f=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?E.toggleVoice().then(()=>{mt.active=E.isVoiceActive(),ro("auto"),E.isVoiceActive()&&U()}):ur("auto"))},600))});ft.push(We);let _e=s.on("action:resubmit",()=>{setTimeout(()=>{E&&!E.isStreaming()&&E.continueConversation()},100)});ft.push(_e);let Ze=()=>{Bt(!T,"user")},Ie=null,Ye=null;if(I&&!k()){let c=r.find(f=>f.renderLauncher);if(c!=null&&c.renderLauncher){let f=c.renderLauncher({config:o,defaultRenderer:()=>Ks(o,Ze).element,onToggle:Ze});f&&(Ye=f)}Ye||(Ie=Ks(o,Ze))}Ie?e.appendChild(Ie.element):Ye&&e.appendChild(Ye),Zo(),uo.render(o.suggestionChips,E,pe,void 0,o.suggestionChipsConfig),fs(),Br(E.isStreaming()),Yo(!0),la(),H&&(!I||k()?setTimeout(()=>Hr(),0):T&&setTimeout(()=>Hr(),200));let Rt=()=>{var O,Ae,ue,Z,he,Ee,Ne,tt,Xe,at,it,Pe,Re,je,R,Me,Be,Ge,Ce,Lt,st,Xt;if(k()){bt(),Zo();return}let c=pn(o),f=(Ae=(O=o.launcher)==null?void 0:O.sidebarMode)!=null?Ae:!1,h=c||f||((Z=(ue=o.launcher)==null?void 0:ue.fullHeight)!=null?Z:!1),y=(he=e.ownerDocument.defaultView)!=null?he:window,P=(Ne=(Ee=o.launcher)==null?void 0:Ee.mobileFullscreen)!=null?Ne:!0,N=(Xe=(tt=o.launcher)==null?void 0:tt.mobileBreakpoint)!=null?Xe:640,V=y.innerWidth<=N,z=P&&V&&I;try{if(z){po(),$r(e,o);return}if(x&&(x=!1,po(),$r(e,o)),!I&&!c){le.style.height="",le.style.width="";return}if(!f&&!c){let cn=(it=(at=o==null?void 0:o.launcher)==null?void 0:at.width)!=null?it:o==null?void 0:o.launcherWidth,Pt=cn!=null?cn:io;le.style.width=Pt,le.style.maxWidth=Pt}if(Co(),!h){let cn=y.innerHeight,Pt=64,An=(Re=(Pe=o.launcher)==null?void 0:Pe.heightOffset)!=null?Re:0,dn=Math.max(200,cn-Pt),Je=Math.min(640,dn),lt=Math.max(200,Je-An);le.style.height=`${lt}px`}}finally{if(bt(),Zo(),T&&I){let Pt=((je=e.ownerDocument.defaultView)!=null?je:window).innerWidth<=((Me=(R=o.launcher)==null?void 0:R.mobileBreakpoint)!=null?Me:640),An=(Ge=(Be=o.launcher)==null?void 0:Be.sidebarMode)!=null?Ge:!1,dn=(Lt=(Ce=o.launcher)==null?void 0:Ce.mobileFullscreen)!=null?Lt:!0,Je=pn(o)&&dn&&Pt,lt=An||dn&&Pt&&I||Je;if(lt&&!Gt){let Tn=e.getRootNode(),mn=Tn instanceof ShadowRoot?Tn.host:e.closest(".persona-host");mn&&!Kt&&(Kt=fl(mn,(Xt=(st=o.launcher)==null?void 0:st.zIndex)!=null?Xt:hn)),Gt=gl(e.ownerDocument)}else lt||(Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null)}}};Rt();let nn=(jc=e.ownerDocument.defaultView)!=null?jc:window;if(nn.addEventListener("resize",Rt),ft.push(()=>nn.removeEventListener("resize",Rt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{bt()});c.observe($e),ft.push(()=>c.disconnect())}go=G.scrollTop;let Ct=G.scrollHeight,Mt=()=>{let c=G.scrollTop,f=G.scrollHeight,h=f<Ct;Ct=f;let{action:y,nextLastScrollTop:P}=ii({following:fo.isFollowing(),currentScrollTop:c,lastScrollTop:go,nearBottom:_s(G,is),userScrollThreshold:aa,isAutoScrolling:Wo||lr||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(go=P,y==="resume"){Go();return}y==="pause"&&ds()};G.addEventListener("scroll",Mt,{passive:!0}),ft.push(()=>G.removeEventListener("scroll",Mt));let on=c=>{let f=li({following:fo.isFollowing(),deltaY:c.deltaY,nearBottom:_s(G,is),resumeWhenNearBottom:!0});f==="pause"?ds():f==="resume"&&Go()};G.addEventListener("wheel",on,{passive:!0}),ft.push(()=>G.removeEventListener("wheel",on)),Tt.addEventListener("click",()=>{G.scrollTop=G.scrollHeight,go=G.scrollTop,Go(),Yo(!0)}),ft.push(()=>Tt.remove()),ft.push(()=>{cs()});let un=()=>{qe&&(jn&&(qe.removeEventListener("click",jn),jn=null),C()?(qe.style.display="",jn=()=>{Bt(!1,"user")},qe.addEventListener("click",jn)):qe.style.display="none")};un(),(()=>{let{clearChatButton:c}=He;c&&c.addEventListener("click",()=>{E.clearMessages(),mo.clear(),Go(),Zr(He.composerOverlay);try{localStorage.removeItem(ts),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ts}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ts)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let f=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(f),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}d={},M.syncFromMetadata(),Y==null||Y.clear(),xe==null||xe.reset(),Se==null||Se.update()})})(),Nt&&Nt.addEventListener("submit",hs),pe==null||pe.addEventListener("keydown",ys),pe==null||pe.addEventListener("input",bs),pe==null||pe.addEventListener("paste",xs);let Yt=(Kc=e.ownerDocument)!=null?Kc:document;Yt.addEventListener("keydown",vs,!0);let so="persona-attachment-drop-active",Cs=0,qi=()=>{Cs=0,ce.classList.remove(so)},Or=()=>{var c;return((c=o.attachments)==null?void 0:c.enabled)===!0&&et!==null},ec=c=>{!Li(c.dataTransfer)||!Or()||(Cs++,Cs===1&&ce.classList.add(so))},tc=c=>{!Li(c.dataTransfer)||!Or()||(Cs--,Cs<=0&&qi())},nc=c=>{!Li(c.dataTransfer)||!Or()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},oc=c=>{var h;if(!Li(c.dataTransfer)||!Or())return;c.preventDefault(),c.stopPropagation(),qi();let f=Array.from((h=c.dataTransfer.files)!=null?h:[]);f.length!==0&&et.handleFiles(f)},tr=!0;ce.addEventListener("dragenter",ec,tr),ce.addEventListener("dragleave",tc,tr),e.addEventListener("dragover",nc,tr),e.addEventListener("drop",oc,tr);let Ca=e.ownerDocument,rc=c=>{Or()&&c.preventDefault()},sc=c=>{Or()&&c.preventDefault()};Ca.addEventListener("dragover",rc),Ca.addEventListener("drop",sc),ft.push(()=>{Nt&&Nt.removeEventListener("submit",hs),pe==null||pe.removeEventListener("keydown",ys),pe==null||pe.removeEventListener("input",bs),pe==null||pe.removeEventListener("paste",xs),Yt.removeEventListener("keydown",vs,!0)}),ft.push(()=>{ce.removeEventListener("dragenter",ec,tr),ce.removeEventListener("dragleave",tc,tr),e.removeEventListener("dragover",nc,tr),e.removeEventListener("drop",oc,tr),Ca.removeEventListener("dragover",rc),Ca.removeEventListener("drop",sc),qi()}),ft.push(()=>{E.cancel()}),Ie?ft.push(()=>{Ie==null||Ie.destroy()}):Ye&&ft.push(()=>{Ye==null||Ye.remove()});let Zt={update(c){var en,To,No,Sa,Aa,Ta,br,ka,Ss,ed,td,nd,od,rd,sd,ad,id,ld,cd,dd,pd,ud,md,fd,gd,hd,bd,yd,vd,xd,wd,Cd,Sd,Ad,Td,kd,Ed,Md,Ld,Id,Rd,Pd,Wd,Bd,Hd,Dd,Fd,Od,Nd,_d,Vd,$d,Ud,zd,qd,jd,Kd,Gd,Yd,Xd,Qd,Jd,Zd,ep,tp,np,op,rp,sp,ap,ip,lp,cp,dp,pp,up,mp,fp,gp,hp,bp,yp,vp,xp,wp,Cp,Sp,Ap,Tp,kp,Ep,Mp,Lp,Ip,Rp,Pp,Wp,Bp,Hp,Dp,Fp,Op,Np,_p,Vp,$p,Up,zp,qp,jp,Kp,Gp,Yp;let f=o.toolCall,h=o.messageActions,y=(en=o.layout)==null?void 0:en.messages,P=o.colorScheme,N=o.loadingIndicator,V=o.iterationDisplay,z=(To=o.features)==null?void 0:To.showReasoning,O=(No=o.features)==null?void 0:No.showToolCalls,Ae=(Sa=o.features)==null?void 0:Sa.toolCallDisplay,ue=(Aa=o.features)==null?void 0:Aa.reasoningDisplay;o={...o,...c},po(),$r(e,o),Ei(e,o),Mi(e,o),zn(),o.colorScheme!==P&&Ko();let Z=Hl.getForInstance(o.plugins);r.length=0,r.push(...Z),I=(br=(Ta=o.launcher)==null?void 0:Ta.enabled)!=null?br:!0,L=(Ss=(ka=o.launcher)==null?void 0:ka.autoExpand)!=null?Ss:!1,se=(td=(ed=o.features)==null?void 0:ed.showReasoning)!=null?td:!0,fe=(od=(nd=o.features)==null?void 0:nd.showToolCalls)!=null?od:!0,be=(sd=(rd=o.features)==null?void 0:rd.scrollToBottom)!=null?sd:{},zt(),Ho();let he=ie;if(ie=(id=(ad=o.features)==null?void 0:ad.showEventStreamToggle)!=null?id:!1,ie&&!he){if(Y||(Q=new Js(ve),Y=new Qs(Le,Q),xe=xe!=null?xe:new Zs,Q.open().then(()=>Y==null?void 0:Y.restore()).catch(()=>{}),E.setSSEEventCallback((X,vt)=>{var Ot;(Ot=o.onSSEEvent)==null||Ot.call(o,X,vt),xe==null||xe.processEvent(X,vt),Y.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:X,timestamp:Date.now(),payload:JSON.stringify(vt)})})),!ut&&Fe){let X=(cd=(ld=o.features)==null?void 0:ld.eventStream)==null?void 0:cd.classNames,vt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(X!=null&&X.toggleButton?" "+X.toggleButton:"");ut=b("button",vt),ut.style.width="28px",ut.style.height="28px",ut.style.color=Mn.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let Ot=Te("activity","18px","currentColor",1.5);Ot&&ut.appendChild(Ot);let ct=He.clearChatButtonWrapper,kt=He.closeButtonWrapper,rn=ct||kt;rn&&rn.parentNode===Fe?Fe.insertBefore(ut,rn):Fe.appendChild(ut),ut.addEventListener("click",()=>{de?On():vn()})}}else!ie&&he&&(On(),ut&&(ut.remove(),ut=null),Y==null||Y.clear(),Q==null||Q.destroy(),Y=null,Q=null,xe==null||xe.reset(),xe=null);if(((dd=o.launcher)==null?void 0:dd.enabled)===!1&&Ie&&(Ie.destroy(),Ie=null),((pd=o.launcher)==null?void 0:pd.enabled)===!1&&Ye&&(Ye.remove(),Ye=null),((ud=o.launcher)==null?void 0:ud.enabled)!==!1&&!Ie&&!Ye){let X=r.find(vt=>vt.renderLauncher);if(X!=null&&X.renderLauncher){let vt=X.renderLauncher({config:o,defaultRenderer:()=>Ks(o,Ze).element,onToggle:Ze});vt&&(Ye=vt,e.appendChild(Ye))}Ye||(Ie=Ks(o,Ze),e.appendChild(Ie.element))}Ie&&Ie.update(o),ke&&((md=o.launcher)==null?void 0:md.title)!==void 0&&(ke.textContent=o.launcher.title),De&&((fd=o.launcher)==null?void 0:fd.subtitle)!==void 0&&(De.textContent=o.launcher.subtitle);let Ee=(gd=o.layout)==null?void 0:gd.header;if((Ee==null?void 0:Ee.layout)!==v&&Fe){let X=Ee?gi(o,Ee,{showClose:C(),onClose:()=>Bt(!1,"user")}):Ar({config:o,showClose:C(),onClose:()=>Bt(!1,"user")});Fe.replaceWith(X.header),Fe=X.header,_=X.iconHolder,ke=X.headerTitle,De=X.headerSubtitle,qe=X.closeButton,v=Ee==null?void 0:Ee.layout}else if(Ee&&(_&&(_.style.display=Ee.showIcon===!1?"none":""),ke&&(ke.style.display=Ee.showTitle===!1?"none":""),De&&(De.style.display=Ee.showSubtitle===!1?"none":""),qe&&(qe.style.display=Ee.showCloseButton===!1?"none":""),He.clearChatButtonWrapper)){let X=Ee.showClearChat;if(X!==void 0){He.clearChatButtonWrapper.style.display=X?"":"none";let{closeButtonWrapper:vt}=He;vt&&!vt.classList.contains("persona-absolute")&&(X?vt.classList.remove("persona-ml-auto"):vt.classList.add("persona-ml-auto"))}}let tt=((hd=o.layout)==null?void 0:hd.showHeader)!==!1;Fe&&(Fe.style.display=tt?"":"none");let Xe=((bd=o.layout)==null?void 0:bd.showFooter)!==!1;$e&&($e.style.display=Xe?"":"none"),bt(),Ho(),I!==W?I?Bt(L,"auto"):(T=!0,Zo()):L!==D&&Bt(L,"auto"),D=L,W=I,Rt(),un();let Pe=JSON.stringify(c.toolCall)!==JSON.stringify(f),Re=JSON.stringify(o.messageActions)!==JSON.stringify(h),je=JSON.stringify((yd=o.layout)==null?void 0:yd.messages)!==JSON.stringify(y),R=((vd=o.loadingIndicator)==null?void 0:vd.render)!==(N==null?void 0:N.render)||((xd=o.loadingIndicator)==null?void 0:xd.renderIdle)!==(N==null?void 0:N.renderIdle)||((wd=o.loadingIndicator)==null?void 0:wd.showBubble)!==(N==null?void 0:N.showBubble),Me=o.iterationDisplay!==V,Be=((Sd=(Cd=o.features)==null?void 0:Cd.showReasoning)!=null?Sd:!0)!==(z!=null?z:!0)||((Td=(Ad=o.features)==null?void 0:Ad.showToolCalls)!=null?Td:!0)!==(O!=null?O:!0)||JSON.stringify((kd=o.features)==null?void 0:kd.toolCallDisplay)!==JSON.stringify(Ae)||JSON.stringify((Ed=o.features)==null?void 0:Ed.reasoningDisplay)!==JSON.stringify(ue);(Pe||Re||je||R||Me||Be)&&E&&(as++,dr(Ve,E.getMessages(),me));let Ce=(Md=o.launcher)!=null?Md:{},Lt=(Ld=Ce.headerIconHidden)!=null?Ld:!1,st=(Rd=(Id=o.layout)==null?void 0:Id.header)==null?void 0:Rd.showIcon,Xt=Lt||st===!1,cn=Ce.headerIconName,Pt=(Pd=Ce.headerIconSize)!=null?Pd:"48px";if(_){let X=ce.querySelector(".persona-border-b-persona-divider"),vt=X==null?void 0:X.querySelector(".persona-flex-col");if(Xt)_.style.display="none",X&&vt&&!X.contains(vt)&&X.insertBefore(vt,X.firstChild);else{if(_.style.display="",_.style.height=Pt,_.style.width=Pt,X&&vt&&(X.contains(_)?_.nextSibling!==vt&&(_.remove(),X.insertBefore(_,vt)):X.insertBefore(_,vt)),cn){let ct=parseFloat(Pt)||24,kt=Te(cn,ct*.6,"#ffffff",2);kt?_.replaceChildren(kt):_.textContent=(Wd=Ce.agentIconText)!=null?Wd:"\u{1F4AC}"}else if(Ce.iconUrl){let ct=_.querySelector("img");if(ct)ct.src=Ce.iconUrl,ct.style.height=Pt,ct.style.width=Pt;else{let kt=document.createElement("img");kt.src=Ce.iconUrl,kt.alt="",kt.className="persona-rounded-xl persona-object-cover",kt.style.height=Pt,kt.style.width=Pt,_.replaceChildren(kt)}}else{let ct=_.querySelector("svg"),kt=_.querySelector("img");(ct||kt)&&_.replaceChildren(),_.textContent=(Bd=Ce.agentIconText)!=null?Bd:"\u{1F4AC}"}let Ot=_.querySelector("img");Ot&&(Ot.style.height=Pt,Ot.style.width=Pt)}}let An=(Dd=(Hd=o.layout)==null?void 0:Hd.header)==null?void 0:Dd.showTitle,dn=(Od=(Fd=o.layout)==null?void 0:Fd.header)==null?void 0:Od.showSubtitle;if(ke&&(ke.style.display=An===!1?"none":""),De&&(De.style.display=dn===!1?"none":""),qe){((_d=(Nd=o.layout)==null?void 0:Nd.header)==null?void 0:_d.showCloseButton)===!1?qe.style.display="none":qe.style.display="";let vt=(Vd=Ce.closeButtonSize)!=null?Vd:"32px",Ot=($d=Ce.closeButtonPlacement)!=null?$d:"inline";qe.style.height=vt,qe.style.width=vt;let{closeButtonWrapper:ct}=He,kt=Ot==="top-right",rn=ct==null?void 0:ct.classList.contains("persona-absolute");if(ct&&kt!==rn)if(ct.remove(),kt)ct.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ce.style.position="relative",ce.appendChild(ct);else{let pt=(zd=(Ud=Ce.clearChat)==null?void 0:Ud.placement)!=null?zd:"inline",sn=(jd=(qd=Ce.clearChat)==null?void 0:qd.enabled)!=null?jd:!0;ct.className=sn&&pt==="inline"?"":"persona-ml-auto";let Hn=ce.querySelector(".persona-border-b-persona-divider");Hn&&Hn.appendChild(ct)}if(qe.style.color=Ce.closeButtonColor||Mn.actionIconColor,Ce.closeButtonBackgroundColor?(qe.style.backgroundColor=Ce.closeButtonBackgroundColor,qe.classList.remove("hover:persona-bg-gray-100")):(qe.style.backgroundColor="",qe.classList.add("hover:persona-bg-gray-100")),Ce.closeButtonBorderWidth||Ce.closeButtonBorderColor){let pt=Ce.closeButtonBorderWidth||"0px",sn=Ce.closeButtonBorderColor||"transparent";qe.style.border=`${pt} solid ${sn}`,qe.classList.remove("persona-border-none")}else qe.style.border="",qe.classList.add("persona-border-none");Ce.closeButtonBorderRadius?(qe.style.borderRadius=Ce.closeButtonBorderRadius,qe.classList.remove("persona-rounded-full")):(qe.style.borderRadius="",qe.classList.add("persona-rounded-full")),Ce.closeButtonPaddingX?(qe.style.paddingLeft=Ce.closeButtonPaddingX,qe.style.paddingRight=Ce.closeButtonPaddingX):(qe.style.paddingLeft="",qe.style.paddingRight=""),Ce.closeButtonPaddingY?(qe.style.paddingTop=Ce.closeButtonPaddingY,qe.style.paddingBottom=Ce.closeButtonPaddingY):(qe.style.paddingTop="",qe.style.paddingBottom="");let fn=(Kd=Ce.closeButtonIconName)!=null?Kd:"x",yo=(Gd=Ce.closeButtonIconText)!=null?Gd:"\xD7";qe.innerHTML="";let En=Te(fn,"28px","currentColor",1);En?qe.appendChild(En):qe.textContent=yo;let Qt=(Yd=Ce.closeButtonTooltipText)!=null?Yd:"Close chat",Xn=(Xd=Ce.closeButtonShowTooltip)!=null?Xd:!0;if(qe.setAttribute("aria-label",Qt),ct&&(ct._cleanupTooltip&&(ct._cleanupTooltip(),delete ct._cleanupTooltip),Xn&&Qt)){let pt=null,sn=()=>{if(pt||!qe)return;let yr=qe.ownerDocument,As=yr.body;if(!As)return;pt=Eo(yr,"div","persona-clear-chat-tooltip"),pt.textContent=Qt;let Ts=Eo(yr,"div");Ts.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Ts);let vr=qe.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(or),pt.style.left=`${vr.left+vr.width/2}px`,pt.style.top=`${vr.top-8}px`,pt.style.transform="translate(-50%, -100%)",As.appendChild(pt)},Hn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};ct.addEventListener("mouseenter",sn),ct.addEventListener("mouseleave",Hn),qe.addEventListener("focus",sn),qe.addEventListener("blur",Hn),ct._cleanupTooltip=()=>{Hn(),ct&&(ct.removeEventListener("mouseenter",sn),ct.removeEventListener("mouseleave",Hn)),qe&&(qe.removeEventListener("focus",sn),qe.removeEventListener("blur",Hn))}}}let{clearChatButton:Je,clearChatButtonWrapper:lt}=He;if(Je){let X=(Qd=Ce.clearChat)!=null?Qd:{},vt=(Jd=X.enabled)!=null?Jd:!0,Ot=(ep=(Zd=o.layout)==null?void 0:Zd.header)==null?void 0:ep.showClearChat,ct=Ot!==void 0?Ot:vt,kt=(tp=X.placement)!=null?tp:"inline";if(lt){lt.style.display=ct?"":"none";let{closeButtonWrapper:rn}=He;!k()&&rn&&!rn.classList.contains("persona-absolute")&&(ct?rn.classList.remove("persona-ml-auto"):rn.classList.add("persona-ml-auto"));let fn=kt==="top-right",yo=lt.classList.contains("persona-absolute");if(!k()&&fn!==yo&&ct){if(lt.remove(),fn)lt.className="persona-absolute persona-top-4 persona-z-50",lt.style.right="48px",ce.style.position="relative",ce.appendChild(lt);else{lt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",lt.style.right="";let Qt=ce.querySelector(".persona-border-b-persona-divider"),Xn=He.closeButtonWrapper;Qt&&Xn&&Xn.parentElement===Qt?Qt.insertBefore(lt,Xn):Qt&&Qt.appendChild(lt)}let En=He.closeButtonWrapper;En&&!En.classList.contains("persona-absolute")&&(fn?En.classList.add("persona-ml-auto"):En.classList.remove("persona-ml-auto"))}}if(ct){if(!k()){let pt=(np=X.size)!=null?np:"32px";Je.style.height=pt,Je.style.width=pt}let rn=(op=X.iconName)!=null?op:"refresh-cw",fn=(rp=X.iconColor)!=null?rp:"";Je.style.color=fn||Mn.actionIconColor,Je.innerHTML="";let yo=k()?"14px":"20px",En=Te(rn,yo,"currentColor",2);if(En&&Je.appendChild(En),X.backgroundColor?(Je.style.backgroundColor=X.backgroundColor,Je.classList.remove("hover:persona-bg-gray-100")):(Je.style.backgroundColor="",Je.classList.add("hover:persona-bg-gray-100")),X.borderWidth||X.borderColor){let pt=X.borderWidth||"0px",sn=X.borderColor||"transparent";Je.style.border=`${pt} solid ${sn}`,Je.classList.remove("persona-border-none")}else Je.style.border="",Je.classList.add("persona-border-none");X.borderRadius?(Je.style.borderRadius=X.borderRadius,Je.classList.remove("persona-rounded-full")):(Je.style.borderRadius="",Je.classList.add("persona-rounded-full")),X.paddingX?(Je.style.paddingLeft=X.paddingX,Je.style.paddingRight=X.paddingX):(Je.style.paddingLeft="",Je.style.paddingRight=""),X.paddingY?(Je.style.paddingTop=X.paddingY,Je.style.paddingBottom=X.paddingY):(Je.style.paddingTop="",Je.style.paddingBottom="");let Qt=(sp=X.tooltipText)!=null?sp:"Clear chat",Xn=(ap=X.showTooltip)!=null?ap:!0;if(Je.setAttribute("aria-label",Qt),lt&&(lt._cleanupTooltip&&(lt._cleanupTooltip(),delete lt._cleanupTooltip),Xn&&Qt)){let pt=null,sn=()=>{if(pt||!Je)return;let yr=Je.ownerDocument,As=yr.body;if(!As)return;pt=Eo(yr,"div","persona-clear-chat-tooltip"),pt.textContent=Qt;let Ts=Eo(yr,"div");Ts.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Ts);let vr=Je.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(or),pt.style.left=`${vr.left+vr.width/2}px`,pt.style.top=`${vr.top-8}px`,pt.style.transform="translate(-50%, -100%)",As.appendChild(pt)},Hn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};lt.addEventListener("mouseenter",sn),lt.addEventListener("mouseleave",Hn),Je.addEventListener("focus",sn),Je.addEventListener("blur",Hn),lt._cleanupTooltip=()=>{Hn(),lt&&(lt.removeEventListener("mouseenter",sn),lt.removeEventListener("mouseleave",Hn)),Je&&(Je.removeEventListener("focus",sn),Je.removeEventListener("blur",Hn))}}}}let Tn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Fl],mn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ea.message,ea.messageAndClick];M=Ol({parsers:Tn,handlers:mn,getSessionMetadata:g,updateSessionMetadata:p,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),me=Om(o,M,j),E.updateConfig(o),dr(Ve,E.getMessages(),me),uo.render(o.suggestionChips,E,pe,void 0,o.suggestionChipsConfig),fs(),Br(E.isStreaming());let mr=((ip=o.voiceRecognition)==null?void 0:ip.enabled)===!0,fr=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),gr=((cp=(lp=o.voiceRecognition)==null?void 0:lp.provider)==null?void 0:cp.type)==="runtype";if(mr&&(fr||gr))if(!q||!_t){let X=wa(o.voiceRecognition,o.sendButton);X&&(q=X.micButton,_t=X.micButtonWrapper,At.insertBefore(_t,Ln),q.addEventListener("click",K),q.disabled=E.isStreaming())}else{let X=(dp=o.voiceRecognition)!=null?dp:{},vt=(pp=o.sendButton)!=null?pp:{},Ot=(up=X.iconName)!=null?up:"mic",ct=(mp=vt.size)!=null?mp:"40px",kt=(fp=X.iconSize)!=null?fp:ct,rn=parseFloat(kt)||24;q.style.width=kt,q.style.height=kt,q.style.minWidth=kt,q.style.minHeight=kt;let fn=(hp=(gp=X.iconColor)!=null?gp:vt.textColor)!=null?hp:"currentColor";q.innerHTML="";let yo=Te(Ot,rn,fn,2);yo?q.appendChild(yo):q.textContent="\u{1F3A4}";let En=(bp=X.backgroundColor)!=null?bp:vt.backgroundColor;En?q.style.backgroundColor=En:q.style.backgroundColor="",fn?q.style.color=fn:q.style.color="var(--persona-text, #111827)",X.borderWidth?(q.style.borderWidth=X.borderWidth,q.style.borderStyle="solid"):(q.style.borderWidth="",q.style.borderStyle=""),X.borderColor?q.style.borderColor=X.borderColor:q.style.borderColor="",X.paddingX?(q.style.paddingLeft=X.paddingX,q.style.paddingRight=X.paddingX):(q.style.paddingLeft="",q.style.paddingRight=""),X.paddingY?(q.style.paddingTop=X.paddingY,q.style.paddingBottom=X.paddingY):(q.style.paddingTop="",q.style.paddingBottom="");let Qt=_t==null?void 0:_t.querySelector(".persona-send-button-tooltip"),Xn=(yp=X.tooltipText)!=null?yp:"Start voice recognition";if(((vp=X.showTooltip)!=null?vp:!1)&&Xn)if(Qt)Qt.textContent=Xn,Qt.style.display="";else{let sn=document.createElement("div");sn.className="persona-send-button-tooltip",sn.textContent=Xn,_t==null||_t.insertBefore(sn,q)}else Qt&&(Qt.style.display="none");_t.style.display="",q.disabled=E.isStreaming()}else q&&_t&&(_t.style.display="none",((wp=(xp=o.voiceRecognition)==null?void 0:xp.provider)==null?void 0:wp.type)==="runtype"?E.isVoiceActive()&&E.toggleVoice():Gn&&bo());if(((Cp=o.attachments)==null?void 0:Cp.enabled)===!0)if(!Ft||!Qe){let X=(Sp=o.attachments)!=null?Sp:{},Ot=(Tp=((Ap=o.sendButton)!=null?Ap:{}).size)!=null?Tp:"40px";ge||(ge=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ge.style.display="none",Nt.insertBefore(ge,pe)),oe||(oe=document.createElement("input"),oe.type="file",oe.accept=((kp=X.allowedTypes)!=null?kp:_o).join(","),oe.multiple=((Ep=X.maxFiles)!=null?Ep:4)>1,oe.style.display="none",oe.setAttribute("aria-label","Attach files"),Nt.insertBefore(oe,pe)),Ft=b("div","persona-send-button-wrapper"),Qe=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Qe.type="button",Qe.setAttribute("aria-label",(Mp=X.buttonTooltipText)!=null?Mp:"Attach file");let ct=(Lp=X.buttonIconName)!=null?Lp:"paperclip",kt=Ot,rn=parseFloat(kt)||40,fn=Math.round(rn*.6);Qe.style.width=kt,Qe.style.height=kt,Qe.style.minWidth=kt,Qe.style.minHeight=kt,Qe.style.fontSize="18px",Qe.style.lineHeight="1",Qe.style.backgroundColor="transparent",Qe.style.color="var(--persona-primary, #111827)",Qe.style.border="none",Qe.style.borderRadius="6px",Qe.style.transition="background-color 0.15s ease",Qe.addEventListener("mouseenter",()=>{Qe.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Qe.addEventListener("mouseleave",()=>{Qe.style.backgroundColor="transparent"});let yo=Te(ct,fn,"currentColor",1.5);yo?Qe.appendChild(yo):Qe.textContent="\u{1F4CE}",Qe.addEventListener("click",Xn=>{Xn.preventDefault(),oe==null||oe.click()}),Ft.appendChild(Qe);let En=(Ip=X.buttonTooltipText)!=null?Ip:"Attach file",Qt=b("div","persona-send-button-tooltip");Qt.textContent=En,Ft.appendChild(Qt),ot.append(Ft),!et&&oe&&ge&&(et=Os.fromConfig(X),et.setPreviewsContainer(ge),oe.addEventListener("change",async()=>{et&&(oe!=null&&oe.files)&&(await et.handleFileSelect(oe.files),oe.value="")})),ce.querySelector(".persona-attachment-drop-overlay")||ce.appendChild(Nm(X.dropOverlay))}else{Ft.style.display="";let X=(Rp=o.attachments)!=null?Rp:{};oe&&(oe.accept=((Pp=X.allowedTypes)!=null?Pp:_o).join(","),oe.multiple=((Wp=X.maxFiles)!=null?Wp:4)>1),et&&et.updateConfig({allowedTypes:X.allowedTypes,maxFileSize:X.maxFileSize,maxFiles:X.maxFiles})}else Ft&&(Ft.style.display="none"),et&&et.clearAttachments(),(Bp=ce.querySelector(".persona-attachment-drop-overlay"))==null||Bp.remove();let qt=(Hp=o.sendButton)!=null?Hp:{},hr=(Dp=qt.useIcon)!=null?Dp:!1,nr=(Fp=qt.iconText)!=null?Fp:"\u2191",ht=qt.iconName,Pn=(Op=qt.tooltipText)!=null?Op:"Send message",Oo=(Np=qt.showTooltip)!=null?Np:!1,kn=(_p=qt.size)!=null?_p:"40px",Wn=qt.backgroundColor,Ht=qt.textColor;if(hr){if(ae.style.width=kn,ae.style.height=kn,ae.style.minWidth=kn,ae.style.minHeight=kn,ae.style.fontSize="18px",ae.style.lineHeight="1",ae.innerHTML="",Ht?ae.style.color=Ht:ae.style.color="var(--persona-button-primary-fg, #ffffff)",ht){let X=parseFloat(kn)||24,vt=(Ht==null?void 0:Ht.trim())||"currentColor",Ot=Te(ht,X,vt,2);Ot?ae.appendChild(Ot):ae.textContent=nr}else ae.textContent=nr;ae.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Wn?(ae.style.backgroundColor=Wn,ae.classList.remove("persona-bg-persona-primary")):(ae.style.backgroundColor="",ae.classList.add("persona-bg-persona-primary"))}else ae.textContent=($p=(Vp=o.copy)==null?void 0:Vp.sendButtonLabel)!=null?$p:"Send",ae.style.width="",ae.style.height="",ae.style.minWidth="",ae.style.minHeight="",ae.style.fontSize="",ae.style.lineHeight="",ae.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Wn?(ae.style.backgroundColor=Wn,ae.classList.remove("persona-bg-persona-accent")):ae.classList.add("persona-bg-persona-accent"),Ht?ae.style.color=Ht:ae.classList.add("persona-text-white");qt.borderWidth?(ae.style.borderWidth=qt.borderWidth,ae.style.borderStyle="solid"):(ae.style.borderWidth="",ae.style.borderStyle=""),qt.borderColor?ae.style.borderColor=qt.borderColor:ae.style.borderColor="",qt.paddingX?(ae.style.paddingLeft=qt.paddingX,ae.style.paddingRight=qt.paddingX):(ae.style.paddingLeft="",ae.style.paddingRight=""),qt.paddingY?(ae.style.paddingTop=qt.paddingY,ae.style.paddingBottom=qt.paddingY):(ae.style.paddingTop="",ae.style.paddingBottom="");let Ut=Ln==null?void 0:Ln.querySelector(".persona-send-button-tooltip");if(Oo&&Pn)if(Ut)Ut.textContent=Pn,Ut.style.display="";else{let X=document.createElement("div");X.className="persona-send-button-tooltip",X.textContent=Pn,Ln==null||Ln.insertBefore(X,ae)}else Ut&&(Ut.style.display="none");let Dt=(Kp=(Up=o.layout)==null?void 0:Up.contentMaxWidth)!=null?Kp:k()?(jp=(qp=(zp=o.launcher)==null?void 0:zp.composerBar)==null?void 0:qp.contentMaxWidth)!=null?jp:"720px":void 0;Dt?(Ve.style.maxWidth=Dt,Ve.style.marginLeft="auto",Ve.style.marginRight="auto",Ve.style.width="100%",Nt&&(Nt.style.maxWidth=Dt,Nt.style.marginLeft="auto",Nt.style.marginRight="auto"),Et&&(Et.style.maxWidth=Dt,Et.style.marginLeft="auto",Et.style.marginRight="auto")):(Ve.style.maxWidth="",Ve.style.marginLeft="",Ve.style.marginRight="",Ve.style.width="",Nt&&(Nt.style.maxWidth="",Nt.style.marginLeft="",Nt.style.marginRight=""),Et&&(Et.style.maxWidth="",Et.style.marginLeft="",Et.style.marginRight=""));let jt=(Gp=o.statusIndicator)!=null?Gp:{},Bn=(Yp=jt.visible)!=null?Yp:!0;if(ln.style.display=Bn?"":"none",E){let X=E.getStatus();nt(ln,(Ot=>{var ct,kt,rn,fn;return Ot==="idle"?(ct=jt.idleText)!=null?ct:gn.idle:Ot==="connecting"?(kt=jt.connectingText)!=null?kt:gn.connecting:Ot==="connected"?(rn=jt.connectedText)!=null?rn:gn.connected:Ot==="error"?(fn=jt.errorText)!=null?fn:gn.error:gn[Ot]})(X),jt,X)}ln.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Yn=jt.align==="left"?"persona-text-left":jt.align==="center"?"persona-text-center":"persona-text-right";ln.classList.add(Yn)},open(){C()&&Bt(!0,"api")},close(){C()&&Bt(!1,"api")},toggle(){C()&&Bt(!T,"api")},clearChat(){xn=!1,E.clearMessages(),mo.clear(),Go();try{localStorage.removeItem(ts),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ts}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ts)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let f=i.clear();f instanceof Promise&&f.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",f)}d={},M.syncFromMetadata(),Y==null||Y.clear(),xe==null||xe.reset(),Se==null||Se.update()},setMessage(c){return!pe||E.isStreaming()?!1:(!T&&C()&&Bt(!0,"system"),pe.value=c,pe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(E.isStreaming())return!1;let f=(c==null?void 0:c.trim())||pe.value.trim();return f?(!T&&C()&&Bt(!0,"system"),pe.value="",pe.style.height="auto",E.sendMessage(f),!0):!1},startVoiceRecognition(){var f,h;return E.isStreaming()?!1:((h=(f=o.voiceRecognition)==null?void 0:f.provider)==null?void 0:h.type)==="runtype"?(E.isVoiceActive()||(!T&&C()&&Bt(!0,"system"),mt.manuallyDeactivated=!1,Rn(),E.toggleVoice().then(()=>{mt.active=E.isVoiceActive(),ro("user"),E.isVoiceActive()&&U()})),!0):Gn?!0:ws()?(!T&&C()&&Bt(!0,"system"),mt.manuallyDeactivated=!1,Rn(),ur("user"),!0):!1},stopVoiceRecognition(){var c,f;return((f=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:f.type)==="runtype"?E.isVoiceActive()?(E.toggleVoice().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Rn(),ro("user"),ee()}),!0):!1:Gn?(mt.manuallyDeactivated=!0,Rn(),bo("user"),!0):!1},injectMessage(c){return!T&&C()&&Bt(!0,"system"),E.injectMessage(c)},injectAssistantMessage(c){!T&&C()&&Bt(!0,"system");let f=E.injectAssistantMessage(c);return F&&(F=!1,$&&(clearTimeout($),$=null),setTimeout(()=>{E&&!E.isStreaming()&&E.continueConversation()},100)),f},injectUserMessage(c){return!T&&C()&&Bt(!0,"system"),E.injectUserMessage(c)},injectSystemMessage(c){return!T&&C()&&Bt(!0,"system"),E.injectSystemMessage(c)},injectMessageBatch(c){return!T&&C()&&Bt(!0,"system"),E.injectMessageBatch(c)},injectComponentDirective(c){return!T&&C()&&Bt(!0,"system"),E.injectComponentDirective(c)},injectTestMessage(c){!T&&C()&&Bt(!0,"system"),E.injectTestEvent(c)},async connectStream(c,f){return E.connectStream(c,f)},__pushEventStreamEvent(c){Y&&(xe==null||xe.processEvent(c.type,c.payload),Y.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!ie||!Y||vn()},hideEventStream(){de&&On()},isEventStreamVisible(){return de},showArtifacts(){co(o)&&(xn=!1,zn(),yt==null||yt.setMobileOpen(!0))},hideArtifacts(){co(o)&&(xn=!0,zn())},upsertArtifact(c){return co(o)?(xn=!1,E.upsertArtifact(c)):null},selectArtifact(c){co(o)&&E.selectArtifact(c)},clearArtifacts(){co(o)&&E.clearArtifacts()},getArtifacts(){var c;return(c=E==null?void 0:E.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=E==null?void 0:E.getSelectedArtifactId())!=null?c:null},focusInput(){return I&&!T&&!k()||!pe?!1:(pe.focus(),!0)},async resolveApproval(c,f){let y=E.getMessages().find(P=>{var N;return P.variant==="approval"&&((N=P.approval)==null?void 0:N.id)===c});if(!(y!=null&&y.approval))throw new Error(`Approval not found: ${c}`);if(y.approval.toolType==="webmcp"){E.resolveWebMcpApproval(y.id,f);return}return E.resolveApproval(y.approval,f)},getMessages(){return E.getMessages()},getStatus(){return E.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){p(c)},on(c,f){return s.on(c,f)},off(c,f){s.off(c,f)},isOpen(){return C()&&T},isVoiceActive(){return mt.active},getState(){return{open:C()&&T,launcherEnabled:I,voiceActive:mt.active,streaming:E.isStreaming()}},showCSATFeedback(c){!T&&C()&&Bt(!0,"system");let f=Ve.querySelector(".persona-feedback-container");f&&f.remove();let h=Hm({onSubmit:async(y,P)=>{var N;E.isClientTokenMode()&&await E.submitCSATFeedback(y,P),(N=c==null?void 0:c.onSubmit)==null||N.call(c,y,P)},onDismiss:c==null?void 0:c.onDismiss,...c});Ve.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!T&&C()&&Bt(!0,"system");let f=Ve.querySelector(".persona-feedback-container");f&&f.remove();let h=Dm({onSubmit:async(y,P)=>{var N;E.isClientTokenMode()&&await E.submitNPSFeedback(y,P),(N=c==null?void 0:c.onSubmit)==null||N.call(c,y,P)},onDismiss:c==null?void 0:c.onDismiss,...c});Ve.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,f){return E.submitCSATFeedback(c,f)},async submitNPSFeedback(c,f){return E.submitNPSFeedback(c,f)},destroy(){Ao!=null&&(clearInterval(Ao),Ao=null),ft.forEach(c=>c()),ye.remove(),Ue==null||Ue.remove(),Ie==null||Ie.destroy(),Ye==null||Ye.remove(),jn&&qe.removeEventListener("click",jn)}};if((((Gc=n==null?void 0:n.debugTools)!=null?Gc:!1)||!!o.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,f={controller:Zt,getMessages:Zt.getMessages,getStatus:Zt.getStatus,getMetadata:Zt.getPersistentMetadata,updateMetadata:Zt.updatePersistentMetadata,clearHistory:()=>Zt.clearChat(),setVoiceActive:h=>h?Zt.startVoiceRecognition():Zt.stopVoiceRecognition()};window.AgentWidgetBrowser=f,ft.push(()=>{window.AgentWidgetBrowser===f&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),f=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&Zt.focusInput()};if(window.addEventListener("persona:focusInput",f),ft.push(()=>{window.removeEventListener("persona:focusInput",f)}),ie){let z=Ae=>{let ue=Ae.detail;(!(ue!=null&&ue.instanceId)||ue.instanceId===c)&&Zt.showEventStream()},O=Ae=>{let ue=Ae.detail;(!(ue!=null&&ue.instanceId)||ue.instanceId===c)&&Zt.hideEventStream()};window.addEventListener("persona:showEventStream",z),window.addEventListener("persona:hideEventStream",O),ft.push(()=>{window.removeEventListener("persona:showEventStream",z),window.removeEventListener("persona:hideEventStream",O)})}let h=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&Zt.showArtifacts()},y=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&Zt.hideArtifacts()},P=z=>{let O=z.detail;O!=null&&O.instanceId&&O.instanceId!==c||O!=null&&O.artifact&&Zt.upsertArtifact(O.artifact)},N=z=>{let O=z.detail;O!=null&&O.instanceId&&O.instanceId!==c||typeof(O==null?void 0:O.id)=="string"&&Zt.selectArtifact(O.id)},V=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&Zt.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",P),window.addEventListener("persona:selectArtifact",N),window.addEventListener("persona:clearArtifacts",V),ft.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",P),window.removeEventListener("persona:selectArtifact",N),window.removeEventListener("persona:clearArtifacts",V)})}let ao=sx(o.persistState);if(ao&&C()){let c=ax(ao.storage),f=`${ao.keyPrefix}widget-open`,h=`${ao.keyPrefix}widget-voice`,y=`${ao.keyPrefix}widget-voice-mode`;if(c){let P=((Yc=ao.persist)==null?void 0:Yc.openState)&&c.getItem(f)==="true",N=((Xc=ao.persist)==null?void 0:Xc.voiceState)&&c.getItem(h)==="true",V=((Qc=ao.persist)==null?void 0:Qc.voiceState)&&c.getItem(y)==="true";if(P&&setTimeout(()=>{Zt.open(),setTimeout(()=>{var z;if(N||V)Zt.startVoiceRecognition();else if((z=ao.persist)!=null&&z.focusInput){let O=e.querySelector("textarea");O&&O.focus()}},100)},0),(Jc=ao.persist)!=null&&Jc.openState&&(s.on("widget:opened",()=>{c.setItem(f,"true")}),s.on("widget:closed",()=>{c.setItem(f,"false")})),(Zc=ao.persist)!=null&&Zc.voiceState&&(s.on("voice:state",z=>{c.setItem(h,z.active?"true":"false")}),s.on("user:message",z=>{c.setItem(y,z.viaVoice?"true":"false")})),ao.clearOnChatClear){let z=()=>{c.removeItem(f),c.removeItem(h),c.removeItem(y)},O=()=>z();window.addEventListener("persona:clear-chat",O),ft.push(()=>{window.removeEventListener("persona:clear-chat",O)})}}}return m&&C()&&setTimeout(()=>{Zt.open()},0),Do(),Zt};var ix=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},Vm=(e,t)=>{var o,r;let n=(r=(o=t==null?void 0:t.launcher)==null?void 0:o.enabled)!=null?r:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},Ul=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},$m=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Ul(e)},_l=e=>{e.style.transition=""},Vl=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform=""},$l=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ii=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},lx=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},cx=(e,t,n,o,r,s)=>{let a=s?t:e;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},Um=(e,t,n,o,r,s,a)=>{var w,S,M,I,L,H;let i=Mo(s),d=i.reveal==="push";lx(e,t,n,o,d),cx(e,t,n,o,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,m=(S=(w=s==null?void 0:s.launcher)==null?void 0:w.mobileFullscreen)!=null?S:!0,u=(I=(M=s==null?void 0:s.launcher)==null?void 0:M.mobileBreakpoint)!=null?I:640,g=l!=null?l.innerWidth<=u:!1;if(m&&g&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Vl(t),_l(o),$m(o),$l(n),Ii(r,o),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String((H=(L=s==null?void 0:s.launcher)==null?void 0:L.zIndex)!=null?H:hn),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),$m(o),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Vl(t),_l(o),$l(n),Ii(r,o);let D=i.animate?"transform 180ms ease":"none",W=i.side==="right"?"translateX(100%)":"translateX(-100%)",v=a?"translateX(0)":W;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=D,o.style.transform=v,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",i.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",_l(o),Ul(o),Ii(r,o);let D=ix(i.width,e.clientWidth),W=Math.max(0,e.clientWidth),v=i.animate?"transform 180ms ease":"none",x=i.side==="right"?a?`translateX(-${D}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${D}px)`;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${W+D}px`,t.style.transition=v,t.style.transform=x,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${W}px`,n.style.maxWidth=`${W}px`,n.style.minWidth=`${W}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.position="relative",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Vl(t),Ul(o),$l(n),Ii(r,o);let D=i.reveal==="emerge";D?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let W=a?i.width:"0px",v=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",x=!a;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${W}`,o.style.width=W,o.style.maxWidth=W,o.style.minWidth=W,o.style.minHeight="0",o.style.position="relative",o.style.overflow=D||x?"hidden":"visible",o.style.transition=v,D&&(o.style.alignItems=i.side==="right"?"flex-start":"flex-end",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.boxSizing="border-box")}},dx=(e,t)=>{let n=e.ownerDocument.createElement("div");return Vm(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Vm(n,o)},destroy(){n.remove()}}},px=(e,t)=>{var L,H,D,W;let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),m=n.createElement("div"),u=(H=(L=t==null?void 0:t.launcher)==null?void 0:L.enabled)==null||H?(W=(D=t==null?void 0:t.launcher)==null?void 0:D.autoExpand)!=null?W:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",m.dataset.personaDockRole="host",l.appendChild(m),o.insertBefore(a,e),d.appendChild(e);let g=null,p=()=>{g==null||g.disconnect(),g=null},w=()=>{p(),Mo(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{Um(a,i,d,l,m,t,u)}),g.observe(a))},S=()=>{Um(a,i,d,l,m,t,u),w()},M=a.ownerDocument.defaultView,I=()=>{S()};return M==null||M.addEventListener("resize",I),Mo(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),S(),{mode:"docked",host:m,shell:a,syncWidgetState(v){let x=v.launcherEnabled?v.open:!0;u!==x&&(u=x,S())},updateConfig(v){var x,k;t=v,((k=(x=t==null?void 0:t.launcher)==null?void 0:x.enabled)!=null?k:!0)===!1&&(u=!0),S()},destroy(){M==null||M.removeEventListener("resize",I),p(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},zm=(e,t)=>pn(t)?px(e,t):dx(e,t);var ns={desktop:{w:1280,h:800},mobile:{w:390,h:844}},zl=.15,ql=1.5,Ri="persona-preview-shell-theme",qm={load:()=>null,save:()=>{},clear:()=>{}},jm=["How do I get started?","Pricing & plans","Talk to support"];function Pi(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Km(e){return e==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function jl(e){let t=Km(e);return`* { box-sizing: border-box; }
|
|
108
108
|
html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
|
|
109
109
|
html { color-scheme: ${e}; }
|
|
110
110
|
body { font-family: system-ui, sans-serif; background: ${t.pageBg}; }
|
|
@@ -128,7 +128,7 @@ _Details: ${n.message}_`:o}var ei=class e{constructor(t={},n){this.config=t;this
|
|
|
128
128
|
.preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
|
|
129
129
|
.preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
|
|
130
130
|
.preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${t.cardBg}; box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
|
|
131
|
-
.preview-workspace-card.short { height: 96px; }`}function
|
|
131
|
+
.preview-workspace-card.short { height: 96px; }`}function Kl(e,t){let n=e.contentDocument;if(!(n!=null&&n.documentElement))return;let o=n.getElementById(Ri);o||(o=n.createElement("style"),o.id=Ri,n.head.appendChild(o)),o.textContent=jl(t)}var Gm=`
|
|
132
132
|
<div class="preview-iframe-mock" aria-hidden="true">
|
|
133
133
|
<div class="preview-iframe-chrome">
|
|
134
134
|
<span class="preview-iframe-dot"></span>
|
|
@@ -147,7 +147,7 @@ _Details: ${n.message}_`:o}var ei=class e{constructor(t={},n){this.config=t;this
|
|
|
147
147
|
<div class="preview-iframe-line body"></div>
|
|
148
148
|
<div class="preview-iframe-line body"></div>
|
|
149
149
|
</div>
|
|
150
|
-
</div>`,
|
|
150
|
+
</div>`,Ym=`
|
|
151
151
|
<div class="preview-workspace-content-shell" aria-hidden="true">
|
|
152
152
|
<div class="preview-iframe-line hero"></div>
|
|
153
153
|
<div class="preview-iframe-line body"></div>
|
|
@@ -160,8 +160,8 @@ _Details: ${n.message}_`:o}var ei=class e{constructor(t={},n){this.config=t;this
|
|
|
160
160
|
<div class="preview-workspace-card short"></div>
|
|
161
161
|
<div class="preview-workspace-card short"></div>
|
|
162
162
|
</div>
|
|
163
|
-
</div>`;function
|
|
164
|
-
${
|
|
163
|
+
</div>`;function Gl(e,t,n,o){let r=`
|
|
164
|
+
${Gm}
|
|
165
165
|
<div style="position:fixed;inset:0;z-index:9999;"><div id="${e}" data-mount-id="${e}"></div></div>`,s=`
|
|
166
166
|
<div class="preview-workspace-shell">
|
|
167
167
|
<div class="preview-workspace-topbar">
|
|
@@ -173,7 +173,7 @@ _Details: ${n.message}_`:o}var ei=class e{constructor(t={},n){this.config=t;this
|
|
|
173
173
|
</div>
|
|
174
174
|
<div class="preview-workspace-body">
|
|
175
175
|
<div id="preview-content-${e}" class="preview-workspace-content" data-mount-id="${e}">
|
|
176
|
-
${
|
|
176
|
+
${Ym}
|
|
177
177
|
</div>
|
|
178
178
|
</div>
|
|
179
179
|
</div>`;return`<!DOCTYPE html>
|
|
@@ -181,19 +181,19 @@ _Details: ${n.message}_`:o}var ei=class e{constructor(t={},n){this.config=t;this
|
|
|
181
181
|
<head>
|
|
182
182
|
<meta charset="UTF-8">
|
|
183
183
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
184
|
-
<link rel="stylesheet" href="${
|
|
185
|
-
<style id="${
|
|
184
|
+
<link rel="stylesheet" href="${Pi(o)}">
|
|
185
|
+
<style id="${Ri}">${jl(t)}</style>
|
|
186
186
|
</head>
|
|
187
187
|
<body>
|
|
188
188
|
${n?s:r}
|
|
189
189
|
</body>
|
|
190
|
-
</html>`}var
|
|
190
|
+
</html>`}var ux={"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 mx(e){return ux[e]}function Yl(e,t=0){let n=new Date(Date.now()-Math.max(0,60-t)*1e3).toISOString(),o=`${e}-${t}`;switch(e){case"user-message":return{id:`preview-seq-user-${o}`,role:"user",content:"Can you continue with the next step?",createdAt:n};case"assistant-message":return{id:`preview-seq-assistant-${o}`,role:"assistant",content:"Absolutely. I can keep going and explain what happens next.",createdAt:n};case"assistant-code-block":return{id:`preview-seq-assistant-code-${o}`,role:"assistant",content:["Here's how you'd wire up a streaming animation:","","```ts","import { createAgentExperience } from '@runtypelabs/persona';","","createAgentExperience(el, {"," features: {",' streamAnimation: { type: "letter-rise", speed: 120 },'," },","});","```","","Swap the `type` value to try the other presets."].join(`
|
|
191
191
|
`),createdAt:n};case"assistant-markdown-table":return{id:`preview-seq-assistant-table-${o}`,role:"assistant",content:["Here are the built-in streaming animations at a glance:","","| Preset | Wrap unit | Best for |","| ------------ | --------- | --------------------------- |","| Typewriter | Character | Classic terminal feel |","| Letter rise | Character | Soft, staggered entrance |","| Word fade | Word | Longer-form assistant replies |","| Pop bubble | Bubble | Short, punchy affirmations |"].join(`
|
|
192
192
|
`),createdAt:n};case"assistant-image":return{id:`preview-seq-assistant-image-${o}`,role:"assistant",content:["Here's the reference diagram you asked for \u2014 let me know if you'd like a different view:","","","","The gradient shows how per-unit delays stagger across the reply."].join(`
|
|
193
|
-
`),createdAt:n};case"reasoning-streaming":return{id:`preview-seq-reasoning-stream-${o}`,role:"assistant",content:"",createdAt:n,streaming:!0,variant:"reasoning",reasoning:{id:`preview-reasoning-stream-${o}`,status:"streaming",chunks:["Thinking through the next step in the workflow..."]}};case"reasoning-complete":return{id:`preview-seq-reasoning-complete-${o}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"reasoning",reasoning:{id:`preview-reasoning-complete-${o}`,status:"complete",chunks:["Reviewed the requirements and finalized the reasoning output."],durationMs:1200}};case"tool-complete":return{id:`preview-seq-tool-complete-${o}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"tool",toolCall:{id:`preview-tool-complete-${o}`,name:"Create build instructions",status:"complete",chunks:["Prepared the build instructions and validated the inputs."],result:{ok:!0},duration:420}};default:return{id:`preview-seq-tool-running-${o}`,role:"assistant",content:"",createdAt:n,streaming:!0,variant:"tool",toolCall:{id:`preview-tool-running-${o}`,name:"Get platform documentation",status:"running",chunks:["Fetching the relevant platform documentation..."]}}}}function
|
|
194
|
-
${
|
|
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 fx(e,t){return[...e,Yl(t,e.length)]}function Xm(e){return e==="assistant-message"||e==="assistant-code-block"||e==="assistant-markdown-table"||e==="assistant-image"}function gx(e,t,n){var d,l;let o=Yl(e,t);if(!Xm(e)||typeof o.content!="string")return[{message:o,delayMs:0,done:!0}];let r=Math.max(1,(d=n==null?void 0:n.chunkSize)!=null?d:24),s=Math.max(0,(l=n==null?void 0:n.delayMs)!=null?l:42),a=o.content,i=[];i.push({message:{...o,content:"",streaming:!0},delayMs:0,done:!1});for(let m=r;m<a.length;m+=r)i.push({message:{...o,content:a.slice(0,m),streaming:!0},delayMs:s,done:!1});return i.push({message:{...o,content:a,streaming:!1},delayMs:s,done:!0}),i}var hx=()=>[{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()}],bx=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 Qm(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"&&bx(t)?[...hx(),...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 Xl(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:jm:e.suggestionChips,initialMessages:Qm(t,e,n),storageAdapter:qm};return t==="artifact"&&(r.features={...r.features,artifacts:{...(a=r.features)==null?void 0:a.artifacts,enabled:!0}}),r}function Lr(e,t){var s,a,i,d;let n=e.theme?tn(e.theme,{validate:!1}):tn(),o=(s=e.scene)!=null?s:"conversation",r={...St,...e.config,theme:n,darkTheme:e.darkTheme,colorScheme:(i=t!=null?t:(a=e.config)==null?void 0:a.colorScheme)!=null?i:"light"};return Xl(r,o,(d=e.appendedMessages)!=null?d:[])}function yx(e,t,n){var a,i,d;let o=e.theme?tn(e.theme,{validate:!1}):tn(),r=(a=e.scene)!=null?a:"conversation",s={...St,...e.config,theme:o,darkTheme:e.darkTheme,colorScheme:(d=n!=null?n:(i=e.config)==null?void 0:i.colorScheme)!=null?d:"light"};return Xl(s,r,t)}function Jm(e){var o,r,s,a,i;let t=(o=e.compareMode)!=null?o:"off",n=(r=e.shellMode)!=null?r:"light";if(t==="themes")return[{mountId:"preview-light",label:"Light",config:Lr(e,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Lr(e,"dark"),shellMode:"dark"}];if(t==="baseline"&&(e.baselineConfig||e.baselineTheme)){let d={...e,config:(s=e.baselineConfig)!=null?s:e.config,theme:(a=e.baselineTheme)!=null?a:e.theme,darkTheme:(i=e.baselineDarkTheme)!=null?i:e.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:Lr(d,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Lr(e,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Lr(e,n),shellMode:n}]}function vx(e,t){let n={...t},o=[],r=[],s=null,a=!1,i=1,d=1,l=0;function m(){var L;return(L=n.device)!=null?L:"desktop"}function u(){var L;return(L=n.zoom)!=null?L:i}function g(){var T,F;let L=getComputedStyle(e),H=parseFloat(L.paddingLeft)+parseFloat(L.paddingRight),D=parseFloat(L.paddingTop)+parseFloat(L.paddingBottom),W=40,v=((T=n.compareMode)!=null?T:"off")!=="off",x=(e.clientWidth-H-W)/(v?2:1),k=e.clientHeight-D-W;if(x<=0||k<=0)return 1;let C=(F=ns[m()])!=null?F:ns.desktop;return Math.min(x/C.w,k/C.h,1)}function p(){var D,W,v;i=g();let L=Math.max(zl,Math.min(ql,u()));d=L;let H=Array.from(e.querySelectorAll(".preview-iframe-wrapper"));for(let x of H){let k=(D=x.dataset.device)!=null?D:"desktop",C=(W=ns[k])!=null?W:ns.desktop;x.style.width=`${C.w*L}px`,x.style.height=`${C.h*L}px`,k==="mobile"&&(x.style.borderRadius=`${32*L}px`);let T=x.querySelector("iframe");T&&(T.style.width=`${C.w}px`,T.style.height=`${C.h}px`,T.style.transformOrigin="top left",T.style.transition="none",T.style.transform=`scale(${L})`)}(v=n.onScaleChange)==null||v.call(n,L)}function w(){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 S(){return Array.from(e.querySelectorAll("iframe[data-mount-id]"))}function M(){var fe,ie,be,Oe;if(a)return;w();let L=++l,H=Jm(n),D=m(),W=((fe=n.compareMode)!=null?fe:"off")!=="off",v=((ie=n.scene)!=null?ie:"conversation")==="minimized",x=(be=n.widgetCssPath)!=null?be:"/widget-dist/widget.css",k=(Oe=n.buildSrcdoc)!=null?Oe:Gl,C=D==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",T=ve=>`<div class="${C}" data-mount-id="${ve.mountId}" data-device="${D}" data-shell-mode="${ve.shellMode}">
|
|
194
|
+
${W?`<div class="preview-frame-meta"><span class="preview-frame-label">${Pi(ve.label)}</span></div>`:""}
|
|
195
195
|
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${ve.mountId}"></iframe>
|
|
196
|
-
</div>`,F=
|
|
196
|
+
</div>`,F=W?`<div class="preview-compare-grid">${H.map(ve=>`<div class="preview-compare-cell">${T(ve)}</div>`).join("")}</div>`:`<div class="preview-single">${T(H[0])}</div>`;n.morphContainer?n.morphContainer(e,F):e.innerHTML=F,p();let $=S(),j=0,me=$.length,se=()=>{var Q,Le,Y,xe,Se;if(a||L!==l)return;for(let de of $){let we=de.dataset.mountId;if(!we||!de.contentDocument)continue;let ze=H.find(ye=>ye.mountId===we);if(!ze)continue;let te=()=>{},ne=pn(ze.config),re=ne?(()=>{var G;let ye=(G=de.contentDocument)==null?void 0:G.getElementById(`preview-content-${we}`);if(!ye)return null;let le=zm(ye,ze.config),Ue=de.contentDocument.createElement("div");Ue.id=we,Ue.style.height="100%",Ue.style.display="flex",Ue.style.flexDirection="column",Ue.style.flex="1",Ue.style.minHeight="0",le.host.appendChild(Ue);let He=()=>le.syncWidgetState(nt.getState()),ce=te;return te=()=>{le.destroy(),ce()},Ue.__syncDock=He,Ue.__hostLayout=le,Ue})():de.contentDocument.getElementById(we);if(!re)continue;let nt=_m(re,ze.config);if(o.push(nt),ne&&re.__syncDock){let ye=re.__syncDock,le=nt.on("widget:opened",ye),Ue=nt.on("widget:closed",ye),He=te;te=()=>{le(),Ue(),He()},ye()}r.push(te),v&&nt.close()}if(((Q=n.scene)!=null?Q:"conversation")==="artifact"||(xe=(Y=(Le=n.config)==null?void 0:Le.features)==null?void 0:Y.artifacts)!=null&&xe.enabled)for(let de of o)de.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
|
|
197
197
|
|
|
198
198
|
This is a preview of the artifact sidebar.
|
|
199
199
|
|
|
@@ -201,4 +201,4 @@ This is a preview of the artifact sidebar.
|
|
|
201
201
|
|
|
202
202
|
- Markdown rendering
|
|
203
203
|
- Document toolbar
|
|
204
|
-
- Resizable panes`});(Se=n.onAfterMount)==null||Se.call(n,{iframes:$,controllers:[...o]})};for(let ve of $){let J=ve.dataset.mountId;if(!J)continue;let Le=H.find(Y=>Y.mountId===J);Le&&(ve.addEventListener("load",()=>{j++,j>=me&&se()},{once:!0}),ve.srcdoc=k(J,Le.shellMode,pn(Le.config),x))}me===0&&se()}function I(){var D;if(a)return;let R=Xm(n);if(o.length!==R.length){M();return}if(R.some(B=>{let v=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${B.mountId}"]`);return!v||v.dataset.shellMode!==B.shellMode})){M();return}o.forEach((B,v)=>{var x;B.update(R[v].config),((x=n.scene)!=null?x:"conversation")==="minimized"&&B.close()});for(let B of R){let v=e.querySelector(`iframe[data-mount-id="${B.mountId}"]`);v&&jl(v,B.shellMode)}(D=n.onAfterUpdate)==null||D.call(n,{iframes:C(),controllers:[...o]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||u()}),s.observe(e)),M(),{update(R){if(a)return;let H=R.device!==void 0&&R.device!==n.device||R.scene!==void 0&&R.scene!==n.scene||R.compareMode!==void 0&&R.compareMode!==n.compareMode||R.widgetCssPath!==void 0&&R.widgetCssPath!==n.widgetCssPath;n={...n,...R},H?M():I()},destroy(){a||(a=!0,w(),s==null||s.disconnect(),e.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},u())},getIframes(){return C()},getScale(){return d},setZoom(R){a||(n={...n,zoom:R},u())}}}function Vo(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}var Pi={black:"#000000",white:"#ffffff",red:"#ff0000",green:"#008000",lime:"#00ff00",blue:"#0000ff",yellow:"#ffff00",cyan:"#00ffff",aqua:"#00ffff",magenta:"#ff00ff",fuchsia:"#ff00ff",silver:"#c0c0c0",gray:"#808080",grey:"#808080",maroon:"#800000",olive:"#808000",purple:"#800080",teal:"#008080",navy:"#000080",orange:"#ffa500",pink:"#ffc0cb",hotpink:"#ff69b4",gold:"#ffd700",indigo:"#4b0082",violet:"#ee82ee",brown:"#a52a2a",beige:"#f5f5dc",ivory:"#fffff0",khaki:"#f0e68c",coral:"#ff7f50",salmon:"#fa8072",tomato:"#ff6347",crimson:"#dc143c",turquoise:"#40e0d0",lavender:"#e6e6fa",plum:"#dda0dd",orchid:"#da70d6",tan:"#d2b48c",chocolate:"#d2691e",sienna:"#a0522d",slategray:"#708090",slategrey:"#708090",steelblue:"#4682b4",royalblue:"#4169e1",dodgerblue:"#1e90ff",skyblue:"#87ceeb",lightblue:"#add8e6",midnightblue:"#191970",forestgreen:"#228b22",seagreen:"#2e8b57",limegreen:"#32cd32",olivedrab:"#6b8e23",darkgreen:"#006400",emerald:"#50c878",mint:"#3eb489",goldenrod:"#daa520",firebrick:"#b22222",darkred:"#8b0000",indianred:"#cd5c5c",deeppink:"#ff1493",mediumpurple:"#9370db",rebeccapurple:"#663399",darkviolet:"#9400d3",slateblue:"#6a5acd",cornflowerblue:"#6495ed",teal2:"#008080",charcoal:"#36454f",graphite:"#3b3b3b",transparent:"transparent"},yx=/^rgba?\(\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*(,\s*(0|1|0?\.\d+|\d{1,3}%)\s*)?\)$/;function vx(e){return yx.test(e)}function ns(e){if(typeof e!="string"||e.trim()==="")throw new Error('Color must be a non-empty string (e.g. "#2563eb" or "blue").');let t=e.trim().toLowerCase(),n=Pi[t];if(n)return n;let o=ks(t);if(Yi(o)||o==="transparent"||vx(o))return o;throw new Error(`"${e}" is not a recognized color. Pass a hex value like "#ef4444" or a CSS color name (e.g. ${Object.keys(Pi).slice(0,6).join(", ")}).`)}var Wi=Ma.map(e=>e==="gray"?"neutral":e),xx={...Object.fromEntries(Wi.map(e=>[e,e])),gray:"neutral",grey:"neutral"};function Bi(e,t=!0){let n=String(e!=null?e:"").trim().toLowerCase(),o=xx[n];if(!o||!t&&o==="neutral"){let r=t?"primary, secondary, accent, neutral":"primary, secondary, accent";throw new Error(`Unknown color family "${e}". Valid families: ${r}.`)}return o}function Hi(e){let t=String(e!=null?e:"solid").trim().toLowerCase();if(t==="solid"||t==="soft")return t;throw new Error(`Unknown intensity "${e}". Valid intensities: solid, soft.`)}function Di(e){let t=String(e!=null?e:"").trim().toLowerCase();if(t==="light"||t==="dark"||t==="auto")return t;if(t==="system")return"auto";throw new Error(`Unknown color scheme "${e}". Valid: light, dark, auto.`)}var wx={sharp:"sharp",square:"sharp",none:"sharp",default:"default",normal:"default",rounded:"rounded",round:"rounded",soft:"rounded",pill:"pill",circle:"pill",full:"pill"};function Fi(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=wx[t];if(!n)throw new Error(`Unknown roundness "${e}". Valid: sharp, default, rounded, pill.`);return n}function Oi(e){if(typeof e=="number"&&Number.isFinite(e))return`${e}px`;if(typeof e=="string"&&e.trim()!==""){let t=e.trim();if(t==="9999px"||/^(100%|9999px)$/.test(t))return"9999px";let n=Ki(t);return Gi(n.value,n.unit)}throw new Error('Radius must be a number (px) or a CSS length string like "0.5rem".')}function Ni(e){for(let t of zr){let n=t.fields.find(o=>o.id===e);if(n!=null&&n.options){let o={};for(let r of n.options){let s=r.value.split(".").pop();s&&(o[s]=r.value)}return o}}return{}}var Qm=Ni("typo-font-family"),Zs=Ni("typo-font-size"),ea=Ni("typo-font-weight"),Ri=Ni("typo-line-height"),Jm={...Qm,monospace:Qm.mono},Zm={...Zs,small:Zs.sm,md:Zs.base,medium:Zs.base,large:Zs.lg},eg={...ea,400:ea.normal,500:ea.medium,600:ea.semibold,700:ea.bold},tg={...Ri,"1.25":Ri.tight,"1.5":Ri.normal,"1.625":Ri.relaxed};function ng(e,t,n){let o=String(e!=null?e:"").trim().toLowerCase(),r=t[o];if(!r){let s=[...new Set(Object.values(t).map(a=>a.split(".").pop()))].join(", ");throw new Error(`Unknown ${n} "${e}". Valid: ${s}.`)}return r}var og="theme.palette.radius.";function Cx(){var t;let e={pill:{sm:"9999px",md:"9999px",lg:"9999px",xl:"9999px",full:"9999px"}};for(let n of zr)for(let o of(t=n.presets)!=null?t:[]){let r=o.id.match(/^radius-(\w+)$/);if(!r)continue;let s={};for(let[a,i]of Object.entries(o.values))a.startsWith(og)&&typeof i=="string"&&(s[a.slice(og.length)]=i);e[r[1]]=s}return e}var na=Cx(),rg=["sm","md","lg","xl","full"];function Vi(e,t,n="theme",o=0){if(o>6)return null;let r=e.get(`${n}.${t}`);return typeof r!="string"||r===""?n==="darkTheme"?Vi(e,t,"theme",o):null:r.startsWith("#")||r.startsWith("rgb")||r==="transparent"?r:r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components.")?Vi(e,r,n,o+1):null}function _i(e,t){let n=e.get(t);if(typeof n!="string")return"unknown";let o=n.split(".");return o[o.length-1]||String(n)}function os(e){return e.replace(/^role-/,"")}function Sx(e){for(let[t,n]of Object.entries(na))if(rg.every(o=>e[o]===n[o]))return t;return"custom"}function Ir(e){var o,r;let t={};for(let s of rg)t[s]=String((o=e.get(`theme.palette.radius.${s}`))!=null?o:"");let n={};for(let s of wr)n[os(s.roleId)]=Zi(a=>e.get(`theme.${a}`),s);return{brand:{primary:Xl(e.get("theme.palette.colors.primary.500")),secondary:Xl(e.get("theme.palette.colors.secondary.500")),accent:Xl(e.get("theme.palette.colors.accent.500"))},roles:n,typography:{fontFamily:_i(e,"theme.semantic.typography.fontFamily"),fontSize:_i(e,"theme.semantic.typography.fontSize"),fontWeight:_i(e,"theme.semantic.typography.fontWeight"),lineHeight:_i(e,"theme.semantic.typography.lineHeight")},roundness:{style:Sx(t),radius:t},colorScheme:String((r=e.get("colorScheme"))!=null?r:"light"),history:{index:e.getHistoryIndex(),canUndo:e.canUndo(),canRedo:e.canRedo()}}}function Xl(e){return typeof e=="string"&&e!==""?e:null}var ta=[{key:"user-message",label:"User message text",fg:"components.message.user.text",bg:"components.message.user.background"},{key:"assistant-message",label:"Assistant message text",fg:"components.message.assistant.text",bg:"components.message.assistant.background"},{key:"header",label:"Header title",fg:"components.header.titleForeground",bg:"components.header.background"},{key:"primary-button",label:"Primary button label",fg:"components.button.primary.foreground",bg:"components.button.primary.background"},{key:"input",label:"Input placeholder",fg:"components.input.placeholder",bg:"components.input.background"},{key:"link",label:"Link text",fg:"components.markdown.link.foreground",bg:"semantic.colors.background"},{key:"scroll",label:"Scroll-to-bottom icon",fg:"components.scrollToBottom.foreground",bg:"components.scrollToBottom.background"},{key:"body",label:"Body text on background",fg:"semantic.colors.text",bg:"semantic.colors.background"},{key:"surface",label:"Body text on surface",fg:"semantic.colors.text",bg:"semantic.colors.surface"}];function sg(e){let t=new Set(e.targets.map(n=>n.path));return ta.filter(n=>t.has(n.fg)||t.has(n.bg)).map(n=>n.key)}var Ax={AA:4.5,AAA:7};function Tx(e){return Math.round(e*100)/100}function kx(e,t,n,o,r){let s=e.get(`${r}.${t}`);if(typeof s!="string")return null;let a=s.match(/^palette\.colors\.(\w+)\.(\d+)$/);if(!a)return null;let i=a[1],d=Ur.indexOf(a[2]),l=null,p=1/0;return Ur.forEach((m,f)=>{let u=e.get(`${r}.palette.colors.${i}.${m}`);if(!(typeof u!="string"||!(u.startsWith("#")||u.startsWith("rgb")))&&Ea(u,n)>=o){let w=d>=0?Math.abs(f-d):f;w<p&&(p=w,l=`palette.colors.${i}.${m}`)}}),l}function oa(e,t="AA",n="both",o){let r=Ax[t],s=n==="both"?["light","dark"]:[n],a=o?ta.filter(d=>o.includes(d.key)):ta,i=[];for(let d of s){let l=d==="light"?"theme":"darkTheme";for(let p of a){let m=Vi(e,p.fg,l),f=Vi(e,p.bg,l);if(!m||!f)continue;let u=Tx(Ea(m,f)),w=u>=r,C={pair:p.key,label:p.label,variant:d,fg:m,bg:f,ratio:u,threshold:r,passes:w};if(!w){let M=kx(e,p.fg,f,r,l);M&&(C.suggestion=M)}i.push(C)}}return{level:t,checks:i,failures:i.filter(d=>!d.passes)}}function rs(e,t,n="light",o="AA"){return t.length===0?[]:oa(e,o,n,t).failures.map(s=>({code:"contrast",pair:s.pair,variant:s.variant,ratio:s.ratio,threshold:s.threshold,message:`${s.label} (${s.variant}) has a contrast ratio of ${s.ratio}:1, below the ${o} threshold of ${s.threshold}:1${s.suggestion?`. Try ${s.suggestion} for the foreground.`:"."}`}))}var an={};for(let e of wr){let t=os(e.roleId);an[t]=e,an[e.roleId]=e}Object.assign(an,{surface:an.surfaces,background:an.surfaces,backgrounds:an.surfaces,user:an["user-messages"],"user-message":an["user-messages"],assistant:an["assistant-messages"],"assistant-message":an["assistant-messages"],actions:an["primary-actions"],buttons:an["primary-actions"],composer:an.input,links:an["links-focus"],focus:an["links-focus"],border:an.borders,dividers:an.borders,scroll:an["scroll-to-bottom"]});function Ex(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=an[t];if(!n){let o=wr.map(r=>os(r.roleId)).join(", ");throw new Error(`Unknown role "${e}". Valid roles: ${o}.`)}return n}function ag(){let e=new Map,t=n=>{for(let o of n)for(let r of o.fields)e.has(r.id)||e.set(r.id,r)};for(let n of tl)t(n.sections);for(let n of Na)t(n.sections);return e}var Mx={voice:"voiceRecognition.enabled",artifacts:"features.artifacts.enabled",attachments:"attachments.enabled",toolCalls:"features.showToolCalls",reasoning:"features.showReasoning",feedback:"messageActions.enabled"},Lx={avatars:"layout.messages.avatar.show",timestamps:"layout.messages.timestamp.show",showHeader:"layout.showHeader",messageStyle:"layout.messages.layout"},Ql=["bottom-right","bottom-left","top-right","top-left"],Jl=["bubble","flat","minimal"],Ix={title:"copy.welcomeTitle",subtitle:"copy.welcomeSubtitle",placeholder:"copy.inputPlaceholder",sendLabel:"copy.sendButtonLabel"};function ig(e,t){var B;let n=(B=t==null?void 0:t.editTarget)!=null?B:"both",o=null,r=v=>v&&typeof v=="object"?v:{},s=(v,x,k=n)=>{let S={};return(k==="light"||k==="both")&&(S[`theme.${v}`]=x),(k==="dark"||k==="both")&&(S[`darkTheme.${v}`]=x),S},a=v=>{if(n==="both")return v;let x={};for(let[k,S]of Object.entries(v))(n==="light"&&k.startsWith("theme.")||n==="dark"&&k.startsWith("darkTheme."))&&(x[k]=S);return x},i=()=>n==="dark"?"dark":"light",d=(v,x=[])=>Vo({ok:!0,summary:Ir(e),warnings:x,applied:v});return[{name:"get_theme_overview",title:"Get current theme & what is editable",description:"Read the current widget theme (brand colors, per-role color assignments, typography, roundness, color scheme, undo/redo state), the available presets, and the high-level levers you can change. Call this FIRST before editing.",annotations:{readOnlyHint:!0},inputSchema:{type:"object",properties:{verbosity:{type:"string",enum:["summary","full"],description:"Use 'full' to also include the field-id index for set_theme_fields."}},additionalProperties:!1},execute(v){let{verbosity:x}=r(v),k={summary:Ir(e),availableRoles:wr.map(S=>({role:os(S.roleId),helper:S.helper})),availableFamilies:Wi,presets:Ms.map(S=>{var E;return{id:S.id,name:S.name,description:S.description,tags:(E=S.tags)!=null?E:[]}}),tools:[{tool:"set_brand_colors",hint:"Recolor the palette (primary/secondary/accent) \u2014 auto-generates shade scales."},{tool:"assign_color_role",hint:"Recolor a region (header, user/assistant messages, actions, input, links, borders, surfaces, scroll) with a family + intensity."},{tool:"set_typography",hint:"Set font family, size, weight, line height."},{tool:"set_roundness",hint:"Set corner roundness (sharp/default/rounded/pill) or granular radii."},{tool:"set_color_scheme",hint:"Set light/dark/auto and which variant edits target."},{tool:"apply_preset",hint:"Apply a complete built-in preset."},{tool:"configure_widget",hint:"Toggle launcher position, features, and layout."},{tool:"set_copy_and_suggestions",hint:"Set welcome copy, placeholder, and suggestion chips."},{tool:"set_theme_fields",hint:"Advanced escape hatch: set any field by id or dot-path."},{tool:"check_contrast",hint:"Audit WCAG contrast across key text/background pairs."},{tool:"manage_session",hint:"Undo, redo, reset, or export the theme."}]};return x==="full"&&(o!=null||(o=ag()),k.fieldIndex=Array.from(o.values()).map(S=>{var E;return{id:S.id,path:S.path,type:S.type,label:S.label,options:(E=S.options)==null?void 0:E.map(F=>F.value)}})),Vo(k)}},{name:"set_brand_colors",title:"Set brand colors",description:'Set one or more brand colors (primary, secondary, accent). Each color auto-generates a full 50\u2013950 shade scale and applies to the light and dark themes (per the current edit target). Accepts hex ("#2563eb", "2563eb", "#18f"), rgb()/rgba() ("rgb(37, 99, 235)"), or CSS color names ("blue", "slateblue").',inputSchema:{type:"object",properties:{primary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},secondary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},accent:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."}},additionalProperties:!1},execute(v){let x=r(v),k=["primary","secondary","accent"],S={},E={};for(let $ of k){if(x[$]===void 0)continue;let j=ns(x[$]);E[$]=j;let me=Qi(j);for(let se of Ur){let ge=me[se];ge!==void 0&&Object.assign(S,s(`palette.colors.${$}.${se}`,ge))}}if(Object.keys(E).length===0)throw new Error("Provide at least one of: primary, secondary, accent.");e.setBatch(S);let F=rs(e,["primary-button","user-message"],i());return d(E,F)}},{name:"assign_color_role",title:"Assign a color family to an interface role",description:"Recolor a semantic region of the widget by choosing a palette family and intensity. One call writes all related tokens (background, text, border, icon) consistently. Roles: header, user-messages, assistant-messages, primary-actions, input, links, borders, surfaces, scroll-to-bottom. Families: primary, secondary, accent, neutral. Intensity: solid (bold) or soft (tinted).",inputSchema:{type:"object",properties:{role:{type:"string",description:'Interface role, e.g. "header" or "user-messages".'},family:{type:"string",enum:Wi},intensity:{type:"string",enum:["solid","soft"],description:"Defaults to 'solid'."}},required:["role","family"],additionalProperties:!1},execute(v){let x=r(v),k=Ex(x.role),S=Bi(x.family,!0),E=Hi(x.intensity),F=a(Oa(S,E,k)),$=Object.keys(F).length;e.setBatch(F);let j=rs(e,sg(k),i());return d({role:os(k.roleId),family:S,intensity:E,tokensWritten:$},j)}},{name:"set_typography",title:"Set typography",description:"Set font family, base size, weight, and line height in one call. fontFamily: sans|serif|mono. fontSize: xs|sm|base|lg|xl. fontWeight: normal|medium|semibold|bold (or 400\u2013700). lineHeight: tight|normal|relaxed (or 1.25/1.5/1.625).",inputSchema:{type:"object",properties:{fontFamily:{type:"string"},fontSize:{type:"string"},fontWeight:{type:["string","number"]},lineHeight:{type:["string","number"]}},additionalProperties:!1},execute(v){let x=r(v),k={},S={},E=(F,$)=>{var me;if(x[F]===void 0)return;let j=ng(x[F],$,F);S[F]=(me=j.split(".").pop())!=null?me:j,Object.assign(k,s(`semantic.typography.${F}`,j))};if(E("fontFamily",Jm),E("fontSize",Zm),E("fontWeight",eg),E("lineHeight",tg),Object.keys(S).length===0)throw new Error("Provide at least one of: fontFamily, fontSize, fontWeight, lineHeight.");return e.setBatch(k),d(S)}},{name:"set_roundness",title:"Set corner roundness",description:"Set overall corner roundness with a keyword (sharp, default, rounded, pill) which maps the full radius scale, OR pass granular radius values. Provide at least one of `style` or `radius`.",inputSchema:{type:"object",properties:{style:{type:"string",enum:["sharp","default","rounded","pill"]},radius:{type:"object",description:"Granular overrides (px number or CSS length).",properties:{sm:{type:["string","number"]},md:{type:["string","number"]},lg:{type:["string","number"]},xl:{type:["string","number"]},full:{type:["string","number"]}},additionalProperties:!1}},additionalProperties:!1},execute(v){let x=r(v),k={},S={};if(x.style!==void 0){let E=Fi(x.style);S.style=E;for(let[F,$]of Object.entries(na[E]))Object.assign(k,s(`palette.radius.${F}`,$))}if(x.radius!==void 0){let E=r(x.radius),F={};for(let $ of["sm","md","lg","xl","full"]){if(E[$]===void 0)continue;let j=Oi(E[$]);F[$]=j,Object.assign(k,s(`palette.radius.${$}`,j))}S.radius=F}if(Object.keys(k).length===0)throw new Error("Provide `style` (sharp|default|rounded|pill) or a `radius` object.");return e.setBatch(k),d(S)}},{name:"set_color_scheme",title:"Set color scheme",description:"Set the shipped widget color scheme (light, dark, or auto/follow-system). Optionally set `editTarget` to choose which theme variant subsequent styling edits write to (light, dark, or both \u2014 default both).",inputSchema:{type:"object",properties:{scheme:{type:"string",enum:["light","dark","auto"]},editTarget:{type:"string",enum:["light","dark","both"]}},additionalProperties:!1},execute(v){let x=r(v),k={};if(x.scheme!==void 0){let S=Di(x.scheme);e.set("colorScheme",S),k.scheme=S}if(x.editTarget!==void 0){let S=String(x.editTarget).trim().toLowerCase();if(S!=="light"&&S!=="dark"&&S!=="both")throw new Error(`Unknown editTarget "${x.editTarget}". Valid: light, dark, both.`);n=S,k.editTarget=S}if(Object.keys(k).length===0)throw new Error("Provide `scheme` and/or `editTarget`.");return Vo({ok:!0,summary:Ir(e),warnings:[],applied:k,editTarget:n})}},{name:"apply_preset",title:"Apply a built-in theme preset",description:"Apply a complete built-in preset, replacing theme tokens. Call get_theme_overview to list preset ids.",inputSchema:{type:"object",properties:{presetId:{type:"string"}},required:["presetId"],additionalProperties:!1},execute(v){let{presetId:x}=r(v),k=nl(String(x!=null?x:""));if(!k){let $=Ms.map(j=>j.id).join(", ");throw new Error(`Unknown preset "${x}". Valid presets: ${$}.`)}let S=tn(k.theme,{validate:!1}),E={...e.getConfig()};k.darkTheme&&(E.darkTheme=tn(k.darkTheme,{validate:!1})),k.toolCall&&(E.toolCall=k.toolCall),e.setFullConfig(E,S);let F=rs(e,["body","assistant-message"],"light");return d({appliedPreset:{id:k.id,name:k.name}},F)}},{name:"configure_widget",title:"Configure launcher, features, and layout",description:"Toggle non-theme widget configuration. launcherPosition: bottom-right|bottom-left|top-right|top-left. features: { voice, artifacts, attachments, toolCalls, reasoning, feedback } booleans. layout: { avatars, timestamps, showHeader } booleans and messageStyle: bubble|flat|minimal.",inputSchema:{type:"object",properties:{launcherPosition:{type:"string",enum:Ql},features:{type:"object",properties:{voice:{type:"boolean"},artifacts:{type:"boolean"},attachments:{type:"boolean"},toolCalls:{type:"boolean"},reasoning:{type:"boolean"},feedback:{type:"boolean"}},additionalProperties:!1},layout:{type:"object",properties:{avatars:{type:"boolean"},timestamps:{type:"boolean"},showHeader:{type:"boolean"},messageStyle:{type:"string",enum:Jl}},additionalProperties:!1}},additionalProperties:!1},execute(v){var $,j,me;let x=r(v),k={},S={};if(x.launcherPosition!==void 0){let se=String(x.launcherPosition);if(!Ql.includes(se))throw new Error(`Unknown launcherPosition "${se}". Valid: ${Ql.join(", ")}.`);k["launcher.position"]=se,S.launcherPosition=se}let E=r(x.features);for(let[se,ge]of Object.entries(Mx))E[se]!==void 0&&(k[ge]=!!E[se],($=S.features)!=null||(S.features={}),S.features[se]=!!E[se]);let F=r(x.layout);for(let[se,ge]of Object.entries(Lx))if(F[se]!==void 0)if(se==="messageStyle"){let ie=String(F[se]);if(!Jl.includes(ie))throw new Error(`Unknown messageStyle "${ie}". Valid: ${Jl.join(", ")}.`);k[ge]=ie,(j=S.layout)!=null||(S.layout={}),S.layout[se]=ie}else k[ge]=!!F[se],(me=S.layout)!=null||(S.layout={}),S.layout[se]=!!F[se];if(Object.keys(k).length===0)throw new Error("Provide launcherPosition, features, and/or layout.");return e.setBatch(k),d(S)}},{name:"set_copy_and_suggestions",title:"Set welcome copy and suggestion chips",description:"Set the widget welcome copy and suggestion chips. title/subtitle are the welcome card text; placeholder is the input placeholder; sendLabel is the send button label; suggestions is an array of suggestion-chip strings (replaces the existing list).",inputSchema:{type:"object",properties:{title:{type:"string"},subtitle:{type:"string"},placeholder:{type:"string"},sendLabel:{type:"string"},suggestions:{type:"array",items:{type:"string"}}},additionalProperties:!1},execute(v){let x=r(v),k={},S={};for(let[E,F]of Object.entries(Ix))x[E]!==void 0&&(k[F]=String(x[E]),S[E]=String(x[E]));if(x.suggestions!==void 0){if(!Array.isArray(x.suggestions))throw new Error("`suggestions` must be an array of strings.");let E=x.suggestions.filter(F=>typeof F=="string");k.suggestionChips=E,S.suggestions=E}if(Object.keys(k).length===0)throw new Error("Provide at least one of: title, subtitle, placeholder, sendLabel, suggestions.");return e.setBatch(k),d(S)}},{name:"set_theme_fields",title:"Set theme fields by id or path (advanced)",description:'Advanced escape hatch: set individual editor fields by field id (see get_theme_overview verbosity:"full") \u2014 theme field ids follow the current edit target (light/dark/both) \u2014 or by raw dot-path (theme.* / darkTheme.* / a config path), which is written as-is. Use only when a higher-level tool does not cover the need. Values are validated against the field metadata.',inputSchema:{type:"object",properties:{updates:{type:"array",items:{type:"object",properties:{field:{type:"string",description:"Field id or dot-path."},value:{type:["string","number","boolean"]}},required:["field","value"],additionalProperties:!1}}},required:["updates"],additionalProperties:!1},execute(v){var F;let{updates:x}=r(v);if(!Array.isArray(x)||x.length===0)throw new Error("`updates` must be a non-empty array of { field, value }.");o!=null||(o=ag());let k={},S=[];for(let $ of x){let j=r($),me=String((F=j.field)!=null?F:"");try{let se=o.get(me),ge=se?se.path:me;if(!se&&!/^(theme|darkTheme)\.|\./.test(ge))throw new Error(`Unknown field "${me}". Pass a known field id or a dot-path (e.g. theme.palette.radius.md).`);let ie=Rx(se,j.value);if(se&&ge.startsWith("theme.")){let be=s(ge.slice(6),ie);Object.assign(k,be),S.push({field:me,resolvedPath:Object.keys(be),ok:!0})}else k[ge]=ie,S.push({field:me,resolvedPath:ge,ok:!0})}catch(se){S.push({field:me,ok:!1,error:se.message})}}let E=S.filter($=>$.ok);return Object.keys(k).length>0&&e.setBatch(k),Vo({ok:E.length>0,summary:Ir(e),warnings:[],applied:{updates:S}})}},{name:"check_contrast",title:"Check accessibility contrast",description:"Run WCAG contrast checks over the key text/background pairs (message text, header title, input/body text, primary button). Returns each ratio, whether it passes, and a suggested foreground shade for failures.",annotations:{readOnlyHint:!0},inputSchema:{type:"object",properties:{level:{type:"string",enum:["AA","AAA"],description:"Defaults to 'AA'."},variant:{type:"string",enum:["light","dark","both"],description:"Defaults to 'both'."}},additionalProperties:!1},execute(v){let x=r(v),k=x.level==="AAA"?"AAA":"AA",S=x.variant==="light"||x.variant==="dark"?x.variant:"both",E=oa(e,k,S);return Vo({level:E.level,passing:E.checks.length-E.failures.length,total:E.checks.length,checks:E.checks,failures:E.failures})}},{name:"manage_session",title:"Undo, redo, reset, or export the theme",description:'Session action. "undo"/"redo" step through edit history; "reset" restores defaults; "export" returns the embeddable theme snapshot (config + theme JSON) with no side effects.',inputSchema:{type:"object",properties:{action:{type:"string",enum:["undo","redo","reset","export"]}},required:["action"],additionalProperties:!1},execute(v){let{action:x}=r(v);switch(x){case"undo":return e.undo(),d({action:"undo"});case"redo":return e.redo(),d({action:"redo"});case"reset":return e.resetToDefaults(),d({action:"reset"});case"export":return Vo({ok:!0,snapshot:e.exportSnapshot()});default:throw new Error(`Unknown action "${x}". Valid: undo, redo, reset, export.`)}}}]}function Rx(e,t){if(!e)return t;switch(e.type){case"color":return e.parseValue?e.parseValue(ns(t)):ns(t);case"toggle":return typeof t=="boolean"?t:t==="true"||t===1;case"slider":{let n=Number(t);if(!Number.isFinite(n))throw new Error(`"${e.id}" expects a number.`);if(e.slider){let{min:o,max:r}=e.slider;if(n<o||n>r)throw new Error(`"${e.id}" must be between ${o} and ${r}.`)}return e.parseValue?e.parseValue(n):n}case"select":{let n=String(t);if(e.options&&!e.options.some(o=>o.value===n))throw new Error(`"${e.id}" must be one of: ${e.options.map(o=>o.value).join(", ")}.`);return e.parseValue?e.parseValue(n):n}default:return e.parseValue?e.parseValue(t):t}}export{bu as ADVANCED_TOKENS_SECTION,wr as ALL_ROLES,tl as ALL_TABS,mu as BRAND_PALETTE_SECTION,vu as BUILT_IN_PRESETS,Og as COLORS_SECTIONS,Ji as COLOR_FAMILIES,du as COMPONENTS_SECTIONS,cu as COMPONENT_COLOR_SECTIONS,lu as COMPONENT_SHAPE_SECTIONS,pu as CONFIGURE_SECTIONS,Na as CONFIGURE_SUB_GROUPS,ta as CONTRAST_PAIRS,Pi as CSS_NAMED_COLORS,ts as DEVICE_DIMENSIONS,zm as HOME_SUGGESTION_CHIPS,fu as INTERFACE_ROLES_SECTION,jm as MOCK_BROWSER_CONTENT,Km as MOCK_WORKSPACE_CONTENT,Dg as PALETTE_SECTION,Um as PREVIEW_STORAGE_ADAPTER,na as RADIUS_PRESETS,Pa as ROLE_ASSISTANT_MESSAGES,Fa as ROLE_BORDERS,Ma as ROLE_FAMILIES,Sg as ROLE_FAMILY_LABELS,Ia as ROLE_HEADER,Ha as ROLE_INPUT,ko as ROLE_INTENSITIES,Da as ROLE_LINKS_FOCUS,Wa as ROLE_PRIMARY_ACTIONS,Ba as ROLE_SCROLL_TO_BOTTOM,La as ROLE_SURFACES,Ra as ROLE_USER_MESSAGES,Fg as SEMANTIC_COLORS_SECTION,Ur as SHADE_KEYS,Li as SHELL_STYLE_ID,hu as STATUS_COLORS_SECTION,gu as STATUS_PALETTE_SECTION,zr as STYLE_SECTIONS,wf as STYLE_SECTIONS_V2,Ms as THEME_EDITOR_PRESETS,uu as THEME_SECTION,ji as ThemeEditorState,zl as ZOOM_MAX,Ul as ZOOM_MIN,ux as appendPreviewTranscriptEntry,Yl as applySceneConfig,jl as applyShellTheme,Lr as buildPreviewConfig,hx as buildPreviewConfigWithMessages,ql as buildShellCss,Kl as buildSrcdoc,Ir as buildSummary,mx as buildTranscriptStreamFrames,ns as coerceColor,Bi as coerceFamily,Hi as coerceIntensity,Oi as coerceRadius,Fi as coerceRoundnessStyle,Di as coerceScheme,xg as convertFromPx,vg as convertToPx,Ym as createPreviewMessages,Gl as createPreviewTranscriptEntry,ig as createThemeEditorTools,bx as createThemePreview,Zi as detectRoleAssignment,Ii as escapeHtml,Sf as findSection,Gi as formatCssValue,Qi as generateColorScale,px as getPreviewTranscriptPresetLabel,qm as getShellPalette,nl as getThemeEditorPreset,ou as hexToHsl,ru as hslToHex,Yi as isValidHex,ks as normalizeColorValue,wg as paletteColorPath,Ki as parseCssValue,Gm as presetStreamsText,rs as quickContrastWarnings,Oa as resolveRoleAssignment,su as resolveThemeColorPath,Xi as rgbToHex,oa as runContrastChecks,Af as scopeSection,Cg as tokenRefDisplayName,Vo as toolResult,Ea as wcagContrastRatio};
|
|
204
|
+
- Resizable panes`});(Se=n.onAfterMount)==null||Se.call(n,{iframes:$,controllers:[...o]})};for(let ve of $){let Q=ve.dataset.mountId;if(!Q)continue;let Le=H.find(Y=>Y.mountId===Q);Le&&(ve.addEventListener("load",()=>{j++,j>=me&&se()},{once:!0}),ve.srcdoc=k(Q,Le.shellMode,pn(Le.config),x))}me===0&&se()}function I(){var D;if(a)return;let L=Jm(n);if(o.length!==L.length){M();return}if(L.some(W=>{let v=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${W.mountId}"]`);return!v||v.dataset.shellMode!==W.shellMode})){M();return}o.forEach((W,v)=>{var x;W.update(L[v].config),((x=n.scene)!=null?x:"conversation")==="minimized"&&W.close()});for(let W of L){let v=e.querySelector(`iframe[data-mount-id="${W.mountId}"]`);v&&Kl(v,W.shellMode)}(D=n.onAfterUpdate)==null||D.call(n,{iframes:S(),controllers:[...o]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||p()}),s.observe(e)),M(),{update(L){if(a)return;let H=L.device!==void 0&&L.device!==n.device||L.scene!==void 0&&L.scene!==n.scene||L.compareMode!==void 0&&L.compareMode!==n.compareMode||L.widgetCssPath!==void 0&&L.widgetCssPath!==n.widgetCssPath;n={...n,...L},H?M():I()},destroy(){a||(a=!0,w(),s==null||s.disconnect(),e.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},p())},getIframes(){return S()},getScale(){return d},setZoom(L){a||(n={...n,zoom:L},p())}}}function Vo(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}var Bi={black:"#000000",white:"#ffffff",red:"#ff0000",green:"#008000",lime:"#00ff00",blue:"#0000ff",yellow:"#ffff00",cyan:"#00ffff",aqua:"#00ffff",magenta:"#ff00ff",fuchsia:"#ff00ff",silver:"#c0c0c0",gray:"#808080",grey:"#808080",maroon:"#800000",olive:"#808000",purple:"#800080",teal:"#008080",navy:"#000080",orange:"#ffa500",pink:"#ffc0cb",hotpink:"#ff69b4",gold:"#ffd700",indigo:"#4b0082",violet:"#ee82ee",brown:"#a52a2a",beige:"#f5f5dc",ivory:"#fffff0",khaki:"#f0e68c",coral:"#ff7f50",salmon:"#fa8072",tomato:"#ff6347",crimson:"#dc143c",turquoise:"#40e0d0",lavender:"#e6e6fa",plum:"#dda0dd",orchid:"#da70d6",tan:"#d2b48c",chocolate:"#d2691e",sienna:"#a0522d",slategray:"#708090",slategrey:"#708090",steelblue:"#4682b4",royalblue:"#4169e1",dodgerblue:"#1e90ff",skyblue:"#87ceeb",lightblue:"#add8e6",midnightblue:"#191970",forestgreen:"#228b22",seagreen:"#2e8b57",limegreen:"#32cd32",olivedrab:"#6b8e23",darkgreen:"#006400",emerald:"#50c878",mint:"#3eb489",goldenrod:"#daa520",firebrick:"#b22222",darkred:"#8b0000",indianred:"#cd5c5c",deeppink:"#ff1493",mediumpurple:"#9370db",rebeccapurple:"#663399",darkviolet:"#9400d3",slateblue:"#6a5acd",cornflowerblue:"#6495ed",teal2:"#008080",charcoal:"#36454f",graphite:"#3b3b3b",transparent:"transparent"},xx=/^rgba?\(\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*(,\s*(0|1|0?\.\d+|\d{1,3}%)\s*)?\)$/;function wx(e){return xx.test(e)}function os(e){if(typeof e!="string"||e.trim()==="")throw new Error('Color must be a non-empty string (e.g. "#2563eb" or "blue").');let t=e.trim().toLowerCase(),n=Bi[t];if(n)return n;let o=Es(t);if(Qi(o)||o==="transparent"||wx(o))return o;throw new Error(`"${e}" is not a recognized color. Pass a hex value like "#ef4444" or a CSS color name (e.g. ${Object.keys(Bi).slice(0,6).join(", ")}).`)}var Hi=Ia.map(e=>e==="gray"?"neutral":e),Cx={...Object.fromEntries(Hi.map(e=>[e,e])),gray:"neutral",grey:"neutral"};function Di(e,t=!0){let n=String(e!=null?e:"").trim().toLowerCase(),o=Cx[n];if(!o||!t&&o==="neutral"){let r=t?"primary, secondary, accent, neutral":"primary, secondary, accent";throw new Error(`Unknown color family "${e}". Valid families: ${r}.`)}return o}function Fi(e){let t=String(e!=null?e:"solid").trim().toLowerCase();if(t==="solid"||t==="soft")return t;throw new Error(`Unknown intensity "${e}". Valid intensities: solid, soft.`)}function Oi(e){let t=String(e!=null?e:"").trim().toLowerCase();if(t==="light"||t==="dark"||t==="auto")return t;if(t==="system")return"auto";throw new Error(`Unknown color scheme "${e}". Valid: light, dark, auto.`)}var Sx={sharp:"sharp",square:"sharp",none:"sharp",default:"default",normal:"default",rounded:"rounded",round:"rounded",soft:"rounded",pill:"pill",circle:"pill",full:"pill"};function Ni(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=Sx[t];if(!n)throw new Error(`Unknown roundness "${e}". Valid: sharp, default, rounded, pill.`);return n}function _i(e){if(typeof e=="number"&&Number.isFinite(e))return`${e}px`;if(typeof e=="string"&&e.trim()!==""){let t=e.trim();if(t==="9999px"||/^(100%|9999px)$/.test(t))return"9999px";let n=Yi(t);return Xi(n.value,n.unit)}throw new Error('Radius must be a number (px) or a CSS length string like "0.5rem".')}function Vi(e){for(let t of zr){let n=t.fields.find(o=>o.id===e);if(n!=null&&n.options){let o={};for(let r of n.options){let s=r.value.split(".").pop();s&&(o[s]=r.value)}return o}}return{}}var Zm=Vi("typo-font-family"),ta=Vi("typo-font-size"),na=Vi("typo-font-weight"),Wi=Vi("typo-line-height"),ef={...Zm,monospace:Zm.mono},tf={...ta,small:ta.sm,md:ta.base,medium:ta.base,large:ta.lg},nf={...na,400:na.normal,500:na.medium,600:na.semibold,700:na.bold},of={...Wi,"1.25":Wi.tight,"1.5":Wi.normal,"1.625":Wi.relaxed};function rf(e,t,n){let o=String(e!=null?e:"").trim().toLowerCase(),r=t[o];if(!r){let s=[...new Set(Object.values(t).map(a=>a.split(".").pop()))].join(", ");throw new Error(`Unknown ${n} "${e}". Valid: ${s}.`)}return r}var sf="theme.palette.radius.";function Ax(){var t;let e={pill:{sm:"9999px",md:"9999px",lg:"9999px",xl:"9999px",full:"9999px"}};for(let n of zr)for(let o of(t=n.presets)!=null?t:[]){let r=o.id.match(/^radius-(\w+)$/);if(!r)continue;let s={};for(let[a,i]of Object.entries(o.values))a.startsWith(sf)&&typeof i=="string"&&(s[a.slice(sf.length)]=i);e[r[1]]=s}return e}var ra=Ax(),af=["sm","md","lg","xl","full"];function Ui(e,t,n="theme",o=0){if(o>6)return null;let r=e.get(`${n}.${t}`);return typeof r!="string"||r===""?n==="darkTheme"?Ui(e,t,"theme",o):null:r.startsWith("#")||r.startsWith("rgb")||r==="transparent"?r:r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components.")?Ui(e,r,n,o+1):null}function $i(e,t){let n=e.get(t);if(typeof n!="string")return"unknown";let o=n.split(".");return o[o.length-1]||String(n)}function rs(e){return e.replace(/^role-/,"")}function Tx(e){for(let[t,n]of Object.entries(ra))if(af.every(o=>e[o]===n[o]))return t;return"custom"}function Ir(e){var o,r;let t={};for(let s of af)t[s]=String((o=e.get(`theme.palette.radius.${s}`))!=null?o:"");let n={};for(let s of wr)n[rs(s.roleId)]=tl(a=>e.get(`theme.${a}`),s);return{brand:{primary:Ql(e.get("theme.palette.colors.primary.500")),secondary:Ql(e.get("theme.palette.colors.secondary.500")),accent:Ql(e.get("theme.palette.colors.accent.500"))},roles:n,typography:{fontFamily:$i(e,"theme.semantic.typography.fontFamily"),fontSize:$i(e,"theme.semantic.typography.fontSize"),fontWeight:$i(e,"theme.semantic.typography.fontWeight"),lineHeight:$i(e,"theme.semantic.typography.lineHeight")},roundness:{style:Tx(t),radius:t},colorScheme:String((r=e.get("colorScheme"))!=null?r:"light"),history:{index:e.getHistoryIndex(),canUndo:e.canUndo(),canRedo:e.canRedo()}}}function Ql(e){return typeof e=="string"&&e!==""?e:null}var oa=[{key:"user-message",label:"User message text",fg:"components.message.user.text",bg:"components.message.user.background"},{key:"assistant-message",label:"Assistant message text",fg:"components.message.assistant.text",bg:"components.message.assistant.background"},{key:"header",label:"Header title",fg:"components.header.titleForeground",bg:"components.header.background"},{key:"primary-button",label:"Primary button label",fg:"components.button.primary.foreground",bg:"components.button.primary.background"},{key:"input",label:"Input placeholder",fg:"components.input.placeholder",bg:"components.input.background"},{key:"link",label:"Link text",fg:"components.markdown.link.foreground",bg:"semantic.colors.background"},{key:"scroll",label:"Scroll-to-bottom icon",fg:"components.scrollToBottom.foreground",bg:"components.scrollToBottom.background"},{key:"body",label:"Body text on background",fg:"semantic.colors.text",bg:"semantic.colors.background"},{key:"surface",label:"Body text on surface",fg:"semantic.colors.text",bg:"semantic.colors.surface"}];function lf(e){let t=new Set(e.targets.map(n=>n.path));return oa.filter(n=>t.has(n.fg)||t.has(n.bg)).map(n=>n.key)}var kx={AA:4.5,AAA:7};function Ex(e){return Math.round(e*100)/100}function Mx(e,t,n,o,r){let s=e.get(`${r}.${t}`);if(typeof s!="string")return null;let a=s.match(/^palette\.colors\.(\w+)\.(\d+)$/);if(!a)return null;let i=a[1],d=Ur.indexOf(a[2]),l=null,m=1/0;return Ur.forEach((u,g)=>{let p=e.get(`${r}.palette.colors.${i}.${u}`);if(!(typeof p!="string"||!(p.startsWith("#")||p.startsWith("rgb")))&&La(p,n)>=o){let w=d>=0?Math.abs(g-d):g;w<m&&(m=w,l=`palette.colors.${i}.${u}`)}}),l}function sa(e,t="AA",n="both",o){let r=kx[t],s=n==="both"?["light","dark"]:[n],a=o?oa.filter(d=>o.includes(d.key)):oa,i=[];for(let d of s){let l=d==="light"?"theme":"darkTheme";for(let m of a){let u=Ui(e,m.fg,l),g=Ui(e,m.bg,l);if(!u||!g)continue;let p=Ex(La(u,g)),w=p>=r,S={pair:m.key,label:m.label,variant:d,fg:u,bg:g,ratio:p,threshold:r,passes:w};if(!w){let M=Mx(e,m.fg,g,r,l);M&&(S.suggestion=M)}i.push(S)}}return{level:t,checks:i,failures:i.filter(d=>!d.passes)}}function ss(e,t,n="light",o="AA"){return t.length===0?[]:sa(e,o,n,t).failures.map(s=>({code:"contrast",pair:s.pair,variant:s.variant,ratio:s.ratio,threshold:s.threshold,message:`${s.label} (${s.variant}) has a contrast ratio of ${s.ratio}:1, below the ${o} threshold of ${s.threshold}:1${s.suggestion?`. Try ${s.suggestion} for the foreground.`:"."}`}))}var an={};for(let e of wr){let t=rs(e.roleId);an[t]=e,an[e.roleId]=e}Object.assign(an,{surface:an.surfaces,background:an.surfaces,backgrounds:an.surfaces,user:an["user-messages"],"user-message":an["user-messages"],assistant:an["assistant-messages"],"assistant-message":an["assistant-messages"],actions:an["primary-actions"],buttons:an["primary-actions"],composer:an.input,links:an["links-focus"],focus:an["links-focus"],border:an.borders,dividers:an.borders,scroll:an["scroll-to-bottom"]});function Lx(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=an[t];if(!n){let o=wr.map(r=>rs(r.roleId)).join(", ");throw new Error(`Unknown role "${e}". Valid roles: ${o}.`)}return n}function cf(){let e=new Map,t=n=>{for(let o of n)for(let r of o.fields)e.has(r.id)||e.set(r.id,r)};for(let n of ol)t(n.sections);for(let n of Va)t(n.sections);return e}var Ix={voice:"voiceRecognition.enabled",artifacts:"features.artifacts.enabled",attachments:"attachments.enabled",toolCalls:"features.showToolCalls",reasoning:"features.showReasoning",feedback:"messageActions.enabled"},Rx={avatars:"layout.messages.avatar.show",timestamps:"layout.messages.timestamp.show",showHeader:"layout.showHeader",messageStyle:"layout.messages.layout"},Jl=["bottom-right","bottom-left","top-right","top-left"],Zl=["bubble","flat","minimal"],Px={title:"copy.welcomeTitle",subtitle:"copy.welcomeSubtitle",placeholder:"copy.inputPlaceholder",sendLabel:"copy.sendButtonLabel"};function df(e,t){var W;let n=(W=t==null?void 0:t.editTarget)!=null?W:"both",o=null,r=v=>v&&typeof v=="object"?v:{},s=(v,x,k=n)=>{let C={};return(k==="light"||k==="both")&&(C[`theme.${v}`]=x),(k==="dark"||k==="both")&&(C[`darkTheme.${v}`]=x),C},a=v=>{if(n==="both")return v;let x={};for(let[k,C]of Object.entries(v))(n==="light"&&k.startsWith("theme.")||n==="dark"&&k.startsWith("darkTheme."))&&(x[k]=C);return x},i=()=>n==="dark"?"dark":"light",d=(v,x=[])=>Vo({ok:!0,summary:Ir(e),warnings:x,applied:v});return[{name:"get_theme_overview",title:"Get current theme & what is editable",description:"Read the current widget theme (brand colors, per-role color assignments, typography, roundness, color scheme, undo/redo state), the available presets, and the high-level levers you can change. Call this FIRST before editing.",annotations:{readOnlyHint:!0},inputSchema:{type:"object",properties:{verbosity:{type:"string",enum:["summary","full"],description:"Use 'full' to also include the field-id index for set_theme_fields."}},additionalProperties:!1},execute(v){let{verbosity:x}=r(v),k={summary:Ir(e),availableRoles:wr.map(C=>({role:rs(C.roleId),helper:C.helper})),availableFamilies:Hi,presets:Ls.map(C=>{var T;return{id:C.id,name:C.name,description:C.description,tags:(T=C.tags)!=null?T:[]}}),tools:[{tool:"set_brand_colors",hint:"Recolor the palette (primary/secondary/accent) \u2014 auto-generates shade scales."},{tool:"assign_color_role",hint:"Recolor a region (header, user/assistant messages, actions, input, links, borders, surfaces, scroll) with a family + intensity."},{tool:"set_typography",hint:"Set font family, size, weight, line height."},{tool:"set_roundness",hint:"Set corner roundness (sharp/default/rounded/pill) or granular radii."},{tool:"set_color_scheme",hint:"Set light/dark/auto and which variant edits target."},{tool:"apply_preset",hint:"Apply a complete built-in preset."},{tool:"configure_widget",hint:"Toggle launcher position, features, and layout."},{tool:"set_copy_and_suggestions",hint:"Set welcome copy, placeholder, and suggestion chips."},{tool:"set_theme_fields",hint:"Advanced escape hatch: set any field by id or dot-path."},{tool:"check_contrast",hint:"Audit WCAG contrast across key text/background pairs."},{tool:"manage_session",hint:"Undo, redo, reset, or export the theme."}]};return x==="full"&&(o!=null||(o=cf()),k.fieldIndex=Array.from(o.values()).map(C=>{var T;return{id:C.id,path:C.path,type:C.type,label:C.label,options:(T=C.options)==null?void 0:T.map(F=>F.value)}})),Vo(k)}},{name:"set_brand_colors",title:"Set brand colors",description:'Set one or more brand colors (primary, secondary, accent). Each color auto-generates a full 50\u2013950 shade scale and applies to the light and dark themes (per the current edit target). Accepts hex ("#2563eb", "2563eb", "#18f"), rgb()/rgba() ("rgb(37, 99, 235)"), or CSS color names ("blue", "slateblue").',inputSchema:{type:"object",properties:{primary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},secondary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},accent:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."}},additionalProperties:!1},execute(v){let x=r(v),k=["primary","secondary","accent"],C={},T={};for(let $ of k){if(x[$]===void 0)continue;let j=os(x[$]);T[$]=j;let me=Zi(j);for(let se of Ur){let fe=me[se];fe!==void 0&&Object.assign(C,s(`palette.colors.${$}.${se}`,fe))}}if(Object.keys(T).length===0)throw new Error("Provide at least one of: primary, secondary, accent.");e.setBatch(C);let F=ss(e,["primary-button","user-message"],i());return d(T,F)}},{name:"assign_color_role",title:"Assign a color family to an interface role",description:"Recolor a semantic region of the widget by choosing a palette family and intensity. One call writes all related tokens (background, text, border, icon) consistently. Roles: header, user-messages, assistant-messages, primary-actions, input, links, borders, surfaces, scroll-to-bottom. Families: primary, secondary, accent, neutral. Intensity: solid (bold) or soft (tinted).",inputSchema:{type:"object",properties:{role:{type:"string",description:'Interface role, e.g. "header" or "user-messages".'},family:{type:"string",enum:Hi},intensity:{type:"string",enum:["solid","soft"],description:"Defaults to 'solid'."}},required:["role","family"],additionalProperties:!1},execute(v){let x=r(v),k=Lx(x.role),C=Di(x.family,!0),T=Fi(x.intensity),F=a(_a(C,T,k)),$=Object.keys(F).length;e.setBatch(F);let j=ss(e,lf(k),i());return d({role:rs(k.roleId),family:C,intensity:T,tokensWritten:$},j)}},{name:"set_typography",title:"Set typography",description:"Set font family, base size, weight, and line height in one call. fontFamily: sans|serif|mono. fontSize: xs|sm|base|lg|xl. fontWeight: normal|medium|semibold|bold (or 400\u2013700). lineHeight: tight|normal|relaxed (or 1.25/1.5/1.625).",inputSchema:{type:"object",properties:{fontFamily:{type:"string"},fontSize:{type:"string"},fontWeight:{type:["string","number"]},lineHeight:{type:["string","number"]}},additionalProperties:!1},execute(v){let x=r(v),k={},C={},T=(F,$)=>{var me;if(x[F]===void 0)return;let j=rf(x[F],$,F);C[F]=(me=j.split(".").pop())!=null?me:j,Object.assign(k,s(`semantic.typography.${F}`,j))};if(T("fontFamily",ef),T("fontSize",tf),T("fontWeight",nf),T("lineHeight",of),Object.keys(C).length===0)throw new Error("Provide at least one of: fontFamily, fontSize, fontWeight, lineHeight.");return e.setBatch(k),d(C)}},{name:"set_roundness",title:"Set corner roundness",description:"Set overall corner roundness with a keyword (sharp, default, rounded, pill) which maps the full radius scale, OR pass granular radius values. Provide at least one of `style` or `radius`.",inputSchema:{type:"object",properties:{style:{type:"string",enum:["sharp","default","rounded","pill"]},radius:{type:"object",description:"Granular overrides (px number or CSS length).",properties:{sm:{type:["string","number"]},md:{type:["string","number"]},lg:{type:["string","number"]},xl:{type:["string","number"]},full:{type:["string","number"]}},additionalProperties:!1}},additionalProperties:!1},execute(v){let x=r(v),k={},C={};if(x.style!==void 0){let T=Ni(x.style);C.style=T;for(let[F,$]of Object.entries(ra[T]))Object.assign(k,s(`palette.radius.${F}`,$))}if(x.radius!==void 0){let T=r(x.radius),F={};for(let $ of["sm","md","lg","xl","full"]){if(T[$]===void 0)continue;let j=_i(T[$]);F[$]=j,Object.assign(k,s(`palette.radius.${$}`,j))}C.radius=F}if(Object.keys(k).length===0)throw new Error("Provide `style` (sharp|default|rounded|pill) or a `radius` object.");return e.setBatch(k),d(C)}},{name:"set_color_scheme",title:"Set color scheme",description:"Set the shipped widget color scheme (light, dark, or auto/follow-system). Optionally set `editTarget` to choose which theme variant subsequent styling edits write to (light, dark, or both \u2014 default both).",inputSchema:{type:"object",properties:{scheme:{type:"string",enum:["light","dark","auto"]},editTarget:{type:"string",enum:["light","dark","both"]}},additionalProperties:!1},execute(v){let x=r(v),k={};if(x.scheme!==void 0){let C=Oi(x.scheme);e.set("colorScheme",C),k.scheme=C}if(x.editTarget!==void 0){let C=String(x.editTarget).trim().toLowerCase();if(C!=="light"&&C!=="dark"&&C!=="both")throw new Error(`Unknown editTarget "${x.editTarget}". Valid: light, dark, both.`);n=C,k.editTarget=C}if(Object.keys(k).length===0)throw new Error("Provide `scheme` and/or `editTarget`.");return Vo({ok:!0,summary:Ir(e),warnings:[],applied:k,editTarget:n})}},{name:"apply_preset",title:"Apply a built-in theme preset",description:"Apply a complete built-in preset, replacing theme tokens. Call get_theme_overview to list preset ids.",inputSchema:{type:"object",properties:{presetId:{type:"string"}},required:["presetId"],additionalProperties:!1},execute(v){let{presetId:x}=r(v),k=rl(String(x!=null?x:""));if(!k){let $=Ls.map(j=>j.id).join(", ");throw new Error(`Unknown preset "${x}". Valid presets: ${$}.`)}let C=tn(k.theme,{validate:!1}),T={...e.getConfig()};k.darkTheme&&(T.darkTheme=tn(k.darkTheme,{validate:!1})),k.toolCall&&(T.toolCall=k.toolCall),e.setFullConfig(T,C);let F=ss(e,["body","assistant-message"],"light");return d({appliedPreset:{id:k.id,name:k.name}},F)}},{name:"configure_widget",title:"Configure launcher, features, and layout",description:"Toggle non-theme widget configuration. launcherPosition: bottom-right|bottom-left|top-right|top-left. features: { voice, artifacts, attachments, toolCalls, reasoning, feedback } booleans. layout: { avatars, timestamps, showHeader } booleans and messageStyle: bubble|flat|minimal.",inputSchema:{type:"object",properties:{launcherPosition:{type:"string",enum:Jl},features:{type:"object",properties:{voice:{type:"boolean"},artifacts:{type:"boolean"},attachments:{type:"boolean"},toolCalls:{type:"boolean"},reasoning:{type:"boolean"},feedback:{type:"boolean"}},additionalProperties:!1},layout:{type:"object",properties:{avatars:{type:"boolean"},timestamps:{type:"boolean"},showHeader:{type:"boolean"},messageStyle:{type:"string",enum:Zl}},additionalProperties:!1}},additionalProperties:!1},execute(v){var $,j,me;let x=r(v),k={},C={};if(x.launcherPosition!==void 0){let se=String(x.launcherPosition);if(!Jl.includes(se))throw new Error(`Unknown launcherPosition "${se}". Valid: ${Jl.join(", ")}.`);k["launcher.position"]=se,C.launcherPosition=se}let T=r(x.features);for(let[se,fe]of Object.entries(Ix))T[se]!==void 0&&(k[fe]=!!T[se],($=C.features)!=null||(C.features={}),C.features[se]=!!T[se]);let F=r(x.layout);for(let[se,fe]of Object.entries(Rx))if(F[se]!==void 0)if(se==="messageStyle"){let ie=String(F[se]);if(!Zl.includes(ie))throw new Error(`Unknown messageStyle "${ie}". Valid: ${Zl.join(", ")}.`);k[fe]=ie,(j=C.layout)!=null||(C.layout={}),C.layout[se]=ie}else k[fe]=!!F[se],(me=C.layout)!=null||(C.layout={}),C.layout[se]=!!F[se];if(Object.keys(k).length===0)throw new Error("Provide launcherPosition, features, and/or layout.");return e.setBatch(k),d(C)}},{name:"set_copy_and_suggestions",title:"Set welcome copy and suggestion chips",description:"Set the widget welcome copy and suggestion chips. title/subtitle are the welcome card text; placeholder is the input placeholder; sendLabel is the send button label; suggestions is an array of suggestion-chip strings (replaces the existing list).",inputSchema:{type:"object",properties:{title:{type:"string"},subtitle:{type:"string"},placeholder:{type:"string"},sendLabel:{type:"string"},suggestions:{type:"array",items:{type:"string"}}},additionalProperties:!1},execute(v){let x=r(v),k={},C={};for(let[T,F]of Object.entries(Px))x[T]!==void 0&&(k[F]=String(x[T]),C[T]=String(x[T]));if(x.suggestions!==void 0){if(!Array.isArray(x.suggestions))throw new Error("`suggestions` must be an array of strings.");let T=x.suggestions.filter(F=>typeof F=="string");k.suggestionChips=T,C.suggestions=T}if(Object.keys(k).length===0)throw new Error("Provide at least one of: title, subtitle, placeholder, sendLabel, suggestions.");return e.setBatch(k),d(C)}},{name:"set_theme_fields",title:"Set theme fields by id or path (advanced)",description:'Advanced escape hatch: set individual editor fields by field id (see get_theme_overview verbosity:"full") \u2014 theme field ids follow the current edit target (light/dark/both) \u2014 or by raw dot-path (theme.* / darkTheme.* / a config path), which is written as-is. Use only when a higher-level tool does not cover the need. Values are validated against the field metadata.',inputSchema:{type:"object",properties:{updates:{type:"array",items:{type:"object",properties:{field:{type:"string",description:"Field id or dot-path."},value:{type:["string","number","boolean"]}},required:["field","value"],additionalProperties:!1}}},required:["updates"],additionalProperties:!1},execute(v){var F;let{updates:x}=r(v);if(!Array.isArray(x)||x.length===0)throw new Error("`updates` must be a non-empty array of { field, value }.");o!=null||(o=cf());let k={},C=[];for(let $ of x){let j=r($),me=String((F=j.field)!=null?F:"");try{let se=o.get(me),fe=se?se.path:me;if(!se&&!/^(theme|darkTheme)\.|\./.test(fe))throw new Error(`Unknown field "${me}". Pass a known field id or a dot-path (e.g. theme.palette.radius.md).`);let ie=Wx(se,j.value);if(se&&fe.startsWith("theme.")){let be=s(fe.slice(6),ie);Object.assign(k,be),C.push({field:me,resolvedPath:Object.keys(be),ok:!0})}else k[fe]=ie,C.push({field:me,resolvedPath:fe,ok:!0})}catch(se){C.push({field:me,ok:!1,error:se.message})}}let T=C.filter($=>$.ok);return Object.keys(k).length>0&&e.setBatch(k),Vo({ok:T.length>0,summary:Ir(e),warnings:[],applied:{updates:C}})}},{name:"check_contrast",title:"Check accessibility contrast",description:"Run WCAG contrast checks over the key text/background pairs (message text, header title, input/body text, primary button). Returns each ratio, whether it passes, and a suggested foreground shade for failures.",annotations:{readOnlyHint:!0},inputSchema:{type:"object",properties:{level:{type:"string",enum:["AA","AAA"],description:"Defaults to 'AA'."},variant:{type:"string",enum:["light","dark","both"],description:"Defaults to 'both'."}},additionalProperties:!1},execute(v){let x=r(v),k=x.level==="AAA"?"AAA":"AA",C=x.variant==="light"||x.variant==="dark"?x.variant:"both",T=sa(e,k,C);return Vo({level:T.level,passing:T.checks.length-T.failures.length,total:T.checks.length,checks:T.checks,failures:T.failures})}},{name:"manage_session",title:"Undo, redo, reset, or export the theme",description:'Session action. "undo"/"redo" step through edit history; "reset" restores defaults; "export" returns the embeddable theme snapshot (config + theme JSON) with no side effects.',inputSchema:{type:"object",properties:{action:{type:"string",enum:["undo","redo","reset","export"]}},required:["action"],additionalProperties:!1},execute(v){let{action:x}=r(v);switch(x){case"undo":return e.undo(),d({action:"undo"});case"redo":return e.redo(),d({action:"redo"});case"reset":return e.resetToDefaults(),d({action:"reset"});case"export":return Vo({ok:!0,snapshot:e.exportSnapshot()});default:throw new Error(`Unknown action "${x}". Valid: undo, redo, reset, export.`)}}}]}function Wx(e,t){if(!e)return t;switch(e.type){case"color":return e.parseValue?e.parseValue(os(t)):os(t);case"toggle":return typeof t=="boolean"?t:t==="true"||t===1;case"slider":{let n=Number(t);if(!Number.isFinite(n))throw new Error(`"${e.id}" expects a number.`);if(e.slider){let{min:o,max:r}=e.slider;if(n<o||n>r)throw new Error(`"${e.id}" must be between ${o} and ${r}.`)}return e.parseValue?e.parseValue(n):n}case"select":{let n=String(t);if(e.options&&!e.options.some(o=>o.value===n))throw new Error(`"${e.id}" must be one of: ${e.options.map(o=>o.value).join(", ")}.`);return e.parseValue?e.parseValue(n):n}default:return e.parseValue?e.parseValue(t):t}}export{yu as ADVANCED_TOKENS_SECTION,wr as ALL_ROLES,ol as ALL_TABS,fu as BRAND_PALETTE_SECTION,xu as BUILT_IN_PRESETS,Vf as COLORS_SECTIONS,el as COLOR_FAMILIES,pu as COMPONENTS_SECTIONS,du as COMPONENT_COLOR_SECTIONS,cu as COMPONENT_SHAPE_SECTIONS,uu as CONFIGURE_SECTIONS,Va as CONFIGURE_SUB_GROUPS,oa as CONTRAST_PAIRS,Bi as CSS_NAMED_COLORS,ns as DEVICE_DIMENSIONS,jm as HOME_SUGGESTION_CHIPS,hu as INTERFACE_ROLES_SECTION,Gm as MOCK_BROWSER_CONTENT,Ym as MOCK_WORKSPACE_CONTENT,Nf as PALETTE_SECTION,qm as PREVIEW_STORAGE_ADAPTER,ra as RADIUS_PRESETS,Ba as ROLE_ASSISTANT_MESSAGES,Na as ROLE_BORDERS,Ia as ROLE_FAMILIES,kf as ROLE_FAMILY_LABELS,Pa as ROLE_HEADER,Fa as ROLE_INPUT,ko as ROLE_INTENSITIES,Oa as ROLE_LINKS_FOCUS,Ha as ROLE_PRIMARY_ACTIONS,Da as ROLE_SCROLL_TO_BOTTOM,Ra as ROLE_SURFACES,Wa as ROLE_USER_MESSAGES,_f as SEMANTIC_COLORS_SECTION,Ur as SHADE_KEYS,Ri as SHELL_STYLE_ID,bu as STATUS_COLORS_SECTION,gu as STATUS_PALETTE_SECTION,zr as STYLE_SECTIONS,Sg as STYLE_SECTIONS_V2,Ls as THEME_EDITOR_PRESETS,mu as THEME_SECTION,Gi as ThemeEditorState,ql as ZOOM_MAX,zl as ZOOM_MIN,fx as appendPreviewTranscriptEntry,Xl as applySceneConfig,Kl as applyShellTheme,Lr as buildPreviewConfig,yx as buildPreviewConfigWithMessages,jl as buildShellCss,Gl as buildSrcdoc,Ir as buildSummary,gx as buildTranscriptStreamFrames,os as coerceColor,Di as coerceFamily,Fi as coerceIntensity,_i as coerceRadius,Ni as coerceRoundnessStyle,Oi as coerceScheme,Sf as convertFromPx,Cf as convertToPx,Qm as createPreviewMessages,Yl as createPreviewTranscriptEntry,df as createThemeEditorTools,vx as createThemePreview,tl as detectRoleAssignment,Pi as escapeHtml,Tg as findSection,Xi as formatCssValue,Zi as generateColorScale,mx as getPreviewTranscriptPresetLabel,Km as getShellPalette,rl as getThemeEditorPreset,ru as hexToHsl,su as hslToHex,Qi as isValidHex,Es as normalizeColorValue,Af as paletteColorPath,Yi as parseCssValue,Xm as presetStreamsText,ss as quickContrastWarnings,_a as resolveRoleAssignment,au as resolveThemeColorPath,Ji as rgbToHex,sa as runContrastChecks,kg as scopeSection,Tf as tokenRefDisplayName,Vo as toolResult,La as wcagContrastRatio};
|