@runtypelabs/persona 3.30.0 → 3.31.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/README.md +15 -2602
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/{types-B_Qazlm4.d.cts → types-quh7NmYD.d.cts} +9 -0
- package/dist/animations/{types-B_Qazlm4.d.ts → types-quh7NmYD.d.ts} +9 -0
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/codegen.cjs +4 -4
- package/dist/codegen.js +3 -3
- package/dist/index.cjs +46 -46
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +52 -0
- package/dist/index.d.ts +52 -0
- package/dist/index.global.js +77 -80
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +45 -45
- package/dist/index.js.map +1 -1
- package/dist/launcher.global.js +2 -2
- package/dist/launcher.global.js.map +1 -1
- package/dist/smart-dom-reader.d.cts +50 -0
- package/dist/smart-dom-reader.d.ts +50 -0
- package/dist/theme-editor.cjs +39 -39
- package/dist/theme-editor.d.cts +50 -0
- package/dist/theme-editor.d.ts +50 -0
- package/dist/theme-editor.js +39 -39
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.js +1 -1
- package/dist/webmcp-polyfill.js +4 -0
- package/dist/widget.css +19 -0
- package/package.json +4 -3
- package/src/client.ts +6 -0
- package/src/components/approval-bubble.test.ts +52 -0
- package/src/components/approval-bubble.ts +20 -0
- package/src/components/panel.ts +7 -1
- package/src/defaults.ts +14 -0
- package/src/generated/runtype-openapi-contract.ts +4 -0
- package/src/index-global.ts +39 -0
- package/src/session.test.ts +62 -0
- package/src/session.ts +27 -0
- package/src/styles/widget.css +19 -0
- package/src/theme-reference.ts +1 -1
- package/src/types.ts +50 -0
- package/src/ui.scroll.test.ts +383 -0
- package/src/ui.ts +390 -40
- package/src/utils/auto-follow.test.ts +91 -0
- package/src/utils/auto-follow.ts +68 -0
- package/src/version.ts +5 -2
- package/src/webmcp-bridge.test.ts +60 -0
- package/src/webmcp-bridge.ts +34 -1
- package/src/webmcp-polyfill.ts +16 -0
package/dist/theme-editor.cjs
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
"use strict";var Yg=Object.create;var Za=Object.defineProperty;var Xg=Object.getOwnPropertyDescriptor;var Qg=Object.getOwnPropertyNames;var Jg=Object.getPrototypeOf,Zg=Object.prototype.hasOwnProperty;var ef=(e,t)=>{for(var n in t)Za(e,n,{get:t[n],enumerable:!0})},Lu=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Qg(t))!Zg.call(e,r)&&r!==n&&Za(e,r,{get:()=>t[r],enumerable:!(o=Xg(t,r))||o.enumerable});return e};var Iu=(e,t,n)=>(n=e!=null?Yg(Jg(e)):{},Lu(t||!e||!e.__esModule?Za(n,"default",{value:e,enumerable:!0}):n,e)),tf=e=>Lu(Za({},"__esModule",{value:!0}),e);var Xy={};ef(Xy,{ADVANCED_TOKENS_SECTION:()=>Wl,ALL_ROLES:()=>ir,ALL_TABS:()=>di,BRAND_PALETTE_SECTION:()=>Ll,BUILT_IN_PRESETS:()=>Bl,COLORS_SECTIONS:()=>Yu,COLOR_FAMILIES:()=>li,COMPONENTS_SECTIONS:()=>Tl,COMPONENT_COLOR_SECTIONS:()=>Al,COMPONENT_SHAPE_SECTIONS:()=>Sl,CONFIGURE_SECTIONS:()=>El,CONFIGURE_SUB_GROUPS:()=>ea,CONTRAST_PAIRS:()=>hs,CSS_NAMED_COLORS:()=>Ia,DEVICE_DIMENSIONS:()=>Nr,HOME_SUGGESTION_CHIPS:()=>Cc,INTERFACE_ROLES_SECTION:()=>Rl,MOCK_BROWSER_CONTENT:()=>Ac,MOCK_WORKSPACE_CONTENT:()=>Tc,PALETTE_SECTION:()=>Ku,PREVIEW_STORAGE_ADAPTER:()=>wc,RADIUS_PRESETS:()=>bs,ROLE_ASSISTANT_MESSAGES:()=>js,ROLE_BORDERS:()=>Qs,ROLE_FAMILIES:()=>$s,ROLE_FAMILY_LABELS:()=>Uu,ROLE_HEADER:()=>zs,ROLE_INPUT:()=>Ys,ROLE_INTENSITIES:()=>ko,ROLE_LINKS_FOCUS:()=>Xs,ROLE_PRIMARY_ACTIONS:()=>Ks,ROLE_SCROLL_TO_BOTTOM:()=>Gs,ROLE_SURFACES:()=>Us,ROLE_USER_MESSAGES:()=>qs,SEMANTIC_COLORS_SECTION:()=>Gu,SHADE_KEYS:()=>Lr,SHELL_STYLE_ID:()=>ka,STATUS_COLORS_SECTION:()=>Pl,STATUS_PALETTE_SECTION:()=>Il,STYLE_SECTIONS:()=>Ir,STYLE_SECTIONS_V2:()=>Xu,THEME_EDITOR_PRESETS:()=>os,THEME_SECTION:()=>Ml,ThemeEditorState:()=>ni,ZOOM_MAX:()=>rl,ZOOM_MIN:()=>ol,appendPreviewTranscriptEntry:()=>Bg,applySceneConfig:()=>cl,applyShellTheme:()=>al,buildPreviewConfig:()=>mr,buildPreviewConfigWithMessages:()=>Dg,buildShellCss:()=>sl,buildSrcdoc:()=>il,buildSummary:()=>gr,buildTranscriptStreamFrames:()=>Hg,coerceColor:()=>_r,coerceFamily:()=>Ra,coerceIntensity:()=>Pa,coerceRadius:()=>Ha,coerceRoundnessStyle:()=>Ba,coerceScheme:()=>Wa,convertFromPx:()=>_u,convertToPx:()=>Nu,createPreviewMessages:()=>Ec,createPreviewTranscriptEntry:()=>ll,createThemeEditorTools:()=>Rc,createThemePreview:()=>Og,detectRoleAssignment:()=>ci,escapeHtml:()=>Ea,findSection:()=>Ju,formatCssValue:()=>ri,generateColorScale:()=>ii,getPreviewTranscriptPresetLabel:()=>Wg,getShellPalette:()=>Sc,getThemeEditorPreset:()=>pi,hexToHsl:()=>vl,hslToHex:()=>xl,isValidHex:()=>si,normalizeColorValue:()=>ts,paletteColorPath:()=>Vu,parseCssValue:()=>oi,presetStreamsText:()=>kc,quickContrastWarnings:()=>Vr,resolveRoleAssignment:()=>Js,resolveThemeColorPath:()=>wl,rgbToHex:()=>ai,runContrastChecks:()=>vs,scopeSection:()=>Zu,tokenRefDisplayName:()=>$u,toolResult:()=>Ho,wcagContrastRatio:()=>Vs});module.exports=tf(Xy);var Ru=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function _s(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];Ru(s)&&Ru(r)?n[o]=_s(s,r):n[o]=r}return n}var fo="min(440px, calc(100vw - 24px))",ei="440px",Rt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:fo,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Pu(e,t){if(!(!e&&!t))return e?t?_s(e,t):e:t}function Wu(e){var t,n,o,r,s,a,i,d,l,m,p,f,u,C,v,M,I,R,W,D,B;return e?{...Rt,...e,theme:Pu(Rt.theme,e.theme),darkTheme:Pu(Rt.darkTheme,e.darkTheme),launcher:{...Rt.launcher,...e.launcher,dock:{...(t=Rt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(o=Rt.launcher)==null?void 0:o.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...Rt.copy,...e.copy},sendButton:{...Rt.sendButton,...e.sendButton},statusIndicator:{...Rt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Rt.voiceRecognition,...e.voiceRecognition},features:(()=>{var ye,Oe,we,K,pe,G,ve,ce;let x=(ye=Rt.features)==null?void 0:ye.artifacts,w=(Oe=e.features)==null?void 0:Oe.artifacts,E=(we=Rt.features)==null?void 0:we.scrollToBottom,S=(K=e.features)==null?void 0:K.scrollToBottom,T=(pe=Rt.features)==null?void 0:pe.streamAnimation,_=(G=e.features)==null?void 0:G.streamAnimation,U=(ve=Rt.features)==null?void 0:ve.askUserQuestion,Y=(ce=e.features)==null?void 0:ce.askUserQuestion,he=x===void 0&&w===void 0?void 0:{...x,...w,layout:{...x==null?void 0:x.layout,...w==null?void 0:w.layout}},fe=E===void 0&&S===void 0?void 0:{...E,...S},ae=T===void 0&&_===void 0?void 0:{...T,..._},Ee=U===void 0&&Y===void 0?void 0:{...U,...Y,styles:{...U==null?void 0:U.styles,...Y==null?void 0:Y.styles}};return{...Rt.features,...e.features,...fe!==void 0?{scrollToBottom:fe}:{},...he!==void 0?{artifacts:he}:{},...ae!==void 0?{streamAnimation:ae}:{},...Ee!==void 0?{askUserQuestion:Ee}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Rt.suggestionChips,suggestionChipsConfig:{...Rt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Rt.layout,...e.layout,header:{...(a=Rt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Rt.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(p=(m=Rt.layout)==null?void 0:m.messages)==null?void 0:p.avatar,...(u=(f=e.layout)==null?void 0:f.messages)==null?void 0:u.avatar},timestamp:{...(v=(C=Rt.layout)==null?void 0:C.messages)==null?void 0:v.timestamp,...(I=(M=e.layout)==null?void 0:M.messages)==null?void 0:I.timestamp}},slots:{...(R=Rt.layout)==null?void 0:R.slots,...(W=e.layout)==null?void 0:W.slots}},markdown:{...Rt.markdown,...e.markdown,options:{...(D=Rt.markdown)==null?void 0:D.options,...(B=e.markdown)==null?void 0:B.options}},messageActions:{...Rt.messageActions,...e.messageActions}}:Rt}var nf={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"}},of={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"}},rf={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:fo,maxWidth:ei,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Zr(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."))?Zr(e,o):o}function Bu(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let i=`${r}.${s}`;if(typeof a=="string"){let d=Zr(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 sf(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function Hu(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=Hu(s,r):n[o]=r}return n}function af(e,t){return t?Hu(e,t):e}function an(e,t={}){var r,s,a,i,d,l,m,p,f,u,C,v,M;let n={palette:nf,semantic:of,components:rf},o={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(m=e==null?void 0:e.semantic)==null?void 0:m.colors,interactive:{...n.semantic.colors.interactive,...(f=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(C=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:C.feedback}},spacing:{...n.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...n.semantic.typography,...(M=e==null?void 0:e.semantic)==null?void 0:M.typography}},components:af(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let I=sf(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 Du(e){var v,M,I,R,W,D,B,x,w,E,S,T,_,U,Y,he,fe,ae,Ee,ye,Oe,we,K,pe,G,ve,ce,ne,Se,ze,te,re,ie,st,Te,ue,Ue,Be,me,Q,_e,Ht,be,de,Pn,Ut,gn,Fn,to,qe,V,Le,He,De,Ve,mt,at,Pt,jt,j,zt,Ze,Vt,se,Ce,kt,Kt,tn,An,Wt,Mt,wt,St,Gt,ot,On,no,Tn,Nn,bt,Lo,_n,fr,Wn,$r,jo,Do,At,Vn,$n,kn,Lt,oo,ro,Un,Ko,Fo,Go,zn,Ft,En,so,Yo,Oo,Xo,Io,qn,yo,vt,Xt,Qt,jn,Qo,ao,vo,Kn,$,io;let t=Bu(e),n={};for(let[xe,Gn]of Object.entries(t)){let lo=xe.replace(/\./g,"-");n[`--persona-${lo}`]=Gn.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v: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"]=(W=n["--persona-semantic-colors-background"])!=null?W: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"]=(x=n["--persona-semantic-colors-text-muted"])!=null?x:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(w=n["--persona-semantic-colors-text-inverse"])!=null?w:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(E=n["--persona-semantic-colors-border"])!=null?E:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(S=n["--persona-semantic-colors-divider"])!=null?S:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(T=n["--persona-components-voice-recording-indicator"])!=null?T:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(_=n["--persona-components-voice-recording-background"])!=null?_:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(U=n["--persona-components-voice-processing-icon"])!=null?U:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(Y=n["--persona-components-voice-speaking-icon"])!=null?Y:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(he=n["--persona-components-approval-requested-background"])!=null?he:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(fe=n["--persona-components-approval-requested-border"])!=null?fe:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(ae=n["--persona-components-approval-requested-text"])!=null?ae:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(Ee=n["--persona-components-approval-requested-shadow"])!=null?Ee:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-approval-approve-bg"]=(ye=n["--persona-components-approval-approve-background"])!=null?ye:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(Oe=n["--persona-components-approval-deny-background"])!=null?Oe:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(we=n["--persona-components-attachment-image-background"])!=null?we:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(K=n["--persona-components-attachment-image-border"])!=null?K:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(pe=n["--persona-semantic-typography-fontFamily"])!=null?pe:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(G=n["--persona-semantic-typography-fontSize"])!=null?G:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(ve=n["--persona-semantic-typography-fontWeight"])!=null?ve:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(ce=n["--persona-semantic-typography-lineHeight"])!=null?ce: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"]=(ne=n["--persona-palette-radius-sm"])!=null?ne:"0.125rem",n["--persona-radius-md"]=(Se=n["--persona-palette-radius-md"])!=null?Se:"0.375rem",n["--persona-radius-lg"]=(ze=n["--persona-palette-radius-lg"])!=null?ze:"0.5rem",n["--persona-radius-xl"]=(te=n["--persona-palette-radius-xl"])!=null?te:"0.75rem",n["--persona-radius-full"]=(re=n["--persona-palette-radius-full"])!=null?re:"9999px",n["--persona-launcher-radius"]=(st=(ie=n["--persona-components-launcher-borderRadius"])!=null?ie:n["--persona-palette-radius-full"])!=null?st:"9999px",n["--persona-launcher-bg"]=(Te=n["--persona-components-launcher-background"])!=null?Te:n["--persona-primary"],n["--persona-launcher-fg"]=(ue=n["--persona-components-launcher-foreground"])!=null?ue:n["--persona-text-inverse"],n["--persona-launcher-border"]=(Ue=n["--persona-components-launcher-border"])!=null?Ue:n["--persona-border"],n["--persona-button-primary-bg"]=(Be=n["--persona-components-button-primary-background"])!=null?Be:n["--persona-primary"],n["--persona-button-primary-fg"]=(me=n["--persona-components-button-primary-foreground"])!=null?me:n["--persona-text-inverse"],n["--persona-button-radius"]=(_e=(Q=n["--persona-components-button-primary-borderRadius"])!=null?Q:n["--persona-palette-radius-full"])!=null?_e:"9999px",n["--persona-panel-radius"]=(be=(Ht=n["--persona-components-panel-borderRadius"])!=null?Ht:n["--persona-radius-xl"])!=null?be:"0.75rem",n["--persona-panel-border"]=(de=n["--persona-components-panel-border"])!=null?de:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Ut=(Pn=n["--persona-components-panel-shadow"])!=null?Pn:n["--persona-palette-shadows-xl"])!=null?Ut:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(gn=n["--persona-components-launcher-shadow"])!=null?gn:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(to=(Fn=n["--persona-components-input-borderRadius"])!=null?Fn:n["--persona-radius-lg"])!=null?to:"0.5rem",n["--persona-message-user-radius"]=(V=(qe=n["--persona-components-message-user-borderRadius"])!=null?qe:n["--persona-radius-lg"])!=null?V:"0.5rem",n["--persona-message-assistant-radius"]=(He=(Le=n["--persona-components-message-assistant-borderRadius"])!=null?Le:n["--persona-radius-lg"])!=null?He:"0.5rem",n["--persona-header-bg"]=(De=n["--persona-components-header-background"])!=null?De:n["--persona-surface"],n["--persona-header-border"]=(Ve=n["--persona-components-header-border"])!=null?Ve:n["--persona-divider"],n["--persona-header-icon-bg"]=(mt=n["--persona-components-header-iconBackground"])!=null?mt:n["--persona-primary"],n["--persona-header-icon-fg"]=(at=n["--persona-components-header-iconForeground"])!=null?at:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(Pt=n["--persona-components-header-titleForeground"])!=null?Pt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(jt=n["--persona-components-header-subtitleForeground"])!=null?jt:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(j=n["--persona-components-header-actionIconForeground"])!=null?j:n["--persona-muted"];let o=(zt=e.components)==null?void 0:zt.header;o!=null&&o.shadow&&(n["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom);let r=(Ze=e.components)==null?void 0:Ze.introCard;n["--persona-intro-card-bg"]=(Vt=n["--persona-components-introCard-background"])!=null?Vt:n["--persona-surface"],n["--persona-intro-card-radius"]=(se=n["--persona-components-introCard-borderRadius"])!=null?se:"1rem",n["--persona-intro-card-padding"]=(Ce=n["--persona-components-introCard-padding"])!=null?Ce:"1.5rem",n["--persona-intro-card-shadow"]=(Kt=(kt=r==null?void 0:r.shadow)!=null?kt:n["--persona-components-introCard-shadow"])!=null?Kt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(tn=n["--persona-components-input-background"])!=null?tn:n["--persona-surface"],n["--persona-input-placeholder"]=(An=n["--persona-components-input-placeholder"])!=null?An:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Wt=n["--persona-components-message-user-background"])!=null?Wt:n["--persona-accent"],n["--persona-message-user-text"]=(Mt=n["--persona-components-message-user-text"])!=null?Mt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(wt=n["--persona-components-message-user-shadow"])!=null?wt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(St=n["--persona-components-message-assistant-background"])!=null?St: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"]=(ot=n["--persona-components-message-assistant-border"])!=null?ot:n["--persona-border"],n["--persona-message-assistant-shadow"]=(On=n["--persona-components-message-assistant-shadow"])!=null?On:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(Tn=(no=n["--persona-components-scrollToBottom-background"])!=null?no:n["--persona-button-primary-bg"])!=null?Tn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(bt=(Nn=n["--persona-components-scrollToBottom-foreground"])!=null?Nn:n["--persona-button-primary-fg"])!=null?bt:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Lo=n["--persona-components-scrollToBottom-border"])!=null?Lo:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(_n=n["--persona-components-scrollToBottom-size"])!=null?_n:"40px",n["--persona-scroll-to-bottom-radius"]=($r=(Wn=(fr=n["--persona-components-scrollToBottom-borderRadius"])!=null?fr:n["--persona-button-radius"])!=null?Wn:n["--persona-radius-full"])!=null?$r:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Do=(jo=n["--persona-components-scrollToBottom-shadow"])!=null?jo:n["--persona-palette-shadows-sm"])!=null?Do:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(At=n["--persona-components-scrollToBottom-padding"])!=null?At:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Vn=n["--persona-components-scrollToBottom-gap"])!=null?Vn:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(kn=($n=n["--persona-components-scrollToBottom-fontSize"])!=null?$n:n["--persona-palette-typography-fontSize-sm"])!=null?kn:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Lt=n["--persona-components-scrollToBottom-iconSize"])!=null?Lt:"14px",n["--persona-tool-bubble-shadow"]=(oo=n["--persona-components-toolBubble-shadow"])!=null?oo:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(ro=n["--persona-components-reasoningBubble-shadow"])!=null?ro:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Un=n["--persona-components-composer-shadow"])!=null?Un:"none",n["--persona-md-inline-code-bg"]=(Ko=n["--persona-components-markdown-inlineCode-background"])!=null?Ko:n["--persona-container"],n["--persona-md-inline-code-color"]=(Fo=n["--persona-components-markdown-inlineCode-foreground"])!=null?Fo:n["--persona-text"],n["--persona-md-link-color"]=(zn=(Go=n["--persona-components-markdown-link-foreground"])!=null?Go:n["--persona-accent"])!=null?zn:"#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"]=(Ft=n["--persona-components-markdown-codeBlock-background"])!=null?Ft:n["--persona-container"],n["--persona-md-code-block-border-color"]=(En=n["--persona-components-markdown-codeBlock-borderColor"])!=null?En:n["--persona-border"],n["--persona-md-code-block-text-color"]=(so=n["--persona-components-markdown-codeBlock-textColor"])!=null?so:"inherit",n["--persona-md-table-header-bg"]=(Yo=n["--persona-components-markdown-table-headerBackground"])!=null?Yo:n["--persona-container"],n["--persona-md-table-border-color"]=(Oo=n["--persona-components-markdown-table-borderColor"])!=null?Oo:n["--persona-border"],n["--persona-md-hr-color"]=(Xo=n["--persona-components-markdown-hr-color"])!=null?Xo:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Io=n["--persona-components-markdown-blockquote-borderColor"])!=null?Io:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(qn=n["--persona-components-markdown-blockquote-background"])!=null?qn:"transparent",n["--persona-md-blockquote-text-color"]=(yo=n["--persona-components-markdown-blockquote-textColor"])!=null?yo:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(vt=n["--persona-components-collapsibleWidget-container"])!=null?vt:n["--persona-surface"],n["--cw-surface"]=(Xt=n["--persona-components-collapsibleWidget-surface"])!=null?Xt:n["--persona-surface"],n["--cw-border"]=(Qt=n["--persona-components-collapsibleWidget-border"])!=null?Qt:n["--persona-border"],n["--persona-message-border"]=(jn=n["--persona-components-message-border"])!=null?jn:n["--persona-border"];let m=e.components,p=m==null?void 0:m.iconButton;p&&(p.background&&(n["--persona-icon-btn-bg"]=p.background),p.border&&(n["--persona-icon-btn-border"]=p.border),p.color&&(n["--persona-icon-btn-color"]=p.color),p.padding&&(n["--persona-icon-btn-padding"]=p.padding),p.borderRadius&&(n["--persona-icon-btn-radius"]=p.borderRadius),p.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=p.hoverBackground),p.hoverColor&&(n["--persona-icon-btn-hover-color"]=p.hoverColor),p.activeBackground&&(n["--persona-icon-btn-active-bg"]=p.activeBackground),p.activeBorder&&(n["--persona-icon-btn-active-border"]=p.activeBorder));let f=m==null?void 0:m.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let u=m==null?void 0:m.toggleGroup;u&&(u.gap&&(n["--persona-toggle-group-gap"]=u.gap),u.borderRadius&&(n["--persona-toggle-group-radius"]=u.borderRadius));let C=m==null?void 0:m.artifact;if(C!=null&&C.toolbar){let xe=C.toolbar;xe.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=xe.iconHoverColor),xe.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=xe.iconHoverBackground),xe.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=xe.iconPadding),xe.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=xe.iconBorderRadius),xe.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=xe.iconBorder),xe.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=xe.toggleGroupGap),xe.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=xe.toggleBorderRadius),xe.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=xe.copyBackground),xe.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=xe.copyBorder),xe.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=xe.copyColor),xe.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=xe.copyBorderRadius),xe.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=xe.copyPadding),xe.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=xe.copyMenuBackground,n["--persona-dropdown-bg"]=(Qo=n["--persona-dropdown-bg"])!=null?Qo:xe.copyMenuBackground),xe.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=xe.copyMenuBorder,n["--persona-dropdown-border"]=(ao=n["--persona-dropdown-border"])!=null?ao:xe.copyMenuBorder),xe.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=xe.copyMenuShadow,n["--persona-dropdown-shadow"]=(vo=n["--persona-dropdown-shadow"])!=null?vo:xe.copyMenuShadow),xe.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=xe.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(Kn=n["--persona-dropdown-radius"])!=null?Kn:xe.copyMenuBorderRadius),xe.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=xe.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=($=n["--persona-dropdown-item-hover-bg"])!=null?$:xe.copyMenuItemHoverBackground),xe.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=xe.iconBackground),xe.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=xe.toolbarBorder)}if(C!=null&&C.tab){let xe=C.tab;xe.background&&(n["--persona-artifact-tab-bg"]=xe.background),xe.activeBackground&&(n["--persona-artifact-tab-active-bg"]=xe.activeBackground),xe.activeBorder&&(n["--persona-artifact-tab-active-border"]=xe.activeBorder),xe.borderRadius&&(n["--persona-artifact-tab-radius"]=xe.borderRadius),xe.textColor&&(n["--persona-artifact-tab-color"]=xe.textColor),xe.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=xe.hoverBackground),xe.listBackground&&(n["--persona-artifact-tab-list-bg"]=xe.listBackground),xe.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=xe.listBorderColor),xe.listPadding&&(n["--persona-artifact-tab-list-padding"]=xe.listPadding)}if(C!=null&&C.pane){let xe=C.pane;if(xe.toolbarBackground){let Gn=(io=Zr(e,xe.toolbarBackground))!=null?io:xe.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Gn}}return n}var lf={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"}}},Fu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},bl=()=>{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"},cf=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":bl()},df=e=>cf(e),pf=e=>an(e),uf=e=>{var n;let t=an(void 0,{validate:!1});return an({...e,palette:{...t.palette,colors:{...lf.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},ti=e=>{let t=df(e),n=Fu(e==null?void 0:e.theme),o=Fu(e==null?void 0:e.darkTheme);return t==="dark"?uf(_s(n!=null?n:{},o!=null?o:{})):pf(n)},mf=e=>Du(e),es=(e,t)=>{let n=ti(t),o=mf(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s)},Ou=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(bl())});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(bl());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 yl(e,t){let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return o}function Mr(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]:Mr((i=a==null?void 0:a[r])!=null?i:{},s.join("."),n)}}var ni=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?{...Rt,...n}:n!=null?n:Rt,this.theme=an(t,{validate:!1}),this.syncThemeIntoConfig(),this.pushHistorySnapshot(this.exportSnapshot(),!0)}get(t){var n;return t.startsWith("theme.")?yl(this.theme,t.replace("theme.","")):t.startsWith("darkTheme.")?yl((n=this.config.darkTheme)!=null?n:{},t.replace("darkTheme.","")):yl(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=Mr(this.theme,r,n),this.syncThemeIntoConfig()}else if(t.startsWith("darkTheme.")){let r=t.replace("darkTheme.",""),s=(o=this.config.darkTheme)!=null?o:an();this.config={...this.config,darkTheme:Mr(s,r,n)}}else this.config=Mr(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=Mr(this.theme,d,i),n=!0}else if(a.startsWith("darkTheme.")){let d=a.replace("darkTheme.",""),l=(s=this.config.darkTheme)!=null?s:an();this.config={...this.config,darkTheme:Mr(l,d,i)},o=!0}else this.config=Mr(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=an((s=n.theme)!=null?s:this.theme,{validate:!1});this.setFullConfig(a,i);return}let o=an(n,{validate:!1});this.setTheme(o)}resetToDefaults(){this.config={...Rt},this.theme=an(),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=an(t.theme,{validate:!1}),this.syncThemeIntoConfig(),this.suppressHistory=!1,this.notifyListeners()}};function oi(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 ri(e,t){return t==="rem"?`${e}rem`:`${e}px`}function Nu(e,t){return t==="rem"?e*16:e}function _u(e,t){return t==="rem"?e/16:e}function ts(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 si(e){return/^#[0-9A-Fa-f]{6}$/.test(e)}function ai(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 Vs(e,t){let n=s=>{var l;let a=ts(s),i=a.startsWith("rgb")?(l=ai(a))!=null?l:"#000000":a,d=[1,3,5].map(m=>{let p=parseInt(i.slice(m,m+2),16)/255;return p<=.03928?p/12.92:Math.pow((p+.055)/1.055,2.4)});return .2126*d[0]+.7152*d[1]+.0722*d[2]},o=n(e),r=n(t);return(Math.max(o,r)+.05)/(Math.min(o,r)+.05)}function vl(e){var f;let t=ts(e),n=t.startsWith("rgb")?(f=ai(t))!=null?f:"#000000":t,o=parseInt(n.slice(1,3),16)/255,r=parseInt(n.slice(3,5),16)/255,s=parseInt(n.slice(5,7),16)/255,a=Math.max(o,r,s),i=Math.min(o,r,s),d=(a+i)/2;if(a===i)return{h:0,s:0,l:d};let l=a-i,m=d>.5?l/(2-a-i):l/(a+i),p;switch(a){case o:p=((r-s)/l+(r<s?6:0))/6;break;case r:p=((s-o)/l+2)/6;break;default:p=((o-r)/l+4)/6;break}return{h:p*360,s:m,l:d}}function xl(e,t,n){let o=(e%360+360)%360,r=(1-Math.abs(2*n-1))*t,s=r*(1-Math.abs(o/60%2-1)),a=n-r/2,i,d,l;o<60?[i,d,l]=[r,s,0]:o<120?[i,d,l]=[s,r,0]:o<180?[i,d,l]=[0,r,s]:o<240?[i,d,l]=[0,s,r]:o<300?[i,d,l]=[s,0,r]:[i,d,l]=[r,0,s];let m=p=>{let f=Math.round((p+a)*255).toString(16);return f.length===1?"0"+f:f};return`#${m(i)}${m(d)}${m(l)}`}function ii(e){let{h:t,s:n,l:o}=vl(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]=xl(t,l,d)}return a}var Lr=["50","100","200","300","400","500","600","700","800","900","950"],li=["primary","secondary","accent","gray","success","warning","error","info"];function Vu(e,t){return`palette.colors.${e}.${t}`}function wl(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.")?wl(e,`theme.${o}`,n+1):"#cbd5e1"}function $u(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"}],$s=["primary","secondary","accent","gray"],Uu={primary:"Primary",secondary:"Secondary",accent:"Accent",gray:"Neutral"},Us={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"}]},zs={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"}]},qs={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"}]},js={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"}]},Ks={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"}]},Gs={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"}]},Ys={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"}]},Xs={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"}]},Qs={roleId:"role-borders",helper:"Borders, dividers, and separators",intensities:ko,targets:[{path:"semantic.colors.border",kind:"border"},{path:"semantic.colors.divider",kind:"border"}]},ir=[Us,zs,qs,js,Ks,Gs,Ys,Xs,Qs];function Js(e,t,n){let o={},r=e==="neutral"?"gray":e;for(let s of n.targets){let a=gf(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 gf(e,t,n,o){let r=t==="solid";if(o==="role-header")return ff(e,r,n);if(o==="role-input")return hf(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 ff(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 hf(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 bf=/^palette\.colors\.(\w+)\.(\d+)$/;function ci(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(bf);if(!r)return null;let s=r[1],a=$s.includes(s)?s:null;if(!a)return null;for(let l of["solid","soft"]){let m=Js(a,l,t);if(t.targets.every(f=>{var C;return String((C=e(f.path))!=null?C:"")===m[`theme.${f.path}`]}))return{family:a,intensity:l}}return null}var yf={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"}]}]},vf={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"}]},xf={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"}}]},wf={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)"}]}]},Cf={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"}]}]},Sf={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"}}]},Af={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)"}]},Tf={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"}]}]},Ir=[vf,xf,Cf,wf,yf,Sf,Af,Tf];function qu(){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:li.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 ju={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"}}]},Ku=qu(),Gu=ju,Yu=[qu(),ju],kf={id:"comp-panel",title:"Panel",collapsed:!1,fields:[{id:"panel-width",label:"Width",type:"text",path:"theme.components.panel.width",defaultValue:fo},{id:"panel-max-width",label:"Max Width",type:"text",path:"theme.components.panel.maxWidth",defaultValue:ei},{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"}]}]},Ef={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"}]}]},Mf={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"}]}]},Lf={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"}]}]},If={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"}]}]},Rf={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"}}]},Pf={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"}}]},Wf={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"}}]},Bf={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"}}]},Hf={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"}]},ns=[{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"}],Cl="0 5px 15px rgba(15, 23, 42, 0.08)",zu=[{value:Cl,label:"Default"},...ns],Df={id:"comp-shadows",title:"Component Shadows",description:"Box-shadow for chat bubbles and surfaces.",collapsed:!0,fields:[{id:"shadow-msg-user",label:"User Message",type:"select",path:"theme.components.message.user.shadow",defaultValue:"palette.shadows.sm",options:ns},{id:"shadow-msg-assistant",label:"Assistant Message",type:"select",path:"theme.components.message.assistant.shadow",defaultValue:"palette.shadows.sm",options:ns},{id:"shadow-tool-bubble",label:"Tool Call Bubble",type:"select",path:"theme.components.toolBubble.shadow",defaultValue:"palette.shadows.sm",options:ns},{id:"shadow-reasoning-bubble",label:"Reasoning Bubble",type:"select",path:"theme.components.reasoningBubble.shadow",defaultValue:"palette.shadows.sm",options:ns},{id:"shadow-approval",label:"Approval Bubble",type:"select",path:"theme.components.approval.requested.shadow",defaultValue:Cl,options:zu},{id:"shadow-intro-card",label:"Intro Card",type:"select",path:"theme.components.introCard.shadow",defaultValue:Cl,options:zu},{id:"shadow-composer",label:"Composer",type:"select",path:"theme.components.composer.shadow",defaultValue:"palette.shadows.none",options:ns}]},Sl=[kf,Ef,Mf,Lf,If,Df],Al=[Rf,Pf,Wf,Bf,Hf],Tl=[...Sl,...Al],kl=1024*1024,Ff=["What can you help me with?","Tell me about your features","How does this work?"],Zs={images:["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],"images-pdf":["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf"],"images-text-pdf":["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf","text/plain","text/markdown","text/csv","application/json"],all:["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp","application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"]};function Of(e){return Number(e)*kl}function Nf(e){let t=Number(e);return Number.isFinite(t)?t>1024?String(Math.round(t/kl)):String(t):"10"}function _f(e){var t;return(t=Zs[String(e)])!=null?t:Zs.images}function Vf(e){let t=Array.isArray(e)?e:Zs.images,n=[...new Set(t)].sort();for(let[o,r]of Object.entries(Zs)){let s=[...r].sort();if(n.length===s.length&&n.every((a,i)=>a===s[i]))return o}return n.some(o=>o.startsWith("application/vnd")||o==="application/msword")?"all":n.some(o=>o==="text/plain"||o==="text/markdown"||o==="text/csv")?"images-text-pdf":n.includes("application/pdf")?"images-pdf":"images"}var $f={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"}]},Uf={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:Ff}]},zf={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:""}]},qf={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}]},jf={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"}]}]},Kf={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"}]}]},Gf={id:"launcher-basics",title:"Launcher",collapsed:!0,fields:[{id:"launch-enabled",label:"Enabled",type:"toggle",path:"launcher.enabled",defaultValue:!0},{id:"launch-mount-mode",label:"Mount Mode",type:"select",path:"launcher.mountMode",defaultValue:"floating",options:[{value:"floating",label:"Floating"},{value:"docked",label:"Docked"}]},{id:"launch-position",label:"Position",type:"select",path:"launcher.position",defaultValue:"bottom-right",options:[{value:"bottom-right",label:"Bottom Right"},{value:"bottom-left",label:"Bottom Left"},{value:"top-right",label:"Top Right"},{value:"top-left",label:"Top Left"}]},{id:"launch-width",label:"Width",type:"text",path:"launcher.width",defaultValue:fo},{id:"launch-auto-expand",label:"Auto Expand",type:"toggle",path:"launcher.autoExpand",defaultValue:!1},{id:"launch-title",label:"Title",type:"text",path:"launcher.title",defaultValue:"Chat Assistant"},{id:"launch-subtitle",label:"Subtitle",type:"text",path:"launcher.subtitle",defaultValue:"Here to help you get answers fast"}]},Yf={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:""}]},Xf={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"}]},Qf={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"}]},Jf={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"}]},Zf={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"}]},eh={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:""}]},th={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)}]},nh={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*kl,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:Nf,parseValue:Of},{id:"attach-types",label:"Allowed File Types",type:"select",path:"attachments.allowedTypes",defaultValue:Zs.images,options:[{value:"images",label:"Images only"},{value:"images-pdf",label:"Images + PDF"},{value:"images-text-pdf",label:"Images + text + PDF"},{value:"all",label:"All supported types"}],formatValue:Vf,parseValue:_f}]},oh={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"}]}]},rh={id:"artifacts-customization",title:"Artifact Customization",collapsed:!0,fields:[{id:"art-toolbar",label:"Toolbar Preset",type:"select",path:"features.artifacts.layout.toolbarPreset",defaultValue:"default",options:[{value:"default",label:"Default"},{value:"document",label:"Document"}]},{id:"art-pane-width",label:"Pane Width",description:"CSS width (e.g. 40%, 28rem)",type:"text",path:"features.artifacts.layout.paneWidth",defaultValue:"40%"},{id:"art-pane-max-width",label:"Pane Max Width",type:"text",path:"features.artifacts.layout.paneMaxWidth",defaultValue:"28rem"},{id:"art-split-gap",label:"Split Gap",type:"text",path:"features.artifacts.layout.splitGap",defaultValue:"0.5rem"},{id:"art-pane-bg",label:"Pane Background",type:"color",path:"features.artifacts.layout.paneBackground",defaultValue:""},{id:"art-unified",label:"Unified Split Chrome",description:"Wrap chat and artifact in a single container",type:"toggle",path:"features.artifacts.layout.unifiedSplitChrome",defaultValue:!1},{id:"art-resizable",label:"Resizable",description:"Allow dragging the pane divider",type:"toggle",path:"features.artifacts.layout.resizable",defaultValue:!1},{id:"art-expand-panel",label:"Expand Panel When Open",description:"Widen the launcher panel to fit artifacts",type:"toggle",path:"features.artifacts.layout.expandLauncherPanelWhenOpen",defaultValue:!0}]},sh={id:"api-integration",title:"API & Integration",description:"Runtime and integration options.",collapsed:!0,fields:[{id:"dev-api-url",label:"API URL",type:"text",path:"apiUrl",defaultValue:""},{id:"dev-flow",label:"Flow ID",type:"text",path:"flowId",defaultValue:""},{id:"dev-parser",label:"Stream Parser",type:"select",path:"parserType",defaultValue:"plain",options:[{value:"plain",label:"Plain Text"},{value:"json",label:"JSON"},{value:"regex-json",label:"Regex JSON"},{value:"xml",label:"XML"}]}]},ah={id:"debug-inspection",title:"Debug & Inspection",collapsed:!0,fields:[{id:"dev-reasoning",label:"Show Reasoning",description:"Display AI reasoning steps",type:"toggle",path:"features.showReasoning",defaultValue:!1},{id:"dev-tool-calls",label:"Show Tool Calls",description:"Display tool call details",type:"toggle",path:"features.showToolCalls",defaultValue:!1},{id:"dev-tool-collapsed-mode",label:"Tool Call Summary",description:"Choose what collapsed tool rows show by default",type:"select",path:"features.toolCallDisplay.collapsedMode",defaultValue:"tool-call",options:[{value:"tool-call",label:"Tool Call"},{value:"tool-name",label:"Tool Name"},{value:"tool-preview",label:"Tool Preview"}]},{id:"dev-tool-active-preview",label:"Tool Preview While Active",description:"Show a lightweight preview in collapsed active tool rows",type:"toggle",path:"features.toolCallDisplay.activePreview",defaultValue:!1},{id:"dev-tool-preview-lines",label:"Tool Preview Lines",type:"select",path:"features.toolCallDisplay.previewMaxLines",defaultValue:3,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"3",label:"3"},{value:"4",label:"4"},{value:"5",label:"5"}],formatValue:e=>String(e!=null?e:3),parseValue:e=>Number(e)},{id:"dev-tool-active-min-height",label:"Tool Active Min Height",description:"CSS min-height for collapsed active tool rows (e.g. 5rem)",type:"text",path:"features.toolCallDisplay.activeMinHeight",defaultValue:""},{id:"dev-tool-expandable",label:"Tool Calls Expandable",description:"Allow expanding tool call rows to see full details",type:"toggle",path:"features.toolCallDisplay.expandable",defaultValue:!0},{id:"dev-tool-grouped",label:"Group Sequential Tool Calls",description:"Render consecutive tool rows inside a grouped container",type:"toggle",path:"features.toolCallDisplay.grouped",defaultValue:!1},{id:"dev-reasoning-expandable",label:"Reasoning Expandable",description:"Allow expanding reasoning rows to see full details",type:"toggle",path:"features.reasoningDisplay.expandable",defaultValue:!0},{id:"dev-reasoning-active-preview",label:"Reasoning Preview While Active",description:"Show a lightweight preview in collapsed active reasoning rows",type:"toggle",path:"features.reasoningDisplay.activePreview",defaultValue:!1},{id:"dev-reasoning-preview-lines",label:"Reasoning Preview Lines",type:"select",path:"features.reasoningDisplay.previewMaxLines",defaultValue:3,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"3",label:"3"},{value:"4",label:"4"},{value:"5",label:"5"}],formatValue:e=>String(e!=null?e:3),parseValue:e=>Number(e)},{id:"dev-reasoning-active-min-height",label:"Reasoning Active Min Height",description:"CSS min-height for collapsed active reasoning rows (e.g. 5rem)",type:"text",path:"features.reasoningDisplay.activeMinHeight",defaultValue:""},{id:"dev-debug",label:"Debug Mode",description:"Show debug information",type:"toggle",path:"debug",defaultValue:!1}]},ih={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}]},ea=[{label:"Content",sections:[$f,Uf]},{label:"Layout",sections:[zf,qf,jf,Kf]},{label:"Widget",sections:[Gf,Yf,Xf,Qf,Jf,Zf]},{label:"Features",sections:[eh,th,nh,oh,rh]},{label:"Developer",collapsedByDefault:!0,sections:[sh,ah,ih]}],El=ea.flatMap(e=>e.sections),Ml={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"}]}]},Ll={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"}]},Il={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"}]},Rl={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:Us},{id:"role-header",label:"Header",type:"role-assignment",path:"theme.components.header.background",roleAssignment:zs},{id:"role-user-messages",label:"User Messages",type:"role-assignment",path:"theme.components.message.user.background",roleAssignment:qs},{id:"role-assistant-messages",label:"Assistant Messages",type:"role-assignment",path:"theme.components.message.assistant.background",roleAssignment:js},{id:"role-primary-actions",label:"Primary Actions",type:"role-assignment",path:"theme.components.button.primary.background",roleAssignment:Ks},{id:"role-scroll-to-bottom",label:"Scroll To Bottom",type:"role-assignment",path:"theme.components.scrollToBottom.background",roleAssignment:Gs},{id:"role-input",label:"Input Field",type:"role-assignment",path:"theme.components.input.background",roleAssignment:Ys},{id:"role-links-focus",label:"Links & Focus",type:"role-assignment",path:"theme.semantic.colors.accent",roleAssignment:Xs},{id:"role-borders",label:"Borders & Dividers",type:"role-assignment",path:"theme.semantic.colors.border",roleAssignment:Qs}]},Pl={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"}}]},Wl={id:"advanced-tokens",title:"Advanced Tokens",description:"Override individual semantic and component values when you need precise control.",collapsed:!0,fields:[]},Xu=[Ml,Ll,Il,Rl,Pl,Wl],di=[{id:"style",label:"Style",sections:Ir},{id:"design-system",label:"Design System",sections:Tl},{id:"configure",label:"Configure",sections:El}];function Qu(e,t){return e.startsWith("theme.")?e.replace(/^theme\./,`${t}.`):e}function lh(e,t,n){return{...e,id:`${n}-${e.id}`,path:Qu(e.path,t)}}function Ju(e,t){let n=e.find(o=>o.id===t);if(!n)throw new Error(`Section "${t}" not found in definitions`);return n}function Zu(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=>lh(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])=>[Qu(d,t),l]))}))}}var Bl=[{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"]}],os=[...Bl];function pi(e){return os.find(t=>t.id===e)}var em=require("marked"),ch=e=>{if(e)return e},Hl=e=>{var r,s;let t=e==null?void 0:e.markedOptions,n=new em.Marked({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=ch(e==null?void 0:e.renderer);return o&&n.use({renderer:o}),a=>n.parse(a)},ui=e=>e?Hl({markedOptions:e.options,renderer:e.renderer}):Hl(),bv=Hl();var ta=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");var tm=Iu(require("dompurify"),1),dh={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"]},ph=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,uh=()=>{let e=(0,tm.default)(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:")&&!ph.test(o)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,dh)},mi=e=>e===!1?null:typeof e=="function"?e:uh();var Rr="webmcp:",Dl=new Map,nm=e=>{var t;Dl.clear();for(let n of e){let o=(t=n.title)==null?void 0:t.trim();o&&Dl.set(n.name,o)}},Fl=e=>Dl.get(sm(e)),gi={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};function rm(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}:${mh(t.join(""))}`}function om(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 mh(e){let t=om(e,0).toString(36),n=om(e,2654435761).toString(36);return`${t}.${n}`}var fi=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 gi.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",r),[]}nm(n);let o=typeof location!="undefined"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=fh(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Eo("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let C=typeof document!="undefined"&&!!document.modelContext;return Eo(C?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=sm(t),a;try{a=await r.getTools()}catch(C){let v=C instanceof Error?C.message:String(C);return Eo(`Failed to read WebMCP registry: ${v}`)}nm(a);let i=a.find(C=>C.name===s);if(!i)return Eo(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Eo(`WebMCP tool not allowed by client allowlist: ${s}`);if(o!=null&&o.aborted)return Eo("Aborted by cancel()");let d=Fl(s),l={toolName:s,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(l))return Eo("User declined the tool call.");if(o!=null&&o.aborted)return Eo("Aborted by cancel()");let m=new AbortController,p=!1,f=setTimeout(()=>{p=!0,m.abort()},this.timeoutMs),u=()=>m.abort();o&&(o.aborted?m.abort():o.addEventListener("abort",u,{once:!0}));try{let C=await r.executeTool(i,vh(n),{signal:m.signal});return hh(C)}catch(C){if(p)return Eo(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return Eo("Aborted by cancel()");let v=C instanceof Error?C.message:String(C);return Eo(v)}finally{clearTimeout(f),o&&o.removeEventListener("abort",u)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){gi.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,gi.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:bh;try{return await n(t)}catch(r){return gi.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=>gh(t,o))}},sm=e=>e.startsWith(Rr)?e.slice(Rr.length):e,rs=e=>e.startsWith(Rr),gh=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},fh=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},hh=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:xh(t)}]}},Eo=e=>({isError:!0,content:[{type:"text",text:e}]}),bh=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=yh(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
1
|
+
"use strict";var Lg=Object.create;var ii=Object.defineProperty;var Ig=Object.getOwnPropertyDescriptor;var Rg=Object.getOwnPropertyNames;var Pg=Object.getPrototypeOf,Wg=Object.prototype.hasOwnProperty;var Bg=(e,t)=>{for(var n in t)ii(e,n,{get:t[n],enumerable:!0})},Zu=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Rg(t))!Wg.call(e,r)&&r!==n&&ii(e,r,{get:()=>t[r],enumerable:!(o=Ig(t,r))||o.enumerable});return e};var em=(e,t,n)=>(n=e!=null?Lg(Pg(e)):{},Zu(t||!e||!e.__esModule?ii(n,"default",{value:e,enumerable:!0}):n,e)),Hg=e=>Zu(ii({},"__esModule",{value:!0}),e);var Lv={};Bg(Lv,{ADVANCED_TOKENS_SECTION:()=>zl,ALL_ROLES:()=>fr,ALL_TABS:()=>yi,BRAND_PALETTE_SECTION:()=>_l,BUILT_IN_PRESETS:()=>ql,COLORS_SECTIONS:()=>vm,COLOR_FAMILIES:()=>hi,COMPONENTS_SECTIONS:()=>Dl,COMPONENT_COLOR_SECTIONS:()=>Hl,COMPONENT_SHAPE_SECTIONS:()=>Bl,CONFIGURE_SECTIONS:()=>Ol,CONFIGURE_SUB_GROUPS:()=>da,CONTRAST_PAIRS:()=>ks,CSS_NAMED_COLORS:()=>Oa,DEVICE_DIMENSIONS:()=>Kr,HOME_SUGGESTION_CHIPS:()=>Wc,INTERFACE_ROLES_SECTION:()=>$l,MOCK_BROWSER_CONTENT:()=>Hc,MOCK_WORKSPACE_CONTENT:()=>Dc,PALETTE_SECTION:()=>bm,PREVIEW_STORAGE_ADAPTER:()=>Pc,RADIUS_PRESETS:()=>Es,ROLE_ASSISTANT_MESSAGES:()=>na,ROLE_BORDERS:()=>ia,ROLE_FAMILIES:()=>Qs,ROLE_FAMILY_LABELS:()=>mm,ROLE_HEADER:()=>ea,ROLE_INPUT:()=>sa,ROLE_INTENSITIES:()=>To,ROLE_LINKS_FOCUS:()=>aa,ROLE_PRIMARY_ACTIONS:()=>oa,ROLE_SCROLL_TO_BOTTOM:()=>ra,ROLE_SURFACES:()=>Zs,ROLE_USER_MESSAGES:()=>ta,SEMANTIC_COLORS_SECTION:()=>ym,SHADE_KEYS:()=>Dr,SHELL_STYLE_ID:()=>Ba,STATUS_COLORS_SECTION:()=>Ul,STATUS_PALETTE_SECTION:()=>Vl,STYLE_SECTIONS:()=>Fr,STYLE_SECTIONS_V2:()=>xm,THEME_EDITOR_PRESETS:()=>ms,THEME_SECTION:()=>Nl,ThemeEditorState:()=>di,ZOOM_MAX:()=>ul,ZOOM_MIN:()=>pl,appendPreviewTranscriptEntry:()=>cg,applySceneConfig:()=>bl,applyShellTheme:()=>fl,buildPreviewConfig:()=>xr,buildPreviewConfigWithMessages:()=>pg,buildShellCss:()=>ml,buildSrcdoc:()=>gl,buildSummary:()=>wr,buildTranscriptStreamFrames:()=>dg,coerceColor:()=>Gr,coerceFamily:()=>Na,coerceIntensity:()=>_a,coerceRadius:()=>Ua,coerceRoundnessStyle:()=>$a,coerceScheme:()=>Va,convertFromPx:()=>dm,convertToPx:()=>cm,createPreviewMessages:()=>Oc,createPreviewTranscriptEntry:()=>hl,createThemeEditorTools:()=>$c,createThemePreview:()=>mg,detectRoleAssignment:()=>bi,escapeHtml:()=>Ha,findSection:()=>Cm,formatCssValue:()=>ui,generateColorScale:()=>gi,getPreviewTranscriptPresetLabel:()=>lg,getShellPalette:()=>Bc,getThemeEditorPreset:()=>vi,hexToHsl:()=>Il,hslToHex:()=>Rl,isValidHex:()=>mi,normalizeColorValue:()=>ps,paletteColorPath:()=>pm,parseCssValue:()=>pi,presetStreamsText:()=>Fc,quickContrastWarnings:()=>Yr,resolveRoleAssignment:()=>la,resolveThemeColorPath:()=>Pl,rgbToHex:()=>fi,runContrastChecks:()=>Ls,scopeSection:()=>Sm,tokenRefDisplayName:()=>um,toolResult:()=>_o,wcagContrastRatio:()=>Js});module.exports=Hg(Lv);var tm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Xs(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];tm(s)&&tm(r)?n[o]=Xs(s,r):n[o]=r}return n}var go="min(440px, calc(100vw - 24px))",li="440px",It={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:go,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"follow",anchorTopOffset:16},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function nm(e,t){if(!(!e&&!t))return e?t?Xs(e,t):e:t}function om(e){var t,n,o,r,s,a,i,d,l,f,u,g,m,C,v,M,I,R,P,D,W;return e?{...It,...e,theme:nm(It.theme,e.theme),darkTheme:nm(It.darkTheme,e.darkTheme),launcher:{...It.launcher,...e.launcher,dock:{...(t=It.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(o=It.launcher)==null?void 0:o.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...It.copy,...e.copy},sendButton:{...It.sendButton,...e.sendButton},statusIndicator:{...It.statusIndicator,...e.statusIndicator},voiceRecognition:{...It.voiceRecognition,...e.voiceRecognition},features:(()=>{var le,J,se,ye,be,K,ae,Re,oe,ee;let w=(le=It.features)==null?void 0:le.artifacts,x=(J=e.features)==null?void 0:J.artifacts,E=(se=It.features)==null?void 0:se.scrollToBottom,S=(ye=e.features)==null?void 0:ye.scrollToBottom,k=(be=It.features)==null?void 0:be.scrollBehavior,V=(K=e.features)==null?void 0:K.scrollBehavior,z=(ae=It.features)==null?void 0:ae.streamAnimation,Y=(Re=e.features)==null?void 0:Re.streamAnimation,he=(oe=It.features)==null?void 0:oe.askUserQuestion,me=(ee=e.features)==null?void 0:ee.askUserQuestion,de=w===void 0&&x===void 0?void 0:{...w,...x,layout:{...w==null?void 0:w.layout,...x==null?void 0:x.layout}},Ee=E===void 0&&S===void 0?void 0:{...E,...S},xe=k===void 0&&V===void 0?void 0:{...k,...V},De=z===void 0&&Y===void 0?void 0:{...z,...Y},Ae=he===void 0&&me===void 0?void 0:{...he,...me,styles:{...he==null?void 0:he.styles,...me==null?void 0:me.styles}};return{...It.features,...e.features,...Ee!==void 0?{scrollToBottom:Ee}:{},...xe!==void 0?{scrollBehavior:xe}:{},...de!==void 0?{artifacts:de}:{},...De!==void 0?{streamAnimation:De}:{},...Ae!==void 0?{askUserQuestion:Ae}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:It.suggestionChips,suggestionChipsConfig:{...It.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...It.layout,...e.layout,header:{...(a=It.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=It.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(u=(f=It.layout)==null?void 0:f.messages)==null?void 0:u.avatar,...(m=(g=e.layout)==null?void 0:g.messages)==null?void 0:m.avatar},timestamp:{...(v=(C=It.layout)==null?void 0:C.messages)==null?void 0:v.timestamp,...(I=(M=e.layout)==null?void 0:M.messages)==null?void 0:I.timestamp}},slots:{...(R=It.layout)==null?void 0:R.slots,...(P=e.layout)==null?void 0:P.slots}},markdown:{...It.markdown,...e.markdown,options:{...(D=It.markdown)==null?void 0:D.options,...(W=e.markdown)==null?void 0:W.options}},messageActions:{...It.messageActions,...e.messageActions}}:It}var Dg={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"}},Fg={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"}},Og={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:go,maxWidth:li,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function cs(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."))?cs(e,o):o}function rm(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=cs(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 Ng(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 sm(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]=sm(s,r):n[o]=r}return n}function _g(e,t){return t?sm(e,t):e}function mn(e,t={}){var r,s,a,i,d,l,f,u,g,m,C,v,M;let n={palette:Dg,semantic:Fg,components:Og},o={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(f=e==null?void 0:e.semantic)==null?void 0:f.colors,interactive:{...n.semantic.colors.interactive,...(g=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:g.interactive},feedback:{...n.semantic.colors.feedback,...(C=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:C.feedback}},spacing:{...n.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...n.semantic.typography,...(M=e==null?void 0:e.semantic)==null?void 0:M.typography}},components:_g(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let I=Ng(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 am(e){var v,M,I,R,P,D,W,w,x,E,S,k,V,z,Y,he,me,de,Ee,xe,De,Ae,le,J,se,ye,be,K,ae,Re,oe,ee,re,it,lt,Le,pe,Je,Be,j,fe,tt,Mt,te,qe,Fn,Dt,an,oo,Mo,F,ue,Fe,Ke,_e,$e,ot,Pt,Kt,Jt,G,xt,st,Se,ce,et,Qt,Gt,In,vn,gt,Lt,Qe,qt,ln,Cn,Sn,yn,Lo,At,Un,zn,Vo,yo,wt,Cr,Io,Sr,On,Xr,Zo,$o,Tt,qn,jn,Rn,Rt,ro,so,Kn,er,Uo,tr,Gn,Ft,Pn,ao,nr,zo,or,Ro,Yn,vo,bt,Zt,en,Xn,rr;let t=rm(e),n={};for(let[we,io]of Object.entries(t)){let lo=we.replace(/\./g,"-");n[`--persona-${lo}`]=io.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v: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"]=(P=n["--persona-semantic-colors-background"])!=null?P: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"]=(w=n["--persona-semantic-colors-text-muted"])!=null?w:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(x=n["--persona-semantic-colors-text-inverse"])!=null?x:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(E=n["--persona-semantic-colors-border"])!=null?E:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(S=n["--persona-semantic-colors-divider"])!=null?S:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(k=n["--persona-components-voice-recording-indicator"])!=null?k:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(V=n["--persona-components-voice-recording-background"])!=null?V:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(z=n["--persona-components-voice-processing-icon"])!=null?z:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(Y=n["--persona-components-voice-speaking-icon"])!=null?Y:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(he=n["--persona-components-approval-requested-background"])!=null?he:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(me=n["--persona-components-approval-requested-border"])!=null?me:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(de=n["--persona-components-approval-requested-text"])!=null?de:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(Ee=n["--persona-components-approval-requested-shadow"])!=null?Ee:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-approval-approve-bg"]=(xe=n["--persona-components-approval-approve-background"])!=null?xe:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(De=n["--persona-components-approval-deny-background"])!=null?De:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Ae=n["--persona-components-attachment-image-background"])!=null?Ae:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(le=n["--persona-components-attachment-image-border"])!=null?le: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"]=(se=n["--persona-semantic-typography-fontSize"])!=null?se:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(ye=n["--persona-semantic-typography-fontWeight"])!=null?ye:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(be=n["--persona-semantic-typography-lineHeight"])!=null?be: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"]=(K=n["--persona-palette-radius-sm"])!=null?K:"0.125rem",n["--persona-radius-md"]=(ae=n["--persona-palette-radius-md"])!=null?ae:"0.375rem",n["--persona-radius-lg"]=(Re=n["--persona-palette-radius-lg"])!=null?Re:"0.5rem",n["--persona-radius-xl"]=(oe=n["--persona-palette-radius-xl"])!=null?oe:"0.75rem",n["--persona-radius-full"]=(ee=n["--persona-palette-radius-full"])!=null?ee:"9999px",n["--persona-launcher-radius"]=(it=(re=n["--persona-components-launcher-borderRadius"])!=null?re:n["--persona-palette-radius-full"])!=null?it:"9999px",n["--persona-launcher-bg"]=(lt=n["--persona-components-launcher-background"])!=null?lt:n["--persona-primary"],n["--persona-launcher-fg"]=(Le=n["--persona-components-launcher-foreground"])!=null?Le:n["--persona-text-inverse"],n["--persona-launcher-border"]=(pe=n["--persona-components-launcher-border"])!=null?pe:n["--persona-border"],n["--persona-button-primary-bg"]=(Je=n["--persona-components-button-primary-background"])!=null?Je: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"]=(fe=(j=n["--persona-components-button-primary-borderRadius"])!=null?j:n["--persona-palette-radius-full"])!=null?fe:"9999px",n["--persona-panel-radius"]=(Mt=(tt=n["--persona-components-panel-borderRadius"])!=null?tt:n["--persona-radius-xl"])!=null?Mt:"0.75rem",n["--persona-panel-border"]=(te=n["--persona-components-panel-border"])!=null?te:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Fn=(qe=n["--persona-components-panel-shadow"])!=null?qe:n["--persona-palette-shadows-xl"])!=null?Fn:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(Dt=n["--persona-components-launcher-shadow"])!=null?Dt:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(oo=(an=n["--persona-components-input-borderRadius"])!=null?an:n["--persona-radius-lg"])!=null?oo:"0.5rem",n["--persona-message-user-radius"]=(F=(Mo=n["--persona-components-message-user-borderRadius"])!=null?Mo:n["--persona-radius-lg"])!=null?F:"0.5rem",n["--persona-message-assistant-radius"]=(Fe=(ue=n["--persona-components-message-assistant-borderRadius"])!=null?ue:n["--persona-radius-lg"])!=null?Fe:"0.5rem",n["--persona-header-bg"]=(Ke=n["--persona-components-header-background"])!=null?Ke:n["--persona-surface"],n["--persona-header-border"]=(_e=n["--persona-components-header-border"])!=null?_e:n["--persona-divider"],n["--persona-header-icon-bg"]=($e=n["--persona-components-header-iconBackground"])!=null?$e:n["--persona-primary"],n["--persona-header-icon-fg"]=(ot=n["--persona-components-header-iconForeground"])!=null?ot:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(Pt=n["--persona-components-header-titleForeground"])!=null?Pt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(Kt=n["--persona-components-header-subtitleForeground"])!=null?Kt:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Jt=n["--persona-components-header-actionIconForeground"])!=null?Jt:n["--persona-muted"];let o=(G=e.components)==null?void 0:G.header;o!=null&&o.shadow&&(n["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom);let r=(xt=e.components)==null?void 0:xt.introCard;n["--persona-intro-card-bg"]=(st=n["--persona-components-introCard-background"])!=null?st:n["--persona-surface"],n["--persona-intro-card-radius"]=(Se=n["--persona-components-introCard-borderRadius"])!=null?Se:"1rem",n["--persona-intro-card-padding"]=(ce=n["--persona-components-introCard-padding"])!=null?ce:"1.5rem",n["--persona-intro-card-shadow"]=(Qt=(et=r==null?void 0:r.shadow)!=null?et:n["--persona-components-introCard-shadow"])!=null?Qt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Gt=n["--persona-components-input-background"])!=null?Gt:n["--persona-surface"],n["--persona-input-placeholder"]=(In=n["--persona-components-input-placeholder"])!=null?In:n["--persona-text-muted"],n["--persona-message-user-bg"]=(vn=n["--persona-components-message-user-background"])!=null?vn:n["--persona-accent"],n["--persona-message-user-text"]=(gt=n["--persona-components-message-user-text"])!=null?gt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Lt=n["--persona-components-message-user-shadow"])!=null?Lt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Qe=n["--persona-components-message-assistant-background"])!=null?Qe:n["--persona-surface"],n["--persona-message-assistant-text"]=(qt=n["--persona-components-message-assistant-text"])!=null?qt:n["--persona-text"],n["--persona-message-assistant-border"]=(ln=n["--persona-components-message-assistant-border"])!=null?ln:n["--persona-border"],n["--persona-message-assistant-shadow"]=(Cn=n["--persona-components-message-assistant-shadow"])!=null?Cn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(yn=(Sn=n["--persona-components-scrollToBottom-background"])!=null?Sn:n["--persona-button-primary-bg"])!=null?yn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(At=(Lo=n["--persona-components-scrollToBottom-foreground"])!=null?Lo:n["--persona-button-primary-fg"])!=null?At:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Un=n["--persona-components-scrollToBottom-border"])!=null?Un:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(zn=n["--persona-components-scrollToBottom-size"])!=null?zn:"40px",n["--persona-scroll-to-bottom-radius"]=(wt=(yo=(Vo=n["--persona-components-scrollToBottom-borderRadius"])!=null?Vo:n["--persona-button-radius"])!=null?yo:n["--persona-radius-full"])!=null?wt:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Io=(Cr=n["--persona-components-scrollToBottom-shadow"])!=null?Cr:n["--persona-palette-shadows-sm"])!=null?Io:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(Sr=n["--persona-components-scrollToBottom-padding"])!=null?Sr:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(On=n["--persona-components-scrollToBottom-gap"])!=null?On:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Zo=(Xr=n["--persona-components-scrollToBottom-fontSize"])!=null?Xr:n["--persona-palette-typography-fontSize-sm"])!=null?Zo:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=($o=n["--persona-components-scrollToBottom-iconSize"])!=null?$o:"14px",n["--persona-tool-bubble-shadow"]=(Tt=n["--persona-components-toolBubble-shadow"])!=null?Tt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(qn=n["--persona-components-reasoningBubble-shadow"])!=null?qn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(jn=n["--persona-components-composer-shadow"])!=null?jn:"none",n["--persona-md-inline-code-bg"]=(Rn=n["--persona-components-markdown-inlineCode-background"])!=null?Rn:n["--persona-container"],n["--persona-md-inline-code-color"]=(Rt=n["--persona-components-markdown-inlineCode-foreground"])!=null?Rt:n["--persona-text"],n["--persona-md-link-color"]=(so=(ro=n["--persona-components-markdown-link-foreground"])!=null?ro:n["--persona-accent"])!=null?so:"#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"]=(Kn=n["--persona-components-markdown-codeBlock-background"])!=null?Kn:n["--persona-container"],n["--persona-md-code-block-border-color"]=(er=n["--persona-components-markdown-codeBlock-borderColor"])!=null?er:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Uo=n["--persona-components-markdown-codeBlock-textColor"])!=null?Uo:"inherit",n["--persona-md-table-header-bg"]=(tr=n["--persona-components-markdown-table-headerBackground"])!=null?tr:n["--persona-container"],n["--persona-md-table-border-color"]=(Gn=n["--persona-components-markdown-table-borderColor"])!=null?Gn:n["--persona-border"],n["--persona-md-hr-color"]=(Ft=n["--persona-components-markdown-hr-color"])!=null?Ft:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Pn=n["--persona-components-markdown-blockquote-borderColor"])!=null?Pn:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(ao=n["--persona-components-markdown-blockquote-background"])!=null?ao:"transparent",n["--persona-md-blockquote-text-color"]=(nr=n["--persona-components-markdown-blockquote-textColor"])!=null?nr:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(zo=n["--persona-components-collapsibleWidget-container"])!=null?zo:n["--persona-surface"],n["--cw-surface"]=(or=n["--persona-components-collapsibleWidget-surface"])!=null?or:n["--persona-surface"],n["--cw-border"]=(Ro=n["--persona-components-collapsibleWidget-border"])!=null?Ro:n["--persona-border"],n["--persona-message-border"]=(Yn=n["--persona-components-message-border"])!=null?Yn:n["--persona-border"];let f=e.components,u=f==null?void 0:f.iconButton;u&&(u.background&&(n["--persona-icon-btn-bg"]=u.background),u.border&&(n["--persona-icon-btn-border"]=u.border),u.color&&(n["--persona-icon-btn-color"]=u.color),u.padding&&(n["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(n["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(n["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(n["--persona-icon-btn-active-border"]=u.activeBorder));let g=f==null?void 0:f.labelButton;g&&(g.background&&(n["--persona-label-btn-bg"]=g.background),g.border&&(n["--persona-label-btn-border"]=g.border),g.color&&(n["--persona-label-btn-color"]=g.color),g.padding&&(n["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(n["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(n["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(n["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(n["--persona-label-btn-gap"]=g.gap));let m=f==null?void 0:f.toggleGroup;m&&(m.gap&&(n["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(n["--persona-toggle-group-radius"]=m.borderRadius));let C=f==null?void 0:f.artifact;if(C!=null&&C.toolbar){let we=C.toolbar;we.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=we.iconHoverColor),we.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=we.iconHoverBackground),we.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=we.iconPadding),we.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=we.iconBorderRadius),we.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=we.iconBorder),we.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=we.toggleGroupGap),we.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=we.toggleBorderRadius),we.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=we.copyBackground),we.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=we.copyBorder),we.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=we.copyColor),we.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=we.copyBorderRadius),we.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=we.copyPadding),we.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=we.copyMenuBackground,n["--persona-dropdown-bg"]=(vo=n["--persona-dropdown-bg"])!=null?vo:we.copyMenuBackground),we.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=we.copyMenuBorder,n["--persona-dropdown-border"]=(bt=n["--persona-dropdown-border"])!=null?bt:we.copyMenuBorder),we.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=we.copyMenuShadow,n["--persona-dropdown-shadow"]=(Zt=n["--persona-dropdown-shadow"])!=null?Zt:we.copyMenuShadow),we.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=we.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(en=n["--persona-dropdown-radius"])!=null?en:we.copyMenuBorderRadius),we.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=we.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(Xn=n["--persona-dropdown-item-hover-bg"])!=null?Xn:we.copyMenuItemHoverBackground),we.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=we.iconBackground),we.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=we.toolbarBorder)}if(C!=null&&C.tab){let we=C.tab;we.background&&(n["--persona-artifact-tab-bg"]=we.background),we.activeBackground&&(n["--persona-artifact-tab-active-bg"]=we.activeBackground),we.activeBorder&&(n["--persona-artifact-tab-active-border"]=we.activeBorder),we.borderRadius&&(n["--persona-artifact-tab-radius"]=we.borderRadius),we.textColor&&(n["--persona-artifact-tab-color"]=we.textColor),we.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=we.hoverBackground),we.listBackground&&(n["--persona-artifact-tab-list-bg"]=we.listBackground),we.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=we.listBorderColor),we.listPadding&&(n["--persona-artifact-tab-list-padding"]=we.listPadding)}if(C!=null&&C.pane){let we=C.pane;if(we.toolbarBackground){let io=(rr=cs(e,we.toolbarBackground))!=null?rr:we.toolbarBackground;n["--persona-artifact-toolbar-bg"]=io}}return n}var Vg={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"}}},im=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ml=()=>{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"},$g=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Ml()},Ug=e=>$g(e),zg=e=>mn(e),qg=e=>{var n;let t=mn(void 0,{validate:!1});return mn({...e,palette:{...t.palette,colors:{...Vg.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},ci=e=>{let t=Ug(e),n=im(e==null?void 0:e.theme),o=im(e==null?void 0:e.darkTheme);return t==="dark"?qg(Xs(n!=null?n:{},o!=null?o:{})):zg(n)},jg=e=>am(e),ds=(e,t)=>{let n=ci(t),o=jg(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s)},lm=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Ml())});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(Ml());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};function Ll(e,t){let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return o}function Hr(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]:Hr((i=a==null?void 0:a[r])!=null?i:{},s.join("."),n)}}var di=class{constructor(t,n,o){this.listeners=[];this.history=[];this.historyIndex=-1;this.suppressHistory=!1;var s;let r=(s=o==null?void 0:o.mergeDefaults)!=null?s:!0;this.config=r?{...It,...n}:n!=null?n:It,this.theme=mn(t,{validate:!1}),this.syncThemeIntoConfig(),this.pushHistorySnapshot(this.exportSnapshot(),!0)}get(t){var n;return t.startsWith("theme.")?Ll(this.theme,t.replace("theme.","")):t.startsWith("darkTheme.")?Ll((n=this.config.darkTheme)!=null?n:{},t.replace("darkTheme.","")):Ll(this.config,t)}getTheme(){return this.theme}getConfig(){return this.config}set(t,n){var o;if(t.startsWith("theme.")){let r=t.replace("theme.","");this.theme=Hr(this.theme,r,n),this.syncThemeIntoConfig()}else if(t.startsWith("darkTheme.")){let r=t.replace("darkTheme.",""),s=(o=this.config.darkTheme)!=null?o:mn();this.config={...this.config,darkTheme:Hr(s,r,n)}}else this.config=Hr(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=Hr(this.theme,d,i),n=!0}else if(a.startsWith("darkTheme.")){let d=a.replace("darkTheme.",""),l=(s=this.config.darkTheme)!=null?s:mn();this.config={...this.config,darkTheme:Hr(l,d,i)},o=!0}else this.config=Hr(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=mn((s=n.theme)!=null?s:this.theme,{validate:!1});this.setFullConfig(a,i);return}let o=mn(n,{validate:!1});this.setTheme(o)}resetToDefaults(){this.config={...It},this.theme=mn(),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=mn(t.theme,{validate:!1}),this.syncThemeIntoConfig(),this.suppressHistory=!1,this.notifyListeners()}};function pi(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 ui(e,t){return t==="rem"?`${e}rem`:`${e}px`}function cm(e,t){return t==="rem"?e*16:e}function dm(e,t){return t==="rem"?e/16:e}function ps(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 mi(e){return/^#[0-9A-Fa-f]{6}$/.test(e)}function fi(e){let t=e.trim().toLowerCase().match(/^rgba?\(([^)]+)\)$/);if(!t)return null;let n=t[1].split(",").map(d=>d.trim());if(n.length<3)return null;let o=d=>{let l=d.endsWith("%"),f=parseFloat(l?d.slice(0,-1):d);return Number.isFinite(f)?Math.max(0,Math.min(255,Math.round(l?f/100*255:f))):NaN},r=o(n[0]),s=o(n[1]),a=o(n[2]);if(!Number.isFinite(r)||!Number.isFinite(s)||!Number.isFinite(a))return null;let i=d=>d.toString(16).padStart(2,"0");return`#${i(r)}${i(s)}${i(a)}`}function Js(e,t){let n=s=>{var l;let a=ps(s),i=a.startsWith("rgb")?(l=fi(a))!=null?l:"#000000":a,d=[1,3,5].map(f=>{let u=parseInt(i.slice(f,f+2),16)/255;return u<=.03928?u/12.92:Math.pow((u+.055)/1.055,2.4)});return .2126*d[0]+.7152*d[1]+.0722*d[2]},o=n(e),r=n(t);return(Math.max(o,r)+.05)/(Math.min(o,r)+.05)}function Il(e){var g;let t=ps(e),n=t.startsWith("rgb")?(g=fi(t))!=null?g:"#000000":t,o=parseInt(n.slice(1,3),16)/255,r=parseInt(n.slice(3,5),16)/255,s=parseInt(n.slice(5,7),16)/255,a=Math.max(o,r,s),i=Math.min(o,r,s),d=(a+i)/2;if(a===i)return{h:0,s:0,l:d};let l=a-i,f=d>.5?l/(2-a-i):l/(a+i),u;switch(a){case o:u=((r-s)/l+(r<s?6:0))/6;break;case r:u=((s-o)/l+2)/6;break;default:u=((o-r)/l+4)/6;break}return{h:u*360,s:f,l:d}}function Rl(e,t,n){let o=(e%360+360)%360,r=(1-Math.abs(2*n-1))*t,s=r*(1-Math.abs(o/60%2-1)),a=n-r/2,i,d,l;o<60?[i,d,l]=[r,s,0]:o<120?[i,d,l]=[s,r,0]:o<180?[i,d,l]=[0,r,s]:o<240?[i,d,l]=[0,s,r]:o<300?[i,d,l]=[s,0,r]:[i,d,l]=[r,0,s];let f=u=>{let g=Math.round((u+a)*255).toString(16);return g.length===1?"0"+g:g};return`#${f(i)}${f(d)}${f(l)}`}function gi(e){let{h:t,s:n,l:o}=Il(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]=Rl(t,l,d)}return a}var Dr=["50","100","200","300","400","500","600","700","800","900","950"],hi=["primary","secondary","accent","gray","success","warning","error","info"];function pm(e,t){return`palette.colors.${e}.${t}`}function Pl(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.")?Pl(e,`theme.${o}`,n+1):"#cbd5e1"}function um(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 To=[{id:"solid",label:"Solid"},{id:"soft",label:"Soft"}],Qs=["primary","secondary","accent","gray"],mm={primary:"Primary",secondary:"Secondary",accent:"Accent",gray:"Neutral"},Zs={roleId:"role-surfaces",helper:"Page and panel backgrounds",previewZone:"container",intensities:To,targets:[{path:"semantic.colors.background",kind:"background"},{path:"semantic.colors.surface",kind:"background"},{path:"semantic.colors.container",kind:"background"}]},ea={roleId:"role-header",helper:"Widget header bar",previewZone:"header",intensities:To,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"}]},ta={roleId:"role-user-messages",helper:"User chat bubbles",previewZone:"user-message",intensities:To,targets:[{path:"components.message.user.background",kind:"background"},{path:"components.message.user.text",kind:"foreground"}]},na={roleId:"role-assistant-messages",helper:"Assistant chat bubbles",previewZone:"assistant-message",intensities:To,targets:[{path:"components.message.assistant.background",kind:"background"},{path:"components.message.assistant.text",kind:"foreground"}]},oa={roleId:"role-primary-actions",helper:"Send button and primary buttons",intensities:To,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"}]},ra={roleId:"role-scroll-to-bottom",helper:"Scroll-to-bottom affordances in transcript and event stream",intensities:To,targets:[{path:"components.scrollToBottom.background",kind:"background"},{path:"components.scrollToBottom.foreground",kind:"foreground"},{path:"components.scrollToBottom.border",kind:"border"}]},sa={roleId:"role-input",helper:"Message input field",previewZone:"composer",intensities:To,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"}]},aa={roleId:"role-links-focus",helper:"Links, focus rings, and interactive highlights",intensities:To,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"}]},ia={roleId:"role-borders",helper:"Borders, dividers, and separators",intensities:To,targets:[{path:"semantic.colors.border",kind:"border"},{path:"semantic.colors.divider",kind:"border"}]},fr=[Zs,ea,ta,na,oa,ra,sa,aa,ia];function la(e,t,n){let o={},r=e==="neutral"?"gray":e;for(let s of n.targets){let a=Kg(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 Kg(e,t,n,o){let r=t==="solid";if(o==="role-header")return Gg(e,r,n);if(o==="role-input")return Yg(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 Gg(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 Yg(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 Xg=/^palette\.colors\.(\w+)\.(\d+)$/;function bi(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(Xg);if(!r)return null;let s=r[1],a=Qs.includes(s)?s:null;if(!a)return null;for(let l of["solid","soft"]){let f=la(a,l,t);if(t.targets.every(g=>{var C;return String((C=e(g.path))!=null?C:"")===f[`theme.${g.path}`]}))return{family:a,intensity:l}}return null}var Jg={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"}]}]},Qg={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"}]},Zg={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"}}]},eh={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)"}]}]},th={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"}]}]},nh={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"}}]},oh={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)"}]},rh={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"}]}]},Fr=[Qg,Zg,th,eh,Jg,nh,oh,rh];function gm(){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:hi.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 hm={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"}}]},bm=gm(),ym=hm,vm=[gm(),hm],sh={id:"comp-panel",title:"Panel",collapsed:!1,fields:[{id:"panel-width",label:"Width",type:"text",path:"theme.components.panel.width",defaultValue:go},{id:"panel-max-width",label:"Max Width",type:"text",path:"theme.components.panel.maxWidth",defaultValue:li},{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"}]}]},ah={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"}]}]},ih={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"}]}]},lh={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"}]}]},ch={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"}]}]},dh={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"}}]},ph={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"}}]},uh={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"}}]},mh={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"}}]},fh={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"}]},us=[{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"}],Wl="0 5px 15px rgba(15, 23, 42, 0.08)",fm=[{value:Wl,label:"Default"},...us],gh={id:"comp-shadows",title:"Component Shadows",description:"Box-shadow for chat bubbles and surfaces.",collapsed:!0,fields:[{id:"shadow-msg-user",label:"User Message",type:"select",path:"theme.components.message.user.shadow",defaultValue:"palette.shadows.sm",options:us},{id:"shadow-msg-assistant",label:"Assistant Message",type:"select",path:"theme.components.message.assistant.shadow",defaultValue:"palette.shadows.sm",options:us},{id:"shadow-tool-bubble",label:"Tool Call Bubble",type:"select",path:"theme.components.toolBubble.shadow",defaultValue:"palette.shadows.sm",options:us},{id:"shadow-reasoning-bubble",label:"Reasoning Bubble",type:"select",path:"theme.components.reasoningBubble.shadow",defaultValue:"palette.shadows.sm",options:us},{id:"shadow-approval",label:"Approval Bubble",type:"select",path:"theme.components.approval.requested.shadow",defaultValue:Wl,options:fm},{id:"shadow-intro-card",label:"Intro Card",type:"select",path:"theme.components.introCard.shadow",defaultValue:Wl,options:fm},{id:"shadow-composer",label:"Composer",type:"select",path:"theme.components.composer.shadow",defaultValue:"palette.shadows.none",options:us}]},Bl=[sh,ah,ih,lh,ch,gh],Hl=[dh,ph,uh,mh,fh],Dl=[...Bl,...Hl],Fl=1024*1024,hh=["What can you help me with?","Tell me about your features","How does this work?"],ca={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 bh(e){return Number(e)*Fl}function yh(e){let t=Number(e);return Number.isFinite(t)?t>1024?String(Math.round(t/Fl)):String(t):"10"}function vh(e){var t;return(t=ca[String(e)])!=null?t:ca.images}function xh(e){let t=Array.isArray(e)?e:ca.images,n=[...new Set(t)].sort();for(let[o,r]of Object.entries(ca)){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 wh={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"}]},Ch={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:hh}]},Sh={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:""}]},Ah={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}]},Th={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"}]}]},kh={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"}]}]},Eh={id:"launcher-basics",title:"Launcher",collapsed:!0,fields:[{id:"launch-enabled",label:"Enabled",type:"toggle",path:"launcher.enabled",defaultValue:!0},{id:"launch-mount-mode",label:"Mount Mode",type:"select",path:"launcher.mountMode",defaultValue:"floating",options:[{value:"floating",label:"Floating"},{value:"docked",label:"Docked"}]},{id:"launch-position",label:"Position",type:"select",path:"launcher.position",defaultValue:"bottom-right",options:[{value:"bottom-right",label:"Bottom Right"},{value:"bottom-left",label:"Bottom Left"},{value:"top-right",label:"Top Right"},{value:"top-left",label:"Top Left"}]},{id:"launch-width",label:"Width",type:"text",path:"launcher.width",defaultValue:go},{id:"launch-auto-expand",label:"Auto Expand",type:"toggle",path:"launcher.autoExpand",defaultValue:!1},{id:"launch-title",label:"Title",type:"text",path:"launcher.title",defaultValue:"Chat Assistant"},{id:"launch-subtitle",label:"Subtitle",type:"text",path:"launcher.subtitle",defaultValue:"Here to help you get answers fast"}]},Mh={id:"launcher-advanced",title:"Launcher Advanced",collapsed:!0,fields:[{id:"launch-dock-side",label:"Dock Side",type:"select",path:"launcher.dock.side",defaultValue:"right",options:[{value:"right",label:"Right"},{value:"left",label:"Left"}]},{id:"launch-dock-width",label:"Dock Width",type:"text",path:"launcher.dock.width",defaultValue:"420px"},{id:"launch-dock-animate",label:"Dock Animate",type:"toggle",path:"launcher.dock.animate",defaultValue:!0},{id:"launch-dock-reveal",label:"Dock Reveal",type:"select",path:"launcher.dock.reveal",defaultValue:"resize",options:[{value:"resize",label:"Resize"},{value:"overlay",label:"Overlay"},{value:"push",label:"Push"},{value:"emerge",label:"Emerge"}]},{id:"launch-text-hidden",label:"Hide Text",type:"toggle",path:"launcher.textHidden",defaultValue:!1},{id:"launch-icon-text",label:"Agent Icon Text",type:"text",path:"launcher.agentIconText",defaultValue:"\u{1F4AC}"},{id:"launch-icon-name",label:"Agent Icon Name (Lucide)",type:"text",path:"launcher.agentIconName",defaultValue:"bot"},{id:"launch-icon-hidden",label:"Hide Agent Icon",type:"toggle",path:"launcher.agentIconHidden",defaultValue:!1},{id:"launch-icon-size",label:"Agent Icon Size",type:"slider",path:"launcher.agentIconSize",defaultValue:"40px",slider:{min:16,max:72,step:2}},{id:"launch-icon-url",label:"Icon Image URL",description:"Custom image URL (overrides emoji/lucide)",type:"text",path:"launcher.iconUrl",defaultValue:""},{id:"launch-header-icon-name",label:"Header Icon Name (Lucide)",type:"text",path:"launcher.headerIconName",defaultValue:"bot"},{id:"launch-header-icon-size",label:"Header Icon Size",type:"slider",path:"launcher.headerIconSize",defaultValue:"48px",slider:{min:24,max:80,step:2}},{id:"launch-header-icon-hidden",label:"Hide Header Icon",type:"toggle",path:"launcher.headerIconHidden",defaultValue:!1},{id:"launch-full-height",label:"Full Height",type:"toggle",path:"launcher.fullHeight",defaultValue:!1},{id:"launch-sidebar",label:"Sidebar Mode",type:"toggle",path:"launcher.sidebarMode",defaultValue:!1},{id:"launch-sidebar-width",label:"Sidebar Width",type:"text",path:"launcher.sidebarWidth",defaultValue:"420px"},{id:"launch-mobile-fullscreen",label:"Mobile Fullscreen",description:"Fullscreen on mobile devices",type:"toggle",path:"launcher.mobileFullscreen",defaultValue:!0},{id:"launch-mobile-breakpoint",label:"Mobile Breakpoint (px)",type:"text",path:"launcher.mobileBreakpoint",defaultValue:640,formatValue:e=>String(e!=null?e:640),parseValue:e=>Number(e)},{id:"launch-height-offset",label:"Height Offset (px)",type:"text",path:"launcher.heightOffset",defaultValue:0,formatValue:e=>String(e!=null?e:0),parseValue:e=>Number(e)},{id:"launch-collapsed-max-width",label:"Collapsed Max Width",description:"Max width of launcher pill when closed",type:"text",path:"launcher.collapsedMaxWidth",defaultValue:""},{id:"launch-cta-text",label:"CTA Icon Text",type:"text",path:"launcher.callToActionIconText",defaultValue:"\u2197"},{id:"launch-cta-name",label:"CTA Icon Name",type:"text",path:"launcher.callToActionIconName",defaultValue:""},{id:"launch-cta-hidden",label:"Hide CTA Icon",type:"toggle",path:"launcher.callToActionIconHidden",defaultValue:!1},{id:"launch-cta-size",label:"CTA Icon Size",type:"slider",path:"launcher.callToActionIconSize",defaultValue:"32px",slider:{min:16,max:64,step:2}},{id:"launch-cta-padding",label:"CTA Icon Padding",type:"slider",path:"launcher.callToActionIconPadding",defaultValue:"5px",slider:{min:0,max:24,step:1}},{id:"launch-cta-bg",label:"CTA Icon Background",type:"color",path:"launcher.callToActionIconBackgroundColor",defaultValue:""}]},Lh={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"}]},Ih={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"}]},Rh={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"}]},Ph={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"}]},Wh={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:""}]},Bh={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)}]},Hh={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*Fl,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:yh,parseValue:bh},{id:"attach-types",label:"Allowed File Types",type:"select",path:"attachments.allowedTypes",defaultValue:ca.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:xh,parseValue:vh}]},Dh={id:"artifacts-config",title:"Artifacts",collapsed:!0,fields:[{id:"art-enabled",label:"Enabled",description:"Show artifact sidebar for documents and components",type:"toggle",path:"features.artifacts.enabled",defaultValue:!1},{id:"art-appearance",label:"Pane Appearance",type:"select",path:"features.artifacts.layout.paneAppearance",defaultValue:"panel",options:[{value:"panel",label:"Panel (bordered)"},{value:"seamless",label:"Seamless"}]}]},Fh={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}]},Oh={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"}]}]},Nh={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}]},_h={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}]},da=[{label:"Content",sections:[wh,Ch]},{label:"Layout",sections:[Sh,Ah,Th,kh]},{label:"Widget",sections:[Eh,Mh,Lh,Ih,Rh,Ph]},{label:"Features",sections:[Wh,Bh,Hh,Dh,Fh]},{label:"Developer",collapsedByDefault:!0,sections:[Oh,Nh,_h]}],Ol=da.flatMap(e=>e.sections),Nl={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"}]}]},_l={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"}]},Vl={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"}]},$l={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:Zs},{id:"role-header",label:"Header",type:"role-assignment",path:"theme.components.header.background",roleAssignment:ea},{id:"role-user-messages",label:"User Messages",type:"role-assignment",path:"theme.components.message.user.background",roleAssignment:ta},{id:"role-assistant-messages",label:"Assistant Messages",type:"role-assignment",path:"theme.components.message.assistant.background",roleAssignment:na},{id:"role-primary-actions",label:"Primary Actions",type:"role-assignment",path:"theme.components.button.primary.background",roleAssignment:oa},{id:"role-scroll-to-bottom",label:"Scroll To Bottom",type:"role-assignment",path:"theme.components.scrollToBottom.background",roleAssignment:ra},{id:"role-input",label:"Input Field",type:"role-assignment",path:"theme.components.input.background",roleAssignment:sa},{id:"role-links-focus",label:"Links & Focus",type:"role-assignment",path:"theme.semantic.colors.accent",roleAssignment:aa},{id:"role-borders",label:"Borders & Dividers",type:"role-assignment",path:"theme.semantic.colors.border",roleAssignment:ia}]},Ul={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"}}]},zl={id:"advanced-tokens",title:"Advanced Tokens",description:"Override individual semantic and component values when you need precise control.",collapsed:!0,fields:[]},xm=[Nl,_l,Vl,$l,Ul,zl],yi=[{id:"style",label:"Style",sections:Fr},{id:"design-system",label:"Design System",sections:Dl},{id:"configure",label:"Configure",sections:Ol}];function wm(e,t){return e.startsWith("theme.")?e.replace(/^theme\./,`${t}.`):e}function Vh(e,t,n){return{...e,id:`${n}-${e.id}`,path:wm(e.path,t)}}function Cm(e,t){let n=e.find(o=>o.id===t);if(!n)throw new Error(`Section "${t}" not found in definitions`);return n}function Sm(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=>Vh(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])=>[wm(d,t),l]))}))}}var ql=[{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=[...ql];function vi(e){return ms.find(t=>t.id===e)}var Am=require("marked"),$h=e=>{if(e)return e},jl=e=>{var r,s;let t=e==null?void 0:e.markedOptions,n=new Am.Marked({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=$h(e==null?void 0:e.renderer);return o&&n.use({renderer:o}),a=>n.parse(a)},xi=e=>e?jl({markedOptions:e.options,renderer:e.renderer}):jl(),Jv=jl();var pa=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");var Tm=em(require("dompurify"),1),Uh={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"]},zh=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,qh=()=>{let e=(0,Tm.default)(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:")&&!zh.test(o)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,Uh)},wi=e=>e===!1?null:typeof e=="function"?e:qh();var Or="webmcp:",Kl=new Map,km=e=>{var t;Kl.clear();for(let n of e){let o=(t=n.title)==null?void 0:t.trim();o&&Kl.set(n.name,o)}},Gl=e=>Kl.get(Im(e)),Ci={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Em=null;function Lm(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}:${jh(t.join(""))}`}function Mm(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 jh(e){let t=Mm(e,0).toString(36),n=Mm(e,2654435761).toString(36);return`${t}.${n}`}var Si=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 Ci.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",r),[]}km(n);let o=typeof location!="undefined"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=Gh(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return ko("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let C=typeof document!="undefined"&&!!document.modelContext;return ko(C?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=Im(t),a;try{a=await r.getTools()}catch(C){let v=C instanceof Error?C.message:String(C);return ko(`Failed to read WebMCP registry: ${v}`)}km(a);let i=a.find(C=>C.name===s);if(!i)return ko(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return ko(`WebMCP tool not allowed by client allowlist: ${s}`);if(o!=null&&o.aborted)return ko("Aborted by cancel()");let d=Gl(s),l={toolName:s,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(l))return ko("User declined the tool call.");if(o!=null&&o.aborted)return ko("Aborted by cancel()");let f=new AbortController,u=!1,g=setTimeout(()=>{u=!0,f.abort()},this.timeoutMs),m=()=>f.abort();o&&(o.aborted?f.abort():o.addEventListener("abort",m,{once:!0}));try{let C=await r.executeTool(i,Qh(n),{signal:f.signal});return Yh(C)}catch(C){if(u)return ko(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return ko("Aborted by cancel()");let v=C instanceof Error?C.message:String(C);return ko(v)}finally{clearTimeout(g),o&&o.removeEventListener("abort",m)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(Em?await Em():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Ci.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,Ci.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:Xh;try{return await n(t)}catch(r){return Ci.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,r),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>Kh(t,o))}},Im=e=>e.startsWith(Or)?e.slice(Or.length):e,fs=e=>e.startsWith(Or),Kh=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Gh=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Yh=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:Zh(t)}]}},ko=e=>({isError:!0,content:[{type:"text",text:e}]}),Xh=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Jh(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)},Jh=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)}},Qh=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Zh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var gs=require("partial-json"),Rm=e=>e.replace(/\\n/g,`
|
|
7
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),hs=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)}},eb=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`},Pm=e=>e.status==="complete"?eb(e):e.status==="pending"?"Waiting":"",tb=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 Wm=e=>e.status==="complete"?tb(e):"Using tool...",Ai=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},ma=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 Ai(t)},Ti=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 Ai(t)},Yl=(e,t,n)=>{var s;if(!t)return n;let o=((s=e.name)==null?void 0:s.trim())||"tool",r=ma(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},ki=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&ua(o,n.slice(s,a.index),[]),a[1]!==void 0?ua(o,a[1],["bold"]):a[2]!==void 0?ua(o,a[2],["italic"]):a[3]!==void 0&&ua(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&ua(o,n.slice(s),[]),o},ua=(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})},nb=()=>{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()=>{}}},Pr=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},cm=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},dm=()=>{var t;let e=Sh();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)}},pm=()=>{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=(0,ss.parse)(n,ss.STR|ss.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?am(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=am(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var um=()=>{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 vi=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 Ah="https://api.runtype.com/v1/dispatch",xi="https://api.runtype.com";function Th(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 Nl=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 kh(e){switch(e){case"json":return pm;case"regex-json":return dm;case"xml":return um;default:return cm}}var mm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Eh(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=mm(n);if(!mm(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Pr(e);return Pr(t)!==null&&a===null?t:e}var ra=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:Ah,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:kh(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 fi(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$/,""))||xi}/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$/,""))||xi}/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,p={sessionId:d.sessionId,messages:t.messages.filter(Nl).map(D=>{var B,x,w;return{id:D.id,role:D.role,content:(w=(x=(B=D.contentParts)!=null?B:D.llmContent)!=null?x:D.rawContent)!=null?w: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}},f=l.clientTools,u=!!(f&&f.length>0),C=u?rm(f):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,M=u&&v&&this.lastSentClientToolsFingerprint===C,I=!1,R=null,W;for(let D=0;;D++){let x={...p,...u&&(I||!M)&&f?{clientTools:f}:{},...C?{clientToolsFingerprint:C}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",x),W=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(x),signal:o.signal}),W.status===409&&D===0&&u){let w=await W.json().catch(()=>null);if((w==null?void 0:w.error)==="client_tools_resend_required"){I=!0,this.lastSentClientToolsFingerprint=null;continue}R=w!=null?w:{error:"Chat request failed"}}break}if(!W.ok){let D=R!=null?R:await W.json().catch(()=>({error:"Chat request failed"}));if(W.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let x=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:x}),x}if(W.status===429){let x=new Error(D.hint||"Message limit reached for this session.");throw n({type:"error",error:x}),x}let B=new Error(D.error||"Failed to send message");throw n({type:"error",error:B}),B}if(!W.body){let D=new Error("No response body received");throw n({type:"error",error:D}),D}this.lastSentClientToolsFingerprint=C!=null?C:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(W.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let r=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||xi}/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(/\/+$/,""))||xi}/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(Nl).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(Nl).sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},r=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(r&&r.length>0&&(o.clientTools=r),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(o.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...o},config:this.config});if(a&&typeof a=="object"){let i=a;return o.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=o.clientTools),i}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return o}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=m=>{let p={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...m!==void 0&&{partId:m}};return o.current=p,r(p),p},l=m=>o.current?o.current:d(m);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let m=l(i.partId);i.partId!==void 0&&!m.partId&&(m.partId=i.partId),m.content+=i.text,r(m)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o){var gn,Fn,to,qe;let r=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,m=V=>{let Le=V.reasoning?{...V.reasoning,chunks:[...V.reasoning.chunks]}:void 0,He=V.toolCall?{...V.toolCall,chunks:V.toolCall.chunks?[...V.toolCall.chunks]:void 0}:void 0,De=V.tools?V.tools.map(Ve=>({...Ve,chunks:Ve.chunks?[...Ve.chunks]:void 0})):void 0;return{...V,reasoning:Le,toolCall:He,tools:De}},p=V=>{if(V.role!=="assistant"||V.variant)return!0;let Le=Array.isArray(V.contentParts)&&V.contentParts.length>0,He=typeof V.rawContent=="string"&&V.rawContent.trim()!=="";return typeof V.content=="string"&&V.content.trim()!==""||Le||He||!!V.stopReason},f=V=>{p(V)&&n({type:"message",message:m(V)})},u=null,C=null,v={current:null},M={current:null},I=!1,R=new Map,W=new Map,D=new Map,B=new Map,x={lastId:null,byStep:new Map},w={lastId:null,byCall:new Map},E=(V,Le,He="")=>`${V}::${Le}::${He}`,S=(V,Le)=>`${V}::${Le}::`,T=(V,Le,He,De)=>{let Ve=E(V,Le,He),mt=D.get(Ve);if(mt)return mt;let at=He?`-${He}`:"",Pt={id:`nested-${V}-${Le}${at}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...He?{partId:He}:{},agentMetadata:{executionId:De,parentToolId:V,parentStepId:Le}};return D.set(Ve,Pt),f(Pt),Pt},_=V=>{if(V==null)return null;try{return String(V)}catch{return null}},U=V=>{var Le,He,De,Ve,mt;return _((mt=(Ve=(De=(He=(Le=V.stepId)!=null?Le:V.step_id)!=null?He:V.step)!=null?De:V.parentId)!=null?Ve:V.flowStepId)!=null?mt:V.flow_step_id)},Y=V=>{var Le,He,De,Ve,mt,at,Pt;return _((Pt=(at=(mt=(Ve=(De=(He=(Le=V.callId)!=null?Le:V.call_id)!=null?He:V.requestId)!=null?De:V.request_id)!=null?Ve:V.toolCallId)!=null?mt:V.tool_call_id)!=null?at:V.stepId)!=null?Pt:V.step_id)},he=o,fe=!1,ae=()=>{if(u)return u;let V;return!fe&&he?(V=he,fe=!0):he&&M.current?V=`${he}_${M.current}`:V=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,u={id:V,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(u),u},Ee=(V,Le)=>{x.lastId=Le,V&&x.byStep.set(V,Le)},ye=(V,Le)=>{var mt;let He=(mt=V.reasoningId)!=null?mt:V.id,De=U(V);if(He){let at=String(He);return Ee(De,at),at}if(De){let at=x.byStep.get(De);if(at)return x.lastId=at,at}if(x.lastId&&!Le)return x.lastId;if(!Le)return null;let Ve=`reason-${l()}`;return Ee(De,Ve),Ve},Oe=V=>{let Le=R.get(V);if(Le)return Le;let He={id:`reason-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:V,status:"streaming",chunks:[]}};return R.set(V,He),f(He),He},we=(V,Le)=>{w.lastId=Le,V&&w.byCall.set(V,Le)},K=new Set,pe=new Map,G=new Set,ve=new Map,ce=V=>{if(!V)return!1;let Le=V.replace(/_+/g,"_").replace(/^_|_$/g,"");return Le==="emit_artifact_markdown"||Le==="emit_artifact_component"},ne=(V,Le)=>{var mt;let He=(mt=V.toolId)!=null?mt:V.id,De=Y(V);if(He){let at=String(He);return we(De,at),at}if(De){let at=w.byCall.get(De);if(at)return w.lastId=at,at}if(w.lastId&&!Le)return w.lastId;if(!Le)return null;let Ve=`tool-${l()}`;return we(De,Ve),Ve},Se=V=>{let Le=W.get(V);if(Le)return Le;let He={id:`tool-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:V,status:"pending"}};return W.set(V,He),f(He),He},ze=V=>{if(typeof V=="number"&&Number.isFinite(V))return V;if(typeof V=="string"){let Le=Number(V);if(!Number.isNaN(Le)&&Number.isFinite(Le))return Le;let He=Date.parse(V);if(!Number.isNaN(He))return He}return Date.now()},te=V=>{if(typeof V=="string")return V;if(V==null)return"";try{return JSON.stringify(V)}catch{return String(V)}},re=new Map,ie=new Map,st=new Map,Te=new Map,ue=null,Ue=(V,Le,He)=>{var Pt;let De=st.get(V);De||(De=[],st.set(V,De));let Ve=0,mt=De.length;for(;Ve<mt;){let jt=Ve+mt>>>1;De[jt].seq<Le?Ve=jt+1:mt=jt}((Pt=De[Ve])==null?void 0:Pt.seq)===Le?De[Ve]={seq:Le,text:He}:De.splice(Ve,0,{seq:Le,text:He});let at="";for(let jt=0;jt<De.length;jt++)at+=De[jt].text;return at},Be=(V,Le)=>{let He=te(Le),De=ie.get(V.id),Ve=Eh(De,He);V.rawContent=Ve;let mt=re.get(V.id),at=Ze=>{var se;let Vt=(se=V.content)!=null?se:"";Ze.trim()!==""&&(Vt.trim().length===0||Ze.startsWith(Vt)||Ze.trimStart().startsWith(Vt.trim()))&&(V.content=Ze)},Pt=()=>{var Ze;if(mt){let Vt=(Ze=mt.close)==null?void 0:Ze.call(mt);Vt instanceof Promise&&Vt.catch(()=>{})}re.delete(V.id),ie.delete(V.id),V.streaming=!1,f(V)};if(!mt){at(He),Pt();return}let jt=Pr(Ve);if(jt!==null&&jt.trim()!==""){at(jt),Pt();return}let j=Ze=>{var Ce;let Vt=typeof Ze=="string"?Ze:(Ce=Ze==null?void 0:Ze.text)!=null?Ce:null;if(Vt!==null&&Vt.trim()!=="")return Vt;let se=mt.getExtractedText();return se!==null&&se.trim()!==""?se:He},zt;try{zt=mt.processChunk(Ve)}catch{at(He),Pt();return}if(zt instanceof Promise){zt.then(Ze=>{at(j(Ze)),Pt()}).catch(()=>{at(He),Pt()});return}at(j(zt)),Pt()},me=[],Q=!1,_e,Ht=()=>{Q||(Q=!0,queueMicrotask(()=>{Q=!1,_e()}))},be=new vi((V,Le)=>{me.push({payloadType:V,payload:Le}),Ht()}),de=null,Pn=new Map,Ut=(gn=this.config.iterationDisplay)!=null?gn:"separate";for(_e=()=>{var V,Le,He,De,Ve,mt,at,Pt,jt,j,zt,Ze,Vt,se,Ce,kt,Kt,tn,An,Wt,Mt,wt,St,Gt,ot,On,no,Tn,Nn,bt,Lo,_n,fr,Wn,$r,jo,Do,At,Vn,$n,kn,Lt,oo,ro,Un,Ko,Fo,Go,zn,Ft,En,so,Yo,Oo,Xo,Io,qn,yo,vt,Xt,Qt,jn,Qo,ao,vo,Kn,$,io,xe,Gn,lo,xo,xs,wo,Co,So,No,hr,Da,ws,Fa,Ur,yt,Cs,co,Bn,Oa,Na,zr,_o,_a,br,Ss,Vo,As,Jo,Zo,Va,$a,fl,yr,er,Ua,Ts,tr,za,ks,nr,Es,qa,$o,ja,or,Ot,qr,jr,Ms,Ro,Ka,Ls,Is,Ga,Kr,Gr,vr,Ya,Xa,Rs,Ps,Ws,Bs,Mn,Yn,Uo,ct,Hs,xr,Ao;for(let Yr=0;Yr<me.length;Yr++){let Ye=me[Yr].payloadType,k=me[Yr].payload;if(Ye==="reason_start"){let z=(V=ye(k,!0))!=null?V:`reason-${l()}`,P=Oe(z);P.reasoning=(Le=P.reasoning)!=null?Le:{id:z,status:"streaming",chunks:[]},P.reasoning.startedAt=(De=P.reasoning.startedAt)!=null?De:ze((He=k.startedAt)!=null?He:k.timestamp),P.reasoning.completedAt=void 0,P.reasoning.durationMs=void 0,P.streaming=!0,P.reasoning.status="streaming",f(P)}else if(Ye==="reason_delta"||Ye==="reason_chunk"){let z=(mt=(Ve=ye(k,!1))!=null?Ve:ye(k,!0))!=null?mt:`reason-${l()}`,P=Oe(z);P.reasoning=(at=P.reasoning)!=null?at:{id:z,status:"streaming",chunks:[]},P.reasoning.startedAt=(jt=P.reasoning.startedAt)!=null?jt:ze((Pt=k.startedAt)!=null?Pt:k.timestamp);let Z=(Ze=(zt=(j=k.reasoningText)!=null?j:k.text)!=null?zt:k.delta)!=null?Ze:"";if(Z&&k.hidden!==!0){let le=typeof k.sequenceIndex=="number"?k.sequenceIndex:void 0;if(le!==void 0){let X=Ue(z,le,String(Z));P.reasoning.chunks=[X]}else P.reasoning.chunks.push(String(Z))}if(P.reasoning.status=k.done?"complete":"streaming",k.done){P.reasoning.completedAt=ze((Vt=k.completedAt)!=null?Vt:k.timestamp);let le=(se=P.reasoning.startedAt)!=null?se:Date.now();P.reasoning.durationMs=Math.max(0,((Ce=P.reasoning.completedAt)!=null?Ce:Date.now())-le)}P.streaming=P.reasoning.status!=="complete",f(P)}else if(Ye==="reason_complete"){let z=(Kt=(kt=ye(k,!1))!=null?kt:ye(k,!0))!=null?Kt:`reason-${l()}`,P=R.get(z);if(P!=null&&P.reasoning){P.reasoning.status="complete",P.reasoning.completedAt=ze((tn=k.completedAt)!=null?tn:k.timestamp);let le=(An=P.reasoning.startedAt)!=null?An:Date.now();P.reasoning.durationMs=Math.max(0,((Wt=P.reasoning.completedAt)!=null?Wt:Date.now())-le),P.streaming=!1,f(P)}let Z=U(k);Z&&x.byStep.delete(Z)}else if(Ye==="tool_start"){let z=(Mt=ne(k,!0))!=null?Mt:`tool-${l()}`,P=(wt=k.toolName)!=null?wt:k.name;if(ce(P)){K.add(z);continue}let Z=Se(z),le=(St=Z.toolCall)!=null?St:{id:z,status:"pending"};le.name=P!=null?P:le.name,le.status="running",k.args!==void 0?le.args=k.args:k.parameters!==void 0&&(le.args=k.parameters),le.startedAt=(ot=le.startedAt)!=null?ot:ze((Gt=k.startedAt)!=null?Gt:k.timestamp),le.completedAt=void 0,le.durationMs=void 0,Z.toolCall=le,Z.streaming=!0;let X=k.agentContext;(X||k.executionId)&&(Z.agentMetadata={executionId:(On=X==null?void 0:X.executionId)!=null?On:k.executionId,iteration:(no=X==null?void 0:X.iteration)!=null?no:k.iteration}),f(Z)}else if(Ye==="tool_chunk"||Ye==="tool_delta"){let z=(Nn=(Tn=ne(k,!1))!=null?Tn:ne(k,!0))!=null?Nn:`tool-${l()}`;if(K.has(z))continue;let P=Se(z),Z=(bt=P.toolCall)!=null?bt:{id:z,status:"running"};Z.startedAt=(_n=Z.startedAt)!=null?_n:ze((Lo=k.startedAt)!=null?Lo:k.timestamp);let le=($r=(Wn=(fr=k.text)!=null?fr:k.delta)!=null?Wn:k.message)!=null?$r:"";le&&(Z.chunks=(jo=Z.chunks)!=null?jo:[],Z.chunks.push(String(le))),Z.status="running",P.toolCall=Z,P.streaming=!0;let X=k.agentContext;(X||k.executionId)&&(P.agentMetadata=(Vn=P.agentMetadata)!=null?Vn:{executionId:(Do=X==null?void 0:X.executionId)!=null?Do:k.executionId,iteration:(At=X==null?void 0:X.iteration)!=null?At:k.iteration}),f(P)}else if(Ye==="tool_complete"){let z=(kn=($n=ne(k,!1))!=null?$n:ne(k,!0))!=null?kn:`tool-${l()}`;if(K.has(z)){K.delete(z);continue}let P=Se(z),Z=(Lt=P.toolCall)!=null?Lt:{id:z,status:"running"};Z.status="complete",k.result!==void 0&&(Z.result=k.result),typeof k.duration=="number"&&(Z.duration=k.duration),Z.completedAt=ze((oo=k.completedAt)!=null?oo:k.timestamp);let le=(ro=k.duration)!=null?ro:k.executionTime;if(typeof le=="number")Z.durationMs=le;else{let Ne=(Un=Z.startedAt)!=null?Un:Date.now();Z.durationMs=Math.max(0,((Ko=Z.completedAt)!=null?Ko:Date.now())-Ne)}P.toolCall=Z,P.streaming=!1;let X=k.agentContext;(X||k.executionId)&&(P.agentMetadata=(zn=P.agentMetadata)!=null?zn:{executionId:(Fo=X==null?void 0:X.executionId)!=null?Fo:k.executionId,iteration:(Go=X==null?void 0:X.iteration)!=null?Go:k.iteration}),f(P);let Re=Y(k);Re&&w.byCall.delete(Re)}else if(Ye==="step_await"&&k.awaitReason==="local_tool_required"&&k.toolName){let z=typeof k.toolCallId=="string"&&k.toolCallId.length>0?k.toolCallId:void 0,P=(Ft=z!=null?z:k.toolId)!=null?Ft:`local-${l()}`,Z=Se(P),le=k.toolName,X=rs(le),Re=(En=Z.toolCall)!=null?En:{id:P,status:"pending"};Re.name=le,Re.args=k.parameters,Re.status=X?"running":"complete",Re.chunks=(so=Re.chunks)!=null?so:[],Re.startedAt=(Oo=Re.startedAt)!=null?Oo:ze((Yo=k.startedAt)!=null?Yo:k.timestamp),X?(Re.completedAt=void 0,Re.duration=void 0,Re.durationMs=void 0):Re.completedAt=(Xo=Re.completedAt)!=null?Xo:Re.startedAt,Z.toolCall=Re,Z.streaming=!1,Z.agentMetadata={...Z.agentMetadata,executionId:(qn=k.executionId)!=null?qn:(Io=Z.agentMetadata)==null?void 0:Io.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},f(Z)}else if(Ye==="text_start"){if((yo=k.toolContext)!=null&&yo.toolId)continue;let z=k.partId;if(z!==void 0&&M.current!==null&&z!==M.current){let P=u;P&&(P.streaming=!1,f(P),ue=P,u=null,I=!0)}z!==void 0&&(M.current=z)}else if(Ye==="text_end"){if((vt=k.toolContext)!=null&&vt.toolId)continue;let z=u;z&&(z.streaming=!1,f(z),ue=z,u=null,I=!0)}else if(Ye==="step_chunk"||Ye==="step_delta"){let z=k.stepType,P=k.executionType;if(z==="tool"||P==="context")continue;let Z=k.toolContext;if(Z!=null&&Z.toolId){let Ne=String((Qt=(Xt=k.id)!=null?Xt:Z.stepId)!=null?Qt:`step-${l()}`),dt=k.partId!==void 0&&k.partId!==null?String(k.partId):"",Xe=`${Z.toolId}::${Ne}`,Qe=B.get(Xe);if(dt!==""&&Qe!==void 0&&Qe!==""&&Qe!==dt){let It=D.get(E(Z.toolId,Ne,Qe));It&&It.streaming!==!1&&(It.streaming=!1,f(It))}dt!==""&&B.set(Xe,dt);let et=T(Z.toolId,Ne,dt,Z.executionId),Jt=(vo=(ao=(Qo=(jn=k.text)!=null?jn:k.delta)!=null?Qo:k.content)!=null?ao:k.chunk)!=null?vo:"";Jt&&(et.content+=String(Jt),et.streaming=!0,f(et)),k.isComplete&&(et.streaming=!1,f(et));continue}let le=k.partId;if(le!==void 0&&M.current!==null&&le!==M.current){let Ne=u;Ne&&(Ne.streaming=!1,f(Ne),ue=Ne,u=null,I=!0)}le!==void 0&&(M.current=le);let X=le!==void 0&&(Kn=Te.get(le))!=null?Kn:ae();le!==void 0&&(X.partId||(X.partId=le),Te.set(le,X));let Re=(Gn=(xe=(io=($=k.text)!=null?$:k.delta)!=null?io:k.content)!=null?xe:k.chunk)!=null?Gn:"";if(Re){let Ne=typeof k.seq=="number"?k.seq:void 0,dt=le!=null?le:X.id,Xe=Ne!==void 0?Ue(dt,Ne,String(Re)):((lo=ie.get(X.id))!=null?lo:"")+Re;X.rawContent=Xe,re.has(X.id)||re.set(X.id,this.createStreamParser());let Qe=re.get(X.id),et=Xe.trim().startsWith("{")||Xe.trim().startsWith("[");if(et&&ie.set(X.id,Xe),Qe.__isPlainTextParser===!0){X.content=Ne!==void 0?Xe:X.content+Re,ie.delete(X.id),re.delete(X.id),X.rawContent=void 0,f(X);continue}let It=Qe.processChunk(Xe);if(It instanceof Promise)It.then(Dt=>{var yn;let ln=typeof Dt=="string"?Dt:(yn=Dt==null?void 0:Dt.text)!=null?yn:null;if(ln!==null&&ln.trim()!=="")X.content=ln,f(X);else if(!et&&!Xe.trim().startsWith("<")){let hn=u,nn=hn&&hn.id===X.id?hn:X;nn.id===X.id&&(nn.content=Ne!==void 0?Xe:nn.content+Re,ie.delete(nn.id),re.delete(nn.id),nn.rawContent=void 0,f(nn))}}).catch(()=>{X.content=Ne!==void 0?Xe:X.content+Re,ie.delete(X.id),re.delete(X.id),X.rawContent=void 0,f(X)});else{let Dt=typeof It=="string"?It:(xo=It==null?void 0:It.text)!=null?xo:null;Dt!==null&&Dt.trim()!==""?(X.content=Dt,f(X)):!et&&!Xe.trim().startsWith("<")&&(X.content=Ne!==void 0?Xe:X.content+Re,ie.delete(X.id),re.delete(X.id),X.rawContent=void 0,f(X))}}if(k.isComplete){let Ne=(wo=(xs=k.result)==null?void 0:xs.response)!=null?wo:X.content;if(Ne){let dt=ie.get(X.id),Xe=dt!=null?dt:te(Ne);X.rawContent=Xe;let Qe=re.get(X.id),et=null,Jt=!1;if(Qe&&(et=Qe.getExtractedText(),et===null&&(et=Pr(Xe)),et===null)){let It=Qe.processChunk(Xe);It instanceof Promise?(Jt=!0,It.then(Dt=>{var yn;let ln=typeof Dt=="string"?Dt:(yn=Dt==null?void 0:Dt.text)!=null?yn:null;if(ln!==null){let hn=u;hn&&hn.id===X.id&&(hn.content=ln,hn.streaming=!1,re.delete(hn.id),ie.delete(hn.id),f(hn))}})):et=typeof It=="string"?It:(Co=It==null?void 0:It.text)!=null?Co:null}if(!Jt){et!==null&&et.trim()!==""?X.content=et:ie.has(X.id)||(X.content=te(Ne));let It=re.get(X.id);if(It){let Dt=(So=It.close)==null?void 0:So.call(It);Dt instanceof Promise&&Dt.catch(()=>{}),re.delete(X.id)}ie.delete(X.id),X.streaming=!1,f(X)}}}}else if(Ye==="step_complete"){let z=k.stepType,P=k.executionType;if(z==="tool"||P==="context")continue;let Z=k.toolContext;if(Z!=null&&Z.toolId){let Ne=String((hr=(No=k.id)!=null?No:Z.stepId)!=null?hr:"");if(Ne){let dt=S(Z.toolId,Ne);for(let[Xe,Qe]of D)Xe.startsWith(dt)&&Qe.streaming!==!1&&(Qe.streaming=!1,f(Qe));B.delete(`${Z.toolId}::${Ne}`)}continue}let le=k.stopReason;if(I){if(u!==null){let Xe=u;le&&(Xe.stopReason=le),re.delete(Xe.id),ie.delete(Xe.id),Xe.streaming!==!1&&(Xe.streaming=!1,f(Xe))}let Ne=(Da=k.result)==null?void 0:Da.response,dt=ue;dt&&(le&&(dt.stopReason=le),Ne!=null?Be(dt,Ne):(re.delete(dt.id),ie.delete(dt.id))),ue=null;continue}let X=(ws=k.result)==null?void 0:ws.response,Re=ae();if(le&&(Re.stopReason=le),X!=null){let Ne=re.get(Re.id),dt=!1,Xe=!1;if(Ne){let Qe=Ne.getExtractedText(),et=ie.get(Re.id),Jt=et!=null?et:te(X);if(Re.rawContent=Jt,Qe!==null&&Qe.trim()!=="")Re.content=Qe,dt=!0;else{let It=Pr(Jt);if(It!==null)Re.content=It,dt=!0;else{let Dt=Ne.processChunk(Jt);if(Dt instanceof Promise)Xe=!0,Dt.then(ln=>{var hn;let yn=typeof ln=="string"?ln:(hn=ln==null?void 0:ln.text)!=null?hn:null;if(yn!==null&&yn.trim()!==""){let nn=u;nn&&nn.id===Re.id&&(nn.content=yn,nn.streaming=!1,re.delete(nn.id),ie.delete(nn.id),f(nn))}else{let nn=Ne.getExtractedText(),po=u;po&&po.id===Re.id&&(nn!==null&&nn.trim()!==""?po.content=nn:ie.has(po.id)||(po.content=te(X)),po.streaming=!1,re.delete(po.id),ie.delete(po.id),f(po))}});else{let ln=typeof Dt=="string"?Dt:(Fa=Dt==null?void 0:Dt.text)!=null?Fa:null;if(ln!==null&&ln.trim()!=="")Re.content=ln,dt=!0;else{let yn=Ne.getExtractedText();yn!==null&&yn.trim()!==""&&(Re.content=yn,dt=!0)}}}}}if(!Xe){if(!Re.rawContent){let Qe=ie.get(Re.id);Re.rawContent=Qe!=null?Qe:te(X)}if(!dt&&!ie.has(Re.id)&&(Re.content=te(X)),Ne){let Qe=(Ur=Ne.close)==null?void 0:Ur.call(Ne);Qe instanceof Promise&&Qe.catch(()=>{})}re.delete(Re.id),ie.delete(Re.id),Re.streaming=!1,f(Re)}}else re.delete(Re.id),ie.delete(Re.id),Re.streaming=!1,f(Re)}else if(Ye==="flow_complete"){let z=(yt=k.result)==null?void 0:yt.response;if(I){if(u!==null){let P=u;re.delete(P.id),ie.delete(P.id),P.streaming!==!1&&(P.streaming=!1,f(P))}}else if(z!=null){let P=ae(),Z=ie.get(P.id),le=Z!=null?Z:te(z);P.rawContent=le;let X=te(z),Re=re.get(P.id);if(Re){let Xe=Pr(le);if(Xe!==null)X=Xe;else{let Qe=Re.processChunk(le);Qe instanceof Promise&&Qe.then(Jt=>{var Dt;let It=typeof Jt=="string"?Jt:(Dt=Jt==null?void 0:Jt.text)!=null?Dt:null;It!==null&&(P.content=It,P.streaming=!1,f(P))});let et=Re.getExtractedText();et!==null&&(X=et)}}re.delete(P.id),ie.delete(P.id);let Ne=X!==P.content,dt=P.streaming!==!1;Ne&&(P.content=X),P.streaming=!1,(Ne||dt)&&f(P)}else if(u!==null){let P=u;re.delete(P.id),ie.delete(P.id),P.streaming!==!1&&(P.streaming=!1,f(P))}n({type:"status",status:"idle"})}else if(Ye==="agent_start")de={executionId:k.executionId,agentId:(Cs=k.agentId)!=null?Cs:"virtual",agentName:(co=k.agentName)!=null?co:"",status:"running",currentIteration:0,maxTurns:(Bn=k.maxTurns)!=null?Bn:1,startedAt:ze(k.startedAt)};else if(Ye==="agent_iteration_start"){if(de&&(de.currentIteration=k.iteration),Ut==="separate"&&k.iteration>1){let z=u;z&&(z.streaming=!1,f(z),Pn.set(k.iteration-1,z),u=null)}}else if(Ye==="agent_turn_start")C=null;else if(Ye==="agent_turn_delta"){if(k.contentType==="text"){let z=ae();z.content+=(Oa=k.delta)!=null?Oa:"",z.agentMetadata={executionId:k.executionId,iteration:k.iteration,turnId:k.turnId,agentName:de==null?void 0:de.agentName},C=z,f(z)}else if(k.contentType==="thinking"){let z=(Na=k.turnId)!=null?Na:`agent-think-${k.iteration}`,P=Oe(z);P.reasoning=(zr=P.reasoning)!=null?zr:{id:z,status:"streaming",chunks:[]},P.reasoning.chunks.push((_o=k.delta)!=null?_o:""),P.agentMetadata={executionId:k.executionId,iteration:k.iteration,turnId:k.turnId},f(P)}else if(k.contentType==="tool_input"){let z=(_a=k.toolCallId)!=null?_a:w.lastId;if(z){let P=W.get(z);P!=null&&P.toolCall&&(P.toolCall.chunks=(br=P.toolCall.chunks)!=null?br:[],P.toolCall.chunks.push((Ss=k.delta)!=null?Ss:""),f(P))}}}else if(Ye==="agent_turn_complete"){let z=k.turnId;if(z){let le=R.get(z);if(le!=null&&le.reasoning){le.reasoning.status="complete",le.reasoning.completedAt=ze(k.completedAt);let X=(Vo=le.reasoning.startedAt)!=null?Vo:Date.now();le.reasoning.durationMs=Math.max(0,((As=le.reasoning.completedAt)!=null?As:Date.now())-X),le.streaming=!1,f(le)}}let P=k.stopReason,Z=u!=null?u:C;if(P&&Z!==null){let le=k.turnId;(!le||((Jo=Z.agentMetadata)==null?void 0:Jo.turnId)===le)&&(Z.stopReason=P,f(Z))}}else if(Ye==="agent_tool_start"){u&&(u.streaming=!1,f(u),u=null);let z=(Zo=k.toolCallId)!=null?Zo:`agent-tool-${l()}`;we(Y(k),z);let P=Se(z),Z=(Va=P.toolCall)!=null?Va:{id:z,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=(fl=($a=k.toolName)!=null?$a:k.name)!=null?fl:Z.name,Z.status="running",k.parameters!==void 0&&(Z.args=k.parameters),Z.startedAt=ze((yr=k.startedAt)!=null?yr:k.timestamp),P.toolCall=Z,P.streaming=!0,P.agentMetadata={executionId:k.executionId,iteration:k.iteration},f(P)}else if(Ye==="agent_tool_delta"){let z=(er=k.toolCallId)!=null?er:w.lastId;if(z){let P=(Ua=W.get(z))!=null?Ua:Se(z);P.toolCall&&(P.toolCall.chunks=(Ts=P.toolCall.chunks)!=null?Ts:[],P.toolCall.chunks.push((tr=k.delta)!=null?tr:""),P.toolCall.status="running",P.streaming=!0,f(P))}}else if(Ye==="agent_tool_complete"){let z=(za=k.toolCallId)!=null?za:w.lastId;if(z){let P=(ks=W.get(z))!=null?ks:Se(z);if(P.toolCall){P.toolCall.status="complete",k.result!==void 0&&(P.toolCall.result=k.result),typeof k.executionTime=="number"&&(P.toolCall.durationMs=k.executionTime),P.toolCall.completedAt=ze((nr=k.completedAt)!=null?nr:k.timestamp),P.streaming=!1,f(P);let Z=Y(k);Z&&w.byCall.delete(Z)}}}else if(Ye==="agent_media"){let z=Array.isArray(k.media)?k.media:[],P=[];for(let Z of z){if(!Z||typeof Z!="object")continue;let le=Z,X=typeof le.type=="string"?le.type:void 0,Re=typeof le.mediaType=="string"?le.mediaType.toLowerCase():"",Ne=null,dt="";if(X==="media"){let Xe=typeof le.data=="string"?le.data:void 0;if(!Xe)continue;dt=Re.length>0?Re:"application/octet-stream",Ne=`data:${dt};base64,${Xe}`}else if(X==="image-url"){let Xe=typeof le.url=="string"?le.url:void 0;if(!Xe)continue;dt=Re,Ne=Xe}else if(X==="file-url"){let Xe=typeof le.url=="string"?le.url:void 0;if(!Xe)continue;dt=Re,Ne=Xe}else continue;if(Ne)if(X==="image-url"||dt.startsWith("image/"))P.push({type:"image",image:Ne,...dt?{mimeType:dt}:{}});else if(dt.startsWith("audio/"))P.push({type:"audio",audio:Ne,mimeType:dt});else if(dt.startsWith("video/"))P.push({type:"video",video:Ne,mimeType:dt});else{let Xe=dt||"application/octet-stream";P.push({type:"file",data:Ne,mimeType:Xe,filename:Th(Xe)})}}if(P.length>0){let Z=l(),le=k.toolCallId,Re={id:`agent-media-${typeof le=="string"&&le.length>0?`${le}-${Z}`:String(Z)}`,role:"assistant",content:"",contentParts:P,createdAt:new Date().toISOString(),streaming:!1,sequence:Z,agentMetadata:{executionId:k.executionId,iteration:k.iteration}};f(Re);let Ne=u;Ne&&(Ne.streaming=!1,f(Ne)),u=null,v.current=null}}else if(Ye!=="agent_iteration_complete"){if(Ye==="agent_reflection"||Ye==="agent_reflect"){let z=`agent-reflection-${k.executionId}-${k.iteration}`,P={id:z,role:"assistant",content:(Es=k.reflection)!=null?Es:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:z,status:"complete",chunks:[(qa=k.reflection)!=null?qa:""]},agentMetadata:{executionId:k.executionId,iteration:k.iteration}};f(P)}else if(Ye==="agent_complete"){de&&(de.status=k.success?"complete":"error",de.completedAt=ze(k.completedAt),de.stopReason=k.stopReason);let z=u;z&&(z.streaming=!1,f(z)),n({type:"status",status:"idle"})}else if(Ye==="agent_error"){let z=typeof k.error=="string"?k.error:(ja=($o=k.error)==null?void 0:$o.message)!=null?ja:"Agent execution error";k.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",z):n({type:"error",error:new Error(z)})}else if(Ye!=="agent_ping"){if(Ye==="agent_approval_start"){let z=(or=k.approvalId)!=null?or:`approval-${l()}`,P={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Ot=de==null?void 0:de.agentId)!=null?Ot:"virtual",executionId:(jr=(qr=k.executionId)!=null?qr:de==null?void 0:de.executionId)!=null?jr:"",toolName:(Ms=k.toolName)!=null?Ms:"",toolType:k.toolType,description:(Ka=k.description)!=null?Ka:`Execute ${(Ro=k.toolName)!=null?Ro:"tool"}`,parameters:k.parameters}};f(P)}else if(Ye==="step_await"&&k.awaitReason==="approval_required"){let z=(Ls=k.approvalId)!=null?Ls:`approval-${l()}`,P={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Is=de==null?void 0:de.agentId)!=null?Is:"virtual",executionId:(Kr=(Ga=k.executionId)!=null?Ga:de==null?void 0:de.executionId)!=null?Kr:"",toolName:(Gr=k.toolName)!=null?Gr:"",toolType:k.toolType,description:(Ya=k.description)!=null?Ya:`Execute ${(vr=k.toolName)!=null?vr:"tool"}`,parameters:k.parameters}};f(P)}else if(Ye==="agent_approval_complete"){let z=k.approvalId;if(z){let Z={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:(Xa=k.decision)!=null?Xa:"approved",agentId:(Rs=de==null?void 0:de.agentId)!=null?Rs:"virtual",executionId:(Ws=(Ps=k.executionId)!=null?Ps:de==null?void 0:de.executionId)!=null?Ws:"",toolName:(Bs=k.toolName)!=null?Bs:"",description:(Mn=k.description)!=null?Mn:"",resolvedAt:Date.now()}};f(Z)}}else if(Ye==="artifact_start"||Ye==="artifact_delta"||Ye==="artifact_update"||Ye==="artifact_complete"){if(Ye==="artifact_start"){let z=k.artifactType,P=String(k.id),Z=typeof k.title=="string"?k.title:void 0;if(n({type:"artifact_start",id:P,artifactType:z,title:Z,component:typeof k.component=="string"?k.component:void 0}),ve.set(P,{markdown:"",title:Z}),!G.has(P)){G.add(P);let le={id:`artifact-ref-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:P,title:Z,artifactType:z,status:"streaming"}})};pe.set(P,le),f(le)}}else if(Ye==="artifact_delta"){let z=String(k.id),P=typeof k.delta=="string"?k.delta:String((Yn=k.delta)!=null?Yn:"");n({type:"artifact_delta",id:z,artDelta:P});let Z=ve.get(z);Z&&(Z.markdown+=P)}else if(Ye==="artifact_update"){let z=k.props&&typeof k.props=="object"&&!Array.isArray(k.props)?k.props:{};n({type:"artifact_update",id:String(k.id),props:z,component:typeof k.component=="string"?k.component:void 0})}else if(Ye==="artifact_complete"){let z=String(k.id);n({type:"artifact_complete",id:z});let P=pe.get(z);if(P){P.streaming=!1;try{let Z=JSON.parse((Uo=P.rawContent)!=null?Uo:"{}");if(Z.props){Z.props.status="complete";let le=ve.get(z);le!=null&&le.markdown&&(Z.props.markdown=le.markdown)}P.rawContent=JSON.stringify(Z)}catch{}ve.delete(z),f(P),pe.delete(z)}}}else if(Ye==="transcript_insert"){let z=k.message;if(!z||typeof z!="object")continue;let P=String((ct=z.id)!=null?ct:`msg-${l()}`),Z=z.role,X={id:P,role:Z==="user"?"user":Z==="system"?"system":"assistant",content:typeof z.content=="string"?z.content:"",rawContent:typeof z.rawContent=="string"?z.rawContent:void 0,createdAt:typeof z.createdAt=="string"?z.createdAt:new Date().toISOString(),streaming:z.streaming===!0,...typeof z.variant=="string"?{variant:z.variant}:{},sequence:l()};if(f(X),X.rawContent)try{let Re=JSON.parse(X.rawContent),Ne=(Hs=Re==null?void 0:Re.props)==null?void 0:Hs.artifactId;typeof Ne=="string"&&G.add(Ne)}catch{}u=null,v.current=null,re.delete(P),ie.delete(P)}else if(Ye==="error"||Ye==="step_error"||Ye==="dispatch_error"||Ye==="flow_error"){let z=null;if(k.error instanceof Error)z=k.error;else if(Ye==="dispatch_error"){let P=(xr=k.message)!=null?xr:k.error;P!=null&&P!==""&&(z=new Error(String(P)))}else if(Ye==="step_error"||Ye==="flow_error"){let P=k.error;typeof P=="string"&&P!==""?z=new Error(P):P!=null&&typeof P=="object"&&"message"in P&&(z=new Error(String((Ao=P.message)!=null?Ao:P)))}else Ye==="error"&&k.error!=null&&k.error!==""&&(z=new Error(String(k.error)));if(z){n({type:"error",error:z});let P=u;P&&P.streaming&&(P.streaming=!1,f(P)),n({type:"status",status:"idle"})}}}}}me.length=0};;){let{done:V,value:Le}=await r.read();if(V)break;a+=s.decode(Le,{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()=>{}}},Nr=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Bm=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Hm=()=>{var t;let e=nb();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)}},Dm=()=>{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=(0,gs.parse)(n,gs.STR|gs.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Rm(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Rm(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var Fm=()=>{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 Ei=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 ob="https://api.runtype.com/v1/dispatch",Mi="https://api.runtype.com";function rb(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 Xl=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 sb(e){switch(e){case"json":return Dm;case"regex-json":return Hm;case"xml":return Fm;default:return Bm}}var Om=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function ab(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=Om(n);if(!Om(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Nr(e);return Nr(t)!==null&&a===null?t:e}var fa=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:ob,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:sb(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 Si(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$/,""))||Mi}/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$/,""))||Mi}/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),f=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(Xl).map(D=>{var W,w,x;return{id:D.id,role:D.role,content:(x=(w=(W=D.contentParts)!=null?W:D.llmContent)!=null?w:D.rawContent)!=null?x:D.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...f&&Object.keys(f).length>0&&{metadata:f},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},g=l.clientTools,m=!!(g&&g.length>0),C=m?Lm(g):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,M=m&&v&&this.lastSentClientToolsFingerprint===C,I=!1,R=null,P;for(let D=0;;D++){let w={...u,...m&&(I||!M)&&g?{clientTools:g}:{},...C?{clientToolsFingerprint:C}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",w),P=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w),signal:o.signal}),P.status===409&&D===0&&m){let x=await P.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(!P.ok){let D=R!=null?R:await P.json().catch(()=>({error:"Chat request failed"}));if(P.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let w=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:w}),w}if(P.status===429){let w=new Error(D.hint||"Message limit reached for this session.");throw n({type:"error",error:w}),w}let W=new Error(D.error||"Failed to send message");throw n({type:"error",error:W}),W}if(!P.body){let D=new Error("No response body received");throw n({type:"error",error:D}),D}this.lastSentClientToolsFingerprint=C!=null?C:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(P.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let r=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Mi}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,o){var l,f;let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Mi}/resume`,a;r&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(f=o==null?void 0:o.streamResponse)!=null?f:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var s;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(Xl).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(Xl).sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},r=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch());if(r&&r.length>0&&(o.clientTools=r),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(o.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...o},config:this.config});if(a&&typeof a=="object"){let i=a;return o.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=o.clientTools),i}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return o}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=f=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...f!==void 0&&{partId:f}};return o.current=u,r(u),u},l=f=>o.current?o.current:d(f);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let f=l(i.partId);i.partId!==void 0&&!f.partId&&(f.partId=i.partId),f.content+=i.text,r(f)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o){var Dt,an,oo,Mo;let r=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,f=F=>{let ue=F.reasoning?{...F.reasoning,chunks:[...F.reasoning.chunks]}:void 0,Fe=F.toolCall?{...F.toolCall,chunks:F.toolCall.chunks?[...F.toolCall.chunks]:void 0}:void 0,Ke=F.tools?F.tools.map(_e=>({..._e,chunks:_e.chunks?[..._e.chunks]:void 0})):void 0;return{...F,reasoning:ue,toolCall:Fe,tools:Ke}},u=F=>{if(F.role!=="assistant"||F.variant)return!0;let ue=Array.isArray(F.contentParts)&&F.contentParts.length>0,Fe=typeof F.rawContent=="string"&&F.rawContent.trim()!=="";return typeof F.content=="string"&&F.content.trim()!==""||ue||Fe||!!F.stopReason},g=F=>{u(F)&&n({type:"message",message:f(F)})},m=null,C=null,v={current:null},M={current:null},I=!1,R=new Map,P=new Map,D=new Map,W=new Map,w={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},E=(F,ue,Fe="")=>`${F}::${ue}::${Fe}`,S=(F,ue)=>`${F}::${ue}::`,k=(F,ue,Fe,Ke)=>{let _e=E(F,ue,Fe),$e=D.get(_e);if($e)return $e;let ot=Fe?`-${Fe}`:"",Pt={id:`nested-${F}-${ue}${ot}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Fe?{partId:Fe}:{},agentMetadata:{executionId:Ke,parentToolId:F,parentStepId:ue}};return D.set(_e,Pt),g(Pt),Pt},V=F=>{if(F==null)return null;try{return String(F)}catch{return null}},z=F=>{var ue,Fe,Ke,_e,$e;return V(($e=(_e=(Ke=(Fe=(ue=F.stepId)!=null?ue:F.step_id)!=null?Fe:F.step)!=null?Ke:F.parentId)!=null?_e:F.flowStepId)!=null?$e:F.flow_step_id)},Y=F=>{var ue,Fe,Ke,_e,$e,ot,Pt;return V((Pt=(ot=($e=(_e=(Ke=(Fe=(ue=F.callId)!=null?ue:F.call_id)!=null?Fe:F.requestId)!=null?Ke:F.request_id)!=null?_e:F.toolCallId)!=null?$e:F.tool_call_id)!=null?ot:F.stepId)!=null?Pt:F.step_id)},he=o,me=!1,de=()=>{if(m)return m;let F;return!me&&he?(F=he,me=!0):he&&M.current?F=`${he}_${M.current}`:F=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:F,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},g(m),m},Ee=(F,ue)=>{w.lastId=ue,F&&w.byStep.set(F,ue)},xe=(F,ue)=>{var $e;let Fe=($e=F.reasoningId)!=null?$e:F.id,Ke=z(F);if(Fe){let ot=String(Fe);return Ee(Ke,ot),ot}if(Ke){let ot=w.byStep.get(Ke);if(ot)return w.lastId=ot,ot}if(w.lastId&&!ue)return w.lastId;if(!ue)return null;let _e=`reason-${l()}`;return Ee(Ke,_e),_e},De=F=>{let ue=R.get(F);if(ue)return ue;let Fe={id:`reason-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:F,status:"streaming",chunks:[]}};return R.set(F,Fe),g(Fe),Fe},Ae=(F,ue)=>{x.lastId=ue,F&&x.byCall.set(F,ue)},le=new Set,J=new Map,se=new Set,ye=new Map,be=F=>{if(!F)return!1;let ue=F.replace(/_+/g,"_").replace(/^_|_$/g,"");return ue==="emit_artifact_markdown"||ue==="emit_artifact_component"},K=(F,ue)=>{var $e;let Fe=($e=F.toolId)!=null?$e:F.id,Ke=Y(F);if(Fe){let ot=String(Fe);return Ae(Ke,ot),ot}if(Ke){let ot=x.byCall.get(Ke);if(ot)return x.lastId=ot,ot}if(x.lastId&&!ue)return x.lastId;if(!ue)return null;let _e=`tool-${l()}`;return Ae(Ke,_e),_e},ae=F=>{let ue=P.get(F);if(ue)return ue;let Fe={id:`tool-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:F,status:"pending"}};return P.set(F,Fe),g(Fe),Fe},Re=F=>{if(typeof F=="number"&&Number.isFinite(F))return F;if(typeof F=="string"){let ue=Number(F);if(!Number.isNaN(ue)&&Number.isFinite(ue))return ue;let Fe=Date.parse(F);if(!Number.isNaN(Fe))return Fe}return Date.now()},oe=F=>{if(typeof F=="string")return F;if(F==null)return"";try{return JSON.stringify(F)}catch{return String(F)}},ee=new Map,re=new Map,it=new Map,lt=new Map,Le=null,pe=(F,ue,Fe)=>{var Pt;let Ke=it.get(F);Ke||(Ke=[],it.set(F,Ke));let _e=0,$e=Ke.length;for(;_e<$e;){let Kt=_e+$e>>>1;Ke[Kt].seq<ue?_e=Kt+1:$e=Kt}((Pt=Ke[_e])==null?void 0:Pt.seq)===ue?Ke[_e]={seq:ue,text:Fe}:Ke.splice(_e,0,{seq:ue,text:Fe});let ot="";for(let Kt=0;Kt<Ke.length;Kt++)ot+=Ke[Kt].text;return ot},Je=(F,ue)=>{let Fe=oe(ue),Ke=re.get(F.id),_e=ab(Ke,Fe);F.rawContent=_e;let $e=ee.get(F.id),ot=xt=>{var Se;let st=(Se=F.content)!=null?Se:"";xt.trim()!==""&&(st.trim().length===0||xt.startsWith(st)||xt.trimStart().startsWith(st.trim()))&&(F.content=xt)},Pt=()=>{var xt;if($e){let st=(xt=$e.close)==null?void 0:xt.call($e);st instanceof Promise&&st.catch(()=>{})}ee.delete(F.id),re.delete(F.id),F.streaming=!1,g(F)};if(!$e){ot(Fe),Pt();return}let Kt=Nr(_e);if(Kt!==null&&Kt.trim()!==""){ot(Kt),Pt();return}let Jt=xt=>{var ce;let st=typeof xt=="string"?xt:(ce=xt==null?void 0:xt.text)!=null?ce:null;if(st!==null&&st.trim()!=="")return st;let Se=$e.getExtractedText();return Se!==null&&Se.trim()!==""?Se:Fe},G;try{G=$e.processChunk(_e)}catch{ot(Fe),Pt();return}if(G instanceof Promise){G.then(xt=>{ot(Jt(xt)),Pt()}).catch(()=>{ot(Fe),Pt()});return}ot(Jt(G)),Pt()},Be=[],j=!1,fe,tt=()=>{j||(j=!0,queueMicrotask(()=>{j=!1,fe()}))},Mt=new Ei((F,ue)=>{Be.push({payloadType:F,payload:ue}),tt()}),te=null,qe=new Map,Fn=(Dt=this.config.iterationDisplay)!=null?Dt:"separate";for(fe=()=>{var F,ue,Fe,Ke,_e,$e,ot,Pt,Kt,Jt,G,xt,st,Se,ce,et,Qt,Gt,In,vn,gt,Lt,Qe,qt,ln,Cn,Sn,yn,Lo,At,Un,zn,Vo,yo,wt,Cr,Io,Sr,On,Xr,Zo,$o,Tt,qn,jn,Rn,Rt,ro,so,Kn,er,Uo,tr,Gn,Ft,Pn,ao,nr,zo,or,Ro,Yn,vo,bt,Zt,en,Xn,rr,we,io,lo,$,Po,qo,jo,Wo,xo,Is,Jn,Qn,wo,Co,Ar,Ko,An,Bo,Jr,Tr,Qr,za,Zr,qa,es,vt,Rs,co,Nn,ja,Ka,ts,Go,Ps,sr,Ws,Bs,Hs,Ds,_n,ns,Ho,Do,Fs,Ga,Os,Ns,kr,Ya,Xa,Ja,Qa,Sl,Er,ar,Za,_s,ir,ei,Vs,lr,$s,ti,Yo,ni,cr,Ot,os,rs,Us;for(let po=0;po<Be.length;po++){let Ge=Be[po].payloadType,T=Be[po].payload;if(Ge==="reason_start"){let U=(F=xe(T,!0))!=null?F:`reason-${l()}`,B=De(U);B.reasoning=(ue=B.reasoning)!=null?ue:{id:U,status:"streaming",chunks:[]},B.reasoning.startedAt=(Ke=B.reasoning.startedAt)!=null?Ke:Re((Fe=T.startedAt)!=null?Fe:T.timestamp),B.reasoning.completedAt=void 0,B.reasoning.durationMs=void 0,B.streaming=!0,B.reasoning.status="streaming",g(B)}else if(Ge==="reason_delta"||Ge==="reason_chunk"){let U=($e=(_e=xe(T,!1))!=null?_e:xe(T,!0))!=null?$e:`reason-${l()}`,B=De(U);B.reasoning=(ot=B.reasoning)!=null?ot:{id:U,status:"streaming",chunks:[]},B.reasoning.startedAt=(Kt=B.reasoning.startedAt)!=null?Kt:Re((Pt=T.startedAt)!=null?Pt:T.timestamp);let Z=(xt=(G=(Jt=T.reasoningText)!=null?Jt:T.text)!=null?G:T.delta)!=null?xt:"";if(Z&&T.hidden!==!0){let ie=typeof T.sequenceIndex=="number"?T.sequenceIndex:void 0;if(ie!==void 0){let X=pe(U,ie,String(Z));B.reasoning.chunks=[X]}else B.reasoning.chunks.push(String(Z))}if(B.reasoning.status=T.done?"complete":"streaming",T.done){B.reasoning.completedAt=Re((st=T.completedAt)!=null?st:T.timestamp);let ie=(Se=B.reasoning.startedAt)!=null?Se:Date.now();B.reasoning.durationMs=Math.max(0,((ce=B.reasoning.completedAt)!=null?ce:Date.now())-ie)}B.streaming=B.reasoning.status!=="complete",g(B)}else if(Ge==="reason_complete"){let U=(Qt=(et=xe(T,!1))!=null?et:xe(T,!0))!=null?Qt:`reason-${l()}`,B=R.get(U);if(B!=null&&B.reasoning){B.reasoning.status="complete",B.reasoning.completedAt=Re((Gt=T.completedAt)!=null?Gt:T.timestamp);let ie=(In=B.reasoning.startedAt)!=null?In:Date.now();B.reasoning.durationMs=Math.max(0,((vn=B.reasoning.completedAt)!=null?vn:Date.now())-ie),B.streaming=!1,g(B)}let Z=z(T);Z&&w.byStep.delete(Z)}else if(Ge==="tool_start"){let U=(gt=K(T,!0))!=null?gt:`tool-${l()}`,B=(Lt=T.toolName)!=null?Lt:T.name;if(be(B)){le.add(U);continue}let Z=ae(U),ie=(Qe=Z.toolCall)!=null?Qe:{id:U,status:"pending"};ie.name=B!=null?B:ie.name,ie.status="running",T.args!==void 0?ie.args=T.args:T.parameters!==void 0&&(ie.args=T.parameters),ie.startedAt=(ln=ie.startedAt)!=null?ln:Re((qt=T.startedAt)!=null?qt:T.timestamp),ie.completedAt=void 0,ie.durationMs=void 0,Z.toolCall=ie,Z.streaming=!0;let X=T.agentContext;(X||T.executionId)&&(Z.agentMetadata={executionId:(Cn=X==null?void 0:X.executionId)!=null?Cn:T.executionId,iteration:(Sn=X==null?void 0:X.iteration)!=null?Sn:T.iteration}),g(Z)}else if(Ge==="tool_chunk"||Ge==="tool_delta"){let U=(Lo=(yn=K(T,!1))!=null?yn:K(T,!0))!=null?Lo:`tool-${l()}`;if(le.has(U))continue;let B=ae(U),Z=(At=B.toolCall)!=null?At:{id:U,status:"running"};Z.startedAt=(zn=Z.startedAt)!=null?zn:Re((Un=T.startedAt)!=null?Un:T.timestamp);let ie=(wt=(yo=(Vo=T.text)!=null?Vo:T.delta)!=null?yo:T.message)!=null?wt:"";ie&&(Z.chunks=(Cr=Z.chunks)!=null?Cr:[],Z.chunks.push(String(ie))),Z.status="running",B.toolCall=Z,B.streaming=!0;let X=T.agentContext;(X||T.executionId)&&(B.agentMetadata=(On=B.agentMetadata)!=null?On:{executionId:(Io=X==null?void 0:X.executionId)!=null?Io:T.executionId,iteration:(Sr=X==null?void 0:X.iteration)!=null?Sr:T.iteration}),g(B)}else if(Ge==="tool_complete"){let U=(Zo=(Xr=K(T,!1))!=null?Xr:K(T,!0))!=null?Zo:`tool-${l()}`;if(le.has(U)){le.delete(U);continue}let B=ae(U),Z=($o=B.toolCall)!=null?$o:{id:U,status:"running"};Z.status="complete",T.result!==void 0&&(Z.result=T.result),typeof T.duration=="number"&&(Z.duration=T.duration),Z.completedAt=Re((Tt=T.completedAt)!=null?Tt:T.timestamp);let ie=(qn=T.duration)!=null?qn:T.executionTime;if(typeof ie=="number")Z.durationMs=ie;else{let Ne=(jn=Z.startedAt)!=null?jn:Date.now();Z.durationMs=Math.max(0,((Rn=Z.completedAt)!=null?Rn:Date.now())-Ne)}B.toolCall=Z,B.streaming=!1;let X=T.agentContext;(X||T.executionId)&&(B.agentMetadata=(so=B.agentMetadata)!=null?so:{executionId:(Rt=X==null?void 0:X.executionId)!=null?Rt:T.executionId,iteration:(ro=X==null?void 0:X.iteration)!=null?ro:T.iteration}),g(B);let Pe=Y(T);Pe&&x.byCall.delete(Pe)}else if(Ge==="step_await"&&T.awaitReason==="local_tool_required"&&T.toolName){let U=typeof T.toolCallId=="string"&&T.toolCallId.length>0?T.toolCallId:void 0,B=(Kn=U!=null?U:T.toolId)!=null?Kn:`local-${l()}`,Z=ae(B),ie=T.toolName,X=fs(ie),Pe=(er=Z.toolCall)!=null?er:{id:B,status:"pending"};Pe.name=ie,Pe.args=T.parameters,Pe.status=X?"running":"complete",Pe.chunks=(Uo=Pe.chunks)!=null?Uo:[],Pe.startedAt=(Gn=Pe.startedAt)!=null?Gn:Re((tr=T.startedAt)!=null?tr:T.timestamp),X?(Pe.completedAt=void 0,Pe.duration=void 0,Pe.durationMs=void 0):Pe.completedAt=(Ft=Pe.completedAt)!=null?Ft:Pe.startedAt,Z.toolCall=Pe,Z.streaming=!1,Z.agentMetadata={...Z.agentMetadata,executionId:(ao=T.executionId)!=null?ao:(Pn=Z.agentMetadata)==null?void 0:Pn.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},g(Z)}else if(Ge==="text_start"){if((nr=T.toolContext)!=null&&nr.toolId)continue;let U=T.partId;if(U!==void 0&&M.current!==null&&U!==M.current){let B=m;B&&(B.streaming=!1,g(B),Le=B,m=null,I=!0)}U!==void 0&&(M.current=U)}else if(Ge==="text_end"){if((zo=T.toolContext)!=null&&zo.toolId)continue;let U=m;U&&(U.streaming=!1,g(U),Le=U,m=null,I=!0)}else if(Ge==="step_chunk"||Ge==="step_delta"){let U=T.stepType,B=T.executionType;if(U==="tool"||B==="context")continue;let Z=T.toolContext;if(Z!=null&&Z.toolId){let Ne=String((Ro=(or=T.id)!=null?or:Z.stepId)!=null?Ro:`step-${l()}`),at=T.partId!==void 0&&T.partId!==null?String(T.partId):"",Ze=`${Z.toolId}::${Ne}`,Ht=W.get(Ze);if(at!==""&&Ht!==void 0&&Ht!==""&&Ht!==at){let ct=D.get(E(Z.toolId,Ne,Ht));ct&&ct.streaming!==!1&&(ct.streaming=!1,g(ct))}at!==""&&W.set(Ze,at);let $t=k(Z.toolId,Ne,at,Z.executionId),_t=(Zt=(bt=(vo=(Yn=T.text)!=null?Yn:T.delta)!=null?vo:T.content)!=null?bt:T.chunk)!=null?Zt:"";_t&&($t.content+=String(_t),$t.streaming=!0,g($t)),T.isComplete&&($t.streaming=!1,g($t));continue}let ie=T.partId;if(ie!==void 0&&M.current!==null&&ie!==M.current){let Ne=m;Ne&&(Ne.streaming=!1,g(Ne),Le=Ne,m=null,I=!0)}ie!==void 0&&(M.current=ie);let X=ie!==void 0&&(en=lt.get(ie))!=null?en:de();ie!==void 0&&(X.partId||(X.partId=ie),lt.set(ie,X));let Pe=(io=(we=(rr=(Xn=T.text)!=null?Xn:T.delta)!=null?rr:T.content)!=null?we:T.chunk)!=null?io:"";if(Pe){let Ne=typeof T.seq=="number"?T.seq:void 0,at=ie!=null?ie:X.id,Ze=Ne!==void 0?pe(at,Ne,String(Pe)):((lo=re.get(X.id))!=null?lo:"")+Pe;X.rawContent=Ze,ee.has(X.id)||ee.set(X.id,this.createStreamParser());let Ht=ee.get(X.id),$t=Ze.trim().startsWith("{")||Ze.trim().startsWith("[");if($t&&re.set(X.id,Ze),Ht.__isPlainTextParser===!0){X.content=Ne!==void 0?Ze:X.content+Pe,re.delete(X.id),ee.delete(X.id),X.rawContent=void 0,g(X);continue}let ct=Ht.processChunk(Ze);if(ct instanceof Promise)ct.then(kt=>{var Tn;let Ue=typeof kt=="string"?kt:(Tn=kt==null?void 0:kt.text)!=null?Tn:null;if(Ue!==null&&Ue.trim()!=="")X.content=Ue,g(X);else if(!$t&&!Ze.trim().startsWith("<")){let fn=m,Ut=fn&&fn.id===X.id?fn:X;Ut.id===X.id&&(Ut.content=Ne!==void 0?Ze:Ut.content+Pe,re.delete(Ut.id),ee.delete(Ut.id),Ut.rawContent=void 0,g(Ut))}}).catch(()=>{X.content=Ne!==void 0?Ze:X.content+Pe,re.delete(X.id),ee.delete(X.id),X.rawContent=void 0,g(X)});else{let kt=typeof ct=="string"?ct:($=ct==null?void 0:ct.text)!=null?$:null;kt!==null&&kt.trim()!==""?(X.content=kt,g(X)):!$t&&!Ze.trim().startsWith("<")&&(X.content=Ne!==void 0?Ze:X.content+Pe,re.delete(X.id),ee.delete(X.id),X.rawContent=void 0,g(X))}}if(T.isComplete){let Ne=(qo=(Po=T.result)==null?void 0:Po.response)!=null?qo:X.content;if(Ne){let at=re.get(X.id),Ze=at!=null?at:oe(Ne);X.rawContent=Ze;let Ht=ee.get(X.id),$t=null,_t=!1;if(Ht&&($t=Ht.getExtractedText(),$t===null&&($t=Nr(Ze)),$t===null)){let ct=Ht.processChunk(Ze);ct instanceof Promise?(_t=!0,ct.then(kt=>{var Tn;let Ue=typeof kt=="string"?kt:(Tn=kt==null?void 0:kt.text)!=null?Tn:null;if(Ue!==null){let fn=m;fn&&fn.id===X.id&&(fn.content=Ue,fn.streaming=!1,ee.delete(fn.id),re.delete(fn.id),g(fn))}})):$t=typeof ct=="string"?ct:(jo=ct==null?void 0:ct.text)!=null?jo:null}if(!_t){$t!==null&&$t.trim()!==""?X.content=$t:re.has(X.id)||(X.content=oe(Ne));let ct=ee.get(X.id);if(ct){let kt=(Wo=ct.close)==null?void 0:Wo.call(ct);kt instanceof Promise&&kt.catch(()=>{}),ee.delete(X.id)}re.delete(X.id),X.streaming=!1,g(X)}}}}else if(Ge==="step_complete"){let U=T.stepType,B=T.executionType;if(U==="tool"||B==="context")continue;let Z=T.toolContext;if(Z!=null&&Z.toolId){let Ne=String((Is=(xo=T.id)!=null?xo:Z.stepId)!=null?Is:"");if(Ne){let at=S(Z.toolId,Ne);for(let[Ze,Ht]of D)Ze.startsWith(at)&&Ht.streaming!==!1&&(Ht.streaming=!1,g(Ht));W.delete(`${Z.toolId}::${Ne}`)}continue}let ie=T.stopReason;if(I){if(m!==null){let Ze=m;ie&&(Ze.stopReason=ie),ee.delete(Ze.id),re.delete(Ze.id),Ze.streaming!==!1&&(Ze.streaming=!1,g(Ze))}let Ne=(Jn=T.result)==null?void 0:Jn.response,at=Le;at&&(ie&&(at.stopReason=ie),Ne!=null?Je(at,Ne):(ee.delete(at.id),re.delete(at.id))),Le=null;continue}let X=(Qn=T.result)==null?void 0:Qn.response,Pe=de();if(ie&&(Pe.stopReason=ie),X!=null){let Ne=ee.get(Pe.id),at=!1,Ze=!1;if(Ne){let Ht=Ne.getExtractedText(),$t=re.get(Pe.id),_t=$t!=null?$t:oe(X);if(Pe.rawContent=_t,Ht!==null&&Ht.trim()!=="")Pe.content=Ht,at=!0;else{let ct=Nr(_t);if(ct!==null)Pe.content=ct,at=!0;else{let kt=Ne.processChunk(_t);if(kt instanceof Promise)Ze=!0,kt.then(Ue=>{var fn;let Tn=typeof Ue=="string"?Ue:(fn=Ue==null?void 0:Ue.text)!=null?fn:null;if(Tn!==null&&Tn.trim()!==""){let Ut=m;Ut&&Ut.id===Pe.id&&(Ut.content=Tn,Ut.streaming=!1,ee.delete(Ut.id),re.delete(Ut.id),g(Ut))}else{let Ut=Ne.getExtractedText(),So=m;So&&So.id===Pe.id&&(Ut!==null&&Ut.trim()!==""?So.content=Ut:re.has(So.id)||(So.content=oe(X)),So.streaming=!1,ee.delete(So.id),re.delete(So.id),g(So))}});else{let Ue=typeof kt=="string"?kt:(wo=kt==null?void 0:kt.text)!=null?wo:null;if(Ue!==null&&Ue.trim()!=="")Pe.content=Ue,at=!0;else{let Tn=Ne.getExtractedText();Tn!==null&&Tn.trim()!==""&&(Pe.content=Tn,at=!0)}}}}}if(!Ze){if(!Pe.rawContent){let Ht=re.get(Pe.id);Pe.rawContent=Ht!=null?Ht:oe(X)}if(!at&&!re.has(Pe.id)&&(Pe.content=oe(X)),Ne){let Ht=(Co=Ne.close)==null?void 0:Co.call(Ne);Ht instanceof Promise&&Ht.catch(()=>{})}ee.delete(Pe.id),re.delete(Pe.id),Pe.streaming=!1,g(Pe)}}else ee.delete(Pe.id),re.delete(Pe.id),Pe.streaming=!1,g(Pe)}else if(Ge==="flow_complete"){let U=(Ar=T.result)==null?void 0:Ar.response;if(I){if(m!==null){let B=m;ee.delete(B.id),re.delete(B.id),B.streaming!==!1&&(B.streaming=!1,g(B))}}else if(U!=null){let B=de(),Z=re.get(B.id),ie=Z!=null?Z:oe(U);B.rawContent=ie;let X=oe(U),Pe=ee.get(B.id);if(Pe){let Ze=Nr(ie);if(Ze!==null)X=Ze;else{let Ht=Pe.processChunk(ie);Ht instanceof Promise&&Ht.then(_t=>{var kt;let ct=typeof _t=="string"?_t:(kt=_t==null?void 0:_t.text)!=null?kt:null;ct!==null&&(B.content=ct,B.streaming=!1,g(B))});let $t=Pe.getExtractedText();$t!==null&&(X=$t)}}ee.delete(B.id),re.delete(B.id);let Ne=X!==B.content,at=B.streaming!==!1;Ne&&(B.content=X),B.streaming=!1,(Ne||at)&&g(B)}else if(m!==null){let B=m;ee.delete(B.id),re.delete(B.id),B.streaming!==!1&&(B.streaming=!1,g(B))}n({type:"status",status:"idle"})}else if(Ge==="agent_start")te={executionId:T.executionId,agentId:(Ko=T.agentId)!=null?Ko:"virtual",agentName:(An=T.agentName)!=null?An:"",status:"running",currentIteration:0,maxTurns:(Bo=T.maxTurns)!=null?Bo:1,startedAt:Re(T.startedAt)};else if(Ge==="agent_iteration_start"){if(te&&(te.currentIteration=T.iteration),Fn==="separate"&&T.iteration>1){let U=m;U&&(U.streaming=!1,g(U),qe.set(T.iteration-1,U),m=null)}}else if(Ge==="agent_turn_start")C=null;else if(Ge==="agent_turn_delta"){if(T.contentType==="text"){let U=de();U.content+=(Jr=T.delta)!=null?Jr:"",U.agentMetadata={executionId:T.executionId,iteration:T.iteration,turnId:T.turnId,agentName:te==null?void 0:te.agentName},C=U,g(U)}else if(T.contentType==="thinking"){let U=(Tr=T.turnId)!=null?Tr:`agent-think-${T.iteration}`,B=De(U);B.reasoning=(Qr=B.reasoning)!=null?Qr:{id:U,status:"streaming",chunks:[]},B.reasoning.chunks.push((za=T.delta)!=null?za:""),B.agentMetadata={executionId:T.executionId,iteration:T.iteration,turnId:T.turnId},g(B)}else if(T.contentType==="tool_input"){let U=(Zr=T.toolCallId)!=null?Zr:x.lastId;if(U){let B=P.get(U);B!=null&&B.toolCall&&(B.toolCall.chunks=(qa=B.toolCall.chunks)!=null?qa:[],B.toolCall.chunks.push((es=T.delta)!=null?es:""),g(B))}}}else if(Ge==="agent_turn_complete"){let U=T.turnId;if(U){let ie=R.get(U);if(ie!=null&&ie.reasoning){ie.reasoning.status="complete",ie.reasoning.completedAt=Re(T.completedAt);let X=(vt=ie.reasoning.startedAt)!=null?vt:Date.now();ie.reasoning.durationMs=Math.max(0,((Rs=ie.reasoning.completedAt)!=null?Rs:Date.now())-X),ie.streaming=!1,g(ie)}}let B=T.stopReason,Z=m!=null?m:C;if(B&&Z!==null){let ie=T.turnId;(!ie||((co=Z.agentMetadata)==null?void 0:co.turnId)===ie)&&(Z.stopReason=B,g(Z))}}else if(Ge==="agent_tool_start"){m&&(m.streaming=!1,g(m),m=null);let U=(Nn=T.toolCallId)!=null?Nn:`agent-tool-${l()}`;Ae(Y(T),U);let B=ae(U),Z=(ja=B.toolCall)!=null?ja:{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=(ts=(Ka=T.toolName)!=null?Ka:T.name)!=null?ts:Z.name,Z.status="running",T.parameters!==void 0&&(Z.args=T.parameters),Z.startedAt=Re((Go=T.startedAt)!=null?Go:T.timestamp),B.toolCall=Z,B.streaming=!0,B.agentMetadata={executionId:T.executionId,iteration:T.iteration},g(B)}else if(Ge==="agent_tool_delta"){let U=(Ps=T.toolCallId)!=null?Ps:x.lastId;if(U){let B=(sr=P.get(U))!=null?sr:ae(U);B.toolCall&&(B.toolCall.chunks=(Ws=B.toolCall.chunks)!=null?Ws:[],B.toolCall.chunks.push((Bs=T.delta)!=null?Bs:""),B.toolCall.status="running",B.streaming=!0,g(B))}}else if(Ge==="agent_tool_complete"){let U=(Hs=T.toolCallId)!=null?Hs:x.lastId;if(U){let B=(Ds=P.get(U))!=null?Ds:ae(U);if(B.toolCall){B.toolCall.status="complete",T.result!==void 0&&(B.toolCall.result=T.result),typeof T.executionTime=="number"&&(B.toolCall.durationMs=T.executionTime),B.toolCall.completedAt=Re((_n=T.completedAt)!=null?_n:T.timestamp),B.streaming=!1,g(B);let Z=Y(T);Z&&x.byCall.delete(Z)}}}else if(Ge==="agent_media"){let U=Array.isArray(T.media)?T.media:[],B=[];for(let Z of U){if(!Z||typeof Z!="object")continue;let ie=Z,X=typeof ie.type=="string"?ie.type:void 0,Pe=typeof ie.mediaType=="string"?ie.mediaType.toLowerCase():"",Ne=null,at="";if(X==="media"){let Ze=typeof ie.data=="string"?ie.data:void 0;if(!Ze)continue;at=Pe.length>0?Pe:"application/octet-stream",Ne=`data:${at};base64,${Ze}`}else if(X==="image-url"){let Ze=typeof ie.url=="string"?ie.url:void 0;if(!Ze)continue;at=Pe,Ne=Ze}else if(X==="file-url"){let Ze=typeof ie.url=="string"?ie.url:void 0;if(!Ze)continue;at=Pe,Ne=Ze}else continue;if(Ne)if(X==="image-url"||at.startsWith("image/"))B.push({type:"image",image:Ne,...at?{mimeType:at}:{}});else if(at.startsWith("audio/"))B.push({type:"audio",audio:Ne,mimeType:at});else if(at.startsWith("video/"))B.push({type:"video",video:Ne,mimeType:at});else{let Ze=at||"application/octet-stream";B.push({type:"file",data:Ne,mimeType:Ze,filename:rb(Ze)})}}if(B.length>0){let Z=l(),ie=T.toolCallId,Pe={id:`agent-media-${typeof ie=="string"&&ie.length>0?`${ie}-${Z}`:String(Z)}`,role:"assistant",content:"",contentParts:B,createdAt:new Date().toISOString(),streaming:!1,sequence:Z,agentMetadata:{executionId:T.executionId,iteration:T.iteration}};g(Pe);let Ne=m;Ne&&(Ne.streaming=!1,g(Ne)),m=null,v.current=null}}else if(Ge!=="agent_iteration_complete"){if(Ge==="agent_reflection"||Ge==="agent_reflect"){let U=`agent-reflection-${T.executionId}-${T.iteration}`,B={id:U,role:"assistant",content:(ns=T.reflection)!=null?ns:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:U,status:"complete",chunks:[(Ho=T.reflection)!=null?Ho:""]},agentMetadata:{executionId:T.executionId,iteration:T.iteration}};g(B)}else if(Ge==="agent_complete"){te&&(te.status=T.success?"complete":"error",te.completedAt=Re(T.completedAt),te.stopReason=T.stopReason);let U=m;U&&(U.streaming=!1,g(U)),n({type:"status",status:"idle"})}else if(Ge==="agent_error"){let U=typeof T.error=="string"?T.error:(Fs=(Do=T.error)==null?void 0:Do.message)!=null?Fs:"Agent execution error";T.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",U):n({type:"error",error:new Error(U)})}else if(Ge!=="agent_ping"){if(Ge==="agent_approval_start"){let U=(Ga=T.approvalId)!=null?Ga:`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:(Os=te==null?void 0:te.agentId)!=null?Os:"virtual",executionId:(kr=(Ns=T.executionId)!=null?Ns:te==null?void 0:te.executionId)!=null?kr:"",toolName:(Ya=T.toolName)!=null?Ya:"",toolType:T.toolType,description:(Ja=T.description)!=null?Ja:`Execute ${(Xa=T.toolName)!=null?Xa:"tool"}`,...typeof T.reason=="string"&&T.reason?{reason:T.reason}:{},parameters:T.parameters}};g(B)}else if(Ge==="step_await"&&T.awaitReason==="approval_required"){let U=(Qa=T.approvalId)!=null?Qa:`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:(Sl=te==null?void 0:te.agentId)!=null?Sl:"virtual",executionId:(ar=(Er=T.executionId)!=null?Er:te==null?void 0:te.executionId)!=null?ar:"",toolName:(Za=T.toolName)!=null?Za:"",toolType:T.toolType,description:(ir=T.description)!=null?ir:`Execute ${(_s=T.toolName)!=null?_s:"tool"}`,...typeof T.reason=="string"&&T.reason?{reason:T.reason}:{},parameters:T.parameters}};g(B)}else if(Ge==="agent_approval_complete"){let U=T.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:(ei=T.decision)!=null?ei:"approved",agentId:(Vs=te==null?void 0:te.agentId)!=null?Vs:"virtual",executionId:($s=(lr=T.executionId)!=null?lr:te==null?void 0:te.executionId)!=null?$s:"",toolName:(ti=T.toolName)!=null?ti:"",description:(Yo=T.description)!=null?Yo:"",resolvedAt:Date.now()}};g(Z)}}else if(Ge==="artifact_start"||Ge==="artifact_delta"||Ge==="artifact_update"||Ge==="artifact_complete"){if(Ge==="artifact_start"){let U=T.artifactType,B=String(T.id),Z=typeof T.title=="string"?T.title:void 0;if(n({type:"artifact_start",id:B,artifactType:U,title:Z,component:typeof T.component=="string"?T.component:void 0}),ye.set(B,{markdown:"",title:Z}),!se.has(B)){se.add(B);let ie={id:`artifact-ref-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:B,title:Z,artifactType:U,status:"streaming"}})};J.set(B,ie),g(ie)}}else if(Ge==="artifact_delta"){let U=String(T.id),B=typeof T.delta=="string"?T.delta:String((ni=T.delta)!=null?ni:"");n({type:"artifact_delta",id:U,artDelta:B});let Z=ye.get(U);Z&&(Z.markdown+=B)}else if(Ge==="artifact_update"){let U=T.props&&typeof T.props=="object"&&!Array.isArray(T.props)?T.props:{};n({type:"artifact_update",id:String(T.id),props:U,component:typeof T.component=="string"?T.component:void 0})}else if(Ge==="artifact_complete"){let U=String(T.id);n({type:"artifact_complete",id:U});let B=J.get(U);if(B){B.streaming=!1;try{let Z=JSON.parse((cr=B.rawContent)!=null?cr:"{}");if(Z.props){Z.props.status="complete";let ie=ye.get(U);ie!=null&&ie.markdown&&(Z.props.markdown=ie.markdown)}B.rawContent=JSON.stringify(Z)}catch{}ye.delete(U),g(B),J.delete(U)}}}else if(Ge==="transcript_insert"){let U=T.message;if(!U||typeof U!="object")continue;let B=String((Ot=U.id)!=null?Ot:`msg-${l()}`),Z=U.role,X={id:B,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(g(X),X.rawContent)try{let Pe=JSON.parse(X.rawContent),Ne=(os=Pe==null?void 0:Pe.props)==null?void 0:os.artifactId;typeof Ne=="string"&&se.add(Ne)}catch{}m=null,v.current=null,ee.delete(B),re.delete(B)}else if(Ge==="error"||Ge==="step_error"||Ge==="dispatch_error"||Ge==="flow_error"){let U=null;if(T.error instanceof Error)U=T.error;else if(Ge==="dispatch_error"){let B=(rs=T.message)!=null?rs:T.error;B!=null&&B!==""&&(U=new Error(String(B)))}else if(Ge==="step_error"||Ge==="flow_error"){let B=T.error;typeof B=="string"&&B!==""?U=new Error(B):B!=null&&typeof B=="object"&&"message"in B&&(U=new Error(String((Us=B.message)!=null?Us:B)))}else Ge==="error"&&T.error!=null&&T.error!==""&&(U=new Error(String(T.error)));if(U){n({type:"error",error:U});let B=m;B&&B.streaming&&(B.streaming=!1,g(B)),n({type:"status",status:"idle"})}}}}}Be.length=0};;){let{done:F,value:ue}=await r.read();if(F)break;a+=s.decode(ue,{stream:!0});let Fe=a.split(`
|
|
10
10
|
|
|
11
|
-
`);a=(
|
|
12
|
-
`),mt="message",at="";for(let j of Ve)j.startsWith("event:")?mt=j.replace("event:","").trim():j.startsWith("data:")&&(at+=j.replace("data:","").trim());if(!at)continue;let Pt;try{Pt=JSON.parse(at)}catch(j){n({type:"error",error:j instanceof Error?j:new Error("Failed to parse chat stream payload")});continue}let jt=mt!=="message"?mt:(to=Pt.type)!=null?to:"message";if((qe=this.onSSEEvent)==null||qe.call(this,jt,Pt),this.parseSSEEvent){v.current=u;let j=await this.handleCustomSSEEvent(Pt,n,v,f,l,M);if(v.current&&v.current!==u&&(u=v.current),j)continue}be.push(jt,Pt),_e()}}be.flushPending(),_e(),be.destroy()}};function wi(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function sa(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ci="[Image]";function _l(e){return{type:"text",text:e}}var gm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Mh=["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"],qo=[...gm,...Mh];function Lh(e){return gm.includes(e)||e.startsWith("image/")}function Si(e){return Lh(e.type)}async function fm(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Si(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 hm(e,t=qo,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 Ih(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function bm(e,t){let n=Ih(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 Ai=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 aa=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=...`,p=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,u)=>{if(!this.ws)return u(new Error("WebSocket not created"));let C=!1,v=I=>{C||(C=!0,clearTimeout(M),u(new Error(I)))},M=setTimeout(()=>v("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{C||(C=!0,clearTimeout(M),f())},{once:!0}),this.ws.addEventListener("error",()=>{v("WebSocket connection failed to "+m+"."+p)},{once:!0}),this.ws.addEventListener("close",I=>{if(!I.wasClean&&!C){let R=I.code!==1006?` (code ${I.code})`:"";v("WebSocket connection failed"+R+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(r){throw this.ws=null,this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(n=>n(new Error("WebSocket error"))),this.statusCallbacks.forEach(n=>n("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let n=JSON.parse(t.data);this.handleWebSocketMessage(n)}catch{this.errorCallbacks.forEach(o=>o(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var n,o;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(r=>r({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),(n=t.response.audio)!=null&&n.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(r=>r("speaking")),this.playAudio(t.response.audio).catch(r=>this.errorCallbacks.forEach(s=>s(r instanceof Error?r:new Error(String(r)))))):(o=t.response.audio)!=null&&o.base64;break;case"audio_end":if(t.requestId&&t.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(r=>r("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(r=>r(new Error(t.error))),this.statusCallbacks.forEach(r=>r("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Ai(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,n,o,r;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(r=(o=this.config)==null?void 0:o.silenceThreshold)!=null?r:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let m=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:m});await this.sendAudio(p),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var s,a;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let n=this.audioContext,o=(a=(s=this.config)==null?void 0:s.silenceThreshold)!=null?a:.01;this.vad.start(n,this.mediaStream,"speech",{threshold:o,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(n=>n(t instanceof Error?t:new Error(String(t))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(t){var n;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(o=>o(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(o=>o("error"));return}try{let o=await this.blobToBase64(t),r=this.getFormatFromMimeType(t.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:o,format:r,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:s}))}catch(o){this.errorCallbacks.forEach(r=>r(o)),this.statusCallbacks.forEach(r=>r("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,o)=>{let r=new FileReader;r.onload=()=>{let a=r.result.split(",")[1];n(a)},r.onerror=o,r.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let n=atob(t.base64),o=new Uint8Array(n.length);for(let l=0;l<n.length;l++)o[l]=n.charCodeAt(l);let r=t.format||"mp3",s=r==="mp3"?"audio/mpeg":`audio/${r}`,a=new Blob([o],{type:s}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Wr=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 ia(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new aa(e.runtype);case"browser":if(!Wr.isSupported())throw new Error("Browser speech recognition not supported");return new Wr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function ym(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return ia({type:"runtype",runtype:e.runtype});if(Wr.isSupported())return ia({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Vl(e){try{return ym(e),!0}catch{return!1}}function vm(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let o="Sorry \u2014 I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
|
|
11
|
+
`);a=(an=Fe.pop())!=null?an:"";for(let Ke of Fe){let _e=Ke.split(`
|
|
12
|
+
`),$e="message",ot="";for(let Jt of _e)Jt.startsWith("event:")?$e=Jt.replace("event:","").trim():Jt.startsWith("data:")&&(ot+=Jt.replace("data:","").trim());if(!ot)continue;let Pt;try{Pt=JSON.parse(ot)}catch(Jt){n({type:"error",error:Jt instanceof Error?Jt:new Error("Failed to parse chat stream payload")});continue}let Kt=$e!=="message"?$e:(oo=Pt.type)!=null?oo:"message";if((Mo=this.onSSEEvent)==null||Mo.call(this,Kt,Pt),this.parseSSEEvent){v.current=m;let Jt=await this.handleCustomSSEEvent(Pt,n,v,g,l,M);if(v.current&&v.current!==m&&(m=v.current),Jt)continue}Mt.push(Kt,Pt),fe()}}Mt.flushPending(),fe(),Mt.destroy()}};function Li(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function ga(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ii="[Image]";function Jl(e){return{type:"text",text:e}}var Nm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ib=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Jo=[...Nm,...ib];function lb(e){return Nm.includes(e)||e.startsWith("image/")}function Ri(e){return lb(e.type)}async function _m(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Ri(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 Vm(e,t=Jo,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 cb(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function $m(e,t){let n=cb(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 Pi=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 Wi=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,o,r,s){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(n),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let f=0;f<a.length;f++)i+=a[f]*a[f];let d=Math.sqrt(i/a.length);(o==="silence"?d<r.threshold:d>=r.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=r.duration&&(this.fired=!0,s()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var ha=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 Wi;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,n,o;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let r=this.w;if(!r||!r.location)throw new Error("Window object or location not available");let s=r.location.protocol==="https:"?"wss:":"ws:",a=(t=this.config)==null?void 0:t.host,i=(n=this.config)==null?void 0:n.agentId,d=(o=this.config)==null?void 0:o.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let f=`${s}//${a}/ws/agents/${i}/voice?token=...`,u=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((g,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let C=!1,v=I=>{C||(C=!0,clearTimeout(M),m(new Error(I)))},M=setTimeout(()=>v("WebSocket connection timed out."+u),1e4);this.ws.addEventListener("open",()=>{C||(C=!0,clearTimeout(M),g())},{once:!0}),this.ws.addEventListener("error",()=>{v("WebSocket connection failed to "+f+"."+u)},{once:!0}),this.ws.addEventListener("close",I=>{if(!I.wasClean&&!C){let R=I.code!==1006?` (code ${I.code})`:"";v("WebSocket connection failed"+R+"."+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 Pi(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,n,o,r;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(r=(o=this.config)==null?void 0:o.silenceThreshold)!=null?r:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(g=>g("processing")),this.processingStartCallbacks.forEach(g=>g());let f=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",u=new Blob(this.audioChunks,{type:f});await this.sendAudio(u),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var s,a;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let n=this.audioContext,o=(a=(s=this.config)==null?void 0:s.silenceThreshold)!=null?a:.01;this.vad.start(n,this.mediaStream,"speech",{threshold:o,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(n=>n(t instanceof Error?t:new Error(String(t))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(t){var n;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(o=>o(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(o=>o("error"));return}try{let o=await this.blobToBase64(t),r=this.getFormatFromMimeType(t.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:o,format:r,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:s}))}catch(o){this.errorCallbacks.forEach(r=>r(o)),this.statusCallbacks.forEach(r=>r("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,o)=>{let r=new FileReader;r.onload=()=>{let a=r.result.split(",")[1];n(a)},r.onerror=o,r.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let n=atob(t.base64),o=new Uint8Array(n.length);for(let l=0;l<n.length;l++)o[l]=n.charCodeAt(l);let r=t.format||"mp3",s=r==="mp3"?"audio/mpeg":`audio/${r}`,a=new Blob([o],{type:s}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var _r=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 ba(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ha(e.runtype);case"browser":if(!_r.isSupported())throw new Error("Browser speech recognition not supported");return new _r(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Um(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return ba({type:"runtype",runtype:e.runtype});if(_r.isSupported())return ba({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ql(e){try{return Um(e),!0}catch{return!1}}function zm(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 la=e=>({isError:!0,content:[{type:"text",text:e}]}),xm=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,ki=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)&&rs(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 ra(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 Vl((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=ia(s);let a=(n=this.config.voiceRecognition)!=null?n:{},i=(o=a.processingText)!=null?o:"\u{1F3A4} Processing voice...",d=(r=a.processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let m=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=m.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var m,p,f,u,C,v;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((m=l.transcript)!=null&&m.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=l.transcript)!=null&&p.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=l.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(u=l.text)!=null&&u.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let M=(v=this.pendingVoiceAssistantMessageId)!=null?v:(C=[...this.messages].reverse().find(I=>I.role==="assistant"))==null?void 0:C.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,p;this.voiceStatus=l,this.voiceActive=l==="listening",(p=(m=this.callbacks).onVoiceStatusChanged)==null||p.call(m,l)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,o,r,s,a,i,d,l,m;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((o=t.runtype)==null?void 0:o.agentId)||"",clientToken:((r=t.runtype)==null?void 0:r.clientToken)||"",host:(s=t.runtype)==null?void 0:s.host,voiceId:(a=t.runtype)==null?void 0:a.voiceId,pauseDuration:(i=t.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=t.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=t.browser)==null?void 0:l.language)||"en-US",continuous:(m=t.browser)==null?void 0:m.continuous}};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let o=await this.client.initSession();return this.setClientSession(o),o}catch(o){return(n=(t=this.callbacks).onError)==null||n.call(t,o instanceof Error?o:new Error(String(o))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let n=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new ra(this.config),this.wireDefaultWebMcpConfirm(),n&&this.client.setSSEEventCallback(n)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:m,rawContent:p}=t,u={id:a!=null?a:n==="user"?wi():n==="assistant"?sa():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...m!==void 0&&{voiceProcessing:m},...p!==void 0&&{rawContent:p}};return this.upsertMessage(u),u}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:m,streaming:p=!1,voiceProcessing:f,rawContent:u}=o,v={id:d!=null?d:r==="user"?wi():r==="assistant"?sa():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:m!=null?m:this.nextSequence(),streaming:p,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...u!==void 0&&{rawContent:u}};n.push(v)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:i,sequence:d}=t,l={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(l),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var l,m,p,f,u;let o=t.trim();if(!o&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let r=wi(),s=sa(),a={id:r,role:"user",content:o||Ci,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(C){let v=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!v){let M=vm(C,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,v||(C instanceof Error?(p=(m=this.callbacks).onError)==null||p.call(m,C):(u=(f=this.callbacks).onError)==null||u.call(f,new Error(String(C))))}}async continueConversation(){var r,s,a,i,d;if(this.streaming)return;(r=this.abortController)==null||r.abort();let t=sa();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(l){let m=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!m){let p=vm(l,this.config.errorMessage);if(p){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:p,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,m||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var r,s,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(r=this.abortController)==null||r.abort();let o=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var r,s,a;try{if(((s=(r=this.config.webmcp)==null?void 0:r.autoApprove)==null?void 0:s.call(r,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(o,i)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r!=null&&r.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){var m,p,f,u,C;let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(v=>v.id===r),i={id:r,role:"assistant",content:"",createdAt:(m=a==null?void 0:a.createdAt)!=null?m:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(p=this.abortController)==null||p.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,l=d&&typeof d=="object"?d.onDecision:void 0;try{let v;if(l?v=await l({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):v=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),v){let M=null;if(v instanceof Response){if(!v.ok){let I=await v.json().catch(()=>null);throw new Error((f=I==null?void 0:I.error)!=null?f:`Approval request failed: ${v.status}`)}M=v.body}else v instanceof ReadableStream&&(M=v);M?await this.connectStream(M,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(v){let M=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,M||(C=(u=this.callbacks).onError)==null||C.call(u,v instanceof Error?v:new Error(String(v)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var m,p,f,u,C,v,M,I,R,W,D,B;let o=this.messages.find(x=>x.id===t.id);if(((m=o==null?void 0:o.agentMetadata)==null?void 0:m.askUserQuestionAnswered)===!0)return;let r=(p=t.agentMetadata)==null?void 0:p.executionId,s=(f=t.toolCall)==null?void 0:f.name;if(!r||!s){(C=(u=this.callbacks).onError)==null||C.call(u,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let x=(v=t.toolCall)==null?void 0:v.args,w=Array.isArray(x==null?void 0:x.questions)?x.questions:[];if(w.length===1){let E=typeof((M=w[0])==null?void 0:M.question)=="string"?w[0].question:"";E&&(a={[E]: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 x=typeof n=="string"?n:Object.entries(n).map(([w,E])=>`${w}: ${Array.isArray(E)?E.join(", "):E}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:x,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let x=a!=null?a:{};l.forEach((w,E)=>{let S=typeof(w==null?void 0:w.question)=="string"?w.question:"";if(!S)return;let T=x[S],_=Array.isArray(T)?T.join(", "):typeof T=="string"?T:"";this.appendMessage({id:`ask-user-q-${i}-${E}`,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${E}`,role:"user",content:_||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let x=await this.client.resumeFlow(r,{[s]:n});if(!x.ok){let w=await x.json().catch(()=>null);throw new Error((W=w==null?void 0:w.error)!=null?W:`Resume failed: ${x.status}`)}x.body?await this.connectStream(x.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(x){let w=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));this.setStreaming(!1),this.abortController=null,w||(B=(D=this.callbacks).onError)==null||B.call(D,x instanceof Error?x:new Error(String(x)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,o=(a=t.toolCall)==null?void 0:a.id;if(!n||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){var r,s;let n=this.messages.find(a=>a.id===t.id),o=[(r=n==null?void 0:n.toolCall)==null?void 0:r.startedAt,(s=t.toolCall)==null?void 0:s.startedAt];for(let a of o)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now()){this.messages.some(s=>s.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,l,m;let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async p=>{var D,B,x,w,E,S,T;let f=(D=p.toolCall)==null?void 0:D.name,u=(B=p.toolCall)==null?void 0:B.id;if(!f||!u)return null;let C=`${t}:${u}`;if(this.webMcpInflightKeys.has(C)||this.webMcpResolvedKeys.has(C))return null;this.webMcpInflightKeys.add(C),o.push(C);let v=this.markWebMcpToolRunning(p),M=new AbortController;this.webMcpResolveControllers.add(M),r.push(M);let I=(w=(x=p.agentMetadata)==null?void 0:x.webMcpToolCallId)!=null?w:f,R=this.client.executeWebMcpToolCall(f,(E=p.toolCall)==null?void 0:E.args,M.signal),W;if(!R)W={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{W=await R}catch(_){let U=_ instanceof Error&&(_.name==="AbortError"||_.message.includes("aborted")||_.message.includes("abort"));return U||(T=(S=this.callbacks).onError)==null||T.call(S,_ instanceof Error?_:new Error(String(_))),this.markWebMcpToolComplete(p,la(U?"Aborted by cancel()":xm(_)),v),this.webMcpInflightKeys.delete(C),null}return M.signal.aborted?(this.markWebMcpToolComplete(p,la("Aborted by cancel()"),v),this.webMcpInflightKeys.delete(C),null):{dedupeKey:C,resumeKey:I,output:W,toolMessage:p,startedAt:v,completedAt:Date.now()}})),i=[];try{if(i=a.filter(u=>u!==null),i.length===0)return;let p={};for(let u of i)p[u.resumeKey]=u.output;let f=await this.client.resumeFlow(t,p,{signal:s.signal});if(!f.ok){let u=await f.json().catch(()=>null);throw new Error((d=u==null?void 0:u.error)!=null?d:`Resume failed: ${f.status}`)}for(let u of i)this.webMcpResolvedKeys.add(u.dedupeKey),this.markWebMcpToolComplete(u.toolMessage,u.output,u.startedAt,u.completedAt);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))(m=(l=this.callbacks).onError)==null||m.call(l,p instanceof Error?p:new Error(String(p)));else for(let u of i)this.markWebMcpToolComplete(u.toolMessage,la("Aborted by cancel()"),u.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of r)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var u,C,v,M,I,R,W,D,B,x,w,E;let n=(u=t.agentMetadata)==null?void 0:u.executionId,o=(C=t.toolCall)==null?void 0:C.name,r=(v=t.toolCall)==null?void 0:v.id;if(!n){(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 S=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(S)||this.webMcpResolvedKeys.has(S))return;this.webMcpInflightKeys.add(S);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(S)}catch(T){(W=(R=this.callbacks).onError)==null||W.call(R,T instanceof Error?T:new Error(String(T)))}finally{this.webMcpInflightKeys.delete(S)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let l=(D=t.toolCall)==null?void 0:D.args,m=this.client.executeWebMcpToolCall(o,l,d),p="execute",f=a;try{let S;if(m?S=await m:S={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),d.aborted){this.markWebMcpToolComplete(t,la("Aborted by cancel()"),a);return}let T=(x=(B=t.agentMetadata)==null?void 0:B.webMcpToolCallId)!=null?x:o;p="resume",await this.resumeWithToolOutput(n,T,S,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,S,a,f)},signal:d})}catch(S){let T=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));(p==="execute"||T||d.aborted)&&this.markWebMcpToolComplete(t,la(T||d.aborted?"Aborted by cancel()":xm(S)),a),T||(E=(w=this.callbacks).onError)==null||E.call(w,S instanceof Error?S:new Error(String(S)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){var a,i;let s=await this.client.resumeFlow(t,{[n]:o},{signal:r==null?void 0:r.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=r==null?void 0:r.onHttpOk)==null||i.call(r),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var r;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let o={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(r=t.props)!=null?r:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),o}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,o;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let r=this.artifacts.get(t.id);(r==null?void 0:r.artifactType)==="markdown"&&(r.markdown=((o=r.markdown)!=null?o:"")+t.artDelta);break}case"artifact_update":{let r=this.artifacts.get(t.id);(r==null?void 0:r.artifactType)==="component"&&(r.props={...r.props,...t.props},t.component&&(r.component=t.component));break}case"artifact_complete":{let r=this.artifacts.get(t.id);r&&(r.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>{var r;return{...o,streaming:!1,sequence:(r=o.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=o.content;r.trim()&&this.speak(r,t)}speak(t,n){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t),s=o.getVoices();if(n.voice){let a=s.find(i=>i.name===n.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=n.pickVoice?n.pickVoice(s):e.pickBestVoice(s));n.rate!==void 0&&(r.rate=n.rate),n.pitch!==void 0&&(r.pitch=n.pitch),setTimeout(()=>o.speak(r),50)}static pickBestVoice(t){var o;let n=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of n){let s=t.find(a=>a.name===r);if(s)return s}return(o=t.find(r=>r.lang.startsWith("en")))!=null?o:t[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{var m,p,f,u,C,v,M,I,R,W;if(s!==o)return r;let a={...r,...n};((m=r.agentMetadata)==null?void 0:m.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(p=n.toolCall)==null?void 0:p.name,d=(f=n.agentMetadata)==null?void 0:f.executionId,l=(u=n.toolCall)==null?void 0:u.id;if(i&&rs(i)&&d&&l&&((C=n.agentMetadata)==null?void 0:C.awaitingLocalTool)===!0){let D=`${d}:${l}`,B=this.webMcpInflightKeys.has(D),x=this.webMcpResolvedKeys.has(D),w=(v=r.toolCall)==null?void 0:v.name,E=((M=r.agentMetadata)==null?void 0:M.executionId)===d&&((I=r.toolCall)==null?void 0:I.id)===l&&w!==void 0&&rs(w)&&((R=r.toolCall)==null?void 0:R.status)==="complete";(B||x||E)&&(a.agentMetadata={...(W=a.agentMetadata)!=null?W:{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{var d,l;let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=(d=n.sequence)!=null?d:0,i=(l=o.sequence)!=null?l:0;return a!==i?a-i:n.id.localeCompare(o.id)})}};var b=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Wo=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o};var A=require("lucide"),Rh={activity:A.Activity,"arrow-down":A.ArrowDown,"arrow-up":A.ArrowUp,"arrow-up-right":A.ArrowUpRight,bot:A.Bot,"chevron-down":A.ChevronDown,"chevron-up":A.ChevronUp,"chevron-right":A.ChevronRight,"chevron-left":A.ChevronLeft,check:A.Check,clipboard:A.Clipboard,"clipboard-copy":A.ClipboardCopy,copy:A.Copy,file:A.File,"file-code":A.FileCode,"file-spreadsheet":A.FileSpreadsheet,"file-text":A.FileText,"image-plus":A.ImagePlus,loader:A.Loader,"loader-circle":A.LoaderCircle,mic:A.Mic,paperclip:A.Paperclip,"refresh-cw":A.RefreshCw,search:A.Search,send:A.Send,"shield-alert":A.ShieldAlert,"shield-check":A.ShieldCheck,"shield-x":A.ShieldX,square:A.Square,"thumbs-down":A.ThumbsDown,"thumbs-up":A.ThumbsUp,upload:A.Upload,"volume-2":A.Volume2,x:A.X,user:A.User,mail:A.Mail,phone:A.Phone,calendar:A.Calendar,clock:A.Clock,building:A.Building,"map-pin":A.MapPin,lock:A.Lock,key:A.Key,"credit-card":A.CreditCard,"at-sign":A.AtSign,hash:A.Hash,globe:A.Globe,link:A.Link,"circle-check":A.CircleCheck,"circle-x":A.CircleX,"triangle-alert":A.TriangleAlert,info:A.Info,ban:A.Ban,shield:A.Shield,"arrow-left":A.ArrowLeft,"arrow-right":A.ArrowRight,"external-link":A.ExternalLink,ellipsis:A.Ellipsis,"ellipsis-vertical":A.EllipsisVertical,menu:A.Menu,house:A.House,plus:A.Plus,minus:A.Minus,pencil:A.Pencil,trash:A.Trash,"trash-2":A.Trash2,save:A.Save,download:A.Download,share:A.Share,funnel:A.Funnel,settings:A.Settings,"rotate-cw":A.RotateCw,maximize:A.Maximize,minimize:A.Minimize,"shopping-cart":A.ShoppingCart,"shopping-bag":A.ShoppingBag,package:A.Package,truck:A.Truck,tag:A.Tag,gift:A.Gift,receipt:A.Receipt,wallet:A.Wallet,store:A.Store,"dollar-sign":A.DollarSign,percent:A.Percent,play:A.Play,pause:A.Pause,"volume-x":A.VolumeX,camera:A.Camera,image:A.Image,film:A.Film,headphones:A.Headphones,"message-circle":A.MessageCircle,"message-square":A.MessageSquare,bell:A.Bell,heart:A.Heart,star:A.Star,eye:A.Eye,"eye-off":A.EyeOff,bookmark:A.Bookmark,"calendar-days":A.CalendarDays,history:A.History,timer:A.Timer,folder:A.Folder,"folder-open":A.FolderOpen,files:A.Files,sparkles:A.Sparkles,zap:A.Zap,sun:A.Sun,moon:A.Moon,flag:A.Flag,monitor:A.Monitor,smartphone:A.Smartphone},Me=(e,t=24,n="currentColor",o=2)=>{let r=Rh[e];return r?Ph(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 Ph(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 Ei={allowedTypes:qo,maxFileSize:10*1024*1024,maxFiles:4};function Wh(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Bh(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 ca=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,o,r;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Ei.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:Ei.maxFileSize,maxFiles:(r=t.maxFiles)!=null?r:Ei.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ei.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,o,r,s,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(o=(n=this.config).onFileRejected)==null||o.call(n,l,"count");continue}let m=hm(l,this.config.allowedTypes,this.config.maxFileSize);if(!m.valid){let p=(r=m.error)!=null&&r.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,p);continue}try{let p=await fm(l),f=Si(l)?URL.createObjectURL(l):null,u={id:Wh(),file:l,previewUrl:f,contentPart:p};this.attachments.push(u),this.renderPreview(u)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let o of this.attachments)o.previewUrl&&URL.revokeObjectURL(o.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Si(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=Bh(t.file.type),d=Me(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=b("span");l.textContent=bm(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=Me("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})}};var wm=require("idiomorph"),Mi=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;wm.Idiomorph.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 Li={index:-1,draft:""};function Cm(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:{...Li}}}function Sm(e,t){var n,o,r,s,a,i,d,l,m,p,f,u,C,v,M,I,R,W,D,B,x,w,E,S,T,_,U,Y,he,fe,ae,Ee,ye,Oe,we,K,pe,G;return[e.id,e.role,(o=(n=e.content)==null?void 0:n.length)!=null?o:0,(s=(r=e.content)==null?void 0:r.slice(-32))!=null?s:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(m=(l=e.llmContent)==null?void 0:l.length)!=null?m:0,(f=(p=e.approval)==null?void 0:p.status)!=null?f:"",(C=(u=e.toolCall)==null?void 0:u.status)!=null?C:"",(M=(v=e.toolCall)==null?void 0:v.name)!=null?M:"",(W=(R=(I=e.toolCall)==null?void 0:I.chunks)==null?void 0:R.length)!=null?W:0,(w=(x=(B=(D=e.toolCall)==null?void 0:D.chunks)==null?void 0:B[e.toolCall.chunks.length-1])==null?void 0:x.slice(-32))!=null?w:"",typeof((E=e.toolCall)==null?void 0:E.args)=="string"?e.toolCall.args.length:(S=e.toolCall)!=null&&S.args?JSON.stringify(e.toolCall.args).length:0,(U=(_=(T=e.reasoning)==null?void 0:T.chunks)==null?void 0:_.length)!=null?U:0,(ae=(fe=(he=(Y=e.reasoning)==null?void 0:Y.chunks)==null?void 0:he[e.reasoning.chunks.length-1])==null?void 0:fe.length)!=null?ae:0,(we=(Oe=(ye=(Ee=e.reasoning)==null?void 0:Ee.chunks)==null?void 0:ye[e.reasoning.chunks.length-1])==null?void 0:Oe.slice(-32))!=null?we:"",(pe=(K=e.contentParts)==null?void 0:K.length)!=null?pe:0,(G=e.stopReason)!=null?G:"",t].join("\0")}function Am(){return new Map}function Tm(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function km(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Em(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Ii(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function da(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function pa(e,t){return da(e)-e.scrollTop<=t}function Ri(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,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 Pi(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 wn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Cn=1e5,lr=Cn+1;var ua={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Hh=["pre","code","a","script","style"],Wi=e=>{var t,n,o,r,s;return{type:(t=e==null?void 0:e.type)!=null?t:ua.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:ua.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:ua.speed,duration:(r=e==null?void 0:e.duration)!=null?r:ua.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:ua.buffer}},Dh=[{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"}],Lm=new Map;for(let e of Dh)Lm.set(e.name,e);var ma=(e,t)=>{var n,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(o=Lm.get(e))!=null?o:null},Bi=(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 ya=e=>({isError:!0,content:[{type:"text",text:e}]}),qm=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Bi=class e{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=t=>{var n,o,r,s,a,i,d,l;if(t.type==="message"){this.upsertMessage(t.message);let f=t.message.toolCall;((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&(f!=null&&f.name)&&fs(f.name)&&this.enqueueWebMcpAwait(t.message),(o=t.message.agentMetadata)!=null&&o.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(r=t.message.agentMetadata.agentName)!=null?r:"",status:"running",currentIteration:(s=t.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let f=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":f||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var o,r;this.messages=[...(o=t.initialMessages)!=null?o:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new fa(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 Ql((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=ba(s);let a=(n=this.config.voiceRecognition)!=null?n:{},i=(o=a.processingText)!=null?o:"\u{1F3A4} Processing voice...",d=(r=a.processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let f=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=f.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var f,u,g,m,C,v;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((f=l.transcript)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(u=l.transcript)!=null&&u.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((g=l.text)!=null&&g.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=l.text)!=null&&m.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let M=(v=this.pendingVoiceAssistantMessageId)!=null?v:(C=[...this.messages].reverse().find(I=>I.role==="assistant"))==null?void 0:C.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 f,u;this.voiceStatus=l,this.voiceActive=l==="listening",(u=(f=this.callbacks).onVoiceStatusChanged)==null||u.call(f,l)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,o,r,s,a,i,d,l,f;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((o=t.runtype)==null?void 0:o.agentId)||"",clientToken:((r=t.runtype)==null?void 0:r.clientToken)||"",host:(s=t.runtype)==null?void 0:s.host,voiceId:(a=t.runtype)==null?void 0:a.voiceId,pauseDuration:(i=t.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=t.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=t.browser)==null?void 0:l.language)||"en-US",continuous:(f=t.browser)==null?void 0:f.continuous}};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let o=await this.client.initSession();return this.setClientSession(o),o}catch(o){return(n=(t=this.callbacks).onError)==null||n.call(t,o instanceof Error?o:new Error(String(o))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let n=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new fa(this.config),this.wireDefaultWebMcpConfirm(),n&&this.client.setSSEEventCallback(n)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:f,rawContent:u}=t,m={id:a!=null?a:n==="user"?Li():n==="assistant"?ga():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...f!==void 0&&{voiceProcessing:f},...u!==void 0&&{rawContent:u}};return this.upsertMessage(m),m}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:f,streaming:u=!1,voiceProcessing:g,rawContent:m}=o,v={id:d!=null?d:r==="user"?Li():r==="assistant"?ga():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:f!=null?f:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...m!==void 0&&{rawContent:m}};n.push(v)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:i,sequence:d}=t,l={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(l),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var l,f,u,g,m;let o=t.trim();if(!o&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let r=Li(),s=ga(),a={id:r,role:"user",content:o||Ii,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(C){let v=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!v){let M=zm(C,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,v||(C instanceof Error?(u=(f=this.callbacks).onError)==null||u.call(f,C):(m=(g=this.callbacks).onError)==null||m.call(g,new Error(String(C))))}}async continueConversation(){var r,s,a,i,d;if(this.streaming)return;(r=this.abortController)==null||r.abort();let t=ga();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(l){let f=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!f){let u=zm(l,this.config.errorMessage);if(u){let g={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,f||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var r,s,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(r=this.abortController)==null||r.abort();let o=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var r,s,a;try{if(((s=(r=this.config.webmcp)==null?void 0:r.autoApprove)==null?void 0:s.call(r,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(o,i)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r!=null&&r.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){var f,u,g,m,C;let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(v=>v.id===r),i={id:r,role:"assistant",content:"",createdAt:(f=a==null?void 0:a.createdAt)!=null?f:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(u=this.abortController)==null||u.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,l=d&&typeof d=="object"?d.onDecision:void 0;try{let v;if(l?v=await l({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):v=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),v){let M=null;if(v instanceof Response){if(!v.ok){let I=await v.json().catch(()=>null);throw new Error((g=I==null?void 0:I.error)!=null?g:`Approval request failed: ${v.status}`)}M=v.body}else v instanceof ReadableStream&&(M=v);M?await this.connectStream(M,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(v){let M=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,M||(C=(m=this.callbacks).onError)==null||C.call(m,v instanceof Error?v:new Error(String(v)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var f,u,g,m,C,v,M,I,R,P,D,W;let o=this.messages.find(w=>w.id===t.id);if(((f=o==null?void 0:o.agentMetadata)==null?void 0:f.askUserQuestionAnswered)===!0)return;let r=(u=t.agentMetadata)==null?void 0:u.executionId,s=(g=t.toolCall)==null?void 0:g.name;if(!r||!s){(C=(m=this.callbacks).onError)==null||C.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let w=(v=t.toolCall)==null?void 0:v.args,x=Array.isArray(w==null?void 0:w.questions)?w.questions:[];if(x.length===1){let E=typeof((M=x[0])==null?void 0:M.question)=="string"?x[0].question:"";E&&(a={[E]: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 w=typeof n=="string"?n:Object.entries(n).map(([x,E])=>`${x}: ${Array.isArray(E)?E.join(", "):E}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:w,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let w=a!=null?a:{};l.forEach((x,E)=>{let S=typeof(x==null?void 0:x.question)=="string"?x.question:"";if(!S)return;let k=w[S],V=Array.isArray(k)?k.join(", "):typeof k=="string"?k:"";this.appendMessage({id:`ask-user-q-${i}-${E}`,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${E}`,role:"user",content:V||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let w=await this.client.resumeFlow(r,{[s]:n});if(!w.ok){let x=await w.json().catch(()=>null);throw new Error((P=x==null?void 0:x.error)!=null?P:`Resume failed: ${w.status}`)}w.body?await this.connectStream(w.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(w){let x=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));this.setStreaming(!1),this.abortController=null,x||(W=(D=this.callbacks).onError)==null||W.call(D,w instanceof Error?w:new Error(String(w)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,o=(a=t.toolCall)==null?void 0:a.id;if(!n||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){var r,s;let n=this.messages.find(a=>a.id===t.id),o=[(r=n==null?void 0:n.toolCall)==null?void 0:r.startedAt,(s=t.toolCall)==null?void 0:s.startedAt];for(let a of o)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now()){this.messages.some(s=>s.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,l,f;let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async u=>{var D,W,w,x,E,S,k;let g=(D=u.toolCall)==null?void 0:D.name,m=(W=u.toolCall)==null?void 0:W.id;if(!g||!m)return null;let C=`${t}:${m}`;if(this.webMcpInflightKeys.has(C)||this.webMcpResolvedKeys.has(C))return null;this.webMcpInflightKeys.add(C),o.push(C);let v=this.markWebMcpToolRunning(u),M=new AbortController;this.webMcpResolveControllers.add(M),r.push(M);let I=(x=(w=u.agentMetadata)==null?void 0:w.webMcpToolCallId)!=null?x:g,R=this.client.executeWebMcpToolCall(g,(E=u.toolCall)==null?void 0:E.args,M.signal),P;if(!R)P={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{P=await R}catch(V){let z=V instanceof Error&&(V.name==="AbortError"||V.message.includes("aborted")||V.message.includes("abort"));return z||(k=(S=this.callbacks).onError)==null||k.call(S,V instanceof Error?V:new Error(String(V))),this.markWebMcpToolComplete(u,ya(z?"Aborted by cancel()":qm(V)),v),this.webMcpInflightKeys.delete(C),null}return M.signal.aborted?(this.markWebMcpToolComplete(u,ya("Aborted by cancel()"),v),this.webMcpInflightKeys.delete(C),null):{dedupeKey:C,resumeKey:I,output:P,toolMessage:u,startedAt:v,completedAt:Date.now()}})),i=[];try{if(i=a.filter(m=>m!==null),i.length===0)return;let u={};for(let m of i)u[m.resumeKey]=m.output;let g=await this.client.resumeFlow(t,u,{signal:s.signal});if(!g.ok){let m=await g.json().catch(()=>null);throw new Error((d=m==null?void 0:m.error)!=null?d:`Resume failed: ${g.status}`)}for(let m of i)this.webMcpResolvedKeys.add(m.dedupeKey),this.markWebMcpToolComplete(m.toolMessage,m.output,m.startedAt,m.completedAt);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(u){if(!(u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))))(f=(l=this.callbacks).onError)==null||f.call(l,u instanceof Error?u:new Error(String(u)));else for(let m of i)this.markWebMcpToolComplete(m.toolMessage,ya("Aborted by cancel()"),m.startedAt)}finally{for(let u of o)this.webMcpInflightKeys.delete(u);for(let u of r)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var m,C,v,M,I,R,P,D,W,w,x,E;let n=(m=t.agentMetadata)==null?void 0:m.executionId,o=(C=t.toolCall)==null?void 0:C.name,r=(v=t.toolCall)==null?void 0:v.id;if(!n){(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 S=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(S)||this.webMcpResolvedKeys.has(S))return;this.webMcpInflightKeys.add(S);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(S)}catch(k){(P=(R=this.callbacks).onError)==null||P.call(R,k instanceof Error?k:new Error(String(k)))}finally{this.webMcpInflightKeys.delete(S)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let l=(D=t.toolCall)==null?void 0:D.args,f=this.client.executeWebMcpToolCall(o,l,d),u="execute",g=a;try{let S;if(f?S=await f:S={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),d.aborted){this.markWebMcpToolComplete(t,ya("Aborted by cancel()"),a);return}let k=(w=(W=t.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?w:o;u="resume",await this.resumeWithToolOutput(n,k,S,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,S,a,g)},signal:d})}catch(S){let k=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));(u==="execute"||k||d.aborted)&&this.markWebMcpToolComplete(t,ya(k||d.aborted?"Aborted by cancel()":qm(S)),a),k||(E=(x=this.callbacks).onError)==null||E.call(x,S instanceof Error?S:new Error(String(S)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){var a,i;let s=await this.client.resumeFlow(t,{[n]:o},{signal:r==null?void 0:r.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=r==null?void 0:r.onHttpOk)==null||i.call(r),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var r;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let o={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(r=t.props)!=null?r:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),o}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,o;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let r=this.artifacts.get(t.id);(r==null?void 0:r.artifactType)==="markdown"&&(r.markdown=((o=r.markdown)!=null?o:"")+t.artDelta);break}case"artifact_update":{let r=this.artifacts.get(t.id);(r==null?void 0:r.artifactType)==="component"&&(r.props={...r.props,...t.props},t.component&&(r.component=t.component));break}case"artifact_complete":{let r=this.artifacts.get(t.id);r&&(r.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>{var r;return{...o,streaming:!1,sequence:(r=o.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=o.content;r.trim()&&this.speak(r,t)}speak(t,n){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t),s=o.getVoices();if(n.voice){let a=s.find(i=>i.name===n.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=n.pickVoice?n.pickVoice(s):e.pickBestVoice(s));n.rate!==void 0&&(r.rate=n.rate),n.pitch!==void 0&&(r.pitch=n.pitch),setTimeout(()=>o.speak(r),50)}static pickBestVoice(t){var o;let n=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of n){let s=t.find(a=>a.name===r);if(s)return s}return(o=t.find(r=>r.lang.startsWith("en")))!=null?o:t[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{var f,u,g,m,C,v,M,I,R,P,D,W,w;if(s!==o)return r;let a={...r,...n};if(((f=r.agentMetadata)==null?void 0:f.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let x=r.approval,E=n.approval;a.approval={...x,...E,executionId:E.executionId||x.executionId,toolName:E.toolName||x.toolName,description:E.description||x.description,toolType:(u=E.toolType)!=null?u:x.toolType,reason:(g=E.reason)!=null?g:x.reason,parameters:(m=E.parameters)!=null?m:x.parameters}}let i=(C=n.toolCall)==null?void 0:C.name,d=(v=n.agentMetadata)==null?void 0:v.executionId,l=(M=n.toolCall)==null?void 0:M.id;if(i&&fs(i)&&d&&l&&((I=n.agentMetadata)==null?void 0:I.awaitingLocalTool)===!0){let x=`${d}:${l}`,E=this.webMcpInflightKeys.has(x),S=this.webMcpResolvedKeys.has(x),k=(R=r.toolCall)==null?void 0:R.name,V=((P=r.agentMetadata)==null?void 0:P.executionId)===d&&((D=r.toolCall)==null?void 0:D.id)===l&&k!==void 0&&fs(k)&&((W=r.toolCall)==null?void 0:W.status)==="complete";(E||S||V)&&(a.agentMetadata={...(w=a.agentMetadata)!=null?w:{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{var d,l;let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=(d=n.sequence)!=null?d:0,i=(l=o.sequence)!=null?l:0;return a!==i?a-i:n.id.localeCompare(o.id)})}};var b=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Oo=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o};var A=require("lucide"),db={activity:A.Activity,"arrow-down":A.ArrowDown,"arrow-up":A.ArrowUp,"arrow-up-right":A.ArrowUpRight,bot:A.Bot,"chevron-down":A.ChevronDown,"chevron-up":A.ChevronUp,"chevron-right":A.ChevronRight,"chevron-left":A.ChevronLeft,check:A.Check,clipboard:A.Clipboard,"clipboard-copy":A.ClipboardCopy,copy:A.Copy,file:A.File,"file-code":A.FileCode,"file-spreadsheet":A.FileSpreadsheet,"file-text":A.FileText,"image-plus":A.ImagePlus,loader:A.Loader,"loader-circle":A.LoaderCircle,mic:A.Mic,paperclip:A.Paperclip,"refresh-cw":A.RefreshCw,search:A.Search,send:A.Send,"shield-alert":A.ShieldAlert,"shield-check":A.ShieldCheck,"shield-x":A.ShieldX,square:A.Square,"thumbs-down":A.ThumbsDown,"thumbs-up":A.ThumbsUp,upload:A.Upload,"volume-2":A.Volume2,x:A.X,user:A.User,mail:A.Mail,phone:A.Phone,calendar:A.Calendar,clock:A.Clock,building:A.Building,"map-pin":A.MapPin,lock:A.Lock,key:A.Key,"credit-card":A.CreditCard,"at-sign":A.AtSign,hash:A.Hash,globe:A.Globe,link:A.Link,"circle-check":A.CircleCheck,"circle-x":A.CircleX,"triangle-alert":A.TriangleAlert,info:A.Info,ban:A.Ban,shield:A.Shield,"arrow-left":A.ArrowLeft,"arrow-right":A.ArrowRight,"external-link":A.ExternalLink,ellipsis:A.Ellipsis,"ellipsis-vertical":A.EllipsisVertical,menu:A.Menu,house:A.House,plus:A.Plus,minus:A.Minus,pencil:A.Pencil,trash:A.Trash,"trash-2":A.Trash2,save:A.Save,download:A.Download,share:A.Share,funnel:A.Funnel,settings:A.Settings,"rotate-cw":A.RotateCw,maximize:A.Maximize,minimize:A.Minimize,"shopping-cart":A.ShoppingCart,"shopping-bag":A.ShoppingBag,package:A.Package,truck:A.Truck,tag:A.Tag,gift:A.Gift,receipt:A.Receipt,wallet:A.Wallet,store:A.Store,"dollar-sign":A.DollarSign,percent:A.Percent,play:A.Play,pause:A.Pause,"volume-x":A.VolumeX,camera:A.Camera,image:A.Image,film:A.Film,headphones:A.Headphones,"message-circle":A.MessageCircle,"message-square":A.MessageSquare,bell:A.Bell,heart:A.Heart,star:A.Star,eye:A.Eye,"eye-off":A.EyeOff,bookmark:A.Bookmark,"calendar-days":A.CalendarDays,history:A.History,timer:A.Timer,folder:A.Folder,"folder-open":A.FolderOpen,files:A.Files,sparkles:A.Sparkles,zap:A.Zap,sun:A.Sun,moon:A.Moon,flag:A.Flag,monitor:A.Monitor,smartphone:A.Smartphone},Me=(e,t=24,n="currentColor",o=2)=>{let r=db[e];return r?pb(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 pb(e,t,n,o){if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,f])=>{l!=="stroke"&&d.setAttribute(l,String(f))}),r.appendChild(d)}),r}var Hi={allowedTypes:Jo,maxFileSize:10*1024*1024,maxFiles:4};function ub(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function mb(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 va=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,o,r;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Hi.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:Hi.maxFileSize,maxFiles:(r=t.maxFiles)!=null?r:Hi.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:Hi.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,o,r,s,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(o=(n=this.config).onFileRejected)==null||o.call(n,l,"count");continue}let f=Vm(l,this.config.allowedTypes,this.config.maxFileSize);if(!f.valid){let u=(r=f.error)!=null&&r.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,u);continue}try{let u=await _m(l),g=Ri(l)?URL.createObjectURL(l):null,m={id:ub(),file:l,previewUrl:g,contentPart:u};this.attachments.push(m),this.renderPreview(m)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let o of this.attachments)o.previewUrl&&URL.revokeObjectURL(o.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Ri(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=mb(t.file.type),d=Me(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=b("span");l.textContent=$m(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=Me("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})}};var jm=require("idiomorph"),Di=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;jm.Idiomorph.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 Fi={index:-1,draft:""};function Km(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:{...Fi}}}function Gm(e,t){var n,o,r,s,a,i,d,l,f,u,g,m,C,v,M,I,R,P,D,W,w,x,E,S,k,V,z,Y,he,me,de,Ee,xe,De,Ae,le,J,se;return[e.id,e.role,(o=(n=e.content)==null?void 0:n.length)!=null?o:0,(s=(r=e.content)==null?void 0:r.slice(-32))!=null?s:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(f=(l=e.llmContent)==null?void 0:l.length)!=null?f:0,(g=(u=e.approval)==null?void 0:u.status)!=null?g:"",(C=(m=e.toolCall)==null?void 0:m.status)!=null?C:"",(M=(v=e.toolCall)==null?void 0:v.name)!=null?M:"",(P=(R=(I=e.toolCall)==null?void 0:I.chunks)==null?void 0:R.length)!=null?P:0,(x=(w=(W=(D=e.toolCall)==null?void 0:D.chunks)==null?void 0:W[e.toolCall.chunks.length-1])==null?void 0:w.slice(-32))!=null?x:"",typeof((E=e.toolCall)==null?void 0:E.args)=="string"?e.toolCall.args.length:(S=e.toolCall)!=null&&S.args?JSON.stringify(e.toolCall.args).length:0,(z=(V=(k=e.reasoning)==null?void 0:k.chunks)==null?void 0:V.length)!=null?z:0,(de=(me=(he=(Y=e.reasoning)==null?void 0:Y.chunks)==null?void 0:he[e.reasoning.chunks.length-1])==null?void 0:me.length)!=null?de:0,(Ae=(De=(xe=(Ee=e.reasoning)==null?void 0:Ee.chunks)==null?void 0:xe[e.reasoning.chunks.length-1])==null?void 0:De.slice(-32))!=null?Ae:"",(J=(le=e.contentParts)==null?void 0:le.length)!=null?J:0,(se=e.stopReason)!=null?se:"",t].join("\0")}function Ym(){return new Map}function Xm(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function Jm(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Qm(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Oi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Qo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Vr(e,t){return Qo(e)-e.scrollTop<=t}function Ni(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,f=n-o;return a||Math.abs(f)<s?{action:"none",delta:f,nextLastScrollTop:n}:!t&&r&&(!l||f>0)?{action:"resume",delta:f,nextLastScrollTop:n}:t&&i&&f<0?{action:"pause",delta:f,nextLastScrollTop:n}:t&&d&&!r?{action:"pause",delta:f,nextLastScrollTop:n}:{action:"none",delta:f,nextLastScrollTop:n}}function _i(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function Zm(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function ef(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function tf(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var En={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Mn=1e5,gr=Mn+1;var xa={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},fb=["pre","code","a","script","style"],Vi=e=>{var t,n,o,r,s;return{type:(t=e==null?void 0:e.type)!=null?t:xa.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:xa.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:xa.speed,duration:(r=e==null?void 0:e.duration)!=null?r:xa.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:xa.buffer}},gb=[{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"}],of=new Map;for(let e of gb)of.set(e.name,e);var wa=(e,t)=>{var n,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(o=of.get(e))!=null?o:null},$i=(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},hb=(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},bb=(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},Zl=/\s/,yb=(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},vb=(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(Zl.test(s[i])){let l=i;for(;l<s.length&&Zl.test(s[l]);)l+=1;a.appendChild(o.createTextNode(s.slice(i,l))),i=l}else{let l=o.createElement("span");l.className="persona-stream-word-group";let f=i;for(;f<s.length&&!Zl.test(s[f]);)l.appendChild(hb(o,s[f],t,n.value)),n.value+=1,f+=1;a.appendChild(l),i=f}r.replaceChild(a,e)},xb=(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(bb(o,l,t,n.value)),n.value+=1));r.replaceChild(a,e)},Ca=(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:fb).map(m=>m.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)yb(d,s)||i.push(d),d=a.nextNode();let l={value:(g=o==null?void 0:o.startIndex)!=null?g:0},f=t==="char"?vb:xb;for(let m of i)f(m,n,l);return r.innerHTML},Ui=(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},Sa=(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},nf=new WeakMap,wb=(e,t)=>{var s;if(!e.styles)return;let n=nf.get(t);if(n||(n=new Set,nf.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)},ec=new WeakMap,Cb=(e,t)=>{if(!e.onAttach)return;let n=ec.get(t);if(n||(n=new Map,ec.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},rf=e=>{let t=ec.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},tc=(e,t)=>{wb(e,t),Cb(e,t)};function nc(e,t=Mn){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 Aa=0,hr=null;function oc(e=document){var n;if(Aa++,Aa===1){let o=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;hr={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,Aa=Math.max(0,Aa-1),Aa===0&&hr)){let r=e.body,s=(o=e.defaultView)!=null?o:window;r.style.overflow=hr.originalOverflow,r.style.position=hr.originalPosition,r.style.top=hr.originalTop,r.style.width=hr.originalWidth,s.scrollTo(0,hr.scrollY),hr=null}}}var zi={side:"right",width:"420px",animate:!0,reveal:"resize"},wn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},Ta=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},No=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:zi.side,width:(r=t==null?void 0:t.width)!=null?r:zi.width,animate:(s=t==null?void 0:t.animate)!=null?s:zi.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:zi.reveal}};var Eo={"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 ka=(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 la=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
20
20
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
21
21
|
</span>
|
|
22
22
|
<span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
23
|
-
`,n.addEventListener("click",t);let o=s=>{var W,D,B,x,w,E,S,T,_,U,Y,he,fe;let a=(W=s.launcher)!=null?W:{},i=bn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let ae=(D=a.title)!=null?D:"Chat Assistant";d.textContent=ae,d.setAttribute("title",ae)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let ae=(B=a.subtitle)!=null?B:"Get answers fast";l.textContent=ae,l.setAttribute("title",ae)}let m=n.querySelector(".persona-flex-col");m&&(a.textHidden||i?m.style.display="none":m.style.display="");let p=n.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let ae=(x=a.agentIconSize)!=null?x:"40px";if(p.style.height=ae,p.style.width=ae,p.innerHTML="",a.agentIconName){let Ee=parseFloat(ae)||24,ye=Me(a.agentIconName,Ee*.6,"var(--persona-text-inverse, #ffffff)",2);ye?(p.appendChild(ye),p.style.display=""):(p.textContent=(w=a.agentIconText)!=null?w:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(E=a.agentIconText)!=null?E:"\u{1F4AC}",p.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let ae=(S=a.agentIconSize)!=null?S:"40px";f.style.height=ae,f.style.width=ae,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 ae=(T=a.callToActionIconSize)!=null?T:"32px";u.style.height=ae,u.style.width=ae,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 Ee=0;if(a.callToActionIconPadding?(u.style.boxSizing="border-box",u.style.padding=a.callToActionIconPadding,Ee=(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 ye=parseFloat(ae)||24,Oe=Math.max(ye-Ee,8),we=Me(a.callToActionIconName,Oe,"currentColor",2);we?u.appendChild(we):u.textContent=(_=a.callToActionIconText)!=null?_:"\u2197"}else u.textContent=(U=a.callToActionIconText)!=null?U:"\u2197"}let C=a.position&&Mo[a.position]?Mo[a.position]:Mo["bottom-right"],v="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",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:`${v} ${C}`,i||(n.style.zIndex=String((Y=a.zIndex)!=null?Y:Cn));let I="1px solid var(--persona-border, #e5e7eb)",R="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(he=a.border)!=null?he:I,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow: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=(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 zh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Fi=(e,t={})=>{var v,M,I,R,W,D;let{showClose:n=!0,wrapperClassName:o=zh,buttonSize:r,iconSize:s="28px"}=t,a=(v=e==null?void 0:e.launcher)!=null?v:{},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",p=(R=a.closeButtonShowTooltip)!=null?R:!0;l.setAttribute("aria-label",m),l.style.display=n?"":"none";let f=(W=a.closeButtonIconName)!=null?W:"x",u=(D=a.closeButtonIconText)!=null?D:"\xD7";l.style.color=a.closeButtonColor||Rn.actionIconColor;let C=Me(f,s,"currentColor",1);if(C?(C.style.display="block",l.appendChild(C)):l.textContent=u,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let B=a.closeButtonBorderWidth||"0px",x=a.closeButtonBorderColor||"transparent";l.style.border=`${B} solid ${x}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),p&&m){let B=null,x=()=>{if(B)return;let E=l.ownerDocument,S=E.body;if(!S)return;B=Wo(E,"div","persona-clear-chat-tooltip"),B.textContent=m;let T=Wo(E,"div");T.className="persona-clear-chat-tooltip-arrow",B.appendChild(T);let _=l.getBoundingClientRect();B.style.position="fixed",B.style.zIndex=String(lr),B.style.left=`${_.left+_.width/2}px`,B.style.top=`${_.top-8}px`,B.style.transform="translate(-50%, -100%)",S.appendChild(B)},w=()=>{B&&B.parentNode&&(B.parentNode.removeChild(B),B=null)};d.addEventListener("mouseenter",x),d.addEventListener("mouseleave",w),l.addEventListener("focus",x),l.addEventListener("blur",w),d._cleanupTooltip=()=>{w(),d.removeEventListener("mouseenter",x),d.removeEventListener("mouseleave",w),l.removeEventListener("focus",x),l.removeEventListener("blur",w)}}return{button:l,wrapper:d}},qh="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Oi=(e,t={})=>{var B,x,w,E,S,T,_,U,Y,he,fe,ae,Ee;let{wrapperClassName:n=qh,buttonSize:o,iconSize:r="20px"}=t,a=(x=((B=e==null?void 0:e.launcher)!=null?B:{}).clearChat)!=null?x:{},i=(w=o!=null?o:a.size)!=null?w:"32px",d=(E=a.iconName)!=null?E:"refresh-cw",l=(S=a.iconColor)!=null?S:"",m=(T=a.backgroundColor)!=null?T:"",p=(_=a.borderWidth)!=null?_:"",f=(U=a.borderColor)!=null?U:"",u=(Y=a.borderRadius)!=null?Y:"",C=(he=a.paddingX)!=null?he:"",v=(fe=a.paddingY)!=null?fe:"",M=(ae=a.tooltipText)!=null?ae:"Clear chat",I=(Ee=a.showTooltip)!=null?Ee:!0,R=b("div",n),W=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");W.style.height=i,W.style.width=i,W.type="button",W.setAttribute("aria-label",M),W.style.color=l||Rn.actionIconColor;let D=Me(d,r,"currentColor",1);if(D&&(D.style.display="block",W.appendChild(D)),m&&(W.style.backgroundColor=m,W.classList.remove("hover:persona-bg-gray-100")),p||f){let ye=p||"0px",Oe=f||"transparent";W.style.border=`${ye} solid ${Oe}`,W.classList.remove("persona-border-none")}if(u&&(W.style.borderRadius=u,W.classList.remove("persona-rounded-full")),C&&(W.style.paddingLeft=C,W.style.paddingRight=C),v&&(W.style.paddingTop=v,W.style.paddingBottom=v),R.appendChild(W),I&&M){let ye=null,Oe=()=>{if(ye)return;let K=W.ownerDocument,pe=K.body;if(!pe)return;ye=Wo(K,"div","persona-clear-chat-tooltip"),ye.textContent=M;let G=Wo(K,"div");G.className="persona-clear-chat-tooltip-arrow",ye.appendChild(G);let ve=W.getBoundingClientRect();ye.style.position="fixed",ye.style.zIndex=String(lr),ye.style.left=`${ve.left+ve.width/2}px`,ye.style.top=`${ve.top-8}px`,ye.style.transform="translate(-50%, -100%)",pe.appendChild(ye)},we=()=>{ye&&ye.parentNode&&(ye.parentNode.removeChild(ye),ye=null)};R.addEventListener("mouseenter",Oe),R.addEventListener("mouseleave",we),W.addEventListener("focus",Oe),W.addEventListener("blur",we),R._cleanupTooltip=()=>{we(),R.removeEventListener("mouseenter",Oe),R.removeEventListener("mouseleave",we),W.removeEventListener("focus",Oe),W.removeEventListener("blur",we)}}return{button:W,wrapper:R}};var Rn={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))"},Br=e=>{var B,x,w,E,S,T,_,U,Y,he,fe,ae,Ee,ye,Oe,we;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=(x=r.headerIconSize)!=null?x:"48px",a=(w=r.closeButtonPlacement)!=null?w:"inline",i=(E=r.headerIconHidden)!=null?E:!1,d=r.headerIconName,l=b("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let K=parseFloat(s)||24,pe=Me(d,K*.6,"currentColor",1);pe?l.replaceChildren(pe):l.textContent=(T=(S=t==null?void 0:t.launcher)==null?void 0:S.agentIconText)!=null?T:"\u{1F4AC}"}else if((_=t==null?void 0:t.launcher)!=null&&_.iconUrl){let K=b("img");K.src=t.launcher.iconUrl,K.alt="",K.className="persona-rounded-xl persona-object-cover",K.style.height=s,K.style.width=s,l.replaceChildren(K)}else l.textContent=(Y=(U=t==null?void 0:t.launcher)==null?void 0:U.agentIconText)!=null?Y:"\u{1F4AC}";let m=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),p=b("span","persona-text-base persona-font-semibold");p.style.color=Rn.titleColor,p.textContent=(fe=(he=t==null?void 0:t.launcher)==null?void 0:he.title)!=null?fe:"Chat Assistant";let f=b("span","persona-text-xs");f.style.color=Rn.subtitleColor,f.textContent=(Ee=(ae=t==null?void 0:t.launcher)==null?void 0:ae.subtitle)!=null?Ee:"Here to help you get answers fast",m.append(p,f),i?o.append(m):o.append(l,m);let u=(ye=r.clearChat)!=null?ye:{},C=(Oe=u.enabled)!=null?Oe:!0,v=(we=u.placement)!=null?we:"inline",M=null,I=null;if(C){let pe=Oi(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=pe.button,I=pe.wrapper,v==="top-right"&&(I.style.right="48px"),v==="inline"&&o.appendChild(I)}let R=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":C&&v==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:W,wrapper:D}=Fi(t,{showClose:n,wrapperClassName:R});return a!=="top-right"&&o.appendChild(D),{header:o,iconHolder:l,headerTitle:p,headerSubtitle:f,closeButton:W,closeButtonWrapper:D,clearChatButton:M,clearChatButtonWrapper:I}},va=(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 is(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(lr)):(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 C=document.createElement("button");if(C.type="button",C.setAttribute("role","menuitem"),C.setAttribute("data-dropdown-item-id",u.id),u.destructive&&C.setAttribute("data-destructive",""),u.icon){let M=Me(u.icon,16,"currentColor",1.5);M&&C.appendChild(M)}let v=document.createElement("span");v.textContent=u.label,C.appendChild(v),C.addEventListener("click",M=>{M.stopPropagation(),m(),n(u.id)}),a.appendChild(C)}let i=null;function d(){if(!s)return;let u=o.getBoundingClientRect();a.style.top=`${u.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-u.right}px`,a.style.left="auto"):(a.style.left=`${u.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let u=C=>{!a.contains(C.target)&&!o.contains(C.target)&&m()};document.addEventListener("click",u,!0),i=()=>document.removeEventListener("click",u,!0)})}function m(){a.classList.add("persona-hidden"),i==null||i(),i=null}function p(){a.classList.contains("persona-hidden")?l():m()}function f(){m(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:m,toggle:p,destroy:f}}function Sn(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=Me(t,o!=null?o:16,"currentColor",r!=null?r:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[m,p]of Object.entries(i))d.setAttribute(m,p);return d}function Kl(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";o!=="default"&&(l+=" persona-label-btn--"+o),l+=" persona-label-btn--"+r,a&&(l+=" "+a);let m=b("button",l);if(m.type="button",m.setAttribute("aria-label",n),t){let f=Me(t,s!=null?s:14,"currentColor",2);f&&m.appendChild(f)}let p=b("span");if(p.textContent=n,m.appendChild(p),i&&m.addEventListener("click",i),d)for(let[f,u]of Object.entries(d))m.setAttribute(f,u);return m}function Rm(e){var u,C;let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:i,hover:d}=e,l=b("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let m=b("span","persona-combo-btn-label");m.textContent=t,l.appendChild(m);let p=Me(n,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",l.appendChild(p)),d&&(l.style.borderRadius=(u=d.borderRadius)!=null?u:"10px",l.style.padding=(C=d.padding)!=null?C:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var v,M;l.style.backgroundColor=(v=d.background)!=null?v:"",l.style.borderColor=(M=d.border)!=null?M:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=is({items:o,onSelect:v=>{l.setAttribute("aria-expanded","false"),r(v)},anchor:l,position:s,portal:a});return a||l.appendChild(f.element),l.addEventListener("click",v=>{v.stopPropagation();let M=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",M?"false":"true"),f.toggle()}),l.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),l.click())}),{element:l,setLabel:v=>{m.textContent=v,l.setAttribute("aria-label",v)},open:()=>{l.setAttribute("aria-expanded","true"),f.show()},close:()=>{l.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let v=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",v?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}var jh=e=>{var o;let t=Br({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 Kh(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=Me(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=is({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 Gh=e=>{var R,W,D,B,x,w,E,S,T;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,m;if(d)l=Rm({label:(W=a.title)!=null?W:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Rn.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=Rn.titleColor,m.textContent=(B=a.title)!=null?B:"Chat Assistant",l.appendChild(m),Kh(l,r==null?void 0:r.trailingActions,(x=r==null?void 0:r.onAction)!=null?x:s),r!=null&&r.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let U=r.onTitleClick;l.addEventListener("click",Y=>{Y.target.closest("button")||U()}),l.addEventListener("keydown",Y=>{(Y.key==="Enter"||Y.key===" ")&&(Y.preventDefault(),U())})}let _=r==null?void 0:r.titleRowHover;_&&(l.style.borderRadius=(w=_.borderRadius)!=null?w:"10px",l.style.padding=(E=_.padding)!=null?E:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var U,Y;l.style.backgroundColor=(U=_.background)!=null?U:"",l.style.borderColor=(Y=_.border)!=null?Y:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let p=(S=a.closeButtonSize)!=null?S:"32px",f=b("div",""),u=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");u.style.height=p,u.style.width=p,u.type="button",u.setAttribute("aria-label","Close chat"),u.style.display=n?"":"none",u.style.color=a.closeButtonColor||Rn.actionIconColor;let C=(T=a.closeButtonIconName)!=null?T:"x",v=Me(C,"28px","currentColor",1);v?u.appendChild(v):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:m,headerSubtitle:I,closeButton:u,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Pm={default:jh,minimal:Gh},Yh=e=>{var t;return(t=Pm[e])!=null?t:Pm.default},Ni=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),m=b("div");m.style.display="none";let p=b("span"),f=b("span"),u=b("button");u.style.display="none";let C=b("div");return C.style.display="none",{header:l,iconHolder:m,headerTitle:p,headerSubtitle:f,closeButton:u,closeButtonWrapper:C,clearChatButton:null,clearChatButtonWrapper:null}}let o=(a=t==null?void 0:t.layout)!=null?a:"default",s=Yh(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 _i=e=>{var a,i;let t=b("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;t.style.maxHeight=`${n*o}px`,t.style.overflowY="auto";let r=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*o},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,r());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},Vi=e=>{var B,x,w,E,S,T,_,U,Y,he,fe,ae;let t=(B=e==null?void 0:e.sendButton)!=null?B:{},n=(x=t.useIcon)!=null?x:!1,o=(w=t.iconText)!=null?w:"\u2191",r=t.iconName,s=(E=t.stopIconName)!=null?E:"square",a=(S=t.tooltipText)!=null?S:"Send message",i=(T=t.stopTooltipText)!=null?T:"Stop generating",d=(U=(_=e==null?void 0:e.copy)==null?void 0:_.sendButtonLabel)!=null?U:"Send",l=(he=(Y=e==null?void 0:e.copy)==null?void 0:Y.stopButtonLabel)!=null?he:"Stop",m=(fe=t.showTooltip)!=null?fe:!1,p=(ae=t.size)!=null?ae:"40px",f=t.backgroundColor,u=t.textColor,C=b("div","persona-send-button-wrapper"),v=b("button",n?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");v.type="submit",v.setAttribute("data-persona-composer-submit","");let M=null,I=null;if(n){v.style.width=p,v.style.height=p,v.style.minWidth=p,v.style.minHeight=p,v.style.fontSize="18px",v.style.lineHeight="1",v.innerHTML="",u?v.style.color=u:v.style.color="var(--persona-button-primary-fg, #ffffff)";let Ee=parseFloat(p)||24,ye=(u==null?void 0:u.trim())||"currentColor";r?(M=Me(r,Ee,ye,2),M?v.appendChild(M):v.textContent=o):v.textContent=o,I=Me(s,Ee,ye,2),f?v.style.backgroundColor=f:v.classList.add("persona-bg-persona-primary")}else v.textContent=d,u?v.style.color=u:v.classList.add("persona-text-white");t.borderWidth&&(v.style.borderWidth=t.borderWidth,v.style.borderStyle="solid"),t.borderColor&&(v.style.borderColor=t.borderColor),t.paddingX?(v.style.paddingLeft=t.paddingX,v.style.paddingRight=t.paddingX):(v.style.paddingLeft="",v.style.paddingRight=""),t.paddingY?(v.style.paddingTop=t.paddingY,v.style.paddingBottom=t.paddingY):(v.style.paddingTop="",v.style.paddingBottom="");let R=null;m&&a&&(R=b("div","persona-send-button-tooltip"),R.textContent=a,C.appendChild(R)),v.setAttribute("aria-label",a),C.appendChild(v);let W="send";return{button:v,wrapper:C,setMode:Ee=>{if(Ee===W)return;W=Ee;let ye=Ee==="stop"?i:a;if(v.setAttribute("aria-label",ye),R&&(R.textContent=ye),n){if(M&&I){let Oe=Ee==="stop"?I:M;v.replaceChildren(Oe)}}else v.textContent=Ee==="stop"?l:d}}},$i=e=>{var R,W,D,B,x,w,E,S,T,_,U,Y;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=((W=t.provider)==null?void 0:W.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=(x=t.iconName)!=null?x:"mic",m=(w=t.iconSize)!=null?w:a,p=parseFloat(m)||24,f=(S=t.backgroundColor)!=null?S:(E=e==null?void 0:e.sendButton)==null?void 0:E.backgroundColor,u=(_=t.iconColor)!=null?_:(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",u?d.style.color=u:d.style.color="var(--persona-text, #111827)";let v=Me(l,p,u||"currentColor",1.5);v?d.appendChild(v):d.textContent="\u{1F3A4}",f&&(d.style.backgroundColor=f),t.borderWidth&&(d.style.borderWidth=t.borderWidth,d.style.borderStyle="solid"),t.borderColor&&(d.style.borderColor=t.borderColor),t.paddingX&&(d.style.paddingLeft=t.paddingX,d.style.paddingRight=t.paddingX),t.paddingY&&(d.style.paddingTop=t.paddingY,d.style.paddingBottom=t.paddingY),i.appendChild(d);let M=(U=t.tooltipText)!=null?U:"Start voice recognition";if(((Y=t.showTooltip)!=null?Y:!1)&&M){let he=b("div","persona-send-button-tooltip");he.textContent=M,i.appendChild(he)}return{button:d,wrapper:i}},Ui=e=>{var C,v,M,I,R,W,D,B;let t=(C=e==null?void 0:e.attachments)!=null?C:{};if(t.enabled!==!0)return null;let n=(M=(v=e==null?void 0:e.sendButton)==null?void 0:v.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:qo).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",(W=t.buttonTooltipText)!=null?W:"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 p=Me(i,m,"currentColor",1.5);p?a.appendChild(p):a.textContent="\u{1F4CE}",a.addEventListener("click",x=>{x.preventDefault(),r.click()}),s.appendChild(a);let f=(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}},zi=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},qi=()=>b("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var ji=e=>{var C,v,M,I,R,W;let{config:t}=e,n=b("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");n.setAttribute("data-persona-theme-zone","composer");let o=qi(),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}=_i(t);a();let i=Vi(t),d=$i(t),l=Ui(t),m=zi(t);l&&(l.previewsContainer.style.gap="8px",r.append(l.previewsContainer,l.input)),r.append(s);let p=b("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),f=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),u=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&f.append(l.wrapper),d&&u.append(d.wrapper),u.append(i.wrapper),p.append(f,u),r.append(p),r.addEventListener("click",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:(C=d==null?void 0:d.button)!=null?C:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v: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:(R=l==null?void 0:l.input)!=null?R:null,attachmentPreviewsContainer:(W=l==null?void 0:l.previewsContainer)!=null?W:null,actionsRow:p,leftActions:f,rightActions:u,setSendButtonMode:i.setMode}};var Wm=()=>{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=Me("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=Me("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},Bm=e=>{var C,v,M,I,R,W;let{config:t}=e,n=b("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let o=qi();o.style.display="none";let r=zi(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=_i(t);s.style.maxHeight="100px",a();let i=Vi(t),d=$i(t),l=Ui(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let m=b("form","persona-widget-composer persona-pill-composer");m.setAttribute("data-persona-composer-form",""),m.style.outline="none";let p=b("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&p.append(l.wrapper);let f=b("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),m.addEventListener("click",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(p,s,f),l&&n.append(l.previewsContainer),n.append(m,o,r);let u=m;return{footer:n,suggestions:o,composerForm:m,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(C=d==null?void 0:d.button)!=null?C:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:r,attachmentButton:(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:(W=l==null?void 0:l.previewsContainer)!=null?W:null,actionsRow:u,leftActions:p,rightActions:f,setSendButtonMode:i.setMode}};var Hm=e=>{var m,p,f,u,C,v,M,I,R,W,D,B,x,w,E,S,T;let t=(p=(m=e==null?void 0:e.launcher)==null?void 0:m.enabled)!=null?p:!0,n=bn(e);if(ba(e)){let _=(u=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?u:{},U=b("div","persona-widget-wrapper persona-fixed persona-transition");U.setAttribute("data-persona-composer-bar",""),U.dataset.state="collapsed",U.dataset.expandedSize=(C=_.expandedSize)!=null?C:"anchored",U.style.zIndex=String((M=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?M:Cn);let Y=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Y.style.width="100%",U.appendChild(Y);let he=b("div","persona-widget-pill-root");return he.setAttribute("data-persona-composer-bar",""),he.dataset.state="collapsed",he.dataset.expandedSize=(I=_.expandedSize)!=null?I:"anchored",he.style.zIndex=String((W=(R=e==null?void 0:e.launcher)==null?void 0:R.zIndex)!=null?W:Cn),{wrapper:U,panel:Y,pillRoot:he}}if(n){let _=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),U=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return _.appendChild(U),{wrapper:_,panel:U}}if(!t){let _=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),U=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Y=(B=(D=e==null?void 0:e.launcher)==null?void 0:D.width)!=null?B:"100%";return _.style.width=Y,U.style.width="100%",_.appendChild(U),{wrapper:_,panel:U}}let r=(x=e==null?void 0:e.launcher)!=null?x:{},s=r.position&&Mo[r.position]?Mo[r.position]:Mo["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((E=(w=e==null?void 0:e.launcher)==null?void 0:w.zIndex)!=null?E:Cn);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(T=(S=e==null?void 0:e.launcher)==null?void 0:S.width)!=null?T:e==null?void 0:e.launcherWidth,l=d!=null?d:fo;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Xh=(e,t)=>{var D,B,x,w,E,S,T,_,U;let n=b("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=Fi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=(x=(B=(D=e==null?void 0:e.launcher)==null?void 0:D.clearChat)==null?void 0:B.enabled)!=null?x:!0,a=null,i=null;if(s){let Y=Oi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=Y.button,i=Y.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=b("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=b("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let m=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");m.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",m.setAttribute("data-persona-intro-card","");let p=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");p.textContent=(E=(w=e==null?void 0:e.copy)==null?void 0:w.welcomeTitle)!=null?E:"Hello \u{1F44B}";let f=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(T=(S=e==null?void 0:e.copy)==null?void 0:S.welcomeSubtitle)!=null?T:"Ask anything about your account or products.",m.append(p,f);let u=b("div","persona-flex persona-flex-col persona-gap-3"),C=(_=e==null?void 0:e.layout)==null?void 0:_.contentMaxWidth;C&&(u.style.maxWidth=C,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),((U=e==null?void 0:e.copy)==null?void 0:U.showWelcomeCard)!==!1||(m.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(m,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=Bm({config:e}),{root:R,textNode:W}=Wm();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:p,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:W}},Dm=(e,t=!0)=>{var M,I,R,W,D,B,x,w,E;if(ba(e))return Xh(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?Ni(e,o,{showClose:t}):Br({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=bn(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(W=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeTitle)!=null?W:"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 m=b("div","persona-flex persona-flex-col persona-gap-3"),p=(x=e==null?void 0:e.layout)==null?void 0:x.contentMaxWidth;p&&(m.style.maxWidth=p,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((w=e==null?void 0:e.copy)==null?void 0:w.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,m);let u=ji({config:e}),C=((E=e==null?void 0:e.layout)==null?void 0:E.showFooter)!==!1;r?va(n,s,e):(s.header.style.display="none",va(n,s,e)),n.append(a);let v=b("div","persona-composer-overlay persona-pointer-events-none");return v.setAttribute("data-persona-composer-overlay",""),v.style.position="absolute",v.style.left="0",v.style.right="0",v.style.bottom="0",v.style.zIndex="20",C||(u.footer.style.display="none"),n.append(u.footer),n.append(v),{container:n,body:a,messagesWrapper:m,composerOverlay:v,suggestions:u.suggestions,textarea:u.textarea,sendButton:u.sendButton,sendButtonWrapper:u.sendButtonWrapper,micButton:u.micButton,micButtonWrapper:u.micButtonWrapper,composerForm:u.composerForm,statusText:u.statusText,introTitle:d,introSubtitle:l,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:u.footer,attachmentButton:u.attachmentButton,attachmentButtonWrapper:u.attachmentButtonWrapper,attachmentInput:u.attachmentInput,attachmentPreviewsContainer:u.attachmentPreviewsContainer,actionsRow:u.actionsRow,leftActions:u.leftActions,rightActions:u.rightActions,setSendButtonMode:u.setSendButtonMode}};var Qh=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}},Jh=(e,t)=>{if(!e)return null;let n=Qh(e);if(n===null)return null;let o=t==null?void 0:t[e],r=o!==void 0?o:n;return r||null},Zh=(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},eb=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Gl=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Yl=320,Om=320,tb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),nb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),ob=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),rb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),sb=(e,t,n)=>{if(e.length===0)return null;try{let o=b("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n==null||n())};return e.forEach((i,d)=>{var p;let l=b("img");l.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${Yl}px`,l.style.maxHeight=`${Om}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}),eb(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}},ab=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!Gl(o.audio))return;let r=b("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Yl}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ib=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!Gl(o.video))return;let r=b("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Yl}px`,r.style.maxHeight=`${Om}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}},lb=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!Gl(o.data))return;let r=b("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},xa=()=>{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},cb=(e,t,n)=>{let o={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:xa};if(t){let r=t(o);if(r!==null)return r}return xa()},db=(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},Fm=(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},pb=(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},ub=(e,t,n)=>{var u,C,v,M,I,R;let o=(u=t.showCopy)!=null?u:!0,r=(C=t.showUpvote)!=null?C:!0,s=(v=t.showDownvote)!=null?v:!0;if(!o&&!r&&!s){let W=b("div");return W.style.display="none",W.id=`actions-${e.id}`,W.setAttribute("data-actions-for",e.id),W}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],m={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${m} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let f=(W,D,B)=>{let x=Sn({icon:W,label:D,size:14,className:"persona-message-action-btn"});return x.setAttribute("data-action",B),x};return o&&p.appendChild(f("copy","Copy message","copy")),r&&p.appendChild(f("thumbs-up","Upvote","upvote")),s&&p.appendChild(f("thumbs-down","Downvote","downvote")),p},Xl=(e,t,n,o,r,s)=>{var K,pe,G,ve,ce,ne,Se,ze,te,re,ie,st,Te,ue,Ue,Be,me;let a=n!=null?n:{},i=(K=a.layout)!=null?K:"bubble",d=a.avatar,l=a.timestamp,m=(pe=d==null?void 0:d.show)!=null?pe:!1,p=(G=l==null?void 0:l.show)!=null?G:!1,f=(ve=d==null?void 0:d.position)!=null?ve:"left",u=(ce=l==null?void 0:l.position)!=null?ce:"below",C=pb(e.role,i),v=b("div",C.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let M=tb(e),I=(Se=(ne=e.content)==null?void 0:ne.trim())!=null?Se:"",W=M.length>0&&I===Ci,D=Wi((te=(ze=s==null?void 0:s.widgetConfig)==null?void 0:ze.features)==null?void 0:te.streamAnimation),B=(st=(ie=(re=s==null?void 0:s.widgetConfig)==null?void 0:re.features)==null?void 0:ie.streamAnimation)==null?void 0:st.plugins,x=e.role==="assistant"&&D.type!=="none"?ma(D.type,B):null,w=e.role==="assistant"&&((Te=x==null?void 0:x.isAnimating)==null?void 0:Te.call(x,e))===!0,E=e.role==="assistant"&&x!==null&&(!!e.streaming||w);E&&(x!=null&&x.bubbleClass)&&v.classList.add(x.bubbleClass);let S=document.createElement("div");S.classList.add("persona-message-content"),E&&x&&(x.containerClass&&S.classList.add(x.containerClass),S.style.setProperty("--persona-stream-step",`${D.speed}ms`),S.style.setProperty("--persona-stream-duration",`${D.duration}ms`));let T=E?Bi((ue=e.content)!=null?ue:"",D.buffer,x,e,!!e.streaming):(Ue=e.content)!=null?Ue:"",_=t({text:T,message:e,streaming:!!e.streaming,raw:e.rawContent}),U=_;E&&(x==null?void 0:x.wrap)==="char"?U=ga(_,"char",e.id,{skipTags:x.skipTags}):E&&(x==null?void 0:x.wrap)==="word"&&(U=ga(_,"word",e.id,{skipTags:x.skipTags}));let Y=null;if(W?(Y=document.createElement("div"),Y.innerHTML=U,Y.style.display="none",S.appendChild(Y)):S.innerHTML=U,E&&(x!=null&&x.useCaret)&&!W&&I){let Q=Hi(),_e=S.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ht=_e[_e.length-1];if(Ht!=null&&Ht.parentNode)Ht.parentNode.insertBefore(Q,Ht.nextSibling);else{let be=S.lastElementChild;be?be.appendChild(Q):S.appendChild(Q)}}if(p&&u==="inline"&&e.createdAt){let Q=Fm(e,l);Q.classList.add("persona-ml-2","persona-inline"),S.appendChild(Q)}if(M.length>0){let Q=sb(M,!W&&!!I,()=>{W&&Y&&(Y.style.display="")});Q?v.appendChild(Q):W&&Y&&(Y.style.display="")}let he=nb(e);if(he.length>0){let Q=ab(he);Q&&v.appendChild(Q)}let fe=ob(e);if(fe.length>0){let Q=ib(fe);Q&&v.appendChild(Q)}let ae=rb(e);if(ae.length>0){let Q=lb(ae);Q&&v.appendChild(Q)}if(v.appendChild(S),p&&u==="below"&&e.createdAt){let Q=Fm(e,l);Q.classList.add("persona-mt-1"),v.appendChild(Q)}let Ee=e.role==="assistant"?Jh(e.stopReason,(me=(Be=s==null?void 0:s.widgetConfig)==null?void 0:Be.copy)==null?void 0:me.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Q=!!(T&&T.trim()),_e=D.placeholder==="skeleton",Ht=_e&&D.buffer==="line"&&Q;if(Q)Ht&&v.appendChild(fa());else if(_e)v.appendChild(fa());else{let be=cb("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);be&&v.appendChild(be)}}if(Ee&&e.stopReason&&!e.streaming&&(I||(S.style.display="none"),v.appendChild(Zh(e.stopReason,Ee))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let Q=ub(e,o,r);v.appendChild(Q)}if(!m||e.role==="system")return v;let Oe=b("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),we=db(d,e.role);return f==="right"||f==="left"&&e.role==="user"?Oe.append(v,we):Oe.append(we,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Oe};var ls=new Set,mb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),gb=(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
|
-
`):""},bb=(e,t)=>{var m,p,f,u,C;let n=e.toolCall,o=(m=t==null?void 0:t.features)==null?void 0:m.toolCallDisplay,r=(p=o==null?void 0:o.collapsedMode)!=null?p:"tool-call",s=hb(e,(f=o==null?void 0:o.previewMaxLines)!=null?f:3),a=n?lm(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(u=t==null?void 0:t.toolCall)!=null?u:{},l=a;return r==="tool-name"?l=((C=n.name)==null?void 0:C.trim())||a:r==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=Ol(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Ol(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},_m=(e,t,n)=>{var m;let o=cs.has(e),r=(m=n==null?void 0:n.toolCall)!=null?m:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let p=r.toggleTextColor||r.headerTextColor||"currentColor",f=Me(o?"chevron-up":"chevron-down",16,p,2);f?l.appendChild(f):l.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},Jl=(e,t)=>{var U,Y,he,fe,ae,Ee,ye,Oe,we;let n=e.toolCall,o=(U=t==null?void 0:t.toolCall)!=null?U:{},r=b("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=(he=(Y=t==null?void 0:t.features)==null?void 0:Y.toolCallDisplay)!=null?he:{},a=s.expandable!==!1,i=a&&cs.has(e.id),{summary:d,previewText:l,isActive:m}=bb(e,t),p=b("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");p.type="button",a&&(p.setAttribute("aria-expanded",i?"true":"false"),p.setAttribute("data-expand-header","true")),p.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(p.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(p.style.paddingLeft=o.headerPaddingX,p.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(p.style.paddingTop=o.headerPaddingY,p.style.paddingBottom=o.headerPaddingY);let f=b("div","persona-flex persona-flex-col persona-text-left"),u=b("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(u.style.color=o.headerTextColor);let C=String((fe=n.startedAt)!=null?fe:Date.now()),v=()=>{let K=b("span","");return K.setAttribute("data-tool-elapsed",C),K.textContent=oa(n),K},M=(Ee=o.renderCollapsedSummary)==null?void 0:Ee.call(o,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(ae=s.collapsedMode)!=null?ae:"tool-call",isActive:m,config:t!=null?t:{},elapsed:oa(n),createElapsedElement:v});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=(ye=s.loadingAnimation)!=null?ye:"none",R=o.activeTextTemplate,W=o.completeTextTemplate,D=m?R:W,B=M instanceof HTMLElement,x=(K,pe,G)=>{let ve=G;for(let ce of pe){let ne=b("span","persona-tool-char");ne.style.setProperty("--char-index",String(ve)),ne.textContent=ce===" "?"\xA0":ce,K.appendChild(ne),ve++}return ve},w=(K,pe)=>{var ne;u.textContent="";let G=((ne=n.name)==null?void 0:ne.trim())||"tool",ve=yi(K,G),ce=0;for(let Se of ve){let ze=Se.styles.length>0?(()=>{let te=b("span",Se.styles.map(re=>`persona-tool-text-${re}`).join(" "));return u.appendChild(te),te})():u;if(Se.isDuration&&m)ze.appendChild(v());else{let te=Se.isDuration?oa(n):Se.text;pe?ce=x(ze,te,ce):ze.appendChild(document.createTextNode(te))}}};if(!B)if(m&&I!=="none"){let K=(Oe=o.loadingAnimationDuration)!=null?Oe:2e3;if(u.setAttribute("data-preserve-animation","true"),I==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`),D&&w(D,!1);else if(u.classList.add(`persona-tool-loading-${I}`),u.style.setProperty("--persona-tool-anim-duration",`${K}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)w(D,!0);else{let pe=u.textContent||d;u.textContent="",x(u,pe,0)}}else D&&w(D,!1);let E=null;if(a){E=b("div","persona-flex persona-items-center");let K=o.toggleTextColor||o.headerTextColor||"currentColor",pe=Me(i?"chevron-up":"chevron-down",16,K,2);pe?E.appendChild(pe):E.textContent=i?"Hide":"Show";let G=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");G.append(E),p.append(f,G)}else p.append(f);let S=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(S.setAttribute("data-persona-collapsed-preview","tool"),S.style.display="none",S.style.whiteSpace="pre-wrap",!i&&m&&s.activePreview&&l){let K=(we=o.renderCollapsedPreview)==null?void 0:we.call(o,{message:e,toolCall:n,defaultPreview:l,isActive:m,config:t!=null?t:{}});fb(S,K)||(S.textContent=l),S.style.display=""}if(!i&&m&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(p,S),r;let T=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(T.style.display=i?"":"none",o.contentBackgroundColor&&(T.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(T.style.color=o.contentTextColor),o.contentPaddingX&&(T.style.paddingLeft=o.contentPaddingX,T.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(T.style.paddingTop=o.contentPaddingY,T.style.paddingBottom=o.contentPaddingY),n.name){let K=b("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?K.style.color=o.contentTextColor:o.headerTextColor&&(K.style.color=o.headerTextColor),K.textContent=n.name,T.appendChild(K)}if(n.args!==void 0){let K=b("div","persona-space-y-1"),pe=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(pe.style.color=o.labelTextColor),pe.textContent="Arguments";let G=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");G.style.fontSize="0.75rem",G.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(G.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(G.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(G.style.color=o.codeBlockTextColor),G.textContent=as(n.args),K.append(pe,G),T.appendChild(K)}if(n.chunks&&n.chunks.length){let K=b("div","persona-space-y-1"),pe=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(pe.style.color=o.labelTextColor),pe.textContent="Activity";let G=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");G.style.fontSize="0.75rem",G.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(G.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(G.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(G.style.color=o.codeBlockTextColor),G.textContent=n.chunks.join(""),K.append(pe,G),T.appendChild(K)}if(n.status==="complete"&&n.result!==void 0){let K=b("div","persona-space-y-1"),pe=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(pe.style.color=o.labelTextColor),pe.textContent="Result";let G=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");G.style.fontSize="0.75rem",G.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(G.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(G.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(G.style.color=o.codeBlockTextColor),G.textContent=as(n.result),K.append(pe,G),T.appendChild(K)}if(n.status==="complete"&&typeof n.duration=="number"){let K=b("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(K.style.color=o.contentTextColor),K.textContent=`Duration: ${n.duration}ms`,T.appendChild(K)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),E){E.innerHTML="";let K=o.toggleTextColor||o.headerTextColor||"currentColor",pe=Me(i?"chevron-up":"chevron-down",16,K,2);pe?E.appendChild(pe):E.textContent=i?"Hide":"Show"}T.style.display=i?"":"none",S.style.display=i?"none":S.textContent||S.childNodes.length?"":"none"})(),r.append(p,S,T),r};var dr=require("partial-json");var yb="ask_user_question",Zl=8,ds="data-persona-ask-sheet-for",vb="Other",xb="Other\u2026",$m="Type your own answer here",Um="Send",wb="Next",Cb="Back",Sb="Submit all",Ab="Skip",Tb=3,ec="data-ask-current-index",tc="data-ask-question-count",zm="data-ask-answers",nc="data-ask-grouped",qm="data-ask-layout",kb=e=>e.layout==="pills"?"pills":"rows",Eb=e=>e.getAttribute(qm)==="pills"?"pills":"rows",Vm=!1,jm=e=>e.replace(/["\\]/g,"\\$&"),Hr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===yb,oc=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},ps=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=(0,dr.parse)(r,dr.STR|dr.OBJ|dr.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},wa=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>Zl&&!Vm&&(Vm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Zl}.`)),t.slice(0,Zl)},Mb=e=>{var t;return(t=wa(e)[0])!=null?t:null},Lb=(e,t)=>{var n;return(n=wa(e)[t])!=null?n:null},Ib=(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))},Km=(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},Rb=(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=Km(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Pb=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},Wb=(e,t,n,o)=>{var m,p,f;let s=b("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(u=>u&&typeof u.label=="string"&&u.label.length>0);if(d.length===0&&!n){for(let u=0;u<Tb;u++)s.appendChild(Pb(o));return s}if(d.forEach((u,C)=>{s.appendChild(Rb(u,C,o,a))}),(e==null?void 0:e.allowFreeText)!==!1){let u=o==="rows"?vb:xb;if(o==="rows"){let C=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");C.setAttribute("data-ask-user-action","focus-free-text"),C.setAttribute("data-option-index",String(d.length)),C.setAttribute("data-ask-other-row","true");let v=b("span","persona-ask-row-content"),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:$m,M.setAttribute("data-ask-free-text-input","true"),M.setAttribute("aria-label",(p=t.freeTextLabel)!=null?p:u),v.appendChild(M),C.appendChild(v);let I=Km(o,a,d.length);I&&C.appendChild(I),s.appendChild(C)}else{let C=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");C.type="button",C.setAttribute("data-ask-user-action","open-free-text"),C.textContent=(f=t.freeTextLabel)!=null?f:u,s.appendChild(C)}}return s},Gm=(e,t)=>{var s,a;let o=b("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=(s=e.freeTextPlaceholder)!=null?s:$m,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let i=b("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:Um,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},Bb=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:Um,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Hb=(e,t,n)=>{var l,m,p,f;let o=b("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=b("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=(l=n.backLabel)!=null?l:Cb,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:Ab,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=b("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(p=n.submitAllLabel)!=null?p:Sb:(f=n.nextLabel)!=null?f:wb,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},Dr=e=>{let t=e.getAttribute(zm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Ym=(e,t)=>{e.setAttribute(zm,JSON.stringify(t))},ho=e=>{var n;let t=Number((n=e.getAttribute(ec))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Db=(e,t)=>{e.setAttribute(ec,String(Math.max(0,Math.floor(t))))},us=e=>{var n;let t=Number((n=e.getAttribute(tc))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},pr=e=>e.getAttribute(nc)==="true",Fb=(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},Ob=(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)))},Ki=(e,t)=>{let{payload:n}=ps(t),o=wa(n),r=Dr(e),s={},a=new Set;return o.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(r,d)&&(s[l]=r[d]))}),s},Xm=e=>{let t=Dr(e),n=ho(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(d=>r.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var p;let l=(p=d.getAttribute("data-option-label"))!=null?p:"",m=r.has(l);d.setAttribute("aria-pressed",m?"true":"false"),d.classList.toggle("persona-ask-pill-selected",m)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!a.has(o)){i.value=o;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Qm=e=>{if(!pr(e))return;let t=Dr(e),n=ho(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}},rc=(e,t,n)=>{let o=oc(n),r=Eb(e),{payload:s,complete:a}=ps(t),i=pr(e),d=ho(e),l=us(e),m=i?Lb(s,d):Mb(s),p=!!(m!=null&&m.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let u=e.querySelector('[data-ask-stepper="true"]');u&&u.remove();let C=e.querySelector('[data-ask-question="true"]');if(C){let R=typeof(m==null?void 0:m.question)=="string"?m.question:"";C.textContent=R,C.classList.toggle("persona-ask-question-skeleton",!R&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let R=Wb(m,o,a,r);v.replaceWith(R)}if(r!=="rows"){let R=e.querySelector('[data-ask-free-text-row="true"]');R&&R.replaceWith(Gm(o,r))}let M=e.querySelector('[data-ask-multi-actions="true"]');!i&&p&&!M?e.appendChild(Bb(o)):(!p||i)&&M&&M.remove(),e.setAttribute("data-multi-select",p?"true":"false");let I=e.querySelector('[data-ask-nav-row="true"]');if(i){let R=Hb(d,l,o);I?I.replaceWith(R):e.appendChild(R)}else I&&I.remove();Xm(e),Qm(e)},Nb=(e,t,n)=>{let o=oc(t),r=kb(o),s=e.toolCall.id,a=wa(n),i=Math.max(1,a.length),d=i>1,l=Fb(e,a),m=d?Ob(e,i):0,p=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(ds,s),p.setAttribute("data-tool-call-id",s),p.setAttribute("data-message-id",e.id),p.setAttribute(tc,String(i)),p.setAttribute(ec,String(m)),p.setAttribute(nc,d?"true":"false"),p.setAttribute(qm,r),Ym(p,l),p.setAttribute("role","group"),p.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&p.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Ib(p,o);let f=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),u=b("div","persona-ask-sheet-question persona-flex-1");u.setAttribute("data-ask-question","true"),u.textContent="",f.appendChild(u);let C=b("span","persona-ask-sheet-step-inline");C.setAttribute("data-ask-step-inline","true"),C.textContent="",f.appendChild(C),p.appendChild(f);let M=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),p.appendChild(M),r!=="rows"&&p.appendChild(Gm(o,r)),rc(p,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p},_b=(e,t,n)=>{let{payload:o}=ps(t),r=Math.max(1,wa(o).length);r>us(e)&&(e.setAttribute(tc,String(r)),r>1&&!pr(e)&&e.setAttribute(nc,"true")),rc(e,t,n)};var Gi=(e,t,n)=>{if(!n||!Hr(e)||oc(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${ds}]`).forEach(l=>{l.getAttribute(ds)!==r&&l.remove()});let a=n.querySelector(`[${ds}="${jm(r)}"]`);if(a){_b(a,e,t);return}let{payload:i}=ps(e),d=Nb(e,t,i);n.appendChild(d)},ms=(e,t)=>{if(!e)return;let n=t?`[${ds}="${jm(t)}"]`:`[${ds}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},sc=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),ur=(e,t)=>{let n=Dr(e),o=ho(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Ym(e,n),Xm(e),Qm(e)},Yi=(e,t,n,o)=>{let r=us(e),s=Math.max(0,Math.min(r-1,o));Db(e,s),rc(e,t,n)};var Xi=new Map,Vb=e=>{let n=(e.startsWith(Rr)?e.slice(Rr.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Jm=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Zm=(e,t)=>{var o,r,s;let n=(r=(o=Jm(t))==null?void 0:o.detailsDisplay)!=null?r:"collapsed";return(s=Xi.get(e))!=null?s:n==="expanded"},eg=(e,t,n)=>{var a,i;let o=Jm(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?(a=o==null?void 0:o.hideDetailsLabel)!=null?a:"Hide details":(i=o==null?void 0:o.showDetailsLabel)!=null?i:"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=Me(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},tg=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=Zm(e,n);eg(o,s,n),r.style.display=s?"":"none"};var Qi=(e,t)=>{var w,E,S,T,_,U,Y,he,fe,ae,Ee,ye,Oe,we;let n=e.approval,o=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,r=(n==null?void 0:n.status)==="pending",s=b("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(w=o==null?void 0:o.backgroundColor)!=null?w:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(E=o==null?void 0:o.borderColor)!=null?E:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(o==null?void 0:o.shadow)!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=b("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",l=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(S=o==null?void 0:o.titleColor)!=null?S:"currentColor",m=Me(d,20,l,2);m&&i.appendChild(m);let p=b("div","persona-flex-1 persona-min-w-0"),f=b("div","persona-flex persona-items-center persona-gap-2"),u=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o!=null&&o.titleColor&&(u.style.color=o.titleColor),u.textContent=(T=o==null?void 0:o.title)!=null?T:"Approval Required",f.appendChild(u),!r){let K=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");K.setAttribute("data-approval-status",n.status),n.status==="approved"?(K.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",K.style.color="var(--persona-palette-colors-success-700, #15803d)",K.textContent="Approved"):n.status==="denied"?(K.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",K.style.color="var(--persona-palette-colors-error-700, #b91c1c)",K.textContent="Denied"):n.status==="timeout"&&(K.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",K.style.color="var(--persona-palette-colors-warning-700, #b45309)",K.textContent="Timeout"),f.appendChild(K)}p.appendChild(f);let v=n.toolType==="webmcp"||n.toolName.startsWith(Rr)?Fl(n.toolName):void 0,M=(_=o==null?void 0:o.formatDescription)==null?void 0:_.call(o,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...v?{displayTitle:v}:{}}),I=!n.toolName,R=M||(I?n.description:`The assistant wants to use \u201C${v!=null?v:Vb(n.toolName)}\u201D.`),W=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");W.setAttribute("data-approval-summary","true"),o!=null&&o.descriptionColor&&(W.style.color=o.descriptionColor),W.textContent=R,p.appendChild(W);let D=(U=o==null?void 0:o.detailsDisplay)!=null?U:"collapsed",B=!!n.description&&!I,x=B||!!n.parameters;if(D!=="hidden"&&x){let K=Zm(e.id,t),pe=b("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");pe.type="button",pe.setAttribute("data-expand-header","true"),pe.setAttribute("data-bubble-type","approval"),o!=null&&o.descriptionColor&&(pe.style.color=o.descriptionColor);let G=b("span");G.setAttribute("data-approval-details-label","true");let ve=b("span","persona-inline-flex persona-items-center");ve.setAttribute("data-approval-details-chevron","true"),pe.append(G,ve),eg(pe,K,t),p.appendChild(pe);let ce=b("div");if(ce.setAttribute("data-approval-details","true"),ce.style.display=K?"":"none",B){let ne=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o!=null&&o.descriptionColor&&(ne.style.color=o.descriptionColor),ne.textContent=n.description,ce.appendChild(ne)}if(n.parameters){let ne=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&&(ne.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(ne.style.color=o.parameterTextColor),ne.style.fontSize="0.75rem",ne.style.lineHeight="1rem",ne.textContent=as(n.parameters),ce.appendChild(ne)}p.appendChild(ce)}if(r){let K=b("div","persona-flex persona-gap-2 persona-mt-2");K.setAttribute("data-approval-buttons","true");let pe=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");pe.type="button",pe.style.backgroundColor=(Y=o==null?void 0:o.approveButtonColor)!=null?Y:"var(--persona-approval-approve-bg, #22c55e)",pe.style.color=(he=o==null?void 0:o.approveButtonTextColor)!=null?he:"#ffffff",pe.setAttribute("data-approval-action","approve");let G=Me("shield-check",14,(fe=o==null?void 0:o.approveButtonTextColor)!=null?fe:"#ffffff",2);G&&(G.style.marginRight="4px",pe.appendChild(G));let ve=document.createTextNode((ae=o==null?void 0:o.approveLabel)!=null?ae:"Approve");pe.appendChild(ve);let ce=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");ce.type="button",ce.style.backgroundColor=(Ee=o==null?void 0:o.denyButtonColor)!=null?Ee:"transparent",ce.style.color=(ye=o==null?void 0:o.denyButtonTextColor)!=null?ye:"var(--persona-feedback-error, #dc2626)",ce.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,ce.setAttribute("data-approval-action","deny");let ne=Me("shield-x",14,(Oe=o==null?void 0:o.denyButtonTextColor)!=null?Oe:"var(--persona-feedback-error, #dc2626)",2);ne&&(ne.style.marginRight="4px",ce.appendChild(ne));let Se=document.createTextNode((we=o==null?void 0:o.denyLabel)!=null?we:"Deny");ce.appendChild(Se),K.append(pe,ce),p.appendChild(K)}return a.append(i,p),s.appendChild(a),s};var ng=e=>{let t=[];return{buttons:t,render:(o,r,s,a,i)=>{if(e.innerHTML="",t.length=0,!o||!o.length||(a!=null?a:r?r.getMessages():[]).some(u=>u.role==="user"))return;let m=document.createDocumentFragment(),p=r?r.isStreaming():!1,f=u=>{switch(u){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};o.forEach(u=>{let C=b("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");C.type="button",C.textContent=u,C.disabled=p,i!=null&&i.fontFamily&&(C.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(C.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(C.style.paddingLeft=i.paddingX,C.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(C.style.paddingTop=i.paddingY,C.style.paddingBottom=i.paddingY),C.addEventListener("click",()=>{!r||r.isStreaming()||(s.value="",r.sendMessage(u))}),m.appendChild(C),t.push(C)}),e.appendChild(m)}}};var Ca=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 Sa=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 $b=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Ub=new Set(["step_start","execution_start"]),zb=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),qb=new Set(["step_complete","agent_turn_complete"]),jb=new Set(["flow_complete","agent_complete"]),og=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),sg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),eo=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Fr=(e,t)=>{let n=e[t];return sg(n)?n:void 0};function ac(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Ji(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Kb(e,t){return typeof t.type=="string"?t.type:e}function Gb(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 Yb(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 rg(e){var o,r,s,a,i;let t=Fr(e,"result"),n=[Fr(e,"tokens"),Fr(e,"totalTokens"),t?Fr(t,"tokens"):void 0,Fr(e,"usage"),t?Fr(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(r=(o=eo(d.output))!=null?o:eo(d.outputTokens))!=null?r:eo(d.completionTokens);if(l!==void 0)return l}return(i=(s=eo(e.outputTokens))!=null?s:eo(e.completionTokens))!=null?i:t?(a=eo(t.outputTokens))!=null?a:eo(t.completionTokens):void 0}function Xb(e){var n,o,r,s,a;let t=Fr(e,"result");return(a=(r=(o=(n=eo(e.executionTime))!=null?n:eo(e.executionTimeMs))!=null?o:eo(e.execution_time))!=null?r:eo(e.duration))!=null?a:t?(s=eo(t.executionTime))!=null?s:eo(t.executionTimeMs):void 0}function Qb(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Aa=class{constructor(t=Qb){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:Ji(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(!sg(n)){og.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Kb(t,n),r=this.now();if($b.has(o)){this.startRun(r);return}if(Ub.has(o)){this.run||this.startRun(r);return}if(zb.has(o)){if(!Yb(o,n))return;let a=Gb(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+ac(i.visibleCharCount),l=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ji(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(qb.has(o)){if(!this.run)return;let a=this.run,i=rg(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+ac(a.visibleCharCount),m=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:Ji(l,m),outputTokens:l,durationMs:m,source:d?"usage":"estimate"};return}if(jb.has(o)){if(!this.run)return;let a=this.run,i=rg(n),d=i!=null?i:a.exactOutputTokens+ac(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",m=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:Ji(d,m),outputTokens:d,durationMs:m,source:l},this.run=null;return}if(og.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=Xb(n);return s!=null?s:o-t.startedAt}};function gs(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Jb={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)"}},Zb={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},ey=["flowName","stepName","reasoningText","text","name","tool","toolName"],ty=100;function ny(e,t){let n={...Jb,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Zb}function oy(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function ry(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 sy(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 ay(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 iy(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 ly(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function cy(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 dy(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 ic(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");gs(l,(f=o.classNames)==null?void 0:f.eventRow);let m=a.find(u=>u.renderEventStreamRow);if(m!=null&&m.renderEventStreamRow&&i){let u=m.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(u)return l.appendChild(u),l}return l.appendChild(p()),l;function p(){var U,Y;let u=b("div",""),C=b("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");C.setAttribute("data-event-id",e.id);let v=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),M=Me(d?"chevron-down":"chevron-right","14px","currentColor",2);M&&v.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=(U=o.timestampFormat)!=null?U:"relative";I.textContent=R==="relative"?oy(e.timestamp,n):ry(e.timestamp);let W=null;o.showSequenceNumbers!==!1&&(W=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),W.textContent=String(t+1));let D=ny(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 x=(Y=o.descriptionFields)!=null?Y:ey,w=sy(e.payload,x),E=null;w&&(E=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),E.textContent=w);let S=b("div","persona-flex-1 persona-min-w-0"),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"),_=Me("clipboard","12px","currentColor",1.5);return _&&T.appendChild(_),T.addEventListener("click",async he=>{he.stopPropagation(),await ay(iy(e)),T.innerHTML="";let fe=Me("check","12px","currentColor",1.5);fe&&T.appendChild(fe),setTimeout(()=>{T.innerHTML="";let ae=Me("clipboard","12px","currentColor",1.5);ae&&T.appendChild(ae)},1500)}),C.appendChild(v),C.appendChild(I),W&&C.appendChild(W),C.appendChild(B),E&&C.appendChild(E),C.appendChild(S),C.appendChild(T),u.appendChild(C),d&&u.appendChild(dy(e,a,i)),u}}function ag(e){var C,v,M,I,R;let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,i=(C=r==null?void 0:r.features)==null?void 0:C.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(v=i==null?void 0:i.iconName)!=null?v:"arrow-down",m=(M=i==null?void 0:i.label)!=null?M:"",p=(R=(I=r==null?void 0:r.features)==null?void 0:I.eventStream)!=null?R:{},f=s.find(W=>W.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&r){let W=f.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>u().element,onClose:o});if(W)return{element:W,update:()=>{},destroy:()=>{}}}return u();function u(){let W=p.classNames,D=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");gs(D,W==null?void 0:W.panel);let B=[],x="",w="",E=null,S=[],T={},_=0,U=Ii(),Y=0,he=0,fe=!1,ae=null,Ee=!1,ye=0,Oe=new Set,we=new Map,K="",pe="",G=null,ve,ce,ne,Se,ze,te=null,re=null,ie=null;function st(){let se=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),Ce=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");gs(Ce,W==null?void 0:W.headerBar);let kt=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(kt.textContent="Events",ve=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"),ve.textContent="0",a){re=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),re.style.cursor="help";let On=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");On.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",ie=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"),ie.style.display="none",ie.style.pointerEvents="none";let no=re,Tn=ie,Nn=()=>{if(!Tn.textContent)return;let Lo=no.getBoundingClientRect(),_n=se.getBoundingClientRect();Tn.style.left=`${Lo.left-_n.left}px`,Tn.style.top=`${Lo.bottom-_n.top+4}px`,Tn.style.display="block"},bt=()=>{Tn.style.display="none"};re.addEventListener("mouseenter",Nn),re.addEventListener("mouseleave",bt),re.appendChild(On),re.appendChild(te)}let Kt=b("div","persona-flex-1");ce=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 tn=b("option","");tn.value="",tn.textContent="All events",ce.appendChild(tn),ne=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"),ne.type="button",ne.title="Copy All";let Wt=Me("clipboard-copy","12px","currentColor",1.5);Wt&&ne.appendChild(Wt);let Mt=b("span","persona-text-xs");Mt.textContent="Copy All",ne.appendChild(Mt),Ce.appendChild(kt),Ce.appendChild(ve),re&&Ce.appendChild(re),Ce.appendChild(Kt),Ce.appendChild(ce),Ce.appendChild(ne);let wt=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");gs(wt,W==null?void 0:W.searchBar);let St=Me("search","14px","var(--persona-muted, #9ca3af)",1.5),Gt=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");St&&Gt.appendChild(St),Se=b("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),gs(Se,W==null?void 0:W.searchInput),Se.type="text",Se.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 ot=Me("x","12px","currentColor",2);return ot&&ze.appendChild(ot),wt.appendChild(Gt),wt.appendChild(Se),wt.appendChild(ze),se.appendChild(Ce),se.appendChild(wt),ie&&se.appendChild(ie),se}let Te,ue=s.find(se=>se.renderEventStreamToolbar);if(ue!=null&&ue.renderEventStreamToolbar&&r){let se=ue.renderEventStreamToolbar({config:r,defaultRenderer:()=>st(),eventCount:t.getSize(),filteredCount:0,onFilterChange:Ce=>{x=Ce,Fn(),V()},onSearchChange:Ce=>{w=Ce,Fn(),V()}});Te=se!=null?se:st()}else Te=st();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 Be(){if(!a||!te||!re)return;let se=a();te.textContent=ly(se);let Ce=cy(se);ie&&(ie.textContent=Ce,Ce||(ie.style.display="none")),Ce?re.setAttribute("aria-label",Ce):re.removeAttribute("aria-label")}let me=b("div","persona-flex-1 persona-min-h-0 persona-relative"),Q=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Q.style.height="100%";let _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");gs(_e,W==null?void 0:W.scrollIndicator),_e.style.display="none",_e.setAttribute("data-persona-scroll-to-bottom-has-label",m?"true":"false");let Ht=Me(l,"14px","currentColor",2);Ht&&_e.appendChild(Ht);let be=b("span","");be.textContent=m,_e.appendChild(be);let de=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");de.style.display="none",me.appendChild(Q),me.appendChild(de),me.appendChild(_e),D.setAttribute("tabindex","0"),D.appendChild(Te),D.appendChild(Ue),D.appendChild(me);function Pn(){let se=t.getAll(),Ce={};for(let Mt of se)Ce[Mt.type]=(Ce[Mt.type]||0)+1;let kt=Object.keys(Ce).sort(),Kt=kt.length!==S.length||!kt.every((Mt,wt)=>Mt===S[wt]),tn=!Kt&&kt.some(Mt=>Ce[Mt]!==T[Mt]),An=se.length!==Object.values(T).reduce((Mt,wt)=>Mt+wt,0);if(!Kt&&!tn&&!An||(S=kt,T=Ce,!ce))return;let Wt=ce.value;if(ce.options[0].textContent="All events",Kt){for(;ce.options.length>1;)ce.remove(1);for(let Mt of kt){let wt=b("option","");wt.value=Mt,wt.textContent=`${Mt} (${Ce[Mt]||0})`,ce.appendChild(wt)}Wt&&kt.includes(Wt)?ce.value=Wt:Wt&&(ce.value="",x="")}else for(let Mt=1;Mt<ce.options.length;Mt++){let wt=ce.options[Mt];wt.textContent=`${wt.value} (${Ce[wt.value]||0})`}}function Ut(){let se=t.getAll();if(x&&(se=se.filter(Ce=>Ce.type===x)),w){let Ce=w.toLowerCase();se=se.filter(kt=>kt.type.toLowerCase().includes(Ce)||kt.payload.toLowerCase().includes(Ce))}return se}function gn(){return x!==""||w!==""}function Fn(){_=0,Y=0,U.resume(),_e.style.display="none"}function to(se){Oe.has(se)?Oe.delete(se):Oe.add(se),G=se;let Ce=Q.scrollTop,kt=U.isFollowing();Ee=!0,U.pause(),V(),Q.scrollTop=Ce,kt&&U.resume(),Ee=!1}function qe(){return pa(Q,50)}function V(){he=Date.now(),fe=!1,Be(),Pn();let se=t.getEvictedCount();se>0?(Ue.textContent=`${se.toLocaleString()} older events truncated`,Ue.style.display=""):Ue.style.display="none",B=Ut();let Ce=B.length,kt=t.getSize()>0;ve&&(ve.textContent=String(t.getSize())),Ce===0&&kt&&gn()?(de.textContent=w?`No events matching '${w}'`:"No events matching filter",de.style.display="",Q.style.display="none"):(de.style.display="none",Q.style.display=""),ne&&(ne.title=gn()?`Copy Filtered (${Ce})`:"Copy All"),d&&!U.isFollowing()&&Ce>_&&(Y+=Ce-_,be.textContent=m?`${m}${Y>0?` (${Y})`:""}`:"",_e.style.display=""),_=Ce;let Kt=t.getAll(),tn=Kt.length>0?Kt[0].timestamp:0,An=new Set(B.map(wt=>wt.id));for(let wt of Oe)An.has(wt)||Oe.delete(wt);let Wt=x!==K||w!==pe,Mt=we.size===0&&B.length>0;if(Wt||Mt||B.length===0){Q.innerHTML="",we.clear();let wt=document.createDocumentFragment();for(let St=0;St<B.length;St++){let Gt=ic(B[St],St,tn,p,Oe,to,s,r);we.set(B[St].id,Gt),wt.appendChild(Gt)}Q.appendChild(wt),K=x,pe=w,G=null}else{if(G!==null){let St=we.get(G);if(St&&St.parentNode===Q){let Gt=B.findIndex(ot=>ot.id===G);if(Gt>=0){let ot=ic(B[Gt],Gt,tn,p,Oe,to,s,r);Q.insertBefore(ot,St),St.remove(),we.set(G,ot)}}G=null}let wt=new Set(B.map(St=>St.id));for(let[St,Gt]of we)wt.has(St)||(Gt.remove(),we.delete(St));for(let St=0;St<B.length;St++){let Gt=B[St];if(!we.has(Gt.id)){let ot=ic(Gt,St,tn,p,Oe,to,s,r);we.set(Gt.id,ot),Q.appendChild(ot)}}}U.isFollowing()&&(Q.scrollTop=Q.scrollHeight)}function Le(){if(Date.now()-he>=ty){ae!==null&&(cancelAnimationFrame(ae),ae=null),V();return}fe||(fe=!0,ae=requestAnimationFrame(()=>{ae=null,V()}))}let He=(se,Ce)=>{if(!ne)return;ne.innerHTML="";let kt=Me(se,"12px","currentColor",1.5);kt&&ne.appendChild(kt);let Kt=b("span","persona-text-xs");Kt.textContent="Copy All",ne.appendChild(Kt),setTimeout(()=>{ne.innerHTML="";let tn=Me("clipboard-copy","12px","currentColor",1.5);tn&&ne.appendChild(tn);let An=b("span","persona-text-xs");An.textContent="Copy All",ne.appendChild(An),ne.disabled=!1},Ce)},De=async()=>{if(ne){ne.disabled=!0;try{let se;gn()?se=B:n?(se=await n(),se.length===0&&(se=t.getAll())):se=t.getAll();let Ce=se.map(kt=>{try{return JSON.parse(kt.payload)}catch{return kt.payload}});await navigator.clipboard.writeText(JSON.stringify(Ce,null,2)),He("check",1500)}catch{He("x",1500)}}},Ve=()=>{ce&&(x=ce.value,Fn(),V())},mt=()=>{!Se||!ze||(ze.style.display=Se.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{w=Se.value,Fn(),V()},150))},at=()=>{!Se||!ze||(Se.value="",w="",ze.style.display="none",E&&clearTimeout(E),Fn(),V())},Pt=()=>{if(Ee)return;let se=Q.scrollTop,{action:Ce,nextLastScrollTop:kt}=Ri({following:U.isFollowing(),currentScrollTop:se,lastScrollTop:ye,nearBottom:qe(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ye=kt,Ce==="resume"?(U.resume(),Y=0,_e.style.display="none"):Ce==="pause"&&(U.pause(),d&&(be.textContent=m,_e.style.display=""))},jt=se=>{let Ce=Pi({following:U.isFollowing(),deltaY:se.deltaY,nearBottom:qe(),resumeWhenNearBottom:!0});Ce==="pause"?(U.pause(),d&&(be.textContent=m,_e.style.display="")):Ce==="resume"&&(U.resume(),Y=0,_e.style.display="none")},j=()=>{d&&(Q.scrollTop=Q.scrollHeight,U.resume(),Y=0,_e.style.display="none")},zt=se=>{let Ce=se.target;if(!Ce||Ce.closest("button"))return;let kt=Ce.closest("[data-event-id]");if(!kt)return;let Kt=kt.getAttribute("data-event-id");Kt&&to(Kt)},Ze=se=>{if((se.metaKey||se.ctrlKey)&&se.key==="f"){se.preventDefault(),Se==null||Se.focus(),Se==null||Se.select();return}se.key==="Escape"&&(Se&&document.activeElement===Se?(at(),Se.blur(),D.focus()):o&&o())};ne&&ne.addEventListener("click",De),ce&&ce.addEventListener("change",Ve),Se&&Se.addEventListener("input",mt),ze&&ze.addEventListener("click",at),Q.addEventListener("scroll",Pt),Q.addEventListener("wheel",jt,{passive:!0}),Q.addEventListener("click",zt),_e.addEventListener("click",j),D.addEventListener("keydown",Ze);function Vt(){E&&clearTimeout(E),ae!==null&&(cancelAnimationFrame(ae),ae=null),fe=!1,we.clear(),ne&&ne.removeEventListener("click",De),ce&&ce.removeEventListener("change",Ve),Se&&Se.removeEventListener("input",mt),ze&&ze.removeEventListener("click",at),Q.removeEventListener("scroll",Pt),Q.removeEventListener("wheel",jt),Q.removeEventListener("click",zt),_e.removeEventListener("click",j),D.removeEventListener("keydown",Ze)}return{element:D,update:Le,destroy:Vt}}}function ig(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",o=typeof e.artifactId=="string"?e.artifactId:"",r=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),o&&i.setAttribute("data-open-artifact",o);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let m=document.createElement("div");m.className="persona-truncate persona-text-sm persona-font-medium",m.style.color="var(--persona-text, #1f2937)",m.textContent=n;let p=document.createElement("div");if(p.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",p.style.color="var(--persona-muted, #9ca3af)",r==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",p.appendChild(f);let u=document.createElement("span");u.textContent=`Generating ${a.toLowerCase()}...`,p.appendChild(u)}else p.textContent=a;if(l.append(m,p),i.append(d,l),r==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${n}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",o),i.append(f)}return i}var lg=(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:()=>ig(e,t)});if(m)return m}return ig(e,t)};var lc=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)})}},Or=new lc;Or.register("PersonaArtifactCard",lg);function py(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 cg(e,t){var ce,ne,Se,ze;let n=(ne=(ce=e.features)==null?void 0:ce.artifacts)==null?void 0:ne.layout,r=((Se=n==null?void 0:n.toolbarPreset)!=null?Se:"default")==="document",s=(ze=n==null?void 0:n.panePadding)==null?void 0:ze.trim(),a=e.markdown?ui(e.markdown):null,i=mi(e.sanitize),d=te=>{let re=a?a(te):ta(te);return i?i(re):re},l=typeof document!="undefined"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,m=()=>{l==null||l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"),_==null||_.hide()};l&&l.addEventListener("click",()=>{var te;m(),(te=t.onDismiss)==null||te.call(t)});let p=b("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");p.setAttribute("data-persona-theme-zone","artifact-pane"),r&&p.classList.add("persona-artifact-pane-document");let f=b("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&f.classList.add("persona-artifact-toolbar-document");let u=b("span","persona-text-xs persona-font-medium persona-truncate");u.textContent="Artifacts";let C=b("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");C.type="button",C.textContent="Close",C.setAttribute("aria-label","Close artifacts panel"),C.addEventListener("click",()=>{var te;m(),(te=t.onDismiss)==null||te.call(t)});let v="rendered",M=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),I=r?Sn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Sn({icon:"eye",label:"Rendered view"}),R=r?Sn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Sn({icon:"code-2",label:"Source"}),W=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,x=n==null?void 0:n.documentToolbarCopyMenuItems,w=!!(B&&x&&x.length>0),E=null,S,T=null,_=null;if(r&&(D||B)&&!w){if(S=D?Kl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Sn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),B){let te=Me("chevron-down",14,"currentColor",2);te&&S.appendChild(te)}}else r&&w?(E=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),S=D?Kl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Sn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),T=Sn({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),E.append(S,T)):r?S=Sn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):S=Sn({icon:"copy",label:"Copy"});let U=r?Sn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Sn({icon:"refresh-cw",label:"Refresh"}),Y=r?Sn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Sn({icon:"x",label:"Close"}),he=()=>{var Te,ue,Ue;let te=(Te=we.find(Be=>Be.id===K))!=null?Te:we[we.length-1],re=(ue=te==null?void 0:te.id)!=null?ue:null,ie=(te==null?void 0:te.artifactType)==="markdown"&&(Ue=te.markdown)!=null?Ue:"",st=te?JSON.stringify({component:te.component,props:te.props},null,2):"";return{markdown:ie,jsonPayload:st,id:re}},fe=async()=>{var Te;let{markdown:te,jsonPayload:re}=he(),ie=(Te=we.find(ue=>ue.id===K))!=null?Te:we[we.length-1],st=(ie==null?void 0:ie.artifactType)==="markdown"?te:ie?re:"";try{await navigator.clipboard.writeText(st)}catch{}};if(S.addEventListener("click",async()=>{let te=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(te&&w){let{markdown:re,jsonPayload:ie,id:st}=he();try{await te({actionId:"primary",artifactId:st,markdown:re,jsonPayload:ie})}catch{}return}await fe()}),T&&(x!=null&&x.length)){let te=()=>{var ie;return(ie=p.closest("[data-persona-root]"))!=null?ie:document.body},re=()=>{_=is({items:x.map(ie=>({id:ie.id,label:ie.label})),onSelect:async ie=>{let{markdown:st,jsonPayload:Te,id:ue}=he(),Ue=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Ue?await Ue({actionId:ie,artifactId:ue,markdown:st,jsonPayload:Te}):ie==="markdown"||ie==="md"?await navigator.clipboard.writeText(st):ie==="json"||ie==="source"?await navigator.clipboard.writeText(Te):await navigator.clipboard.writeText(st||Te)}catch{}},anchor:E!=null?E:T,position:"bottom-right",portal:te()})};p.isConnected?re():requestAnimationFrame(re),T.addEventListener("click",ie=>{ie.stopPropagation(),_==null||_.toggle()})}U.addEventListener("click",async()=>{var te;try{await((te=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:te.call(n))}catch{}G()}),Y.addEventListener("click",()=>{var te;m(),(te=t.onDismiss)==null||te.call(t)});let ae=()=>{r&&(I.setAttribute("aria-pressed",v==="rendered"?"true":"false"),R.setAttribute("aria-pressed",v==="source"?"true":"false"))};I.addEventListener("click",()=>{v="rendered",ae(),G()}),R.addEventListener("click",()=>{v="source",ae(),G()});let Ee=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),E?W.append(E,U,Y):W.append(S,U,Y),f.append(M,Ee,W),ae()):(f.appendChild(u),f.appendChild(C)),s&&(f.style.paddingLeft=s,f.style.paddingRight=s);let ye=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&&(ye.style.paddingLeft=s,ye.style.paddingRight=s,Oe.style.padding=s),p.appendChild(f),p.appendChild(ye),p.appendChild(Oe);let we=[],K=null,pe=!1,G=()=>{var st,Te,ue,Ue;let te=r&&we.length<=1;ye.classList.toggle("persona-hidden",te),ye.replaceChildren();for(let Be of we){let me=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");me.type="button",me.textContent=Be.title||Be.id.slice(0,8),Be.id===K&&me.classList.add("persona-bg-persona-container","persona-border-persona-border"),me.addEventListener("click",()=>t.onSelect(Be.id)),ye.appendChild(me)}Oe.replaceChildren();let re=K&&we.find(Be=>Be.id===K)||we[we.length-1];if(!re)return;if(r){let Be=re.artifactType==="markdown"?"MD":(st=re.component)!=null?st:"Component",Q=(re.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Ee.textContent=`${Q} \xB7 ${Be}`}else u.textContent="Artifacts";if(re.artifactType==="markdown"){if(r&&v==="source"){let me=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");me.textContent=(Te=re.markdown)!=null?Te:"",Oe.appendChild(me);return}let Be=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Be.innerHTML=d((ue=re.markdown)!=null?ue:""),Oe.appendChild(Be);return}let ie=re.component?Or.get(re.component):void 0;if(ie){let me={message:{id:re.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Q=ie((Ue=re.props)!=null?Ue:{},me);if(Q){Oe.appendChild(Q);return}}catch{}}Oe.appendChild(py(re))},ve=()=>{var re;let te=we.length>0;if(p.classList.toggle("persona-hidden",!te),l){let ie=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,Te=((re=ie==null?void 0:ie.classList.contains("persona-artifact-narrow-host"))!=null?re:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;te&&Te&&pe?(l.classList.remove("persona-hidden"),p.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"))}};return{element:p,backdrop:l,update(te){var re,ie,st;we=te.artifacts,K=(st=(ie=te.selectedId)!=null?ie:(re=te.artifacts[te.artifacts.length-1])==null?void 0:re.id)!=null?st:null,we.length>0&&(pe=!0),G(),ve()},setMobileOpen(te){pe=te,!te&&l?(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):ve()}}}function bo(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 dg(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"),!bo(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 uy(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 Zi(e,t){var d,l,m,p,f,u,C,v,M,I;if(!bo(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"),uy(e),dg(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(m=n==null?void 0:n.splitGap)!=null?m:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=n==null?void 0:n.paneWidth)!=null?p:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=n==null?void 0:n.paneMaxWidth)!=null?f:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=(u=n==null?void 0:n.paneBackground)==null?void 0:u.trim();o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let r=(C=n==null?void 0:n.panePadding)==null?void 0:C.trim();r?e.style.setProperty("--persona-artifact-pane-padding",r):e.style.removeProperty("--persona-artifact-pane-padding");let s=(v=n==null?void 0:n.documentToolbarIconColor)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(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"),dg(e,t)}var pg=["panel","seamless"];function el(e,t){var i,d,l,m,p,f;for(let u of pg)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"),!bo(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=pg.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${r}`);let s=(m=n==null?void 0:n.paneBorderRadius)==null?void 0:m.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(p=n==null?void 0:n.paneShadow)==null?void 0:p.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let u=((f=n.unifiedSplitOuterRadius)==null?void 0:f.trim())||s;u&&e.style.setProperty("--persona-artifact-unified-outer-radius",u)}}function ug(e,t){var n,o,r;return!t||!bo(e)?!1:((r=(o=(n=e.features)==null?void 0:n.artifacts)==null?void 0:o.layout)==null?void 0:r.expandLauncherPanelWhenOpen)!==!1}function my(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 gy(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 fy(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function hy(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function mg(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 gg(e,t,n,o,r,s){let a=my(r,200),i=hy(t,n,o,200);i=Math.max(a,i);let d=gy(s);return d!==null&&(i=Math.min(i,d)),fy(e,a,i)}var fg={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"}},cc=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var C,v,M;if(s.dataset.enhanced==="true")return;let a=(C=s.dataset.tvForm)!=null?C:"init";s.dataset.enhanced="true";let i=(v=fg[a])!=null?v:fg.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 x,w;let R=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");R.htmlFor=`${t.id}-${a}-${I.name}`;let W=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");W.textContent=I.label,R.appendChild(W);let D=(x=I.type)!=null?x:"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=(w=I.placeholder)!=null?w:"",I.required&&(B.required=!0),R.appendChild(B),m.appendChild(R)});let p=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),u=b("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");u.type="submit",u.textContent=(M=i.submitLabel)!=null?M:"Submit",p.appendChild(f),p.appendChild(u),m.appendChild(p),s.replaceChildren(d,m),m.addEventListener("submit",async I=>{var B,x;I.preventDefault();let R=(B=n.formEndpoint)!=null?B:"/form",W=new FormData(m),D={};W.forEach((w,E)=>{D[E]=w}),D.type=a,u.disabled=!0,f.textContent="Submitting\u2026";try{let w=await fetch(R,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D)});if(!w.ok)throw new Error(`Form submission failed (${w.status})`);let E=await w.json();f.textContent=(x=E.message)!=null?x:"Thanks! We'll be in touch soon.",E.success&&E.nextPrompt&&await o.sendMessage(String(E.nextPrompt))}catch(w){f.textContent=w instanceof Error?w.message:"Something went wrong. Please try again."}finally{u.disabled=!1}})})};var dc=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()}},pc=new dc;var hg=()=>{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 by=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},yy=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},mc=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=by(e),n=yy(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}},uc=e=>typeof e=="string"?e:e==null?"":String(e),Ta={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:uc(e.payload.text)},messageAndClick:(e,t)=>{var r;if(e.type!=="message_and_click")return;let n=e.payload,o=uc(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:uc(n.text)}}},bg=e=>Array.isArray(e)?e.map(t=>String(t)):[],gc=e=>{let t=new Set(bg(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(bg(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,m)=>l||(m==null?void 0:m({text:a,message:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),o();let d={action:i,message:s.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let m=()=>{e.emit("action:resubmit",d)},p=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:m});if(!p)continue;if(p.handled){let f=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:f,resubmit:p.resubmit}}}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",m)}return{text:"",persist:!0}},syncFromMetadata:n}};var vy=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}},xy=e=>e.map(t=>({...t,streaming:!1})),wy=e=>e.map(t=>({...t,status:"complete"})),yg=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?vy(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?xy(n.messages):void 0,artifacts:n.artifacts?wy(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)}}}};var fc=require("partial-json");function vg(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Or.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 xg(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 wg(e){let t=xg(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 Cg(e){let t=xg(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 Cy=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Sg(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=Cy}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-csat",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Customer satisfaction feedback");let p=null,f=document.createElement("div");f.className="persona-feedback-content";let u=document.createElement("div");u.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,u.appendChild(C);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=r,u.appendChild(v),f.appendChild(u);let 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 x=1;x<=5;x++){let w=document.createElement("button");w.type="button",w.className="persona-feedback-rating-btn persona-feedback-star-btn",w.setAttribute("role","radio"),w.setAttribute("aria-checked","false"),w.setAttribute("aria-label",`${x} star${x>1?"s":""}: ${l[x-1]}`),w.title=l[x-1],w.dataset.rating=String(x),w.innerHTML=`
|
|
23
|
+
`,n.addEventListener("click",t);let o=s=>{var P,D,W,w,x,E,S,k,V,z,Y,he,me;let a=(P=s.launcher)!=null?P:{},i=wn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let de=(D=a.title)!=null?D:"Chat Assistant";d.textContent=de,d.setAttribute("title",de)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let de=(W=a.subtitle)!=null?W:"Get answers fast";l.textContent=de,l.setAttribute("title",de)}let f=n.querySelector(".persona-flex-col");f&&(a.textHidden||i?f.style.display="none":f.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let de=(w=a.agentIconSize)!=null?w:"40px";if(u.style.height=de,u.style.width=de,u.innerHTML="",a.agentIconName){let Ee=parseFloat(de)||24,xe=Me(a.agentIconName,Ee*.6,"var(--persona-text-inverse, #ffffff)",2);xe?(u.appendChild(xe),u.style.display=""):(u.textContent=(x=a.agentIconText)!=null?x:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(E=a.agentIconText)!=null?E:"\u{1F4AC}",u.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let de=(S=a.agentIconSize)!=null?S:"40px";g.style.height=de,g.style.width=de,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let m=n.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let de=(k=a.callToActionIconSize)!=null?k:"32px";m.style.height=de,m.style.width=de,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let Ee=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,Ee=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let xe=parseFloat(de)||24,De=Math.max(xe-Ee,8),Ae=Me(a.callToActionIconName,De,"currentColor",2);Ae?m.appendChild(Ae):m.textContent=(V=a.callToActionIconText)!=null?V:"\u2197"}else m.textContent=(z=a.callToActionIconText)!=null?z:"\u2197"}let C=a.position&&Eo[a.position]?Eo[a.position]:Eo["bottom-right"],v="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",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:`${v} ${C}`,i||(n.style.zIndex=String((Y=a.zIndex)!=null?Y:Mn));let I="1px solid var(--persona-border, #e5e7eb)",R="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(he=a.border)!=null?he:I,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow: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=(me=a.collapsedMaxWidth)!=null?me:"",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 Sb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",qi=(e,t={})=>{var v,M,I,R,P,D;let{showClose:n=!0,wrapperClassName:o=Sb,buttonSize:r,iconSize:s="28px"}=t,a=(v=e==null?void 0:e.launcher)!=null?v:{},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 f=(I=a.closeButtonTooltipText)!=null?I:"Close chat",u=(R=a.closeButtonShowTooltip)!=null?R:!0;l.setAttribute("aria-label",f),l.style.display=n?"":"none";let g=(P=a.closeButtonIconName)!=null?P:"x",m=(D=a.closeButtonIconText)!=null?D:"\xD7";l.style.color=a.closeButtonColor||Dn.actionIconColor;let C=Me(g,s,"currentColor",1);if(C?(C.style.display="block",l.appendChild(C)):l.textContent=m,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let W=a.closeButtonBorderWidth||"0px",w=a.closeButtonBorderColor||"transparent";l.style.border=`${W} solid ${w}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),u&&f){let W=null,w=()=>{if(W)return;let E=l.ownerDocument,S=E.body;if(!S)return;W=Oo(E,"div","persona-clear-chat-tooltip"),W.textContent=f;let k=Oo(E,"div");k.className="persona-clear-chat-tooltip-arrow",W.appendChild(k);let V=l.getBoundingClientRect();W.style.position="fixed",W.style.zIndex=String(gr),W.style.left=`${V.left+V.width/2}px`,W.style.top=`${V.top-8}px`,W.style.transform="translate(-50%, -100%)",S.appendChild(W)},x=()=>{W&&W.parentNode&&(W.parentNode.removeChild(W),W=null)};d.addEventListener("mouseenter",w),d.addEventListener("mouseleave",x),l.addEventListener("focus",w),l.addEventListener("blur",x),d._cleanupTooltip=()=>{x(),d.removeEventListener("mouseenter",w),d.removeEventListener("mouseleave",x),l.removeEventListener("focus",w),l.removeEventListener("blur",x)}}return{button:l,wrapper:d}},Ab="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ji=(e,t={})=>{var W,w,x,E,S,k,V,z,Y,he,me,de,Ee;let{wrapperClassName:n=Ab,buttonSize:o,iconSize:r="20px"}=t,a=(w=((W=e==null?void 0:e.launcher)!=null?W:{}).clearChat)!=null?w:{},i=(x=o!=null?o:a.size)!=null?x:"32px",d=(E=a.iconName)!=null?E:"refresh-cw",l=(S=a.iconColor)!=null?S:"",f=(k=a.backgroundColor)!=null?k:"",u=(V=a.borderWidth)!=null?V:"",g=(z=a.borderColor)!=null?z:"",m=(Y=a.borderRadius)!=null?Y:"",C=(he=a.paddingX)!=null?he:"",v=(me=a.paddingY)!=null?me:"",M=(de=a.tooltipText)!=null?de:"Clear chat",I=(Ee=a.showTooltip)!=null?Ee:!0,R=b("div",n),P=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");P.style.height=i,P.style.width=i,P.type="button",P.setAttribute("aria-label",M),P.style.color=l||Dn.actionIconColor;let D=Me(d,r,"currentColor",1);if(D&&(D.style.display="block",P.appendChild(D)),f&&(P.style.backgroundColor=f,P.classList.remove("hover:persona-bg-gray-100")),u||g){let xe=u||"0px",De=g||"transparent";P.style.border=`${xe} solid ${De}`,P.classList.remove("persona-border-none")}if(m&&(P.style.borderRadius=m,P.classList.remove("persona-rounded-full")),C&&(P.style.paddingLeft=C,P.style.paddingRight=C),v&&(P.style.paddingTop=v,P.style.paddingBottom=v),R.appendChild(P),I&&M){let xe=null,De=()=>{if(xe)return;let le=P.ownerDocument,J=le.body;if(!J)return;xe=Oo(le,"div","persona-clear-chat-tooltip"),xe.textContent=M;let se=Oo(le,"div");se.className="persona-clear-chat-tooltip-arrow",xe.appendChild(se);let ye=P.getBoundingClientRect();xe.style.position="fixed",xe.style.zIndex=String(gr),xe.style.left=`${ye.left+ye.width/2}px`,xe.style.top=`${ye.top-8}px`,xe.style.transform="translate(-50%, -100%)",J.appendChild(xe)},Ae=()=>{xe&&xe.parentNode&&(xe.parentNode.removeChild(xe),xe=null)};R.addEventListener("mouseenter",De),R.addEventListener("mouseleave",Ae),P.addEventListener("focus",De),P.addEventListener("blur",Ae),R._cleanupTooltip=()=>{Ae(),R.removeEventListener("mouseenter",De),R.removeEventListener("mouseleave",Ae),P.removeEventListener("focus",De),P.removeEventListener("blur",Ae)}}return{button:P,wrapper:R}};var Dn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},$r=e=>{var W,w,x,E,S,k,V,z,Y,he,me,de,Ee,xe,De,Ae;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=(w=r.headerIconSize)!=null?w:"48px",a=(x=r.closeButtonPlacement)!=null?x:"inline",i=(E=r.headerIconHidden)!=null?E:!1,d=r.headerIconName,l=b("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let le=parseFloat(s)||24,J=Me(d,le*.6,"currentColor",1);J?l.replaceChildren(J):l.textContent=(k=(S=t==null?void 0:t.launcher)==null?void 0:S.agentIconText)!=null?k:"\u{1F4AC}"}else if((V=t==null?void 0:t.launcher)!=null&&V.iconUrl){let le=b("img");le.src=t.launcher.iconUrl,le.alt="",le.className="persona-rounded-xl persona-object-cover",le.style.height=s,le.style.width=s,l.replaceChildren(le)}else l.textContent=(Y=(z=t==null?void 0:t.launcher)==null?void 0:z.agentIconText)!=null?Y:"\u{1F4AC}";let f=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=b("span","persona-text-base persona-font-semibold");u.style.color=Dn.titleColor,u.textContent=(me=(he=t==null?void 0:t.launcher)==null?void 0:he.title)!=null?me:"Chat Assistant";let g=b("span","persona-text-xs");g.style.color=Dn.subtitleColor,g.textContent=(Ee=(de=t==null?void 0:t.launcher)==null?void 0:de.subtitle)!=null?Ee:"Here to help you get answers fast",f.append(u,g),i?o.append(f):o.append(l,f);let m=(xe=r.clearChat)!=null?xe:{},C=(De=m.enabled)!=null?De:!0,v=(Ae=m.placement)!=null?Ae:"inline",M=null,I=null;if(C){let J=ji(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=J.button,I=J.wrapper,v==="top-right"&&(I.style.right="48px"),v==="inline"&&o.appendChild(I)}let R=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":C&&v==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:P,wrapper:D}=qi(t,{showClose:n,wrapperClassName:R});return a!=="top-right"&&o.appendChild(D),{header:o,iconHolder:l,headerTitle:u,headerSubtitle:g,closeButton:P,closeButtonWrapper:D,clearChatButton:M,clearChatButtonWrapper:I}},Ea=(e,t,n)=>{var a,i,d,l;let o=(a=n==null?void 0:n.launcher)!=null?a:{},r=(i=o.closeButtonPlacement)!=null?i:"inline",s=(l=(d=o.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function bs(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(gr)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of t){if(m.dividerBefore){let M=document.createElement("hr");a.appendChild(M)}let C=document.createElement("button");if(C.type="button",C.setAttribute("role","menuitem"),C.setAttribute("data-dropdown-item-id",m.id),m.destructive&&C.setAttribute("data-destructive",""),m.icon){let M=Me(m.icon,16,"currentColor",1.5);M&&C.appendChild(M)}let v=document.createElement("span");v.textContent=m.label,C.appendChild(v),C.addEventListener("click",M=>{M.stopPropagation(),f(),n(m.id)}),a.appendChild(C)}let i=null;function d(){if(!s)return;let m=o.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=C=>{!a.contains(C.target)&&!o.contains(C.target)&&f()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function f(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?l():f()}function g(){f(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:f,toggle:u,destroy:g}}function Ln(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=Me(t,o!=null?o:16,"currentColor",r!=null?r:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[f,u]of Object.entries(i))d.setAttribute(f,u);return d}function rc(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";o!=="default"&&(l+=" persona-label-btn--"+o),l+=" persona-label-btn--"+r,a&&(l+=" "+a);let f=b("button",l);if(f.type="button",f.setAttribute("aria-label",n),t){let g=Me(t,s!=null?s:14,"currentColor",2);g&&f.appendChild(g)}let u=b("span");if(u.textContent=n,f.appendChild(u),i&&f.addEventListener("click",i),d)for(let[g,m]of Object.entries(d))f.setAttribute(g,m);return f}function sf(e){var m,C;let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:i,hover:d}=e,l=b("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let f=b("span","persona-combo-btn-label");f.textContent=t,l.appendChild(f);let u=Me(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",l.appendChild(u)),d&&(l.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",l.style.padding=(C=d.padding)!=null?C:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var v,M;l.style.backgroundColor=(v=d.background)!=null?v:"",l.style.borderColor=(M=d.border)!=null?M:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let g=bs({items:o,onSelect:v=>{l.setAttribute("aria-expanded","false"),r(v)},anchor:l,position:s,portal:a});return a||l.appendChild(g.element),l.addEventListener("click",v=>{v.stopPropagation();let M=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",M?"false":"true"),g.toggle()}),l.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),l.click())}),{element:l,setLabel:v=>{f.textContent=v,l.setAttribute("aria-label",v)},open:()=>{l.setAttribute("aria-expanded","true"),g.show()},close:()=>{l.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let v=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",v?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),l.remove()}}}var Tb=e=>{var o;let t=$r({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(o=e.layoutHeaderConfig)==null?void 0:o.onTitleClick;if(n){let r=t.headerTitle.parentElement;r&&(r.style.cursor="pointer",r.setAttribute("role","button"),r.setAttribute("tabindex","0"),r.addEventListener("click",()=>n()),r.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function kb(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=Me(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=bs({items:a.menuItems,onSelect:f=>n==null?void 0:n(f),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",f=>{f.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var Eb=e=>{var R,P,D,W,w,x,E,S,k;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,f;if(d)l=sf({label:(P=a.title)!=null?P:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Dn.titleColor,f=(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"),f=b("span","persona-text-base persona-font-semibold persona-truncate"),f.style.color=Dn.titleColor,f.textContent=(W=a.title)!=null?W:"Chat Assistant",l.appendChild(f),kb(l,r==null?void 0:r.trailingActions,(w=r==null?void 0:r.onAction)!=null?w:s),r!=null&&r.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let z=r.onTitleClick;l.addEventListener("click",Y=>{Y.target.closest("button")||z()}),l.addEventListener("keydown",Y=>{(Y.key==="Enter"||Y.key===" ")&&(Y.preventDefault(),z())})}let V=r==null?void 0:r.titleRowHover;V&&(l.style.borderRadius=(x=V.borderRadius)!=null?x:"10px",l.style.padding=(E=V.padding)!=null?E:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var z,Y;l.style.backgroundColor=(z=V.background)!=null?z:"",l.style.borderColor=(Y=V.border)!=null?Y:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let u=(S=a.closeButtonSize)!=null?S:"32px",g=b("div",""),m=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=u,m.style.width=u,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=n?"":"none",m.style.color=a.closeButtonColor||Dn.actionIconColor;let C=(k=a.closeButtonIconName)!=null?k:"x",v=Me(C,"28px","currentColor",1);v?m.appendChild(v):m.textContent="\xD7",o&&m.addEventListener("click",o),g.appendChild(m),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:f,headerSubtitle:I,closeButton:m,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},af={default:Tb,minimal:Eb},Mb=e=>{var t;return(t=af[e])!=null?t:af.default},Ki=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),f=b("div");f.style.display="none";let u=b("span"),g=b("span"),m=b("button");m.style.display="none";let C=b("div");return C.style.display="none",{header:l,iconHolder:f,headerTitle:u,headerSubtitle:g,closeButton:m,closeButtonWrapper:C,clearChatButton:null,clearChatButtonWrapper:null}}let o=(a=t==null?void 0:t.layout)!=null?a:"default",s=Mb(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}},Yi=e=>{var W,w,x,E,S,k,V,z,Y,he,me,de;let t=(W=e==null?void 0:e.sendButton)!=null?W:{},n=(w=t.useIcon)!=null?w:!1,o=(x=t.iconText)!=null?x:"\u2191",r=t.iconName,s=(E=t.stopIconName)!=null?E:"square",a=(S=t.tooltipText)!=null?S:"Send message",i=(k=t.stopTooltipText)!=null?k:"Stop generating",d=(z=(V=e==null?void 0:e.copy)==null?void 0:V.sendButtonLabel)!=null?z:"Send",l=(he=(Y=e==null?void 0:e.copy)==null?void 0:Y.stopButtonLabel)!=null?he:"Stop",f=(me=t.showTooltip)!=null?me:!1,u=(de=t.size)!=null?de:"40px",g=t.backgroundColor,m=t.textColor,C=b("div","persona-send-button-wrapper"),v=b("button",n?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");v.type="submit",v.setAttribute("data-persona-composer-submit","");let M=null,I=null;if(n){v.style.width=u,v.style.height=u,v.style.minWidth=u,v.style.minHeight=u,v.style.fontSize="18px",v.style.lineHeight="1",v.innerHTML="",m?v.style.color=m:v.style.color="var(--persona-button-primary-fg, #ffffff)";let Ee=parseFloat(u)||24,xe=(m==null?void 0:m.trim())||"currentColor";r?(M=Me(r,Ee,xe,2),M?v.appendChild(M):v.textContent=o):v.textContent=o,I=Me(s,Ee,xe,2),g?v.style.backgroundColor=g:v.classList.add("persona-bg-persona-primary")}else v.textContent=d,m?v.style.color=m:v.classList.add("persona-text-white");t.borderWidth&&(v.style.borderWidth=t.borderWidth,v.style.borderStyle="solid"),t.borderColor&&(v.style.borderColor=t.borderColor),t.paddingX?(v.style.paddingLeft=t.paddingX,v.style.paddingRight=t.paddingX):(v.style.paddingLeft="",v.style.paddingRight=""),t.paddingY?(v.style.paddingTop=t.paddingY,v.style.paddingBottom=t.paddingY):(v.style.paddingTop="",v.style.paddingBottom="");let R=null;f&&a&&(R=b("div","persona-send-button-tooltip"),R.textContent=a,C.appendChild(R)),v.setAttribute("aria-label",a),C.appendChild(v);let P="send";return{button:v,wrapper:C,setMode:Ee=>{if(Ee===P)return;P=Ee;let xe=Ee==="stop"?i:a;if(v.setAttribute("aria-label",xe),R&&(R.textContent=xe),n){if(M&&I){let De=Ee==="stop"?I:M;v.replaceChildren(De)}}else v.textContent=Ee==="stop"?l:d}}},Xi=e=>{var R,P,D,W,w,x,E,S,k,V,z,Y;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=((P=t.provider)==null?void 0:P.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=(w=t.iconName)!=null?w:"mic",f=(x=t.iconSize)!=null?x:a,u=parseFloat(f)||24,g=(S=t.backgroundColor)!=null?S:(E=e==null?void 0:e.sendButton)==null?void 0:E.backgroundColor,m=(V=t.iconColor)!=null?V:(k=e==null?void 0:e.sendButton)==null?void 0:k.textColor;d.style.width=f,d.style.height=f,d.style.minWidth=f,d.style.minHeight=f,d.style.fontSize="18px",d.style.lineHeight="1",m?d.style.color=m:d.style.color="var(--persona-text, #111827)";let v=Me(l,u,m||"currentColor",1.5);v?d.appendChild(v):d.textContent="\u{1F3A4}",g&&(d.style.backgroundColor=g),t.borderWidth&&(d.style.borderWidth=t.borderWidth,d.style.borderStyle="solid"),t.borderColor&&(d.style.borderColor=t.borderColor),t.paddingX&&(d.style.paddingLeft=t.paddingX,d.style.paddingRight=t.paddingX),t.paddingY&&(d.style.paddingTop=t.paddingY,d.style.paddingBottom=t.paddingY),i.appendChild(d);let M=(z=t.tooltipText)!=null?z:"Start voice recognition";if(((Y=t.showTooltip)!=null?Y:!1)&&M){let he=b("div","persona-send-button-tooltip");he.textContent=M,i.appendChild(he)}return{button:d,wrapper:i}},Ji=e=>{var C,v,M,I,R,P,D,W;let t=(C=e==null?void 0:e.attachments)!=null?C:{};if(t.enabled!==!0)return null;let n=(M=(v=e==null?void 0:e.sendButton)==null?void 0:v.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:Jo).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",(P=t.buttonTooltipText)!=null?P:"Attach file");let i=(D=t.buttonIconName)!=null?D:"paperclip",d=n,l=parseFloat(d)||40,f=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let u=Me(i,f,"currentColor",1.5);u?a.appendChild(u):a.textContent="\u{1F4CE}",a.addEventListener("click",w=>{w.preventDefault(),r.click()}),s.appendChild(a);let g=(W=t.buttonTooltipText)!=null?W:"Attach file",m=b("div","persona-send-button-tooltip");return m.textContent=g,s.appendChild(m),{button:a,wrapper:s,input:r,previewsContainer:o}},Qi=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},Zi=()=>b("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var el=e=>{var C,v,M,I,R,P;let{config:t}=e,n=b("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");n.setAttribute("data-persona-theme-zone","composer");let o=Zi(),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=Yi(t),d=Xi(t),l=Ji(t),f=Qi(t);l&&(l.previewsContainer.style.gap="8px",r.append(l.previewsContainer,l.input)),r.append(s);let u=b("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),g=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&g.append(l.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),u.append(g,m),r.append(u),r.addEventListener("click",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,f),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(C=d==null?void 0:d.button)!=null?C:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:f,attachmentButton:(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:(P=l==null?void 0:l.previewsContainer)!=null?P:null,actionsRow:u,leftActions:g,rightActions:m,setSendButtonMode:i.setMode}};var lf=()=>{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=Me("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=Me("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},cf=e=>{var C,v,M,I,R,P;let{config:t}=e,n=b("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let o=Zi();o.style.display="none";let r=Qi(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=Gi(t);s.style.maxHeight="100px",a();let i=Yi(t),d=Xi(t),l=Ji(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let f=b("form","persona-widget-composer persona-pill-composer");f.setAttribute("data-persona-composer-form",""),f.style.outline="none";let u=b("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&u.append(l.wrapper);let g=b("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),f.addEventListener("click",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&&f.append(l.input),f.append(u,s,g),l&&n.append(l.previewsContainer),n.append(f,o,r);let m=f;return{footer:n,suggestions:o,composerForm:f,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(C=d==null?void 0:d.button)!=null?C:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:r,attachmentButton:(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:(P=l==null?void 0:l.previewsContainer)!=null?P:null,actionsRow:m,leftActions:u,rightActions:g,setSendButtonMode:i.setMode}};var df=e=>{var f,u,g,m,C,v,M,I,R,P,D,W,w,x,E,S,k;let t=(u=(f=e==null?void 0:e.launcher)==null?void 0:f.enabled)!=null?u:!0,n=wn(e);if(Ta(e)){let V=(m=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?m:{},z=b("div","persona-widget-wrapper persona-fixed persona-transition");z.setAttribute("data-persona-composer-bar",""),z.dataset.state="collapsed",z.dataset.expandedSize=(C=V.expandedSize)!=null?C:"anchored",z.style.zIndex=String((M=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?M:Mn);let Y=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Y.style.width="100%",z.appendChild(Y);let he=b("div","persona-widget-pill-root");return he.setAttribute("data-persona-composer-bar",""),he.dataset.state="collapsed",he.dataset.expandedSize=(I=V.expandedSize)!=null?I:"anchored",he.style.zIndex=String((P=(R=e==null?void 0:e.launcher)==null?void 0:R.zIndex)!=null?P:Mn),{wrapper:z,panel:Y,pillRoot:he}}if(n){let V=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),z=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return V.appendChild(z),{wrapper:V,panel:z}}if(!t){let V=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),z=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Y=(W=(D=e==null?void 0:e.launcher)==null?void 0:D.width)!=null?W:"100%";return V.style.width=Y,z.style.width="100%",V.appendChild(z),{wrapper:V,panel:z}}let r=(w=e==null?void 0:e.launcher)!=null?w:{},s=r.position&&Eo[r.position]?Eo[r.position]:Eo["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((E=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?E:Mn);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(k=(S=e==null?void 0:e.launcher)==null?void 0:S.width)!=null?k:e==null?void 0:e.launcherWidth,l=d!=null?d:go;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Lb=(e,t)=>{var D,W,w,x,E,S,k,V,z;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}=qi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=(w=(W=(D=e==null?void 0:e.launcher)==null?void 0:D.clearChat)==null?void 0:W.enabled)!=null?w:!0,a=null,i=null;if(s){let Y=ji(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=Y.button,i=Y.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=b("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=b("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages"),l.style.setProperty("scrollbar-gutter","stable");let f=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");f.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",f.setAttribute("data-persona-intro-card","");let u=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");u.textContent=(E=(x=e==null?void 0:e.copy)==null?void 0:x.welcomeTitle)!=null?E:"Hello \u{1F44B}";let g=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");g.textContent=(k=(S=e==null?void 0:e.copy)==null?void 0:S.welcomeSubtitle)!=null?k:"Ask anything about your account or products.",f.append(u,g);let m=b("div","persona-flex persona-flex-col persona-gap-3"),C=(V=e==null?void 0:e.layout)==null?void 0:V.contentMaxWidth;C&&(m.style.maxWidth=C,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((z=e==null?void 0:e.copy)==null?void 0:z.showWelcomeCard)!==!1||(f.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(f,m);let M=b("div","persona-composer-overlay persona-pointer-events-none");M.setAttribute("data-persona-composer-overlay",""),M.style.position="absolute",M.style.left="0",M.style.right="0",M.style.bottom="0",M.style.zIndex="20";let I=cf({config:e}),{root:R,textNode:P}=lf();return n.append(d,r,l,M),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:m,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:R,peekTextNode:P}},pf=(e,t=!0)=>{var M,I,R,P,D,W,w,x,E;if(Ta(e))return Lb(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?Ki(e,o,{showClose:t}):$r({config:e,showClose:t}),a=b("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages"),a.style.setProperty("scrollbar-gutter","stable");let i=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=wn(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(P=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeTitle)!=null?P:"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 f=b("div","persona-flex persona-flex-col persona-gap-3"),u=(w=e==null?void 0:e.layout)==null?void 0:w.contentMaxWidth;u&&(f.style.maxWidth=u,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((x=e==null?void 0:e.copy)==null?void 0:x.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,f);let m=el({config:e}),C=((E=e==null?void 0:e.layout)==null?void 0:E.showFooter)!==!1;r?Ea(n,s,e):(s.header.style.display="none",Ea(n,s,e)),n.append(a);let v=b("div","persona-composer-overlay persona-pointer-events-none");return v.setAttribute("data-persona-composer-overlay",""),v.style.position="absolute",v.style.left="0",v.style.right="0",v.style.bottom="0",v.style.zIndex="20",C||(m.footer.style.display="none"),n.append(m.footer),n.append(v),{container:n,body:a,messagesWrapper:f,composerOverlay:v,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:d,introSubtitle:l,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var Ib=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}},Rb=(e,t)=>{if(!e)return null;let n=Ib(e);if(n===null)return null;let o=t==null?void 0:t[e],r=o!==void 0?o:n;return r||null},Pb=(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},Wb=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},sc=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(":"))},ac=320,mf=320,Bb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Hb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Db=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Fb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Ob=(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=`${ac}px`,l.style.maxHeight=`${mf}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let f=!1;r+=1,l.addEventListener("error",()=>{f||(f=!0,r=Math.max(0,r-1),l.remove(),r===0&&a())}),l.addEventListener("load",()=>{f=!0}),Wb(i.image)?(l.src=i.image,o.appendChild(l)):(f=!0,r=Math.max(0,r-1),l.remove())}),r===0?(a(),null):o}catch{return n==null||n(),null}},Nb=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(!sc(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=`${ac}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},_b=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(!sc(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=`${ac}px`,r.style.maxHeight=`${mf}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}},Vb=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(!sc(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}},Ma=()=>{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},$b=(e,t,n)=>{let o={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Ma};if(t){let r=t(o);if(r!==null)return r}return Ma()},Ub=(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},uf=(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},zb=(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},qb=(e,t,n)=>{var m,C,v,M,I,R;let o=(m=t.showCopy)!=null?m:!0,r=(C=t.showUpvote)!=null?C:!0,s=(v=t.showDownvote)!=null?v:!0;if(!o&&!r&&!s){let P=b("div");return P.style.display="none",P.id=`actions-${e.id}`,P.setAttribute("data-actions-for",e.id),P}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],f={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],u=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${f} ${a==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${e.id}`,u.setAttribute("data-actions-for",e.id);let g=(P,D,W)=>{let w=Ln({icon:P,label:D,size:14,className:"persona-message-action-btn"});return w.setAttribute("data-action",W),w};return o&&u.appendChild(g("copy","Copy message","copy")),r&&u.appendChild(g("thumbs-up","Upvote","upvote")),s&&u.appendChild(g("thumbs-down","Downvote","downvote")),u},ic=(e,t,n,o,r,s)=>{var le,J,se,ye,be,K,ae,Re,oe,ee,re,it,lt,Le,pe,Je,Be;let a=n!=null?n:{},i=(le=a.layout)!=null?le:"bubble",d=a.avatar,l=a.timestamp,f=(J=d==null?void 0:d.show)!=null?J:!1,u=(se=l==null?void 0:l.show)!=null?se:!1,g=(ye=d==null?void 0:d.position)!=null?ye:"left",m=(be=l==null?void 0:l.position)!=null?be:"below",C=zb(e.role,i),v=b("div",C.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let M=Bb(e),I=(ae=(K=e.content)==null?void 0:K.trim())!=null?ae:"",P=M.length>0&&I===Ii,D=Vi((oe=(Re=s==null?void 0:s.widgetConfig)==null?void 0:Re.features)==null?void 0:oe.streamAnimation),W=(it=(re=(ee=s==null?void 0:s.widgetConfig)==null?void 0:ee.features)==null?void 0:re.streamAnimation)==null?void 0:it.plugins,w=e.role==="assistant"&&D.type!=="none"?wa(D.type,W):null,x=e.role==="assistant"&&((lt=w==null?void 0:w.isAnimating)==null?void 0:lt.call(w,e))===!0,E=e.role==="assistant"&&w!==null&&(!!e.streaming||x);E&&(w!=null&&w.bubbleClass)&&v.classList.add(w.bubbleClass);let S=document.createElement("div");S.classList.add("persona-message-content"),E&&w&&(w.containerClass&&S.classList.add(w.containerClass),S.style.setProperty("--persona-stream-step",`${D.speed}ms`),S.style.setProperty("--persona-stream-duration",`${D.duration}ms`));let k=E?$i((Le=e.content)!=null?Le:"",D.buffer,w,e,!!e.streaming):(pe=e.content)!=null?pe:"",V=t({text:k,message:e,streaming:!!e.streaming,raw:e.rawContent}),z=V;E&&(w==null?void 0:w.wrap)==="char"?z=Ca(V,"char",e.id,{skipTags:w.skipTags}):E&&(w==null?void 0:w.wrap)==="word"&&(z=Ca(V,"word",e.id,{skipTags:w.skipTags}));let Y=null;if(P?(Y=document.createElement("div"),Y.innerHTML=z,Y.style.display="none",S.appendChild(Y)):S.innerHTML=z,E&&(w!=null&&w.useCaret)&&!P&&I){let j=Ui(),fe=S.querySelectorAll(".persona-stream-char, .persona-stream-word"),tt=fe[fe.length-1];if(tt!=null&&tt.parentNode)tt.parentNode.insertBefore(j,tt.nextSibling);else{let Mt=S.lastElementChild;Mt?Mt.appendChild(j):S.appendChild(j)}}if(u&&m==="inline"&&e.createdAt){let j=uf(e,l);j.classList.add("persona-ml-2","persona-inline"),S.appendChild(j)}if(M.length>0){let j=Ob(M,!P&&!!I,()=>{P&&Y&&(Y.style.display="")});j?v.appendChild(j):P&&Y&&(Y.style.display="")}let he=Hb(e);if(he.length>0){let j=Nb(he);j&&v.appendChild(j)}let me=Db(e);if(me.length>0){let j=_b(me);j&&v.appendChild(j)}let de=Fb(e);if(de.length>0){let j=Vb(de);j&&v.appendChild(j)}if(v.appendChild(S),u&&m==="below"&&e.createdAt){let j=uf(e,l);j.classList.add("persona-mt-1"),v.appendChild(j)}let Ee=e.role==="assistant"?Rb(e.stopReason,(Be=(Je=s==null?void 0:s.widgetConfig)==null?void 0:Je.copy)==null?void 0:Be.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let j=!!(k&&k.trim()),fe=D.placeholder==="skeleton",tt=fe&&D.buffer==="line"&&j;if(j)tt&&v.appendChild(Sa());else if(fe)v.appendChild(Sa());else{let Mt=$b("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Mt&&v.appendChild(Mt)}}if(Ee&&e.stopReason&&!e.streaming&&(I||(S.style.display="none"),v.appendChild(Pb(e.stopReason,Ee))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let j=qb(e,o,r);v.appendChild(j)}if(!f||e.role==="system")return v;let De=b("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Ae=Ub(d,e.role);return g==="right"||g==="left"&&e.role==="user"?De.append(v,Ae):De.append(Ae,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),De};var ys=new Set,jb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Kb=(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
|
+
`):""},ff=(e,t)=>{let n=ys.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=Me(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")},lc=(e,t)=>{var me,de,Ee,xe,De,Ae,le,J,se,ye,be;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=(de=(me=t==null?void 0:t.features)==null?void 0:me.reasoningDisplay)!=null?de:{},s=r.expandable!==!1,a=s&&ys.has(e.id),i=n.status!=="complete",d=Kb(e,(Ee=r.previewMaxLines)!=null?Ee:3),l=b("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",s&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let f=b("div","persona-flex persona-flex-col persona-text-left"),u=b("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",m=(xe=t==null?void 0:t.reasoning)!=null?xe:{},C=String((De=n.startedAt)!=null?De:Date.now()),v=()=>{let K=b("span","");return K.setAttribute("data-tool-elapsed",C),K.textContent=Ti(n),K},M=(Ae=m.renderCollapsedSummary)==null?void 0:Ae.call(m,{message:e,reasoning:n,defaultSummary:g,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Ti(n),createElapsedElement:v});typeof M=="string"&&M.trim()?(u.textContent=M,f.appendChild(u)):M instanceof HTMLElement?f.appendChild(M):(u.textContent=g,f.appendChild(u));let I=b("span","persona-text-xs persona-text-persona-primary");I.textContent=Pm(n),f.appendChild(I);let R=(le=r.loadingAnimation)!=null?le:"none",P=m.activeTextTemplate,D=m.completeTextTemplate,W=i?P:D,w=M instanceof HTMLElement,x=(K,ae,Re)=>{let oe=Re;for(let ee of ae){let re=b("span","persona-tool-char");re.style.setProperty("--char-index",String(oe)),re.textContent=ee===" "?"\xA0":ee,K.appendChild(re),oe++}return oe},E=(K,ae)=>{u.textContent="";let Re=ki(K,""),oe=0;for(let ee of Re){let re=ee.styles.length>0?(()=>{let it=b("span",ee.styles.map(lt=>`persona-tool-text-${lt}`).join(" "));return u.appendChild(it),it})():u;if(ee.isDuration&&i)re.appendChild(v());else{let it=ee.isDuration?Ti(n):ee.text;ae?oe=x(re,it,oe):re.appendChild(document.createTextNode(it))}}};if(!w&&W)if(I.style.display="none",u.style.display="",i&&R!=="none"){let K=(J=m.loadingAnimationDuration)!=null?J:2e3;u.setAttribute("data-preserve-animation","true"),R==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`),E(W,!1)):(u.classList.add(`persona-tool-loading-${R}`),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`),R==="shimmer-color"&&(m.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),E(W,!0))}else E(W,!1);else if(!w&&i&&R!=="none"){u.style.display="";let K=(se=m.loadingAnimationDuration)!=null?se:2e3;if(u.setAttribute("data-preserve-animation","true"),R==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`);else{u.classList.add(`persona-tool-loading-${R}`),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`),R==="shimmer-color"&&(m.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let ae=u.textContent||g;u.textContent="",x(u,ae,0)}n.status==="complete"&&(u.style.display="none")}else w||(n.status==="complete"?u.style.display="none":u.style.display="");let S=null;if(s){S=b("div","persona-flex persona-items-center");let ae=Me(a?"chevron-up":"chevron-down",16,"currentColor",2);ae?S.appendChild(ae):S.textContent=a?"Hide":"Show";let Re=b("div","persona-flex persona-items-center persona-ml-auto");Re.append(S),l.append(f,Re)}else l.append(f);let k=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(k.setAttribute("data-persona-collapsed-preview","reasoning"),k.style.display="none",k.style.whiteSpace="pre-wrap",!a&&i&&r.activePreview&&d){let K=(be=(ye=t==null?void 0:t.reasoning)==null?void 0:ye.renderCollapsedPreview)==null?void 0:be.call(ye,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});jb(k,K)||(k.textContent=d),k.style.display=""}if(!a&&i&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(l,k),o;let V=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");V.style.display=a?"":"none";let z=n.chunks.join(""),Y=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Y.textContent=z||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),V.appendChild(Y),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),S){S.innerHTML="";let ae=Me(a?"chevron-up":"chevron-down",16,"currentColor",2);ae?S.appendChild(ae):S.textContent=a?"Hide":"Show"}V.style.display=a?"":"none",k.style.display=a?"none":k.textContent||k.childNodes.length?"":"none"})(),o.append(l,k,V),o};var vs=new Set,Gb=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Yb=(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=hs(n.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
|
|
26
|
+
`):""},Xb=(e,t)=>{var f,u,g,m,C;let n=e.toolCall,o=(f=t==null?void 0:t.features)==null?void 0:f.toolCallDisplay,r=(u=o==null?void 0:o.collapsedMode)!=null?u:"tool-call",s=Yb(e,(g=o==null?void 0:o.previewMaxLines)!=null?g:3),a=n?Wm(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(m=t==null?void 0:t.toolCall)!=null?m:{},l=a;return r==="tool-name"?l=((C=n.name)==null?void 0:C.trim())||a:r==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=Yl(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Yl(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},gf=(e,t,n)=>{var f;let o=vs.has(e),r=(f=n==null?void 0:n.toolCall)!=null?f:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let u=r.toggleTextColor||r.headerTextColor||"currentColor",g=Me(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")},cc=(e,t)=>{var z,Y,he,me,de,Ee,xe,De,Ae;let n=e.toolCall,o=(z=t==null?void 0:t.toolCall)!=null?z:{},r=b("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=(he=(Y=t==null?void 0:t.features)==null?void 0:Y.toolCallDisplay)!=null?he:{},a=s.expandable!==!1,i=a&&vs.has(e.id),{summary:d,previewText:l,isActive:f}=Xb(e,t),u=b("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");u.type="button",a&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let g=b("div","persona-flex persona-flex-col persona-text-left"),m=b("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(m.style.color=o.headerTextColor);let C=String((me=n.startedAt)!=null?me:Date.now()),v=()=>{let le=b("span","");return le.setAttribute("data-tool-elapsed",C),le.textContent=ma(n),le},M=(Ee=o.renderCollapsedSummary)==null?void 0:Ee.call(o,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(de=s.collapsedMode)!=null?de:"tool-call",isActive:f,config:t!=null?t:{},elapsed:ma(n),createElapsedElement:v});typeof M=="string"&&M.trim()?(m.textContent=M,g.appendChild(m)):M instanceof HTMLElement?g.appendChild(M):(m.textContent=d,g.appendChild(m));let I=(xe=s.loadingAnimation)!=null?xe:"none",R=o.activeTextTemplate,P=o.completeTextTemplate,D=f?R:P,W=M instanceof HTMLElement,w=(le,J,se)=>{let ye=se;for(let be of J){let K=b("span","persona-tool-char");K.style.setProperty("--char-index",String(ye)),K.textContent=be===" "?"\xA0":be,le.appendChild(K),ye++}return ye},x=(le,J)=>{var K;m.textContent="";let se=((K=n.name)==null?void 0:K.trim())||"tool",ye=ki(le,se),be=0;for(let ae of ye){let Re=ae.styles.length>0?(()=>{let oe=b("span",ae.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return m.appendChild(oe),oe})():m;if(ae.isDuration&&f)Re.appendChild(v());else{let oe=ae.isDuration?ma(n):ae.text;J?be=w(Re,oe,be):Re.appendChild(document.createTextNode(oe))}}};if(!W)if(f&&I!=="none"){let le=(De=o.loadingAnimationDuration)!=null?De:2e3;if(m.setAttribute("data-preserve-animation","true"),I==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${le}ms`),D&&x(D,!1);else if(m.classList.add(`persona-tool-loading-${I}`),m.style.setProperty("--persona-tool-anim-duration",`${le}ms`),I==="shimmer-color"&&(o.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),D)x(D,!0);else{let J=m.textContent||d;m.textContent="",w(m,J,0)}}else D&&x(D,!1);let E=null;if(a){E=b("div","persona-flex persona-items-center");let le=o.toggleTextColor||o.headerTextColor||"currentColor",J=Me(i?"chevron-up":"chevron-down",16,le,2);J?E.appendChild(J):E.textContent=i?"Hide":"Show";let se=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");se.append(E),u.append(g,se)}else u.append(g);let S=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(S.setAttribute("data-persona-collapsed-preview","tool"),S.style.display="none",S.style.whiteSpace="pre-wrap",!i&&f&&s.activePreview&&l){let le=(Ae=o.renderCollapsedPreview)==null?void 0:Ae.call(o,{message:e,toolCall:n,defaultPreview:l,isActive:f,config:t!=null?t:{}});Gb(S,le)||(S.textContent=l),S.style.display=""}if(!i&&f&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(u,S),r;let k=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(k.style.display=i?"":"none",o.contentBackgroundColor&&(k.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(k.style.color=o.contentTextColor),o.contentPaddingX&&(k.style.paddingLeft=o.contentPaddingX,k.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(k.style.paddingTop=o.contentPaddingY,k.style.paddingBottom=o.contentPaddingY),n.name){let le=b("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?le.style.color=o.contentTextColor:o.headerTextColor&&(le.style.color=o.headerTextColor),le.textContent=n.name,k.appendChild(le)}if(n.args!==void 0){let le=b("div","persona-space-y-1"),J=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(J.style.color=o.labelTextColor),J.textContent="Arguments";let se=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");se.style.fontSize="0.75rem",se.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(se.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(se.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(se.style.color=o.codeBlockTextColor),se.textContent=hs(n.args),le.append(J,se),k.appendChild(le)}if(n.chunks&&n.chunks.length){let le=b("div","persona-space-y-1"),J=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(J.style.color=o.labelTextColor),J.textContent="Activity";let se=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");se.style.fontSize="0.75rem",se.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(se.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(se.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(se.style.color=o.codeBlockTextColor),se.textContent=n.chunks.join(""),le.append(J,se),k.appendChild(le)}if(n.status==="complete"&&n.result!==void 0){let le=b("div","persona-space-y-1"),J=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(J.style.color=o.labelTextColor),J.textContent="Result";let se=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");se.style.fontSize="0.75rem",se.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(se.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(se.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(se.style.color=o.codeBlockTextColor),se.textContent=hs(n.result),le.append(J,se),k.appendChild(le)}if(n.status==="complete"&&typeof n.duration=="number"){let le=b("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(le.style.color=o.contentTextColor),le.textContent=`Duration: ${n.duration}ms`,k.appendChild(le)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),E){E.innerHTML="";let le=o.toggleTextColor||o.headerTextColor||"currentColor",J=Me(i?"chevron-up":"chevron-down",16,le,2);J?E.appendChild(J):E.textContent=i?"Hide":"Show"}k.style.display=i?"":"none",S.style.display=i?"none":S.textContent||S.childNodes.length?"":"none"})(),r.append(u,S,k),r};var br=require("partial-json");var Jb="ask_user_question",dc=8,xs="data-persona-ask-sheet-for",Qb="Other",Zb="Other\u2026",bf="Type your own answer here",yf="Send",ey="Next",ty="Back",ny="Submit all",oy="Skip",ry=3,pc="data-ask-current-index",uc="data-ask-question-count",vf="data-ask-answers",mc="data-ask-grouped",xf="data-ask-layout",sy=e=>e.layout==="pills"?"pills":"rows",ay=e=>e.getAttribute(xf)==="pills"?"pills":"rows",hf=!1,wf=e=>e.replace(/["\\]/g,"\\$&"),Ur=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Jb,fc=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},ws=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=(0,br.parse)(r,br.STR|br.OBJ|br.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},La=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>dc&&!hf&&(hf=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${dc}.`)),t.slice(0,dc)},iy=e=>{var t;return(t=La(e)[0])!=null?t:null},ly=(e,t)=>{var n;return(n=La(e)[t])!=null?n:null},cy=(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))},Cf=(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},dy=(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=Cf(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},py=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},uy=(e,t,n,o)=>{var f,u,g;let s=b("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!n){for(let m=0;m<ry;m++)s.appendChild(py(o));return s}if(d.forEach((m,C)=>{s.appendChild(dy(m,C,o,a))}),(e==null?void 0:e.allowFreeText)!==!1){let m=o==="rows"?Qb:Zb;if(o==="rows"){let C=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");C.setAttribute("data-ask-user-action","focus-free-text"),C.setAttribute("data-option-index",String(d.length)),C.setAttribute("data-ask-other-row","true");let v=b("span","persona-ask-row-content"),M=document.createElement("input");M.type="text",M.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",M.placeholder=(f=t.freeTextPlaceholder)!=null?f:bf,M.setAttribute("data-ask-free-text-input","true"),M.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:m),v.appendChild(M),C.appendChild(v);let I=Cf(o,a,d.length);I&&C.appendChild(I),s.appendChild(C)}else{let C=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");C.type="button",C.setAttribute("data-ask-user-action","open-free-text"),C.textContent=(g=t.freeTextLabel)!=null?g:m,s.appendChild(C)}}return s},Sf=(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:bf,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:yf,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},my=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:yf,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},fy=(e,t,n)=>{var l,f,u,g;let o=b("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=b("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=(l=n.backLabel)!=null?l:ty,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(f=n.skipLabel)!=null?f:oy,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:ny:(g=n.nextLabel)!=null?g:ey,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},zr=e=>{let t=e.getAttribute(vf);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Af=(e,t)=>{e.setAttribute(vf,JSON.stringify(t))},ho=e=>{var n;let t=Number((n=e.getAttribute(pc))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},gy=(e,t)=>{e.setAttribute(pc,String(Math.max(0,Math.floor(t))))},Cs=e=>{var n;let t=Number((n=e.getAttribute(uc))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},yr=e=>e.getAttribute(mc)==="true",hy=(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},by=(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)))},tl=(e,t)=>{let{payload:n}=ws(t),o=La(n),r=zr(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},Tf=e=>{let t=zr(e),n=ho(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(d=>r.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var u;let l=(u=d.getAttribute("data-option-label"))!=null?u:"",f=r.has(l);d.setAttribute("aria-pressed",f?"true":"false"),d.classList.toggle("persona-ask-pill-selected",f)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!a.has(o)){i.value=o;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},kf=e=>{if(!yr(e))return;let t=zr(e),n=ho(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}},gc=(e,t,n)=>{let o=fc(n),r=ay(e),{payload:s,complete:a}=ws(t),i=yr(e),d=ho(e),l=Cs(e),f=i?ly(s,d):iy(s),u=!!(f!=null&&f.multiSelect),g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${l}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let C=e.querySelector('[data-ask-question="true"]');if(C){let R=typeof(f==null?void 0:f.question)=="string"?f.question:"";C.textContent=R,C.classList.toggle("persona-ask-question-skeleton",!R&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let R=uy(f,o,a,r);v.replaceWith(R)}if(r!=="rows"){let R=e.querySelector('[data-ask-free-text-row="true"]');R&&R.replaceWith(Sf(o,r))}let M=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!M?e.appendChild(my(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 R=fy(d,l,o);I?I.replaceWith(R):e.appendChild(R)}else I&&I.remove();Tf(e),kf(e)},yy=(e,t,n)=>{let o=fc(t),r=sy(o),s=e.toolCall.id,a=La(n),i=Math.max(1,a.length),d=i>1,l=hy(e,a),f=d?by(e,i):0,u=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(xs,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(uc,String(i)),u.setAttribute(pc,String(f)),u.setAttribute(mc,d?"true":"false"),u.setAttribute(xf,r),Af(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`),cy(u,o);let g=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=b("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",g.appendChild(m);let C=b("span","persona-ask-sheet-step-inline");C.setAttribute("data-ask-step-inline","true"),C.textContent="",g.appendChild(C),u.appendChild(g);let 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(Sf(o,r)),gc(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},vy=(e,t,n)=>{let{payload:o}=ws(t),r=Math.max(1,La(o).length);r>Cs(e)&&(e.setAttribute(uc,String(r)),r>1&&!yr(e)&&e.setAttribute(mc,"true")),gc(e,t,n)};var nl=(e,t,n)=>{if(!n||!Ur(e)||fc(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${xs}]`).forEach(l=>{l.getAttribute(xs)!==r&&l.remove()});let a=n.querySelector(`[${xs}="${wf(r)}"]`);if(a){vy(a,e,t);return}let{payload:i}=ws(e),d=yy(e,t,i);n.appendChild(d)},Ss=(e,t)=>{if(!e)return;let n=t?`[${xs}="${wf(t)}"]`:`[${xs}]`;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)})},hc=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),vr=(e,t)=>{let n=zr(e),o=ho(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Af(e,n),Tf(e),kf(e)},ol=(e,t,n,o)=>{let r=Cs(e),s=Math.max(0,Math.min(r-1,o));gy(e,s),gc(e,t,n)};var rl=new Map,xy=e=>{let n=(e.startsWith(Or)?e.slice(Or.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Ef=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Mf=(e,t)=>{var o,r,s;let n=(r=(o=Ef(t))==null?void 0:o.detailsDisplay)!=null?r:"collapsed";return(s=rl.get(e))!=null?s:n==="expanded"},Lf=(e,t,n)=>{var a,i;let o=Ef(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?(a=o==null?void 0:o.hideDetailsLabel)!=null?a:"Hide details":(i=o==null?void 0:o.showDetailsLabel)!=null?i:"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=Me(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},If=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=Mf(e,n);Lf(o,s,n),r.style.display=s?"":"none"};var sl=(e,t)=>{var x,E,S,k,V,z,Y,he,me,de,Ee,xe,De,Ae,le;let n=e.approval,o=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,r=(n==null?void 0:n.status)==="pending",s=b("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(x=o==null?void 0:o.backgroundColor)!=null?x:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(E=o==null?void 0:o.borderColor)!=null?E:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(o==null?void 0:o.shadow)!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=b("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",l=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(S=o==null?void 0:o.titleColor)!=null?S:"currentColor",f=Me(d,20,l,2);f&&i.appendChild(f);let u=b("div","persona-flex-1 persona-min-w-0"),g=b("div","persona-flex persona-items-center persona-gap-2"),m=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o!=null&&o.titleColor&&(m.style.color=o.titleColor),m.textContent=(k=o==null?void 0:o.title)!=null?k:"Approval Required",g.appendChild(m),!r){let J=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");J.setAttribute("data-approval-status",n.status),n.status==="approved"?(J.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",J.style.color="var(--persona-palette-colors-success-700, #15803d)",J.textContent="Approved"):n.status==="denied"?(J.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",J.style.color="var(--persona-palette-colors-error-700, #b91c1c)",J.textContent="Denied"):n.status==="timeout"&&(J.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",J.style.color="var(--persona-palette-colors-warning-700, #b45309)",J.textContent="Timeout"),g.appendChild(J)}u.appendChild(g);let v=n.toolType==="webmcp"||n.toolName.startsWith(Or)?Gl(n.toolName):void 0,M=(V=o==null?void 0:o.formatDescription)==null?void 0:V.call(o,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...v?{displayTitle:v}:{},...n.reason?{reason:n.reason}:{}}),I=!n.toolName,R=M||(I?n.description:`The assistant wants to use \u201C${v!=null?v:xy(n.toolName)}\u201D.`),P=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(P.setAttribute("data-approval-summary","true"),o!=null&&o.descriptionColor&&(P.style.color=o.descriptionColor),P.textContent=R,u.appendChild(P),n.reason){let J=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");J.setAttribute("data-approval-reason","true"),o!=null&&o.reasonColor?J.style.color=o.reasonColor:o!=null&&o.descriptionColor&&(J.style.color=o.descriptionColor);let se=b("span","persona-font-medium");se.textContent=`${(z=o==null?void 0:o.reasonLabel)!=null?z:"Agent's stated reason:"} `,J.appendChild(se),J.appendChild(document.createTextNode(n.reason)),u.appendChild(J)}let D=(Y=o==null?void 0:o.detailsDisplay)!=null?Y:"collapsed",W=!!n.description&&!I,w=W||!!n.parameters;if(D!=="hidden"&&w){let J=Mf(e.id,t),se=b("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");se.type="button",se.setAttribute("data-expand-header","true"),se.setAttribute("data-bubble-type","approval"),o!=null&&o.descriptionColor&&(se.style.color=o.descriptionColor);let ye=b("span");ye.setAttribute("data-approval-details-label","true");let be=b("span","persona-inline-flex persona-items-center");be.setAttribute("data-approval-details-chevron","true"),se.append(ye,be),Lf(se,J,t),u.appendChild(se);let K=b("div");if(K.setAttribute("data-approval-details","true"),K.style.display=J?"":"none",W){let ae=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o!=null&&o.descriptionColor&&(ae.style.color=o.descriptionColor),ae.textContent=n.description,K.appendChild(ae)}if(n.parameters){let ae=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&&(ae.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(ae.style.color=o.parameterTextColor),ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",ae.textContent=hs(n.parameters),K.appendChild(ae)}u.appendChild(K)}if(r){let J=b("div","persona-flex persona-gap-2 persona-mt-2");J.setAttribute("data-approval-buttons","true");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-border-none persona-cursor-pointer");se.type="button",se.style.backgroundColor=(he=o==null?void 0:o.approveButtonColor)!=null?he:"var(--persona-approval-approve-bg, #22c55e)",se.style.color=(me=o==null?void 0:o.approveButtonTextColor)!=null?me:"#ffffff",se.setAttribute("data-approval-action","approve");let ye=Me("shield-check",14,(de=o==null?void 0:o.approveButtonTextColor)!=null?de:"#ffffff",2);ye&&(ye.style.marginRight="4px",se.appendChild(ye));let be=document.createTextNode((Ee=o==null?void 0:o.approveLabel)!=null?Ee:"Approve");se.appendChild(be);let K=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");K.type="button",K.style.backgroundColor=(xe=o==null?void 0:o.denyButtonColor)!=null?xe:"transparent",K.style.color=(De=o==null?void 0:o.denyButtonTextColor)!=null?De:"var(--persona-feedback-error, #dc2626)",K.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,K.setAttribute("data-approval-action","deny");let ae=Me("shield-x",14,(Ae=o==null?void 0:o.denyButtonTextColor)!=null?Ae:"var(--persona-feedback-error, #dc2626)",2);ae&&(ae.style.marginRight="4px",K.appendChild(ae));let Re=document.createTextNode((le=o==null?void 0:o.denyLabel)!=null?le:"Deny");K.appendChild(Re),J.append(se,K),u.appendChild(J)}return a.append(i,u),s.appendChild(a),s};var Rf=e=>{let t=[];return{buttons:t,render:(o,r,s,a,i)=>{if(e.innerHTML="",t.length=0,!o||!o.length||(a!=null?a:r?r.getMessages():[]).some(m=>m.role==="user"))return;let f=document.createDocumentFragment(),u=r?r.isStreaming():!1,g=m=>{switch(m){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};o.forEach(m=>{let C=b("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");C.type="button",C.textContent=m,C.disabled=u,i!=null&&i.fontFamily&&(C.style.fontFamily=g(i.fontFamily)),i!=null&&i.fontWeight&&(C.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(C.style.paddingLeft=i.paddingX,C.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(C.style.paddingTop=i.paddingY,C.style.paddingBottom=i.paddingY),C.addEventListener("click",()=>{!r||r.isStreaming()||(s.value="",r.sendMessage(m))}),f.appendChild(C),t.push(C)}),e.appendChild(f)}}};var Ia=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Ra=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}};var wy=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Cy=new Set(["step_start","execution_start"]),Sy=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Ay=new Set(["step_complete","agent_turn_complete"]),Ty=new Set(["flow_complete","agent_complete"]),Pf=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Bf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),no=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,qr=(e,t)=>{let n=e[t];return Bf(n)?n:void 0};function bc(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function al(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function ky(e,t){return typeof t.type=="string"?t.type:e}function Ey(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 My(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 Wf(e){var o,r,s,a,i;let t=qr(e,"result"),n=[qr(e,"tokens"),qr(e,"totalTokens"),t?qr(t,"tokens"):void 0,qr(e,"usage"),t?qr(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(r=(o=no(d.output))!=null?o:no(d.outputTokens))!=null?r:no(d.completionTokens);if(l!==void 0)return l}return(i=(s=no(e.outputTokens))!=null?s:no(e.completionTokens))!=null?i:t?(a=no(t.outputTokens))!=null?a:no(t.completionTokens):void 0}function Ly(e){var n,o,r,s,a;let t=qr(e,"result");return(a=(r=(o=(n=no(e.executionTime))!=null?n:no(e.executionTimeMs))!=null?o:no(e.execution_time))!=null?r:no(e.duration))!=null?a:t?(s=no(t.executionTime))!=null?s:no(t.executionTimeMs):void 0}function Iy(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Pa=class{constructor(t=Iy){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:al(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(!Bf(n)){Pf.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=ky(t,n),r=this.now();if(wy.has(o)){this.startRun(r);return}if(Cy.has(o)){this.run||this.startRun(r);return}if(Sy.has(o)){if(!My(o,n))return;let a=Ey(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+bc(i.visibleCharCount),l=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:al(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Ay.has(o)){if(!this.run)return;let a=this.run,i=Wf(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+bc(a.visibleCharCount),f=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:al(l,f),outputTokens:l,durationMs:f,source:d?"usage":"estimate"};return}if(Ty.has(o)){if(!this.run)return;let a=this.run,i=Wf(n),d=i!=null?i:a.exactOutputTokens+bc(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",f=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:al(d,f),outputTokens:d,durationMs:f,source:l},this.run=null;return}if(Pf.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=Ly(n);return s!=null?s:o-t.startedAt}};function As(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Ry={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)"}},Py={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Wy=["flowName","stepName","reasoningText","text","name","tool","toolName"],By=100;function Hy(e,t){let n={...Ry,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Py}function Dy(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Fy(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 Oy(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 Ny(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 _y(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 Vy(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function $y(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 Uy(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 yc(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");As(l,(g=o.classNames)==null?void 0:g.eventRow);let f=a.find(m=>m.renderEventStreamRow);if(f!=null&&f.renderEventStreamRow&&i){let m=f.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(m)return l.appendChild(m),l}return l.appendChild(u()),l;function u(){var z,Y;let m=b("div",""),C=b("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");C.setAttribute("data-event-id",e.id);let v=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),M=Me(d?"chevron-down":"chevron-right","14px","currentColor",2);M&&v.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=(z=o.timestampFormat)!=null?z:"relative";I.textContent=R==="relative"?Dy(e.timestamp,n):Fy(e.timestamp);let P=null;o.showSequenceNumbers!==!1&&(P=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),P.textContent=String(t+1));let D=Hy(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 w=(Y=o.descriptionFields)!=null?Y:Wy,x=Oy(e.payload,w),E=null;x&&(E=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),E.textContent=x);let S=b("div","persona-flex-1 persona-min-w-0"),k=b("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),V=Me("clipboard","12px","currentColor",1.5);return V&&k.appendChild(V),k.addEventListener("click",async he=>{he.stopPropagation(),await Ny(_y(e)),k.innerHTML="";let me=Me("check","12px","currentColor",1.5);me&&k.appendChild(me),setTimeout(()=>{k.innerHTML="";let de=Me("clipboard","12px","currentColor",1.5);de&&k.appendChild(de)},1500)}),C.appendChild(v),C.appendChild(I),P&&C.appendChild(P),C.appendChild(W),E&&C.appendChild(E),C.appendChild(S),C.appendChild(k),m.appendChild(C),d&&m.appendChild(Uy(e,a,i)),m}}function Hf(e){var C,v,M,I,R;let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,i=(C=r==null?void 0:r.features)==null?void 0:C.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(v=i==null?void 0:i.iconName)!=null?v:"arrow-down",f=(M=i==null?void 0:i.label)!=null?M:"",u=(R=(I=r==null?void 0:r.features)==null?void 0:I.eventStream)!=null?R:{},g=s.find(P=>P.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&r){let P=g.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>m().element,onClose:o});if(P)return{element:P,update:()=>{},destroy:()=>{}}}return m();function m(){let P=u.classNames,D=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");As(D,P==null?void 0:P.panel);let W=[],w="",x="",E=null,S=[],k={},V=0,z=Oi(),Y=0,he=0,me=!1,de=null,Ee=!1,xe=0,De=new Set,Ae=new Map,le="",J="",se=null,ye,be,K,ae,Re,oe=null,ee=null,re=null;function it(){let Se=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ce=b("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");As(ce,P==null?void 0:P.headerBar);let et=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(et.textContent="Events",ye=b("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),ye.textContent="0",a){ee=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ee.style.cursor="help";let Cn=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Cn.textContent="Throughput",oe=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"),oe.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 Sn=ee,yn=re,Lo=()=>{if(!yn.textContent)return;let Un=Sn.getBoundingClientRect(),zn=Se.getBoundingClientRect();yn.style.left=`${Un.left-zn.left}px`,yn.style.top=`${Un.bottom-zn.top+4}px`,yn.style.display="block"},At=()=>{yn.style.display="none"};ee.addEventListener("mouseenter",Lo),ee.addEventListener("mouseleave",At),ee.appendChild(Cn),ee.appendChild(oe)}let Qt=b("div","persona-flex-1");be=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 Gt=b("option","");Gt.value="",Gt.textContent="All events",be.appendChild(Gt),K=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"),K.type="button",K.title="Copy All";let vn=Me("clipboard-copy","12px","currentColor",1.5);vn&&K.appendChild(vn);let gt=b("span","persona-text-xs");gt.textContent="Copy All",K.appendChild(gt),ce.appendChild(et),ce.appendChild(ye),ee&&ce.appendChild(ee),ce.appendChild(Qt),ce.appendChild(be),ce.appendChild(K);let Lt=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");As(Lt,P==null?void 0:P.searchBar);let Qe=Me("search","14px","var(--persona-muted, #9ca3af)",1.5),qt=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Qe&&qt.appendChild(Qe),ae=b("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),As(ae,P==null?void 0:P.searchInput),ae.type="text",ae.placeholder="Search event payloads...",Re=b("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Re.type="button",Re.style.display="none";let ln=Me("x","12px","currentColor",2);return ln&&Re.appendChild(ln),Lt.appendChild(qt),Lt.appendChild(ae),Lt.appendChild(Re),Se.appendChild(ce),Se.appendChild(Lt),re&&Se.appendChild(re),Se}let lt,Le=s.find(Se=>Se.renderEventStreamToolbar);if(Le!=null&&Le.renderEventStreamToolbar&&r){let Se=Le.renderEventStreamToolbar({config:r,defaultRenderer:()=>it(),eventCount:t.getSize(),filteredCount:0,onFilterChange:ce=>{w=ce,an(),F()},onSearchChange:ce=>{x=ce,an(),F()}});lt=Se!=null?Se:it()}else lt=it();let pe=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");pe.style.display="none";function Je(){if(!a||!oe||!ee)return;let Se=a();oe.textContent=Vy(Se);let ce=$y(Se);re&&(re.textContent=ce,ce||(re.style.display="none")),ce?ee.setAttribute("aria-label",ce):ee.removeAttribute("aria-label")}let Be=b("div","persona-flex-1 persona-min-h-0 persona-relative"),j=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");j.style.height="100%";let fe=b("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");As(fe,P==null?void 0:P.scrollIndicator),fe.style.display="none",fe.setAttribute("data-persona-scroll-to-bottom-has-label",f?"true":"false");let tt=Me(l,"14px","currentColor",2);tt&&fe.appendChild(tt);let Mt=b("span","");Mt.textContent=f,fe.appendChild(Mt);let te=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");te.style.display="none",Be.appendChild(j),Be.appendChild(te),Be.appendChild(fe),D.setAttribute("tabindex","0"),D.appendChild(lt),D.appendChild(pe),D.appendChild(Be);function qe(){let Se=t.getAll(),ce={};for(let gt of Se)ce[gt.type]=(ce[gt.type]||0)+1;let et=Object.keys(ce).sort(),Qt=et.length!==S.length||!et.every((gt,Lt)=>gt===S[Lt]),Gt=!Qt&&et.some(gt=>ce[gt]!==k[gt]),In=Se.length!==Object.values(k).reduce((gt,Lt)=>gt+Lt,0);if(!Qt&&!Gt&&!In||(S=et,k=ce,!be))return;let vn=be.value;if(be.options[0].textContent="All events",Qt){for(;be.options.length>1;)be.remove(1);for(let gt of et){let Lt=b("option","");Lt.value=gt,Lt.textContent=`${gt} (${ce[gt]||0})`,be.appendChild(Lt)}vn&&et.includes(vn)?be.value=vn:vn&&(be.value="",w="")}else for(let gt=1;gt<be.options.length;gt++){let Lt=be.options[gt];Lt.textContent=`${Lt.value} (${ce[Lt.value]||0})`}}function Fn(){let Se=t.getAll();if(w&&(Se=Se.filter(ce=>ce.type===w)),x){let ce=x.toLowerCase();Se=Se.filter(et=>et.type.toLowerCase().includes(ce)||et.payload.toLowerCase().includes(ce))}return Se}function Dt(){return w!==""||x!==""}function an(){V=0,Y=0,z.resume(),fe.style.display="none"}function oo(Se){De.has(Se)?De.delete(Se):De.add(Se),se=Se;let ce=j.scrollTop,et=z.isFollowing();Ee=!0,z.pause(),F(),j.scrollTop=ce,et&&z.resume(),Ee=!1}function Mo(){return Vr(j,50)}function F(){he=Date.now(),me=!1,Je(),qe();let Se=t.getEvictedCount();Se>0?(pe.textContent=`${Se.toLocaleString()} older events truncated`,pe.style.display=""):pe.style.display="none",W=Fn();let ce=W.length,et=t.getSize()>0;ye&&(ye.textContent=String(t.getSize())),ce===0&&et&&Dt()?(te.textContent=x?`No events matching '${x}'`:"No events matching filter",te.style.display="",j.style.display="none"):(te.style.display="none",j.style.display=""),K&&(K.title=Dt()?`Copy Filtered (${ce})`:"Copy All"),d&&!z.isFollowing()&&ce>V&&(Y+=ce-V,Mt.textContent=f?`${f}${Y>0?` (${Y})`:""}`:"",fe.style.display=""),V=ce;let Qt=t.getAll(),Gt=Qt.length>0?Qt[0].timestamp:0,In=new Set(W.map(Lt=>Lt.id));for(let Lt of De)In.has(Lt)||De.delete(Lt);let vn=w!==le||x!==J,gt=Ae.size===0&&W.length>0;if(vn||gt||W.length===0){j.innerHTML="",Ae.clear();let Lt=document.createDocumentFragment();for(let Qe=0;Qe<W.length;Qe++){let qt=yc(W[Qe],Qe,Gt,u,De,oo,s,r);Ae.set(W[Qe].id,qt),Lt.appendChild(qt)}j.appendChild(Lt),le=w,J=x,se=null}else{if(se!==null){let Qe=Ae.get(se);if(Qe&&Qe.parentNode===j){let qt=W.findIndex(ln=>ln.id===se);if(qt>=0){let ln=yc(W[qt],qt,Gt,u,De,oo,s,r);j.insertBefore(ln,Qe),Qe.remove(),Ae.set(se,ln)}}se=null}let Lt=new Set(W.map(Qe=>Qe.id));for(let[Qe,qt]of Ae)Lt.has(Qe)||(qt.remove(),Ae.delete(Qe));for(let Qe=0;Qe<W.length;Qe++){let qt=W[Qe];if(!Ae.has(qt.id)){let ln=yc(qt,Qe,Gt,u,De,oo,s,r);Ae.set(qt.id,ln),j.appendChild(ln)}}}z.isFollowing()&&(j.scrollTop=j.scrollHeight)}function ue(){if(Date.now()-he>=By){de!==null&&(cancelAnimationFrame(de),de=null),F();return}me||(me=!0,de=requestAnimationFrame(()=>{de=null,F()}))}let Fe=(Se,ce)=>{if(!K)return;K.innerHTML="";let et=Me(Se,"12px","currentColor",1.5);et&&K.appendChild(et);let Qt=b("span","persona-text-xs");Qt.textContent="Copy All",K.appendChild(Qt),setTimeout(()=>{K.innerHTML="";let Gt=Me("clipboard-copy","12px","currentColor",1.5);Gt&&K.appendChild(Gt);let In=b("span","persona-text-xs");In.textContent="Copy All",K.appendChild(In),K.disabled=!1},ce)},Ke=async()=>{if(K){K.disabled=!0;try{let Se;Dt()?Se=W:n?(Se=await n(),Se.length===0&&(Se=t.getAll())):Se=t.getAll();let ce=Se.map(et=>{try{return JSON.parse(et.payload)}catch{return et.payload}});await navigator.clipboard.writeText(JSON.stringify(ce,null,2)),Fe("check",1500)}catch{Fe("x",1500)}}},_e=()=>{be&&(w=be.value,an(),F())},$e=()=>{!ae||!Re||(Re.style.display=ae.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{x=ae.value,an(),F()},150))},ot=()=>{!ae||!Re||(ae.value="",x="",Re.style.display="none",E&&clearTimeout(E),an(),F())},Pt=()=>{if(Ee)return;let Se=j.scrollTop,{action:ce,nextLastScrollTop:et}=Ni({following:z.isFollowing(),currentScrollTop:Se,lastScrollTop:xe,nearBottom:Mo(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});xe=et,ce==="resume"?(z.resume(),Y=0,fe.style.display="none"):ce==="pause"&&(z.pause(),d&&(Mt.textContent=f,fe.style.display=""))},Kt=Se=>{let ce=_i({following:z.isFollowing(),deltaY:Se.deltaY,nearBottom:Mo(),resumeWhenNearBottom:!0});ce==="pause"?(z.pause(),d&&(Mt.textContent=f,fe.style.display="")):ce==="resume"&&(z.resume(),Y=0,fe.style.display="none")},Jt=()=>{d&&(j.scrollTop=j.scrollHeight,z.resume(),Y=0,fe.style.display="none")},G=Se=>{let ce=Se.target;if(!ce||ce.closest("button"))return;let et=ce.closest("[data-event-id]");if(!et)return;let Qt=et.getAttribute("data-event-id");Qt&&oo(Qt)},xt=Se=>{if((Se.metaKey||Se.ctrlKey)&&Se.key==="f"){Se.preventDefault(),ae==null||ae.focus(),ae==null||ae.select();return}Se.key==="Escape"&&(ae&&document.activeElement===ae?(ot(),ae.blur(),D.focus()):o&&o())};K&&K.addEventListener("click",Ke),be&&be.addEventListener("change",_e),ae&&ae.addEventListener("input",$e),Re&&Re.addEventListener("click",ot),j.addEventListener("scroll",Pt),j.addEventListener("wheel",Kt,{passive:!0}),j.addEventListener("click",G),fe.addEventListener("click",Jt),D.addEventListener("keydown",xt);function st(){E&&clearTimeout(E),de!==null&&(cancelAnimationFrame(de),de=null),me=!1,Ae.clear(),K&&K.removeEventListener("click",Ke),be&&be.removeEventListener("change",_e),ae&&ae.removeEventListener("input",$e),Re&&Re.removeEventListener("click",ot),j.removeEventListener("scroll",Pt),j.removeEventListener("wheel",Kt),j.removeEventListener("click",G),fe.removeEventListener("click",Jt),D.removeEventListener("keydown",xt)}return{element:D,update:ue,destroy:st}}}function Df(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",o=typeof e.artifactId=="string"?e.artifactId:"",r=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),o&&i.setAttribute("data-open-artifact",o);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let f=document.createElement("div");f.className="persona-truncate persona-text-sm persona-font-medium",f.style.color="var(--persona-text, #1f2937)",f.textContent=n;let u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.style.color="var(--persona-muted, #9ca3af)",r==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(g);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(m)}else u.textContent=a;if(l.append(f,u),i.append(d,l),r==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${n}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",o),i.append(g)}return i}var Ff=(e,t)=>{var o,r,s;let n=(s=(r=(o=t==null?void 0:t.config)==null?void 0:o.features)==null?void 0:r.artifacts)==null?void 0:s.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",f=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>Df(e,t)});if(f)return f}return Df(e,t)};var vc=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)})}},jr=new vc;jr.register("PersonaArtifactCard",Ff);function zy(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 Of(e,t){var be,K,ae,Re;let n=(K=(be=e.features)==null?void 0:be.artifacts)==null?void 0:K.layout,r=((ae=n==null?void 0:n.toolbarPreset)!=null?ae:"default")==="document",s=(Re=n==null?void 0:n.panePadding)==null?void 0:Re.trim(),a=e.markdown?xi(e.markdown):null,i=wi(e.sanitize),d=oe=>{let ee=a?a(oe):pa(oe);return i?i(ee):ee},l=typeof document!="undefined"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,f=()=>{l==null||l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),V==null||V.hide()};l&&l.addEventListener("click",()=>{var oe;f(),(oe=t.onDismiss)==null||oe.call(t)});let u=b("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");u.setAttribute("data-persona-theme-zone","artifact-pane"),r&&u.classList.add("persona-artifact-pane-document");let g=b("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&g.classList.add("persona-artifact-toolbar-document");let m=b("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let C=b("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");C.type="button",C.textContent="Close",C.setAttribute("aria-label","Close artifacts panel"),C.addEventListener("click",()=>{var oe;f(),(oe=t.onDismiss)==null||oe.call(t)});let v="rendered",M=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),I=r?Ln({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Ln({icon:"eye",label:"Rendered view"}),R=r?Ln({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Ln({icon:"code-2",label:"Source"}),P=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,w=n==null?void 0:n.documentToolbarCopyMenuItems,x=!!(W&&w&&w.length>0),E=null,S,k=null,V=null;if(r&&(D||W)&&!x){if(S=D?rc({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Ln({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W){let oe=Me("chevron-down",14,"currentColor",2);oe&&S.appendChild(oe)}}else r&&x?(E=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),S=D?rc({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Ln({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),k=Ln({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),E.append(S,k)):r?S=Ln({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):S=Ln({icon:"copy",label:"Copy"});let z=r?Ln({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Ln({icon:"refresh-cw",label:"Refresh"}),Y=r?Ln({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Ln({icon:"x",label:"Close"}),he=()=>{var lt,Le,pe;let oe=(lt=Ae.find(Je=>Je.id===le))!=null?lt:Ae[Ae.length-1],ee=(Le=oe==null?void 0:oe.id)!=null?Le:null,re=(oe==null?void 0:oe.artifactType)==="markdown"&&(pe=oe.markdown)!=null?pe:"",it=oe?JSON.stringify({component:oe.component,props:oe.props},null,2):"";return{markdown:re,jsonPayload:it,id:ee}},me=async()=>{var lt;let{markdown:oe,jsonPayload:ee}=he(),re=(lt=Ae.find(Le=>Le.id===le))!=null?lt:Ae[Ae.length-1],it=(re==null?void 0:re.artifactType)==="markdown"?oe:re?ee:"";try{await navigator.clipboard.writeText(it)}catch{}};if(S.addEventListener("click",async()=>{let oe=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(oe&&x){let{markdown:ee,jsonPayload:re,id:it}=he();try{await oe({actionId:"primary",artifactId:it,markdown:ee,jsonPayload:re})}catch{}return}await me()}),k&&(w!=null&&w.length)){let oe=()=>{var re;return(re=u.closest("[data-persona-root]"))!=null?re:document.body},ee=()=>{V=bs({items:w.map(re=>({id:re.id,label:re.label})),onSelect:async re=>{let{markdown:it,jsonPayload:lt,id:Le}=he(),pe=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{pe?await pe({actionId:re,artifactId:Le,markdown:it,jsonPayload:lt}):re==="markdown"||re==="md"?await navigator.clipboard.writeText(it):re==="json"||re==="source"?await navigator.clipboard.writeText(lt):await navigator.clipboard.writeText(it||lt)}catch{}},anchor:E!=null?E:k,position:"bottom-right",portal:oe()})};u.isConnected?ee():requestAnimationFrame(ee),k.addEventListener("click",re=>{re.stopPropagation(),V==null||V.toggle()})}z.addEventListener("click",async()=>{var oe;try{await((oe=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:oe.call(n))}catch{}se()}),Y.addEventListener("click",()=>{var oe;f(),(oe=t.onDismiss)==null||oe.call(t)});let de=()=>{r&&(I.setAttribute("aria-pressed",v==="rendered"?"true":"false"),R.setAttribute("aria-pressed",v==="source"?"true":"false"))};I.addEventListener("click",()=>{v="rendered",de(),se()}),R.addEventListener("click",()=>{v="source",de(),se()});let Ee=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,R),E?P.append(E,z,Y):P.append(S,z,Y),g.append(M,Ee,P),de()):(g.appendChild(m),g.appendChild(C)),s&&(g.style.paddingLeft=s,g.style.paddingRight=s);let xe=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"),De=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(xe.style.paddingLeft=s,xe.style.paddingRight=s,De.style.padding=s),u.appendChild(g),u.appendChild(xe),u.appendChild(De);let Ae=[],le=null,J=!1,se=()=>{var it,lt,Le,pe;let oe=r&&Ae.length<=1;xe.classList.toggle("persona-hidden",oe),xe.replaceChildren();for(let Je of Ae){let Be=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");Be.type="button",Be.textContent=Je.title||Je.id.slice(0,8),Je.id===le&&Be.classList.add("persona-bg-persona-container","persona-border-persona-border"),Be.addEventListener("click",()=>t.onSelect(Je.id)),xe.appendChild(Be)}De.replaceChildren();let ee=le&&Ae.find(Je=>Je.id===le)||Ae[Ae.length-1];if(!ee)return;if(r){let Je=ee.artifactType==="markdown"?"MD":(it=ee.component)!=null?it:"Component",j=(ee.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Ee.textContent=`${j} \xB7 ${Je}`}else m.textContent="Artifacts";if(ee.artifactType==="markdown"){if(r&&v==="source"){let Be=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Be.textContent=(lt=ee.markdown)!=null?lt:"",De.appendChild(Be);return}let Je=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Je.innerHTML=d((Le=ee.markdown)!=null?Le:""),De.appendChild(Je);return}let re=ee.component?jr.get(ee.component):void 0;if(re){let Be={message:{id:ee.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let j=re((pe=ee.props)!=null?pe:{},Be);if(j){De.appendChild(j);return}}catch{}}De.appendChild(zy(ee))},ye=()=>{var ee;let oe=Ae.length>0;if(u.classList.toggle("persona-hidden",!oe),l){let re=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,lt=((ee=re==null?void 0:re.classList.contains("persona-artifact-narrow-host"))!=null?ee:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;oe&<&&J?(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(oe){var ee,re,it;Ae=oe.artifacts,le=(it=(re=oe.selectedId)!=null?re:(ee=oe.artifacts[oe.artifacts.length-1])==null?void 0:ee.id)!=null?it:null,Ae.length>0&&(J=!0),se(),ye()},setMobileOpen(oe){J=oe,!oe&&l?(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):ye()}}}function bo(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 Nf(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"),!bo(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 qy(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 il(e,t){var d,l,f,u,g,m,C,v,M,I;if(!bo(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"),qy(e),Nf(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(f=n==null?void 0:n.splitGap)!=null?f:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(u=n==null?void 0:n.paneWidth)!=null?u:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(g=n==null?void 0:n.paneMaxWidth)!=null?g:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=(m=n==null?void 0:n.paneBackground)==null?void 0:m.trim();o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let r=(C=n==null?void 0:n.panePadding)==null?void 0:C.trim();r?e.style.setProperty("--persona-artifact-pane-padding",r):e.style.removeProperty("--persona-artifact-pane-padding");let s=(v=n==null?void 0:n.documentToolbarIconColor)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(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"),Nf(e,t)}var _f=["panel","seamless"];function ll(e,t){var i,d,l,f,u,g;for(let m of _f)e.classList.remove(`persona-artifact-appearance-${m}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!bo(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=_f.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${r}`);let s=(f=n==null?void 0:n.paneBorderRadius)==null?void 0:f.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(u=n==null?void 0:n.paneShadow)==null?void 0:u.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((g=n.unifiedSplitOuterRadius)==null?void 0:g.trim())||s;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Vf(e,t){var n,o,r;return!t||!bo(e)?!1:((r=(o=(n=e.features)==null?void 0:n.artifacts)==null?void 0:o.layout)==null?void 0:r.expandLauncherPanelWhenOpen)!==!1}function jy(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 Ky(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 Gy(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Yy(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function $f(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 Uf(e,t,n,o,r,s){let a=jy(r,200),i=Yy(t,n,o,200);i=Math.max(a,i);let d=Ky(s);return d!==null&&(i=Math.min(i,d)),Gy(e,a,i)}var zf={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"}},xc=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var C,v,M;if(s.dataset.enhanced==="true")return;let a=(C=s.dataset.tvForm)!=null?C:"init";s.dataset.enhanced="true";let i=(v=zf[a])!=null?v:zf.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 f=document.createElement("form");f.className="persona-form-grid persona-space-y-3",i.fields.forEach(I=>{var w,x;let R=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");R.htmlFor=`${t.id}-${a}-${I.name}`;let P=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");P.textContent=I.label,R.appendChild(P);let D=(w=I.type)!=null?w:"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),R.appendChild(W),f.appendChild(R)});let u=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=b("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(M=i.submitLabel)!=null?M:"Submit",u.appendChild(g),u.appendChild(m),f.appendChild(u),s.replaceChildren(d,f),f.addEventListener("submit",async I=>{var W,w;I.preventDefault();let R=(W=n.formEndpoint)!=null?W:"/form",P=new FormData(f),D={};P.forEach((x,E)=>{D[E]=x}),D.type=a,m.disabled=!0,g.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 E=await x.json();g.textContent=(w=E.message)!=null?w:"Thanks! We'll be in touch soon.",E.success&&E.nextPrompt&&await o.sendMessage(String(E.nextPrompt))}catch(x){g.textContent=x instanceof Error?x.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var wc=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()}},Cc=new wc;var qf=()=>{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 Xy=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Jy=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},Ac=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Xy(e),n=Jy(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}},Sc=e=>typeof e=="string"?e:e==null?"":String(e),Wa={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Sc(e.payload.text)},messageAndClick:(e,t)=>{var r;if(e.type!=="message_and_click")return;let n=e.payload,o=Sc(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:Sc(n.text)}}},jf=e=>Array.isArray(e)?e.map(t=>String(t)):[],Tc=e=>{let t=new Set(jf(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(jf(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,f)=>l||(f==null?void 0:f({text:a,message:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),o();let d={action:i,message:s.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let f=()=>{e.emit("action:resubmit",d)},u=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:f});if(!u)continue;if(u.handled){let g=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:g,resubmit:u.resubmit}}}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",f)}return{text:"",persist:!0}},syncFromMetadata:n}};var Qy=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}},Zy=e=>e.map(t=>({...t,streaming:!1})),ev=e=>e.map(t=>({...t,status:"complete"})),Kf=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Qy(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?Zy(n.messages):void 0,artifacts:n.artifacts?ev(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)}}}};var kc=require("partial-json");function Gf(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=jr.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 Yf(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function Xf(e){let t=Yf(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 Jf(e){let t=Yf(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 tv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Qf(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=tv}=e,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-csat",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Customer satisfaction feedback");let u=null,g=document.createElement("div");g.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,m.appendChild(C);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=r,m.appendChild(v),g.appendChild(m);let 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 w=1;w<=5;w++){let x=document.createElement("button");x.type="button",x.className="persona-feedback-rating-btn persona-feedback-star-btn",x.setAttribute("role","radio"),x.setAttribute("aria-checked","false"),x.setAttribute("aria-label",`${w} star${w>1?"s":""}: ${l[w-1]}`),x.title=l[w-1],x.dataset.rating=String(w),x.innerHTML=`
|
|
27
27
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
28
28
|
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
|
|
29
29
|
</svg>
|
|
30
|
-
`,w.addEventListener("click",()=>{p=x,I.forEach((E,S)=>{let T=S<x;E.classList.toggle("selected",T),E.setAttribute("aria-checked",S===x-1?"true":"false")})}),I.push(w),M.appendChild(w)}f.appendChild(M);let R=null;if(d){let x=document.createElement("div");x.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"),x.appendChild(R),f.appendChild(x)}let W=document.createElement("div");W.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 B=document.createElement("button");return B.type="button",B.className="persona-feedback-btn persona-feedback-btn-submit",B.textContent=a,B.addEventListener("click",async()=>{if(p===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}B.disabled=!0,B.textContent="Submitting...";try{let x=(R==null?void 0:R.value.trim())||void 0;await t(p,x),m.remove()}catch(x){B.disabled=!1,B.textContent=a,console.error("[CSAT Feedback] Failed to submit:",x)}}),W.appendChild(D),W.appendChild(B),f.appendChild(W),m.appendChild(f),m}function Ag(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:m="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let f=null,u=document.createElement("div");u.className="persona-feedback-content";let C=document.createElement("div");C.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=o,C.appendChild(v);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=r,C.appendChild(M),u.appendChild(C);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 W=document.createElement("span");W.className="persona-feedback-label-low",W.textContent=l;let D=document.createElement("span");D.className="persona-feedback-label-high",D.textContent=m,R.appendChild(W),R.appendChild(D);let B=document.createElement("div");B.className="persona-feedback-numbers";let x=[];for(let _=0;_<=10;_++){let U=document.createElement("button");U.type="button",U.className="persona-feedback-rating-btn persona-feedback-number-btn",U.setAttribute("role","radio"),U.setAttribute("aria-checked","false"),U.setAttribute("aria-label",`Rating ${_} out of 10`),U.textContent=String(_),U.dataset.rating=String(_),_<=6?U.classList.add("persona-feedback-detractor"):_<=8?U.classList.add("persona-feedback-passive"):U.classList.add("persona-feedback-promoter"),U.addEventListener("click",()=>{f=_,x.forEach((Y,he)=>{Y.classList.toggle("selected",he===_),Y.setAttribute("aria-checked",he===_?"true":"false")})}),x.push(U),B.appendChild(U)}I.appendChild(R),I.appendChild(B),u.appendChild(I);let w=null;if(d){let _=document.createElement("div");_.className="persona-feedback-comment-container",w=document.createElement("textarea"),w.className="persona-feedback-comment",w.placeholder=s,w.rows=3,w.setAttribute("aria-label","Additional comments"),_.appendChild(w),u.appendChild(_)}let E=document.createElement("div");E.className="persona-feedback-actions";let S=document.createElement("button");S.type="button",S.className="persona-feedback-btn persona-feedback-btn-skip",S.textContent=i,S.addEventListener("click",()=>{n==null||n(),p.remove()});let 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(f===null){B.classList.add("persona-feedback-shake"),setTimeout(()=>B.classList.remove("persona-feedback-shake"),500);return}T.disabled=!0,T.textContent="Submitting...";try{let _=(w==null?void 0:w.value.trim())||void 0;await t(f,_),p.remove()}catch(_){T.disabled=!1,T.textContent=a,console.error("[NPS Feedback] Failed to submit:",_)}}),E.appendChild(S),E.appendChild(T),u.appendChild(E),p.appendChild(u),p}var fs="persona-chat-history",Sy=30*1e3,Ay={"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 Ty(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=Ay[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 tl(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 ky(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 Ey(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var hc=e=>!e||typeof e!="object"?{}:{...e},Tg=e=>e.map(t=>({...t,streaming:!1})),kg=(e,t,n)=>{let o=e!=null&&e.markdown?ui(e.markdown):null,r=mi(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&r&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var l,m,p;let a=(l=s.text)!=null?l:"",i=(m=s.message.rawContent)!=null?m:null;if(t){let f=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});f!==null&&(a=f.text,f.persist||(s.message.__skipPersist=!0),f.resubmit&&!s.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...s,text:a,raw:(p=i!=null?i:s.text)!=null?p:""}):o?d=o(a):d=ta(a),r?r(d):d}};function Eg(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=Me(n,o,r,s);if(a&&t.appendChild(a),e!=null&&e.label){let p=b("span","persona-drop-overlay-label");p.textContent=e.label,t.appendChild(p)}return t}var Mg=(e,t,n)=>{var Nc,_c,Vc,$c,Uc,zc,qc,jc,Kc,Gc,Yc,Xc,Qc,Jc,Zc,ed,td,nd,od,rd,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,bd,yd,vd,xd,wd,Cd,Sd,Ad,Td,kd,Ed,Md,Ld,Id,Rd,Pd;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=Wu(t),r=pc.getForInstance(o.plugins);o.components&&Or.registerAll(o.components);let s=hg(),i=o.persistState===!1?null:(Nc=o.storageAdapter)!=null?Nc:yg(),d={},l=null,m=!1,p=c=>{if(o.onStateLoaded)try{let g=o.onStateLoaded(c);if(g&&typeof g=="object"&&"state"in g){let{state:h,open:y}=g;return y&&(m=!0),h}return g}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(g=>{let h=g!=null?g:{messages:[],metadata:{}};return p(h)});else{let g=c!=null?c:{messages:[],metadata:{}},h=p(g);h.metadata&&(d=hc(h.metadata)),(_c=h.messages)!=null&&_c.length&&(o={...o,initialMessages:h.messages}),(Vc=h.artifacts)!=null&&Vc.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:($c=h.selectedArtifactId)!=null?$c:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(o.onStateLoaded)try{let c=p({messages:[],metadata:{}});(Uc=c.messages)!=null&&Uc.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:{},zr()},C=o.actionParsers&&o.actionParsers.length?o.actionParsers:[mc],v=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Ta.message,Ta.messageAndClick],M=gc({parsers:C,handlers:v,getSessionMetadata:f,updateSessionMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let I=(qc=(zc=o.launcher)==null?void 0:zc.enabled)!=null?qc:!0,R=(Kc=(jc=o.launcher)==null?void 0:jc.autoExpand)!=null?Kc:!1,W=(Gc=o.autoFocusInput)!=null?Gc:!1,D=R,B=I,x=(Xc=(Yc=o.layout)==null?void 0:Yc.header)==null?void 0:Xc.layout,w=!1,E=()=>ba(o),S=()=>I||E(),T=E()?!1:I?R:!0,_=!1,U=null,Y=()=>{_=!0,U&&clearTimeout(U),U=setTimeout(()=>{_&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),_=!1)},1e4)},he=kg(o,M,Y),fe=(Jc=(Qc=o.features)==null?void 0:Qc.showReasoning)!=null?Jc:!0,ae=(ed=(Zc=o.features)==null?void 0:Zc.showToolCalls)!=null?ed:!0,Ee=(nd=(td=o.features)==null?void 0:td.showEventStreamToggle)!=null?nd:!1,ye=(rd=(od=o.features)==null?void 0:od.scrollToBottom)!=null?rd:{},we=`${(ad=typeof o.persistState=="object"?(sd=o.persistState)==null?void 0:sd.keyPrefix:void 0)!=null?ad:"persona-"}event-stream`,K=Ee?new Sa(we):null,pe=(cd=(ld=(id=o.features)==null?void 0:id.eventStream)==null?void 0:ld.maxEvents)!=null?cd:2e3,G=Ee?new Ca(pe,K):null,ve=Ee?new Aa:null,ce=null,ne=!1,Se=null,ze=0;K==null||K.open().then(()=>G==null?void 0:G.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),$!=null&&$.isClientTokenMode()&&$.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),$!=null&&$.isClientTokenMode()&&$.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)}},re=(dd=o.statusIndicator)!=null?dd:{},ie=c=>{var g,h,y,L;return c==="idle"?(g=re.idleText)!=null?g:wn.idle:c==="connecting"?(h=re.connectingText)!=null?h:wn.connecting:c==="connected"?(y=re.connectedText)!=null?y:wn.connected:c==="error"?(L=re.errorText)!=null?L:wn.error:wn[c]};function st(c,g,h,y){if(y==="idle"&&h.idleLink){c.textContent="";let L=document.createElement("a");L.href=h.idleLink,L.target="_blank",L.rel="noopener noreferrer",L.textContent=g,L.style.color="inherit",L.style.textDecoration="none",c.appendChild(L)}else c.textContent=g}let{wrapper:Te,panel:ue,pillRoot:Ue}=Hm(o),Be=Dm(o,S()),{container:me,body:Q,messagesWrapper:_e,suggestions:Ht,textarea:be,sendButton:de,sendButtonWrapper:Pn,composerForm:Ut,statusText:gn,introTitle:Fn,introSubtitle:to,closeButton:qe,iconHolder:V,headerTitle:Le,headerSubtitle:He,header:De,footer:Ve,actionsRow:mt,leftActions:at,rightActions:Pt}=Be,jt=Be.setSendButtonMode,j=Be.micButton,zt=Be.micButtonWrapper,Ze=Be.attachmentButton,Vt=Be.attachmentButtonWrapper,se=Be.attachmentInput,Ce=Be.attachmentPreviewsContainer;me.classList.add("persona-relative"),Q.classList.add("persona-relative");let kt=12,Kt=()=>{var c;return(c=ye.label)!=null?c:""},tn=()=>{var c;return(c=ye.iconName)!=null?c:"arrow-down"},An=()=>ye.enabled!==!1,Wt=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");Wt.type="button",Wt.style.display="none",Wt.setAttribute("data-persona-scroll-to-bottom","true");let Mt=b("span","persona-flex persona-items-center"),wt=b("span","");Wt.append(Mt,wt),me.appendChild(Wt);let St=()=>{let g=Ve.style.display==="none"?0:Ve.offsetHeight;Wt.style.bottom=`${g+kt}px`};St();let Gt=()=>{let c=!!Kt();Wt.setAttribute("aria-label",Kt()||"Jump to latest"),Wt.title=Kt(),Wt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Mt.innerHTML="";let g=Me(tn(),"14px","currentColor",2);g?(Mt.appendChild(g),Mt.style.display=""):Mt.style.display="none",wt.textContent=Kt(),wt.style.display=c?"":"none"};Gt();let ot=null,On=null,no=r.find(c=>c.renderHeader);if(no!=null&&no.renderHeader){let c=no.renderHeader({config:o,defaultRenderer:()=>{let g=Br({config:o,showClose:S()});return va(me,g,o),g.header},onClose:()=>Ot(!1,"user")});if(c){let g=me.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),De=c)}}let Tn=()=>{var g,h,y,L;if(!G)return;if(ne=!0,!ce&&G&&(ce=ag({buffer:G,getFullHistory:()=>G.getAllFromStore(),onClose:()=>Nn(),config:o,plugins:r,getThroughput:()=>{var O;return(O=ve==null?void 0:ve.getMetric())!=null?O:{status:"idle"}}})),ce&&(Q.style.display="none",(g=Ve.parentNode)==null||g.insertBefore(ce.element,Ve),ce.update()),bt){bt.style.boxShadow=`inset 0 0 0 1.5px ${Rn.actionIconColor}`;let O=(L=(y=(h=o.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:L.toggleButtonActive;O&&O.split(/\s+/).forEach(N=>N&&bt.classList.add(N))}let c=()=>{if(!ne)return;let O=Date.now();O-ze>=200&&(ce==null||ce.update(),ze=O),Se=requestAnimationFrame(c)};ze=0,Se=requestAnimationFrame(c),Vo(),s.emit("eventStream:opened",{timestamp:Date.now()})},Nn=()=>{var c,g,h;if(ne){if(ne=!1,ce&&ce.element.remove(),Q.style.display="",bt){bt.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(L=>L&&bt.classList.remove(L))}Se!==null&&(cancelAnimationFrame(Se),Se=null),Vo(),s.emit("eventStream:closed",{timestamp:Date.now()})}},bt=null;if(Ee){let c=(ud=(pd=o.features)==null?void 0:pd.eventStream)==null?void 0:ud.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:"");bt=b("button",g),bt.style.width="28px",bt.style.height="28px",bt.style.color=Rn.actionIconColor,bt.type="button",bt.setAttribute("aria-label","Event Stream"),bt.title="Event Stream";let h=Me("activity","18px","currentColor",1.5);h&&bt.appendChild(h);let y=Be.clearChatButtonWrapper,L=Be.closeButtonWrapper,O=y||L;O&&O.parentNode===De?De.insertBefore(bt,O):De.appendChild(bt),bt.addEventListener("click",()=>{ne?Nn():Tn()})}let Lo=c=>{var y,L,O;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 N=c.querySelector("[data-persona-composer-form]");N!=null&&N.parentNode?N.parentNode.insertBefore(h,N):c.insertBefore(h,c.firstChild)}if(!c.querySelector('input[type="file"]')){let N=b("input");N.type="file",N.accept=((y=g.allowedTypes)!=null?y:qo).join(","),N.multiple=((L=g.maxFiles)!=null?L:4)>1,N.style.display="none",N.setAttribute("aria-label",(O=g.buttonTooltipText)!=null?O:"Attach files"),c.appendChild(N)}},_n=r.find(c=>c.renderComposer);if(_n!=null&&_n.renderComposer){let c=o.composer,g=_n.renderComposer({config:o,defaultRenderer:()=>ji({config:o}).footer,onSubmit:h=>{var N;if(!$||$.isStreaming())return;let y=h.trim(),L=(N=ot==null?void 0:ot.hasAttachments())!=null?N:!1;if(!y&&!L)return;Ls();let O;L&&(O=[],O.push(...ot.getContentParts()),y&&O.push(_l(y))),$.sendMessage(y,{contentParts:O}),L&&ot.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{se==null||se.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:((md=o.voiceRecognition)==null?void 0:md.enabled)===!0?()=>{On==null||On()}:void 0});g&&(Ve.replaceWith(g),Ve=g)}let fr=c=>{let g=c.querySelector("[data-persona-composer-form]"),h=c.querySelector("[data-persona-composer-input]"),y=c.querySelector("[data-persona-composer-submit]"),L=c.querySelector("[data-persona-composer-mic]"),O=c.querySelector("[data-persona-composer-status]");g&&(Ut=g),h&&(be=h),y&&(de=y),L&&(j=L,zt=L.parentElement),O&&(gn=O);let N=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");N&&(Ht=N);let q=c.querySelector(".persona-attachment-button");q&&(Ze=q,Vt=q.parentElement),se=c.querySelector('input[type="file"]'),Ce=c.querySelector(".persona-attachment-previews");let F=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");F&&(mt=F)};Lo(Ve),fr(Ve);let Wn=(yd=(gd=o.layout)==null?void 0:gd.contentMaxWidth)!=null?yd:E()?(bd=(hd=(fd=o.launcher)==null?void 0:fd.composerBar)==null?void 0:hd.contentMaxWidth)!=null?bd:"720px":void 0;if(Wn&&(_e.style.maxWidth=Wn,_e.style.marginLeft="auto",_e.style.marginRight="auto",_e.style.width="100%"),Wn&&Ut&&!E()&&(Ut.style.maxWidth=Wn,Ut.style.marginLeft="auto",Ut.style.marginRight="auto"),Wn&&Ht&&!E()&&(Ht.style.maxWidth=Wn,Ht.style.marginLeft="auto",Ht.style.marginRight="auto"),Wn&&Ce&&!E()&&(Ce.style.maxWidth=Wn,Ce.style.marginLeft="auto",Ce.style.marginRight="auto"),(vd=o.attachments)!=null&&vd.enabled&&se&&Ce){ot=ca.fromConfig(o.attachments),ot.setPreviewsContainer(Ce),se.addEventListener("change",h=>{let y=h.target;ot==null||ot.handleFileSelect(y.files),y.value=""});let c=o.attachments.dropOverlay,g=Eg(c);me.appendChild(g)}(()=>{var y,L;let c=(L=(y=o.layout)==null?void 0:y.slots)!=null?L:{},g=O=>{switch(O){case"body-top":return me.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return _e;case"footer-top":return Ht;case"composer":return Ut;case"footer-bottom":return gn;default:return null}},h=(O,N)=>{var q;switch(O){case"header-left":case"header-center":case"header-right":if(O==="header-left")De.insertBefore(N,De.firstChild);else if(O==="header-right")De.appendChild(N);else{let F=De.querySelector(".persona-flex-col");F?(q=F.parentNode)==null||q.insertBefore(N,F.nextSibling):De.appendChild(N)}break;case"body-top":{let F=Q.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");F?F.replaceWith(N):Q.insertBefore(N,Q.firstChild);break}case"body-bottom":Q.appendChild(N);break;case"footer-top":Ht.replaceWith(N);break;case"footer-bottom":gn.replaceWith(N);break;default:break}};for(let[O,N]of Object.entries(c))if(N)try{let q=N({config:o,defaultContent:()=>g(O)});q&&h(O,q)}catch(q){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${O}":`,q)}})();let jo=c=>{var N,q;let h=c.target.closest('button[data-expand-header="true"]');if(!h)return;let y=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!y)return;let L=y.getAttribute("data-message-id");if(!L)return;let O=h.getAttribute("data-bubble-type");if(O==="reasoning")ls.has(L)?ls.delete(L):ls.add(L),Nm(L,y);else if(O==="tool")cs.has(L)?cs.delete(L):cs.add(L),_m(L,y,o);else if(O==="approval"){let F=o.approval!==!1?o.approval:void 0,ke=((N=F==null?void 0:F.detailsDisplay)!=null?N:"collapsed")==="expanded",ge=(q=Xi.get(L))!=null?q:ke;Xi.set(L,!ge),tg(L,y,o)}xe.delete(L)};_e.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),jo(c))}),_e.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),jo(c))});let Do=new Map;_e.addEventListener("click",c=>{var N;let h=c.target.closest(".persona-message-action-btn[data-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.closest("[data-actions-for]");if(!y)return;let L=y.getAttribute("data-actions-for");if(!L)return;let O=h.getAttribute("data-action");if(O==="copy"){let F=$.getMessages().find(ke=>ke.id===L);if(F&&te.onCopy){let ke=F.content||"";navigator.clipboard.writeText(ke).then(()=>{h.classList.add("persona-message-action-success");let ge=Me("check",14,"currentColor",2);ge&&(h.innerHTML="",h.appendChild(ge)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let ee=Me("copy",14,"currentColor",2);ee&&(h.innerHTML="",h.appendChild(ee))},2e3)}).catch(ge=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ge)}),te.onCopy(F)}}else if(O==="upvote"||O==="downvote"){let F=((N=Do.get(L))!=null?N:null)===O,ke=O==="upvote"?"thumbs-up":"thumbs-down";if(F){Do.delete(L),h.classList.remove("persona-message-action-active");let ge=Me(ke,14,"currentColor",2);ge&&(h.innerHTML="",h.appendChild(ge))}else{let ge=O==="upvote"?"downvote":"upvote",ee=y.querySelector(`[data-action="${ge}"]`);if(ee){ee.classList.remove("persona-message-action-active");let Ke=Me(ge==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ke&&(ee.innerHTML="",ee.appendChild(Ke))}Do.set(L,O),h.classList.add("persona-message-action-active");let Ae=Me(ke,14,"currentColor",2);Ae&&(Ae.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(Ae)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let $e=$.getMessages().find(rt=>rt.id===L);$e&&te.onFeedback&&te.onFeedback({type:O,messageId:$e.id,message:$e})}}}),_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 L=y.getAttribute("data-message-id");if(!L)return;let O=h.getAttribute("data-approval-action");if(!O)return;let N=O==="approve"?"approved":"denied",F=$.getMessages().find(ge=>ge.id===L);if(!(F!=null&&F.approval))return;let ke=y.querySelector("[data-approval-buttons]");ke&&ke.querySelectorAll("button").forEach(ee=>{ee.disabled=!0,ee.style.opacity="0.5",ee.style.cursor="not-allowed"}),F.approval.toolType==="webmcp"?$.resolveWebMcpApproval(L,N):$.resolveApproval(F.approval,N)});let At=null,Vn=null,$n={artifacts:[],selectedId:null},kn=!1,Lt={current:null};_e.addEventListener("click",c=>{var ee,Ae,Ie,$e,rt;let h=c.target.closest("[data-download-artifact]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||((Ie=(Ae=(ee=o.features)==null?void 0:ee.artifacts)==null?void 0:Ae.onArtifactAction)==null?void 0:Ie.call(Ae,{type:"download",artifactId:y}))===!0)return;let O=$.getArtifactById(y),N=O==null?void 0:O.markdown,q=(O==null?void 0:O.title)||"artifact";if(!N){let Ke=h.closest("[data-open-artifact]"),gt=Ke==null?void 0:Ke.closest("[data-message-id]"),pt=gt==null?void 0:gt.getAttribute("data-message-id");if(pt){let Pe=$.getMessages().find(je=>je.id===pt);if(Pe!=null&&Pe.rawContent)try{let je=JSON.parse(Pe.rawContent);N=($e=je==null?void 0:je.props)==null?void 0:$e.markdown,q=((rt=je==null?void 0:je.props)==null?void 0:rt.title)||q}catch{}}}if(!N)return;let F=new Blob([N],{type:"text/markdown"}),ke=URL.createObjectURL(F),ge=document.createElement("a");ge.href=ke,ge.download=`${q}.md`,ge.click(),URL.revokeObjectURL(ke)}),_e.addEventListener("click",c=>{var O,N,q;let h=c.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||((q=(N=(O=o.features)==null?void 0:O.artifacts)==null?void 0:N.onArtifactAction)==null?void 0:q.call(N,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),kn=!1,$.selectArtifact(y),qn())}),_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 oo=Be.composerOverlay,ro=(c,g,h)=>{var q,F,ke,ge;let y=g.trim();if(!y||!Lt.current)return;let L=(q=c.getAttribute("data-tool-call-id"))!=null?q:"",O=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:L,answer:y,answers:h.structured,values:(F=h.values)!=null?F:h.source==="multi"?y.split(", "):[y],isFreeText:O,source:h.source},bubbles:!0,composed:!0})),ms(oo,L);let N=Lt.current.getMessages().find(ee=>{var Ae;return((Ae=ee.toolCall)==null?void 0:Ae.id)===L});(ke=N==null?void 0:N.agentMetadata)!=null&&ke.awaitingLocalTool?Lt.current.resolveAskUserQuestion(N,(ge=h.structured)!=null?ge:y):Lt.current.sendMessage(y)},Un=c=>{var L;let g=Lt.current;if(!g)return;let h=(L=c.getAttribute("data-tool-call-id"))!=null?L:"",y=g.getMessages().find(O=>{var N;return((N=O.toolCall)==null?void 0:N.id)===h});y&&g.persistAskUserQuestionProgress(y,{answers:Ki(c,y),currentIndex:ho(c)})},Ko=c=>Object.entries(c).map(([g,h])=>`${g}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Fo=c=>{var L,O,N;if(((O=(L=o.features)==null?void 0:L.askUserQuestion)==null?void 0:O.groupedAutoAdvance)===!1)return;let g=ho(c),h=us(c);if(g>=h-1)return;let y=(N=Lt.current)==null?void 0:N.getMessages().find(q=>{var F;return((F=q.toolCall)==null?void 0:F.id)===c.getAttribute("data-tool-call-id")});y&&(Yi(c,y,o,g+1),Un(c))};oo.addEventListener("click",c=>{var O,N,q,F,ke,ge,ee,Ae,Ie,$e,rt,Ke,gt,pt;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 L=h.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),L==="dismiss"){let We=(O=y.getAttribute("data-tool-call-id"))!=null?O:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:We},bubbles:!0,composed:!0})),ms(oo,We);let Pe=(N=Lt.current)==null?void 0:N.getMessages().find(je=>{var Je;return((Je=je.toolCall)==null?void 0:Je.id)===We});(q=Pe==null?void 0:Pe.agentMetadata)!=null&&q.awaitingLocalTool&&((F=Lt.current)==null||F.markAskUserQuestionResolved(Pe),(ke=Lt.current)==null||ke.resolveAskUserQuestion(Pe,"(dismissed)"));return}if(L==="pick"){let We=h.getAttribute("data-option-label");if(!We)return;let Pe=y.getAttribute("data-multi-select")==="true",je=pr(y);if(je&&Pe){let Je=Dr(y)[ho(y)],xt=new Set(Array.isArray(Je)?Je:[]);xt.has(We)?xt.delete(We):xt.add(We),ur(y,Array.from(xt)),Un(y);return}if(je){ur(y,We),Un(y),Fo(y);return}if(Pe){let Je=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Je?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Je);let xt=y.querySelector('[data-ask-user-action="submit-multi"]');xt&&(xt.disabled=sc(y).length===0);return}ro(y,We,{source:"pick",values:[We]});return}if(L==="submit-multi"){let We=sc(y);if(We.length===0)return;ro(y,We.join(", "),{source:"multi",values:We});return}if(L==="open-free-text"){let We=y.querySelector('[data-ask-free-text-row="true"]');if(We){We.classList.remove("persona-hidden");let Pe=We.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus()}return}if(L==="focus-free-text"){let We=y.querySelector('[data-ask-free-text-input="true"]');We==null||We.focus();return}if(L==="submit-free-text"){let We=y.querySelector('[data-ask-free-text-input="true"]'),Pe=(ge=We==null?void 0:We.value)!=null?ge:"";if(!Pe.trim())return;if(pr(y)){ur(y,Pe.trim()),Un(y),Fo(y);return}ro(y,Pe,{source:"free-text"});return}if(L==="next"||L==="back"){if(!Lt.current)return;let We=(ee=y.getAttribute("data-tool-call-id"))!=null?ee:"",Pe=Lt.current.getMessages().find(Fe=>{var oe;return((oe=Fe.toolCall)==null?void 0:oe.id)===We});if(!Pe)return;let je=y.querySelector('[data-ask-free-text-input="true"]'),Je=(Ie=(Ae=je==null?void 0:je.value)==null?void 0:Ae.trim())!=null?Ie:"";if(Je){let Fe=Dr(y)[ho(y)];(typeof Fe!="string"||Fe!==Je)&&ur(y,Je)}let xt=L==="next"?1:-1,H=ho(y)+xt;Yi(y,Pe,o,H),Un(y);return}if(L==="submit-all"){if(!Lt.current)return;let We=($e=y.getAttribute("data-tool-call-id"))!=null?$e:"",Pe=Lt.current.getMessages().find(Fe=>{var oe;return((oe=Fe.toolCall)==null?void 0:oe.id)===We});if(!Pe)return;let je=y.querySelector('[data-ask-free-text-input="true"]'),Je=(Ke=(rt=je==null?void 0:je.value)==null?void 0:rt.trim())!=null?Ke:"";Je&&ur(y,Je);let xt=Ki(y,Pe);Lt.current.persistAskUserQuestionProgress(Pe,{answers:xt,currentIndex:ho(y)});let H=Ko(xt);ro(y,H||"(submitted)",{source:"submit-all",structured:xt});return}if(L==="skip"){if(!Lt.current)return;let We=(gt=y.getAttribute("data-tool-call-id"))!=null?gt:"",Pe=Lt.current.getMessages().find(oe=>{var tt;return((tt=oe.toolCall)==null?void 0:tt.id)===We});if(!Pe)return;let je=pr(y),Je=ho(y),xt=us(y),H=Je>=xt-1;if(!je){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:We},bubbles:!0,composed:!0})),ms(oo,We),(pt=Pe.agentMetadata)!=null&&pt.awaitingLocalTool&&(Lt.current.markAskUserQuestionResolved(Pe),Lt.current.resolveAskUserQuestion(Pe,"(dismissed)"));return}ur(y,"");let Fe=y.querySelector('[data-ask-free-text-input="true"]');if(Fe&&(Fe.value=""),H){let oe=Ki(y,Pe),tt=Ko(oe);ro(y,tt||"(skipped)",{source:"submit-all",structured:oe});return}Yi(y,Pe,o,Je+1),Un(y);return}}),oo.addEventListener("keydown",c=>{var O;if(c.key!=="Enter")return;let h=c.target;if(!((O=h.matches)!=null&&O.call(h,'[data-ask-free-text-input="true"]')))return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;c.preventDefault();let L=h.value;if(L.trim()){if(pr(y)){ur(y,L.trim()),Un(y),Fo(y);return}ro(y,L,{source:"free-text"})}});let Go=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=oo.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let y=Number(c.key),O=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];O&&(c.preventDefault(),O.click())};document.addEventListener("keydown",Go);let zn=null,Ft=null,En=null,so=null,Yo=()=>{};function Oo(){so==null||so(),so=null}let Xo=()=>{var N;if(!zn||!Ft)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),h=((N=e.ownerDocument.defaultView)!=null?N:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||h){Ft.style.removeProperty("position"),Ft.style.removeProperty("left"),Ft.style.removeProperty("top"),Ft.style.removeProperty("bottom"),Ft.style.removeProperty("width"),Ft.style.removeProperty("z-index");return}let y=zn.firstElementChild;if(!y||y===Ft)return;let L=10;Ft.style.position="absolute",Ft.style.top="0",Ft.style.bottom="0",Ft.style.width=`${L}px`,Ft.style.zIndex="5";let O=y.offsetWidth-L/2;Ft.style.left=`${Math.max(0,O)}px`},Io=()=>{},qn=()=>{var h,y,L,O,N;if(!At||!bo(o))return;Zi(e,o),el(e,o),Io();let c=(O=(L=(y=(h=o.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:L.narrowHostMaxWidth)!=null?O:520,g=ue.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),At.update($n),kn?(At.setMobileOpen(!1),At.element.classList.add("persona-hidden"),(N=At.backdrop)==null||N.classList.add("persona-hidden")):$n.artifacts.length>0&&(At.element.classList.remove("persona-hidden"),At.setMobileOpen(!0)),Yo()};if(bo(o)){ue.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(me),At=cg(o,{onSelect:h=>{var y;return(y=Lt.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{kn=!0,qn()}}),At.element.classList.add("persona-hidden"),zn=g,g.appendChild(c),g.appendChild(At.element),At.backdrop&&ue.appendChild(At.backdrop),ue.appendChild(g),Yo=()=>{var y,L,O,N;if(!zn||!At)return;if(!(((O=(L=(y=o.features)==null?void 0:y.artifacts)==null?void 0:L.layout)==null?void 0:O.resizable)===!0)){En==null||En(),En=null,Oo(),Ft&&(Ft.remove(),Ft=null),At.element.style.removeProperty("width"),At.element.style.removeProperty("maxWidth");return}if(!Ft){let q=b("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");q.setAttribute("role","separator"),q.setAttribute("aria-orientation","vertical"),q.setAttribute("aria-label","Resize artifacts panel"),q.tabIndex=0;let F=e.ownerDocument,ke=(N=F.defaultView)!=null?N:window,ge=ee=>{var gt,pt;if(!At||ee.button!==0||e.classList.contains("persona-artifact-narrow-host")||ke.innerWidth<=640)return;ee.preventDefault(),Oo();let Ae=ee.clientX,Ie=At.element.getBoundingClientRect().width,$e=(pt=(gt=o.features)==null?void 0:gt.artifacts)==null?void 0:pt.layout,rt=We=>{let Pe=zn.getBoundingClientRect().width,je=e.classList.contains("persona-artifact-appearance-seamless"),Je=je?0:mg(zn,ke),xt=je?0:q.getBoundingClientRect().width||6,H=Ie-(We.clientX-Ae),Fe=gg(H,Pe,Je,xt,$e==null?void 0:$e.resizableMinWidth,$e==null?void 0:$e.resizableMaxWidth);At.element.style.width=`${Fe}px`,At.element.style.maxWidth="none",Xo()},Ke=()=>{F.removeEventListener("pointermove",rt),F.removeEventListener("pointerup",Ke),F.removeEventListener("pointercancel",Ke),so=null;try{q.releasePointerCapture(ee.pointerId)}catch{}};so=Ke,F.addEventListener("pointermove",rt),F.addEventListener("pointerup",Ke),F.addEventListener("pointercancel",Ke);try{q.setPointerCapture(ee.pointerId)}catch{}};q.addEventListener("pointerdown",ge),Ft=q,zn.insertBefore(q,At.element),En=()=>{q.removeEventListener("pointerdown",ge)}}if(Ft){let q=$n.artifacts.length>0&&!kn;Ft.classList.toggle("persona-hidden",!q),Xo()}},Io=()=>{var ke,ge,ee,Ae,Ie,$e,rt,Ke,gt,pt,We,Pe,je,Je;if(!I||!At||((ge=(ke=o.launcher)==null?void 0:ke.sidebarMode)!=null?ge:!1)||bn(o)&&Bo(o).reveal==="emerge")return;let y=(ee=e.ownerDocument.defaultView)!=null?ee:window,L=(Ie=(Ae=o.launcher)==null?void 0:Ae.mobileFullscreen)!=null?Ie:!0,O=(rt=($e=o.launcher)==null?void 0:$e.mobileBreakpoint)!=null?rt:640;if(L&&y.innerWidth<=O||!ug(o,I))return;let N=(pt=(gt=(Ke=o.launcher)==null?void 0:Ke.width)!=null?gt:o.launcherWidth)!=null?pt:fo,q=(Je=(je=(Pe=(We=o.features)==null?void 0:We.artifacts)==null?void 0:Pe.layout)==null?void 0:je.expandedPanelWidth)!=null?Je:"min(720px, calc(100vw - 24px))";$n.artifacts.length>0&&!kn?(ue.style.width=q,ue.style.maxWidth=q):(ue.style.width=N,ue.style.maxWidth=N)},typeof ResizeObserver!="undefined"&&(Vn=new ResizeObserver(()=>{qn()}),Vn.observe(ue))}else ue.appendChild(me),E()&&Ue&&(Be.peekBanner&&Ue.appendChild(Be.peekBanner),Ue.appendChild(Ve));e.appendChild(Te),Ue&&e.appendChild(Ue);let yo=()=>{var Fe,oe,tt,_t,Nt,qt,it,cn,Xn,Ge,Ct,Qn,rn,mo,Jn,wr,Qr,Jr,Yt,Cr,sr,ar,zo,Sr,nt,vn,fn,dn;if(E()){ue.style.width="100%",ue.style.maxWidth="100%";let ft=(oe=(Fe=o.launcher)==null?void 0:Fe.composerBar)!=null?oe:{},lt=Te.dataset.state==="expanded",Et=(tt=ft.expandedSize)!=null?tt:"anchored";if(!(lt&&Et!=="fullscreen")){me.style.background="",me.style.border="",me.style.borderRadius="",me.style.overflow="",me.style.boxShadow="";return}let en=(Nt=(_t=o.theme)==null?void 0:_t.components)==null?void 0:Nt.panel,Po=ti(o),sn=(Tr,Ja)=>{var Fs;return Tr==null||Tr===""?Ja:(Fs=Zr(Po,Tr))!=null?Fs:Tr},Ln="1px solid var(--persona-border)",go="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Ar="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";me.style.background="var(--persona-surface, #ffffff)",me.style.border=sn(en==null?void 0:en.border,Ln),me.style.borderRadius=sn(en==null?void 0:en.borderRadius,Ar),me.style.boxShadow=sn(en==null?void 0:en.shadow,go),me.style.overflow="hidden";return}let c=bn(o),g=(it=(qt=o.launcher)==null?void 0:qt.sidebarMode)!=null?it:!1,h=c||g||((Xn=(cn=o.launcher)==null?void 0:cn.fullHeight)!=null?Xn:!1),y=((Ge=o.launcher)==null?void 0:Ge.enabled)===!1,L=(Qn=(Ct=o.theme)==null?void 0:Ct.components)==null?void 0:Qn.panel,O=ti(o),N=(ft,lt)=>{var Et;return ft==null||ft===""?lt:(Et=Zr(O,ft))!=null?Et:ft},q=(rn=e.ownerDocument.defaultView)!=null?rn:window,F=(Jn=(mo=o.launcher)==null?void 0:mo.mobileFullscreen)!=null?Jn:!0,ke=(Qr=(wr=o.launcher)==null?void 0:wr.mobileBreakpoint)!=null?Qr:640,ge=q.innerWidth<=ke,ee=F&&ge&&I,Ae=(Yt=(Jr=o.launcher)==null?void 0:Jr.position)!=null?Yt:"bottom-left",Ie=Ae==="bottom-left"||Ae==="top-left",$e=(sr=(Cr=o.launcher)==null?void 0:Cr.zIndex)!=null?sr:Cn,rt=g||ee?"none":"1px solid var(--persona-border)",Ke=ee?"none":g?Ie?"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&&(Ke="none",rt="none");let gt=g||ee?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",pt=N(L==null?void 0:L.border,rt),We=N(L==null?void 0:L.shadow,Ke),Pe=N(L==null?void 0:L.borderRadius,gt),je=Q.scrollTop;e.style.cssText="",Te.style.cssText="",ue.style.cssText="",me.style.cssText="",Q.style.cssText="",Ve.style.cssText="";let Je=()=>{var lt;if(je<=0)return;((lt=Q.ownerDocument.defaultView)!=null?lt:window).requestAnimationFrame(()=>{if(Q.scrollTop===je)return;let Et=Q.scrollHeight-Q.clientHeight;Et<=0||(Q.scrollTop=Math.min(je,Et))})};if(ee){Te.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"),Te.style.cssText=`
|
|
30
|
+
`,x.addEventListener("click",()=>{u=w,I.forEach((E,S)=>{let k=S<w;E.classList.toggle("selected",k),E.setAttribute("aria-checked",S===w-1?"true":"false")})}),I.push(x),M.appendChild(x)}g.appendChild(M);let R=null;if(d){let w=document.createElement("div");w.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"),w.appendChild(R),g.appendChild(w)}let P=document.createElement("div");P.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(),f.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 w=(R==null?void 0:R.value.trim())||void 0;await t(u,w),f.remove()}catch(w){W.disabled=!1,W.textContent=a,console.error("[CSAT Feedback] Failed to submit:",w)}}),P.appendChild(D),P.appendChild(W),g.appendChild(P),f.appendChild(g),f}function Zf(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:f="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let g=null,m=document.createElement("div");m.className="persona-feedback-content";let C=document.createElement("div");C.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=o,C.appendChild(v);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=r,C.appendChild(M),m.appendChild(C);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 P=document.createElement("span");P.className="persona-feedback-label-low",P.textContent=l;let D=document.createElement("span");D.className="persona-feedback-label-high",D.textContent=f,R.appendChild(P),R.appendChild(D);let W=document.createElement("div");W.className="persona-feedback-numbers";let w=[];for(let V=0;V<=10;V++){let z=document.createElement("button");z.type="button",z.className="persona-feedback-rating-btn persona-feedback-number-btn",z.setAttribute("role","radio"),z.setAttribute("aria-checked","false"),z.setAttribute("aria-label",`Rating ${V} out of 10`),z.textContent=String(V),z.dataset.rating=String(V),V<=6?z.classList.add("persona-feedback-detractor"):V<=8?z.classList.add("persona-feedback-passive"):z.classList.add("persona-feedback-promoter"),z.addEventListener("click",()=>{g=V,w.forEach((Y,he)=>{Y.classList.toggle("selected",he===V),Y.setAttribute("aria-checked",he===V?"true":"false")})}),w.push(z),W.appendChild(z)}I.appendChild(R),I.appendChild(W),m.appendChild(I);let x=null;if(d){let V=document.createElement("div");V.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"),V.appendChild(x),m.appendChild(V)}let E=document.createElement("div");E.className="persona-feedback-actions";let S=document.createElement("button");S.type="button",S.className="persona-feedback-btn persona-feedback-btn-skip",S.textContent=i,S.addEventListener("click",()=>{n==null||n(),u.remove()});let k=document.createElement("button");return k.type="button",k.className="persona-feedback-btn persona-feedback-btn-submit",k.textContent=a,k.addEventListener("click",async()=>{if(g===null){W.classList.add("persona-feedback-shake"),setTimeout(()=>W.classList.remove("persona-feedback-shake"),500);return}k.disabled=!0,k.textContent="Submitting...";try{let V=(x==null?void 0:x.value.trim())||void 0;await t(g,V),u.remove()}catch(V){k.disabled=!1,k.textContent=a,console.error("[NPS Feedback] Failed to submit:",V)}}),E.appendChild(S),E.appendChild(k),m.appendChild(E),u.appendChild(m),u}var Ts="persona-chat-history",nv=30*1e3,ov={"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 rv(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=ov[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 cl(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 sv(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 av(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Ec=e=>!e||typeof e!="object"?{}:{...e},eg=e=>e.map(t=>({...t,streaming:!1})),tg=(e,t,n)=>{let o=e!=null&&e.markdown?xi(e.markdown):null,r=wi(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&r&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var l,f,u;let a=(l=s.text)!=null?l:"",i=(f=s.message.rawContent)!=null?f:null;if(t){let g=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});g!==null&&(a=g.text,g.persist||(s.message.__skipPersist=!0),g.resubmit&&!s.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...s,text:a,raw:(u=i!=null?i:s.text)!=null?u:""}):o?d=o(a):d=pa(a),r?r(d):d}};function ng(e){var i,d,l,f;let t=b("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",o=(d=e==null?void 0:e.iconSize)!=null?d:"48px",r=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(f=e==null?void 0:e.iconStrokeWidth)!=null?f:.5,a=Me(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 og=(e,t,n)=>{var 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,Jd,Qd,Zd;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=om(t),r=Cc.getForInstance(o.plugins);o.components&&jr.registerAll(o.components);let s=qf(),i=o.persistState===!1?null:(rd=o.storageAdapter)!=null?rd:Kf(),d={},l=null,f=!1,u=c=>{if(o.onStateLoaded)try{let p=o.onStateLoaded(c);if(p&&typeof p=="object"&&"state"in p){let{state:h,open:y}=p;return y&&(f=!0),h}return p}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",p)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(p=>{let h=p!=null?p:{messages:[],metadata:{}};return u(h)});else{let p=c!=null?c:{messages:[],metadata:{}},h=u(p);h.metadata&&(d=Ec(h.metadata)),(sd=h.messages)!=null&&sd.length&&(o={...o,initialMessages:h.messages}),(ad=h.artifacts)!=null&&ad.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(id=h.selectedArtifactId)!=null?id: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:{}});(ld=c.messages)!=null&&ld.length&&(o={...o,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let g=()=>d,m=c=>{var h;d=(h=c({...d}))!=null?h:{},ts()},C=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Ac],v=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Wa.message,Wa.messageAndClick],M=Tc({parsers:C,handlers:v,getSessionMetadata:g,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let I=(dd=(cd=o.launcher)==null?void 0:cd.enabled)!=null?dd:!0,R=(ud=(pd=o.launcher)==null?void 0:pd.autoExpand)!=null?ud:!1,P=(md=o.autoFocusInput)!=null?md:!1,D=R,W=I,w=(gd=(fd=o.layout)==null?void 0:fd.header)==null?void 0:gd.layout,x=!1,E=()=>Ta(o),S=()=>I||E(),k=E()?!1:I?R:!0,V=!1,z=null,Y=()=>{V=!0,z&&clearTimeout(z),z=setTimeout(()=>{V&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),V=!1)},1e4)},he=tg(o,M,Y),me=(bd=(hd=o.features)==null?void 0:hd.showReasoning)!=null?bd:!0,de=(vd=(yd=o.features)==null?void 0:yd.showToolCalls)!=null?vd:!0,Ee=(wd=(xd=o.features)==null?void 0:xd.showEventStreamToggle)!=null?wd:!1,xe=(Sd=(Cd=o.features)==null?void 0:Cd.scrollToBottom)!=null?Sd:{},De=(Td=(Ad=o.features)==null?void 0:Ad.scrollBehavior)!=null?Td:{},le=`${(Ed=typeof o.persistState=="object"?(kd=o.persistState)==null?void 0:kd.keyPrefix:void 0)!=null?Ed:"persona-"}event-stream`,J=Ee?new Ra(le):null,se=(Id=(Ld=(Md=o.features)==null?void 0:Md.eventStream)==null?void 0:Ld.maxEvents)!=null?Id:2e3,ye=Ee?new Ia(se,J):null,be=Ee?new Pa:null,K=null,ae=!1,Re=null,oe=0;J==null||J.open().then(()=>ye==null?void 0:ye.restore()).catch(c=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let ee={onCopy:c=>{var p,h;s.emit("message:copy",c),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(c.id,"copy").catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",y)}),(h=(p=o.messageActions)==null?void 0:p.onCopy)==null||h.call(p,c)},onFeedback:c=>{var p,h;s.emit("message:feedback",c),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(c.messageId,c.type).catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",y)}),(h=(p=o.messageActions)==null?void 0:p.onFeedback)==null||h.call(p,c)}},re=(Rd=o.statusIndicator)!=null?Rd:{},it=c=>{var p,h,y,L;return c==="idle"?(p=re.idleText)!=null?p:En.idle:c==="connecting"?(h=re.connectingText)!=null?h:En.connecting:c==="connected"?(y=re.connectedText)!=null?y:En.connected:c==="error"?(L=re.errorText)!=null?L:En.error:En[c]};function lt(c,p,h,y){if(y==="idle"&&h.idleLink){c.textContent="";let L=document.createElement("a");L.href=h.idleLink,L.target="_blank",L.rel="noopener noreferrer",L.textContent=p,L.style.color="inherit",L.style.textDecoration="none",c.appendChild(L)}else c.textContent=p}let{wrapper:Le,panel:pe,pillRoot:Je}=df(o),Be=pf(o,S()),{container:j,body:fe,messagesWrapper:tt,suggestions:Mt,textarea:te,sendButton:qe,sendButtonWrapper:Fn,composerForm:Dt,statusText:an,introTitle:oo,introSubtitle:Mo,closeButton:F,iconHolder:ue,headerTitle:Fe,headerSubtitle:Ke,header:_e,footer:$e,actionsRow:ot,leftActions:Pt,rightActions:Kt}=Be,Jt=Be.setSendButtonMode,G=Be.micButton,xt=Be.micButtonWrapper,st=Be.attachmentButton,Se=Be.attachmentButtonWrapper,ce=Be.attachmentInput,et=Be.attachmentPreviewsContainer;j.classList.add("persona-relative"),fe.classList.add("persona-relative");let Qt=12,Gt=()=>{var c;return(c=xe.label)!=null?c:""},In=()=>{var c;return(c=xe.iconName)!=null?c:"arrow-down"},vn=()=>xe.enabled!==!1,gt=()=>{var c;return(c=De.mode)!=null?c:"follow"},Lt=()=>{var c;return(c=De.anchorTopOffset)!=null?c:16},Qe=b("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Qe.type="button",Qe.style.display="none",Qe.setAttribute("data-persona-scroll-to-bottom","true");let qt=b("span","persona-flex persona-items-center"),ln=b("span",""),Cn=b("span","");Cn.setAttribute("data-persona-scroll-to-bottom-count",""),Cn.style.display="none",Qe.append(qt,ln,Cn),j.appendChild(Qe);let Sn=b("div","persona-stream-anchor-spacer");Sn.setAttribute("aria-hidden","true"),Sn.setAttribute("data-persona-anchor-spacer",""),Sn.style.flexShrink="0",Sn.style.pointerEvents="none",Sn.style.height="0px",fe.appendChild(Sn);let yn=()=>{let p=$e.style.display==="none"?0:$e.offsetHeight;Qe.style.bottom=`${p+Qt}px`};yn();let Lo=()=>{let c=!!Gt();Qe.setAttribute("aria-label",Gt()||"Jump to latest"),Qe.title=Gt(),Qe.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),qt.innerHTML="";let p=Me(In(),"14px","currentColor",2);p?(qt.appendChild(p),qt.style.display=""):qt.style.display="none",ln.textContent=Gt(),ln.style.display=c?"":"none"};Lo();let At=null,Un=null,zn=r.find(c=>c.renderHeader);if(zn!=null&&zn.renderHeader){let c=zn.renderHeader({config:o,defaultRenderer:()=>{let p=$r({config:o,showClose:S()});return Ea(j,p,o),p.header},onClose:()=>Ot(!1,"user")});if(c){let p=j.querySelector(".persona-border-b-persona-divider");p&&(p.replaceWith(c),_e=c)}}let Vo=()=>{var p,h,y,L;if(!ye)return;if(ae=!0,!K&&ye&&(K=Hf({buffer:ye,getFullHistory:()=>ye.getAllFromStore(),onClose:()=>yo(),config:o,plugins:r,getThroughput:()=>{var N;return(N=be==null?void 0:be.getMetric())!=null?N:{status:"idle"}}})),K&&(fe.style.display="none",(p=$e.parentNode)==null||p.insertBefore(K.element,$e),K.update()),wt){wt.style.boxShadow=`inset 0 0 0 1.5px ${Dn.actionIconColor}`;let N=(L=(y=(h=o.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:L.toggleButtonActive;N&&N.split(/\s+/).forEach(_=>_&&wt.classList.add(_))}let c=()=>{if(!ae)return;let N=Date.now();N-oe>=200&&(K==null||K.update(),oe=N),Re=requestAnimationFrame(c)};oe=0,Re=requestAnimationFrame(c),_n(),s.emit("eventStream:opened",{timestamp:Date.now()})},yo=()=>{var c,p,h;if(ae){if(ae=!1,K&&K.element.remove(),fe.style.display="",wt){wt.style.boxShadow="";let y=(h=(p=(c=o.features)==null?void 0:c.eventStream)==null?void 0:p.classNames)==null?void 0:h.toggleButtonActive;y&&y.split(/\s+/).forEach(L=>L&&wt.classList.remove(L))}Re!==null&&(cancelAnimationFrame(Re),Re=null),_n(),s.emit("eventStream:closed",{timestamp:Date.now()})}},wt=null;if(Ee){let c=(Wd=(Pd=o.features)==null?void 0:Pd.eventStream)==null?void 0:Wd.classNames,p="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");wt=b("button",p),wt.style.width="28px",wt.style.height="28px",wt.style.color=Dn.actionIconColor,wt.type="button",wt.setAttribute("aria-label","Event Stream"),wt.title="Event Stream";let h=Me("activity","18px","currentColor",1.5);h&&wt.appendChild(h);let y=Be.clearChatButtonWrapper,L=Be.closeButtonWrapper,N=y||L;N&&N.parentNode===_e?_e.insertBefore(wt,N):_e.appendChild(wt),wt.addEventListener("click",()=>{ae?yo():Vo()})}let Cr=c=>{var y,L,N;let p=o.attachments;if(!(p!=null&&p.enabled))return;let h=c.querySelector(".persona-attachment-previews");if(!h){h=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.style.display="none";let _=c.querySelector("[data-persona-composer-form]");_!=null&&_.parentNode?_.parentNode.insertBefore(h,_):c.insertBefore(h,c.firstChild)}if(!c.querySelector('input[type="file"]')){let _=b("input");_.type="file",_.accept=((y=p.allowedTypes)!=null?y:Jo).join(","),_.multiple=((L=p.maxFiles)!=null?L:4)>1,_.style.display="none",_.setAttribute("aria-label",(N=p.buttonTooltipText)!=null?N:"Attach files"),c.appendChild(_)}},Io=r.find(c=>c.renderComposer);if(Io!=null&&Io.renderComposer){let c=o.composer,p=Io.renderComposer({config:o,defaultRenderer:()=>el({config:o}).footer,onSubmit:h=>{var _;if(!$||$.isStreaming())return;let y=h.trim(),L=(_=At==null?void 0:At.hasAttachments())!=null?_:!1;if(!y&&!L)return;T();let N;L&&(N=[],N.push(...At.getContentParts()),y&&N.push(Jl(y))),$.sendMessage(y,{contentParts:N}),L&&At.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{ce==null||ce.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:((Bd=o.voiceRecognition)==null?void 0:Bd.enabled)===!0?()=>{Un==null||Un()}:void 0});p&&($e.replaceWith(p),$e=p)}let Sr=c=>{let p=c.querySelector("[data-persona-composer-form]"),h=c.querySelector("[data-persona-composer-input]"),y=c.querySelector("[data-persona-composer-submit]"),L=c.querySelector("[data-persona-composer-mic]"),N=c.querySelector("[data-persona-composer-status]");p&&(Dt=p),h&&(te=h),y&&(qe=y),L&&(G=L,xt=L.parentElement),N&&(an=N);let _=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");_&&(Mt=_);let q=c.querySelector(".persona-attachment-button");q&&(st=q,Se=q.parentElement),ce=c.querySelector('input[type="file"]'),et=c.querySelector(".persona-attachment-previews");let O=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");O&&(ot=O)};Cr($e),Sr($e);let On=(Nd=(Hd=o.layout)==null?void 0:Hd.contentMaxWidth)!=null?Nd:E()?(Od=(Fd=(Dd=o.launcher)==null?void 0:Dd.composerBar)==null?void 0:Fd.contentMaxWidth)!=null?Od:"720px":void 0;if(On&&(tt.style.maxWidth=On,tt.style.marginLeft="auto",tt.style.marginRight="auto",tt.style.width="100%"),On&&Dt&&!E()&&(Dt.style.maxWidth=On,Dt.style.marginLeft="auto",Dt.style.marginRight="auto"),On&&Mt&&!E()&&(Mt.style.maxWidth=On,Mt.style.marginLeft="auto",Mt.style.marginRight="auto"),On&&et&&!E()&&(et.style.maxWidth=On,et.style.marginLeft="auto",et.style.marginRight="auto"),(_d=o.attachments)!=null&&_d.enabled&&ce&&et){At=va.fromConfig(o.attachments),At.setPreviewsContainer(et),ce.addEventListener("change",h=>{let y=h.target;At==null||At.handleFileSelect(y.files),y.value=""});let c=o.attachments.dropOverlay,p=ng(c);j.appendChild(p)}(()=>{var y,L;let c=(L=(y=o.layout)==null?void 0:y.slots)!=null?L:{},p=N=>{switch(N){case"body-top":return j.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return tt;case"footer-top":return Mt;case"composer":return Dt;case"footer-bottom":return an;default:return null}},h=(N,_)=>{var q;switch(N){case"header-left":case"header-center":case"header-right":if(N==="header-left")_e.insertBefore(_,_e.firstChild);else if(N==="header-right")_e.appendChild(_);else{let O=_e.querySelector(".persona-flex-col");O?(q=O.parentNode)==null||q.insertBefore(_,O.nextSibling):_e.appendChild(_)}break;case"body-top":{let O=fe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");O?O.replaceWith(_):fe.insertBefore(_,fe.firstChild);break}case"body-bottom":fe.appendChild(_);break;case"footer-top":Mt.replaceWith(_);break;case"footer-bottom":an.replaceWith(_);break;default:break}};for(let[N,_]of Object.entries(c))if(_)try{let q=_({config:o,defaultContent:()=>p(N)});q&&h(N,q)}catch(q){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${N}":`,q)}})();let Zo=c=>{var _,q;let h=c.target.closest('button[data-expand-header="true"]');if(!h)return;let y=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!y)return;let L=y.getAttribute("data-message-id");if(!L)return;let N=h.getAttribute("data-bubble-type");if(N==="reasoning")ys.has(L)?ys.delete(L):ys.add(L),ff(L,y);else if(N==="tool")vs.has(L)?vs.delete(L):vs.add(L),gf(L,y,o);else if(N==="approval"){let O=o.approval!==!1?o.approval:void 0,Ce=((_=O==null?void 0:O.detailsDisplay)!=null?_:"collapsed")==="expanded",ge=(q=rl.get(L))!=null?q:Ce;rl.set(L,!ge),If(L,y,o)}qo.delete(L)};tt.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Zo(c))}),tt.addEventListener("keydown",c=>{let p=c.target;(c.key==="Enter"||c.key===" ")&&p.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Zo(c))});let $o=new Map;tt.addEventListener("click",c=>{var _;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 L=y.getAttribute("data-actions-for");if(!L)return;let N=h.getAttribute("data-action");if(N==="copy"){let O=$.getMessages().find(Ce=>Ce.id===L);if(O&&ee.onCopy){let Ce=O.content||"";navigator.clipboard.writeText(Ce).then(()=>{h.classList.add("persona-message-action-success");let ge=Me("check",14,"currentColor",2);ge&&(h.innerHTML="",h.appendChild(ge)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let ne=Me("copy",14,"currentColor",2);ne&&(h.innerHTML="",h.appendChild(ne))},2e3)}).catch(ge=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ge)}),ee.onCopy(O)}}else if(N==="upvote"||N==="downvote"){let O=((_=$o.get(L))!=null?_:null)===N,Ce=N==="upvote"?"thumbs-up":"thumbs-down";if(O){$o.delete(L),h.classList.remove("persona-message-action-active");let ge=Me(Ce,14,"currentColor",2);ge&&(h.innerHTML="",h.appendChild(ge))}else{let ge=N==="upvote"?"downvote":"upvote",ne=y.querySelector(`[data-action="${ge}"]`);if(ne){ne.classList.remove("persona-message-action-active");let je=Me(ge==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);je&&(ne.innerHTML="",ne.appendChild(je))}$o.set(L,N),h.classList.add("persona-message-action-active");let ke=Me(Ce,14,"currentColor",2);ke&&(ke.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(ke)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Te=$.getMessages().find(nt=>nt.id===L);Te&&ee.onFeedback&&ee.onFeedback({type:N,messageId:Te.id,message:Te})}}}),tt.addEventListener("click",c=>{let h=c.target.closest("button[data-approval-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.closest(".persona-approval-bubble");if(!y)return;let L=y.getAttribute("data-message-id");if(!L)return;let N=h.getAttribute("data-approval-action");if(!N)return;let _=N==="approve"?"approved":"denied",O=$.getMessages().find(ge=>ge.id===L);if(!(O!=null&&O.approval))return;let Ce=y.querySelector("[data-approval-buttons]");Ce&&Ce.querySelectorAll("button").forEach(ne=>{ne.disabled=!0,ne.style.opacity="0.5",ne.style.cursor="not-allowed"}),O.approval.toolType==="webmcp"?$.resolveWebMcpApproval(L,_):$.resolveApproval(O.approval,_)});let Tt=null,qn=null,jn={artifacts:[],selectedId:null},Rn=!1,Rt={current:null};tt.addEventListener("click",c=>{var ne,ke,Ve,Te,nt;let h=c.target.closest("[data-download-artifact]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||((Ve=(ke=(ne=o.features)==null?void 0:ne.artifacts)==null?void 0:ke.onArtifactAction)==null?void 0:Ve.call(ke,{type:"download",artifactId:y}))===!0)return;let N=$.getArtifactById(y),_=N==null?void 0:N.markdown,q=(N==null?void 0:N.title)||"artifact";if(!_){let je=h.closest("[data-open-artifact]"),dt=je==null?void 0:je.closest("[data-message-id]"),pt=dt==null?void 0:dt.getAttribute("data-message-id");if(pt){let Ie=$.getMessages().find(ze=>ze.id===pt);if(Ie!=null&&Ie.rawContent)try{let ze=JSON.parse(Ie.rawContent);_=(Te=ze==null?void 0:ze.props)==null?void 0:Te.markdown,q=((nt=ze==null?void 0:ze.props)==null?void 0:nt.title)||q}catch{}}}if(!_)return;let O=new Blob([_],{type:"text/markdown"}),Ce=URL.createObjectURL(O),ge=document.createElement("a");ge.href=Ce,ge.download=`${q}.md`,ge.click(),URL.revokeObjectURL(Ce)}),tt.addEventListener("click",c=>{var N,_,q;let h=c.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||((q=(_=(N=o.features)==null?void 0:N.artifacts)==null?void 0:_.onArtifactAction)==null?void 0:q.call(_,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),Rn=!1,$.selectArtifact(y),Yn())}),tt.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let p=c.target;p.hasAttribute("data-open-artifact")&&(c.preventDefault(),p.click())});let ro=Be.composerOverlay,so=(c,p,h)=>{var q,O,Ce,ge;let y=p.trim();if(!y||!Rt.current)return;let L=(q=c.getAttribute("data-tool-call-id"))!=null?q:"",N=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:L,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})),Ss(ro,L);let _=Rt.current.getMessages().find(ne=>{var ke;return((ke=ne.toolCall)==null?void 0:ke.id)===L});(Ce=_==null?void 0:_.agentMetadata)!=null&&Ce.awaitingLocalTool?Rt.current.resolveAskUserQuestion(_,(ge=h.structured)!=null?ge:y):Rt.current.sendMessage(y)},Kn=c=>{var L;let p=Rt.current;if(!p)return;let h=(L=c.getAttribute("data-tool-call-id"))!=null?L:"",y=p.getMessages().find(N=>{var _;return((_=N.toolCall)==null?void 0:_.id)===h});y&&p.persistAskUserQuestionProgress(y,{answers:tl(c,y),currentIndex:ho(c)})},er=c=>Object.entries(c).map(([p,h])=>`${p}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Uo=c=>{var L,N,_;if(((N=(L=o.features)==null?void 0:L.askUserQuestion)==null?void 0:N.groupedAutoAdvance)===!1)return;let p=ho(c),h=Cs(c);if(p>=h-1)return;let y=(_=Rt.current)==null?void 0:_.getMessages().find(q=>{var O;return((O=q.toolCall)==null?void 0:O.id)===c.getAttribute("data-tool-call-id")});y&&(ol(c,y,o,p+1),Kn(c))};ro.addEventListener("click",c=>{var N,_,q,O,Ce,ge,ne,ke,Ve,Te,nt,je,dt,pt;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 L=h.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),L==="dismiss"){let We=(N=y.getAttribute("data-tool-call-id"))!=null?N:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:We},bubbles:!0,composed:!0})),Ss(ro,We);let Ie=(_=Rt.current)==null?void 0:_.getMessages().find(ze=>{var Ye;return((Ye=ze.toolCall)==null?void 0:Ye.id)===We});(q=Ie==null?void 0:Ie.agentMetadata)!=null&&q.awaitingLocalTool&&((O=Rt.current)==null||O.markAskUserQuestionResolved(Ie),(Ce=Rt.current)==null||Ce.resolveAskUserQuestion(Ie,"(dismissed)"));return}if(L==="pick"){let We=h.getAttribute("data-option-label");if(!We)return;let Ie=y.getAttribute("data-multi-select")==="true",ze=yr(y);if(ze&&Ie){let Ye=zr(y)[ho(y)],Ct=new Set(Array.isArray(Ye)?Ye:[]);Ct.has(We)?Ct.delete(We):Ct.add(We),vr(y,Array.from(Ct)),Kn(y);return}if(ze){vr(y,We),Kn(y),Uo(y);return}if(Ie){let Ye=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Ye?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Ye);let Ct=y.querySelector('[data-ask-user-action="submit-multi"]');Ct&&(Ct.disabled=hc(y).length===0);return}so(y,We,{source:"pick",values:[We]});return}if(L==="submit-multi"){let We=hc(y);if(We.length===0)return;so(y,We.join(", "),{source:"multi",values:We});return}if(L==="open-free-text"){let We=y.querySelector('[data-ask-free-text-row="true"]');if(We){We.classList.remove("persona-hidden");let Ie=We.querySelector('[data-ask-free-text-input="true"]');Ie==null||Ie.focus()}return}if(L==="focus-free-text"){let We=y.querySelector('[data-ask-free-text-input="true"]');We==null||We.focus();return}if(L==="submit-free-text"){let We=y.querySelector('[data-ask-free-text-input="true"]'),Ie=(ge=We==null?void 0:We.value)!=null?ge:"";if(!Ie.trim())return;if(yr(y)){vr(y,Ie.trim()),Kn(y),Uo(y);return}so(y,Ie,{source:"free-text"});return}if(L==="next"||L==="back"){if(!Rt.current)return;let We=(ne=y.getAttribute("data-tool-call-id"))!=null?ne:"",Ie=Rt.current.getMessages().find(He=>{var Oe;return((Oe=He.toolCall)==null?void 0:Oe.id)===We});if(!Ie)return;let ze=y.querySelector('[data-ask-free-text-input="true"]'),Ye=(Ve=(ke=ze==null?void 0:ze.value)==null?void 0:ke.trim())!=null?Ve:"";if(Ye){let He=zr(y)[ho(y)];(typeof He!="string"||He!==Ye)&&vr(y,Ye)}let Ct=L==="next"?1:-1,H=ho(y)+Ct;ol(y,Ie,o,H),Kn(y);return}if(L==="submit-all"){if(!Rt.current)return;let We=(Te=y.getAttribute("data-tool-call-id"))!=null?Te:"",Ie=Rt.current.getMessages().find(He=>{var Oe;return((Oe=He.toolCall)==null?void 0:Oe.id)===We});if(!Ie)return;let ze=y.querySelector('[data-ask-free-text-input="true"]'),Ye=(je=(nt=ze==null?void 0:ze.value)==null?void 0:nt.trim())!=null?je:"";Ye&&vr(y,Ye);let Ct=tl(y,Ie);Rt.current.persistAskUserQuestionProgress(Ie,{answers:Ct,currentIndex:ho(y)});let H=er(Ct);so(y,H||"(submitted)",{source:"submit-all",structured:Ct});return}if(L==="skip"){if(!Rt.current)return;let We=(dt=y.getAttribute("data-tool-call-id"))!=null?dt:"",Ie=Rt.current.getMessages().find(Oe=>{var ve;return((ve=Oe.toolCall)==null?void 0:ve.id)===We});if(!Ie)return;let ze=yr(y),Ye=ho(y),Ct=Cs(y),H=Ye>=Ct-1;if(!ze){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:We},bubbles:!0,composed:!0})),Ss(ro,We),(pt=Ie.agentMetadata)!=null&&pt.awaitingLocalTool&&(Rt.current.markAskUserQuestionResolved(Ie),Rt.current.resolveAskUserQuestion(Ie,"(dismissed)"));return}vr(y,"");let He=y.querySelector('[data-ask-free-text-input="true"]');if(He&&(He.value=""),H){let Oe=tl(y,Ie),ve=er(Oe);so(y,ve||"(skipped)",{source:"submit-all",structured:Oe});return}ol(y,Ie,o,Ye+1),Kn(y);return}}),ro.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 L=h.value;if(L.trim()){if(yr(y)){vr(y,L.trim()),Kn(y),Uo(y);return}so(y,L,{source:"free-text"})}});let tr=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let p=c.target;if((p==null?void 0:p.tagName)==="INPUT"||(p==null?void 0:p.tagName)==="TEXTAREA"||p!=null&&p.isContentEditable)return;let h=ro.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",tr);let Gn=null,Ft=null,Pn=null,ao=null,nr=()=>{};function zo(){ao==null||ao(),ao=null}let or=()=>{var _;if(!Gn||!Ft)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),h=((_=e.ownerDocument.defaultView)!=null?_:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||h){Ft.style.removeProperty("position"),Ft.style.removeProperty("left"),Ft.style.removeProperty("top"),Ft.style.removeProperty("bottom"),Ft.style.removeProperty("width"),Ft.style.removeProperty("z-index");return}let y=Gn.firstElementChild;if(!y||y===Ft)return;let L=10;Ft.style.position="absolute",Ft.style.top="0",Ft.style.bottom="0",Ft.style.width=`${L}px`,Ft.style.zIndex="5";let N=y.offsetWidth-L/2;Ft.style.left=`${Math.max(0,N)}px`},Ro=()=>{},Yn=()=>{var h,y,L,N,_;if(!Tt||!bo(o))return;il(e,o),ll(e,o),Ro();let c=(N=(L=(y=(h=o.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:L.narrowHostMaxWidth)!=null?N:520,p=pe.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",p>0&&p<=c),Tt.update(jn),Rn?(Tt.setMobileOpen(!1),Tt.element.classList.add("persona-hidden"),(_=Tt.backdrop)==null||_.classList.add("persona-hidden")):jn.artifacts.length>0&&(Tt.element.classList.remove("persona-hidden"),Tt.setMobileOpen(!0)),nr()};if(bo(o)){pe.style.position="relative";let c=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),p=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(j),Tt=Of(o,{onSelect:h=>{var y;return(y=Rt.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{Rn=!0,Yn()}}),Tt.element.classList.add("persona-hidden"),Gn=p,p.appendChild(c),p.appendChild(Tt.element),Tt.backdrop&&pe.appendChild(Tt.backdrop),pe.appendChild(p),nr=()=>{var y,L,N,_;if(!Gn||!Tt)return;if(!(((N=(L=(y=o.features)==null?void 0:y.artifacts)==null?void 0:L.layout)==null?void 0:N.resizable)===!0)){Pn==null||Pn(),Pn=null,zo(),Ft&&(Ft.remove(),Ft=null),Tt.element.style.removeProperty("width"),Tt.element.style.removeProperty("maxWidth");return}if(!Ft){let q=b("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");q.setAttribute("role","separator"),q.setAttribute("aria-orientation","vertical"),q.setAttribute("aria-label","Resize artifacts panel"),q.tabIndex=0;let O=e.ownerDocument,Ce=(_=O.defaultView)!=null?_:window,ge=ne=>{var dt,pt;if(!Tt||ne.button!==0||e.classList.contains("persona-artifact-narrow-host")||Ce.innerWidth<=640)return;ne.preventDefault(),zo();let ke=ne.clientX,Ve=Tt.element.getBoundingClientRect().width,Te=(pt=(dt=o.features)==null?void 0:dt.artifacts)==null?void 0:pt.layout,nt=We=>{let Ie=Gn.getBoundingClientRect().width,ze=e.classList.contains("persona-artifact-appearance-seamless"),Ye=ze?0:$f(Gn,Ce),Ct=ze?0:q.getBoundingClientRect().width||6,H=Ve-(We.clientX-ke),He=Uf(H,Ie,Ye,Ct,Te==null?void 0:Te.resizableMinWidth,Te==null?void 0:Te.resizableMaxWidth);Tt.element.style.width=`${He}px`,Tt.element.style.maxWidth="none",or()},je=()=>{O.removeEventListener("pointermove",nt),O.removeEventListener("pointerup",je),O.removeEventListener("pointercancel",je),ao=null;try{q.releasePointerCapture(ne.pointerId)}catch{}};ao=je,O.addEventListener("pointermove",nt),O.addEventListener("pointerup",je),O.addEventListener("pointercancel",je);try{q.setPointerCapture(ne.pointerId)}catch{}};q.addEventListener("pointerdown",ge),Ft=q,Gn.insertBefore(q,Tt.element),Pn=()=>{q.removeEventListener("pointerdown",ge)}}if(Ft){let q=jn.artifacts.length>0&&!Rn;Ft.classList.toggle("persona-hidden",!q),or()}},Ro=()=>{var Ce,ge,ne,ke,Ve,Te,nt,je,dt,pt,We,Ie,ze,Ye;if(!I||!Tt||((ge=(Ce=o.launcher)==null?void 0:Ce.sidebarMode)!=null?ge:!1)||wn(o)&&No(o).reveal==="emerge")return;let y=(ne=e.ownerDocument.defaultView)!=null?ne:window,L=(Ve=(ke=o.launcher)==null?void 0:ke.mobileFullscreen)!=null?Ve:!0,N=(nt=(Te=o.launcher)==null?void 0:Te.mobileBreakpoint)!=null?nt:640;if(L&&y.innerWidth<=N||!Vf(o,I))return;let _=(pt=(dt=(je=o.launcher)==null?void 0:je.width)!=null?dt:o.launcherWidth)!=null?pt:go,q=(Ye=(ze=(Ie=(We=o.features)==null?void 0:We.artifacts)==null?void 0:Ie.layout)==null?void 0:ze.expandedPanelWidth)!=null?Ye:"min(720px, calc(100vw - 24px))";jn.artifacts.length>0&&!Rn?(pe.style.width=q,pe.style.maxWidth=q):(pe.style.width=_,pe.style.maxWidth=_)},typeof ResizeObserver!="undefined"&&(qn=new ResizeObserver(()=>{Yn()}),qn.observe(pe))}else pe.appendChild(j),E()&&Je&&(Be.peekBanner&&Je.appendChild(Be.peekBanner),Je.appendChild($e));e.appendChild(Le),Je&&e.appendChild(Je);let vo=()=>{var He,Oe,ve,Vt,Nt,Yt,St,jt,Zn,rn,Xe,Wt,dn,mo,eo,Mr,Lr,is,ls,Xt,Ir,ur,mr,Xo,rt,xn,Wn,sn;if(E()){pe.style.width="100%",pe.style.maxWidth="100%";let ut=(Oe=(He=o.launcher)==null?void 0:He.composerBar)!=null?Oe:{},yt=Le.dataset.state==="expanded",mt=(ve=ut.expandedSize)!=null?ve:"anchored";if(!(yt&&mt!=="fullscreen")){j.style.background="",j.style.border="",j.style.borderRadius="",j.style.overflow="",j.style.boxShadow="";return}let pn=(Nt=(Vt=o.theme)==null?void 0:Vt.components)==null?void 0:Nt.panel,Fo=ci(o),un=(Pr,ai)=>{var Ks;return Pr==null||Pr===""?ai:(Ks=cs(Fo,Pr))!=null?Ks:Pr},Bn="1px solid var(--persona-border)",fo="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Rr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";j.style.background="var(--persona-surface, #ffffff)",j.style.border=un(pn==null?void 0:pn.border,Bn),j.style.borderRadius=un(pn==null?void 0:pn.borderRadius,Rr),j.style.boxShadow=un(pn==null?void 0:pn.shadow,fo),j.style.overflow="hidden";return}let c=wn(o),p=(St=(Yt=o.launcher)==null?void 0:Yt.sidebarMode)!=null?St:!1,h=c||p||((Zn=(jt=o.launcher)==null?void 0:jt.fullHeight)!=null?Zn:!1),y=((rn=o.launcher)==null?void 0:rn.enabled)===!1,L=(Wt=(Xe=o.theme)==null?void 0:Xe.components)==null?void 0:Wt.panel,N=ci(o),_=(ut,yt)=>{var mt;return ut==null||ut===""?yt:(mt=cs(N,ut))!=null?mt:ut},q=(dn=e.ownerDocument.defaultView)!=null?dn:window,O=(eo=(mo=o.launcher)==null?void 0:mo.mobileFullscreen)!=null?eo:!0,Ce=(Lr=(Mr=o.launcher)==null?void 0:Mr.mobileBreakpoint)!=null?Lr:640,ge=q.innerWidth<=Ce,ne=O&&ge&&I,ke=(ls=(is=o.launcher)==null?void 0:is.position)!=null?ls:"bottom-left",Ve=ke==="bottom-left"||ke==="top-left",Te=(Ir=(Xt=o.launcher)==null?void 0:Xt.zIndex)!=null?Ir:Mn,nt=p||ne?"none":"1px solid var(--persona-border)",je=ne?"none":p?Ve?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!ne&&(je="none",nt="none");let dt=p||ne?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",pt=_(L==null?void 0:L.border,nt),We=_(L==null?void 0:L.shadow,je),Ie=_(L==null?void 0:L.borderRadius,dt),ze=fe.scrollTop;e.style.cssText="",Le.style.cssText="",pe.style.cssText="",j.style.cssText="",fe.style.cssText="",$e.style.cssText="";let Ye=()=>{var yt;if(ze<=0)return;((yt=fe.ownerDocument.defaultView)!=null?yt:window).requestAnimationFrame(()=>{if(fe.scrollTop===ze)return;let mt=fe.scrollHeight-fe.clientHeight;mt<=0||(fe.scrollTop=Math.min(ze,mt))})};if(ne){Le.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Le.style.cssText=`
|
|
31
31
|
position: fixed !important;
|
|
32
32
|
inset: 0 !important;
|
|
33
33
|
width: 100% !important;
|
|
@@ -37,9 +37,9 @@ _Details: ${n.message}_`:o}var la=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
37
37
|
padding: 0 !important;
|
|
38
38
|
display: flex !important;
|
|
39
39
|
flex-direction: column !important;
|
|
40
|
-
z-index: ${
|
|
40
|
+
z-index: ${Te} !important;
|
|
41
41
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
42
|
-
`,
|
|
42
|
+
`,pe.style.cssText=`
|
|
43
43
|
position: relative !important;
|
|
44
44
|
display: flex !important;
|
|
45
45
|
flex-direction: column !important;
|
|
@@ -52,7 +52,7 @@ _Details: ${n.message}_`:o}var la=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
52
52
|
padding: 0 !important;
|
|
53
53
|
box-shadow: none !important;
|
|
54
54
|
border-radius: 0 !important;
|
|
55
|
-
`,
|
|
55
|
+
`,j.style.cssText=`
|
|
56
56
|
display: flex !important;
|
|
57
57
|
flex-direction: column !important;
|
|
58
58
|
flex: 1 1 0% !important;
|
|
@@ -63,20 +63,20 @@ _Details: ${n.message}_`:o}var la=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
63
63
|
overflow: hidden !important;
|
|
64
64
|
border-radius: 0 !important;
|
|
65
65
|
border: none !important;
|
|
66
|
-
`,
|
|
66
|
+
`,fe.style.flex="1 1 0%",fe.style.minHeight="0",fe.style.overflowY="auto",$e.style.flexShrink="0",x=!0,Ye();return}let Ct=(mr=(ur=o==null?void 0:o.launcher)==null?void 0:ur.width)!=null?mr:o==null?void 0:o.launcherWidth,H=Ct!=null?Ct:go;if(!p&&!c)y&&h?(pe.style.width="100%",pe.style.maxWidth="100%"):(pe.style.width=H,pe.style.maxWidth=H);else if(c)if(No(o).reveal==="emerge"){let yt=No(o).width;pe.style.width=yt,pe.style.maxWidth=yt}else pe.style.width="100%",pe.style.maxWidth="100%";if(Ro(),pe.style.boxShadow=We,pe.style.borderRadius=Ie,j.style.border=pt,j.style.borderRadius=Ie,c&&!ne&&(L==null?void 0:L.border)===void 0&&(j.style.border="none",No(o).side==="right"?j.style.borderLeft="1px solid var(--persona-border)":j.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",y&&(e.style.width="100%"),Le.style.display="flex",Le.style.flexDirection="column",Le.style.flex="1 1 0%",Le.style.minHeight="0",Le.style.maxHeight="100%",Le.style.height="100%",y&&(Le.style.overflow="hidden"),pe.style.display="flex",pe.style.flexDirection="column",pe.style.flex="1 1 0%",pe.style.minHeight="0",pe.style.maxHeight="100%",pe.style.height="100%",pe.style.overflow="hidden",j.style.display="flex",j.style.flexDirection="column",j.style.flex="1 1 0%",j.style.minHeight="0",j.style.maxHeight="100%",j.style.overflow="hidden",fe.style.flex="1 1 0%",fe.style.minHeight="0",fe.style.overflowY="auto",$e.style.flexShrink="0"),Le.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!p&&!y&&!c&&((Xo=Eo[ke])!=null?Xo:Eo["bottom-right"]).split(" ").forEach(yt=>Le.classList.add(yt)),p){let ut=(xn=(rt=o.launcher)==null?void 0:rt.sidebarWidth)!=null?xn:"420px";Le.style.cssText=`
|
|
67
67
|
position: fixed !important;
|
|
68
68
|
top: 0 !important;
|
|
69
69
|
bottom: 0 !important;
|
|
70
|
-
width: ${
|
|
70
|
+
width: ${ut} !important;
|
|
71
71
|
height: 100vh !important;
|
|
72
72
|
max-height: 100vh !important;
|
|
73
73
|
margin: 0 !important;
|
|
74
74
|
padding: 0 !important;
|
|
75
75
|
display: flex !important;
|
|
76
76
|
flex-direction: column !important;
|
|
77
|
-
z-index: ${
|
|
78
|
-
${
|
|
79
|
-
`,
|
|
77
|
+
z-index: ${Te} !important;
|
|
78
|
+
${Ve?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
79
|
+
`,pe.style.cssText=`
|
|
80
80
|
position: relative !important;
|
|
81
81
|
display: flex !important;
|
|
82
82
|
flex-direction: column !important;
|
|
@@ -88,8 +88,8 @@ _Details: ${n.message}_`:o}var la=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
88
88
|
margin: 0 !important;
|
|
89
89
|
padding: 0 !important;
|
|
90
90
|
box-shadow: ${We} !important;
|
|
91
|
-
border-radius: ${
|
|
92
|
-
`,
|
|
91
|
+
border-radius: ${Ie} !important;
|
|
92
|
+
`,pe.style.setProperty("width","100%","important"),pe.style.setProperty("max-width","100%","important"),j.style.cssText=`
|
|
93
93
|
display: flex !important;
|
|
94
94
|
flex-direction: column !important;
|
|
95
95
|
flex: 1 1 0% !important;
|
|
@@ -98,13 +98,13 @@ _Details: ${n.message}_`:o}var la=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
98
98
|
min-height: 0 !important;
|
|
99
99
|
max-height: 100% !important;
|
|
100
100
|
overflow: hidden !important;
|
|
101
|
-
border-radius: ${
|
|
101
|
+
border-radius: ${Ie} !important;
|
|
102
102
|
border: ${pt} !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 ft="max-height: -moz-available !important; max-height: stretch !important;",lt=g?"":"padding-top: 1.25em !important;",Et=g?"":`z-index: ${(dn=(fn=o.launcher)==null?void 0:fn.zIndex)!=null?dn:Cn} !important;`;Te.style.cssText+=ft+lt+Et}Je()};yo(),es(e,o),Zi(e,o),el(e,o);let vt=[];vt.push(()=>{document.removeEventListener("keydown",Go)});let Xt=null,Qt=null;vt.push(()=>{Xt==null||Xt(),Xt=null,Qt==null||Qt(),Qt=null}),Vn&&vt.push(()=>{Vn==null||Vn.disconnect(),Vn=null}),vt.push(()=>{En==null||En(),En=null,Oo(),Ft&&(Ft.remove(),Ft=null),At==null||At.element.style.removeProperty("width"),At==null||At.element.style.removeProperty("maxWidth")}),Ee&&vt.push(()=>{Se!==null&&(cancelAnimationFrame(Se),Se=null),ce==null||ce.destroy(),ce=null,G==null||G.destroy(),G=null,K=null});let jn=null,Qo=()=>{jn&&(jn(),jn=null),o.colorScheme==="auto"&&(jn=Ou(()=>{es(e,o)}))};Qo(),vt.push(()=>{jn&&(jn(),jn=null)});let ao=(xd=o.features)==null?void 0:xd.streamAnimation;if(ao!=null&&ao.type&&ao.type!=="none"){let c=ma(ao.type,ao.plugins);c&&(zl(c,e),vt.push(()=>Im(e)))}let vo=ng(Ht),Kn=null,$,io=!1,xe=Am(),Gn=new Map,lo=new Map,xo=new Map,xs=0,wo=Ii(),Co=0,So=null,No=!1,hr=!1,Da=4,ws=24,Fa=80,Ur=new Map,yt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Cs=(Cd=(wd=o.voiceRecognition)==null?void 0:wd.autoResume)!=null?Cd:!1,co=c=>{s.emit("voice:state",{active:yt.active,source:c,timestamp:Date.now()})},Bn=()=>{u(c=>({...c,voiceState:{active:yt.active,timestamp:Date.now(),manuallyDeactivated:yt.manuallyDeactivated}}))},Oa=()=>{var y,L;if(((y=o.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=hc(d.voiceState),g=!!c.active,h=Number((L=c.timestamp)!=null?L:0);yt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-h<Sy&&setTimeout(()=>{var O,N;yt.active||(yt.manuallyDeactivated=!1,((N=(O=o.voiceRecognition)==null?void 0:O.provider)==null?void 0:N.type)==="runtype"?$.toggleVoice().then(()=>{yt.active=$.isVoiceActive(),co("restore"),$.isVoiceActive()&&P()}):xr("restore"))},1e3)},Na=()=>$?Tg($.getMessages()).filter(c=>!c.__skipPersist):[];function zr(c){if(!(i!=null&&i.save))return;let h={messages:c?Tg(c):$?Na():[],metadata:d,artifacts:$n.artifacts,selectedArtifactId:$n.selectedId};try{let y=i.save(h);y instanceof Promise&&y.catch(L=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",L)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let _o=null,_a=()=>Te.querySelector("#persona-scroll-container")||Q,br=()=>{_o!==null&&(cancelAnimationFrame(_o),_o=null),No=!1},Ss=()=>{So!==null&&(cancelAnimationFrame(So),So=null),hr=!1,br()},Vo=()=>{if(!An()||ne){Wt.parentNode&&Wt.remove(),Wt.style.display="none";return}Wt.parentNode!==me&&me.appendChild(Wt),St();let c=da(Q)>0;Wt.style.display=wo.isFollowing()||!c?"none":""},As=()=>{wo.pause()&&(Ss(),Vo())},Jo=()=>{wo.resume(),Vo()},Zo=(c=!1)=>{wo.isFollowing()&&(!c&&!io||(So!==null&&(cancelAnimationFrame(So),So=null),hr=!0,So=requestAnimationFrame(()=>{So=null,hr=!1,wo.isFollowing()&&Va(_a(),c?220:140)})))},Va=(c,g=500)=>{let h=c.scrollTop,y=da(c),L=y-h;if(Math.abs(L)<1){Co=c.scrollTop;return}if(Math.abs(L)>=Fa){br(),No=!0,c.scrollTop=y,Co=c.scrollTop,No=!1;return}br();let O=performance.now();No=!0;let N=F=>1-Math.pow(1-F,3),q=F=>{if(!wo.isFollowing()){br();return}let ke=da(c);ke!==y&&(y=ke,L=y-h);let ge=F-O,ee=Math.min(ge/g,1),Ae=N(ee),Ie=h+L*Ae;c.scrollTop=Ie,Co=c.scrollTop,ee<1?_o=requestAnimationFrame(q):(c.scrollTop=y,Co=c.scrollTop,_o=null,No=!1)};_o=requestAnimationFrame(q)},$a=c=>{let g=new Map;c.forEach(h=>{let y=Ur.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}))}),Ur.clear(),g.forEach((h,y)=>{Ur.set(y,h)})},yr=(c,g,h)=>{var pt,We,Pe,je,Je,xt;let y=document.createElement("div"),O=(()=>{var Fe;let H=r.find(oe=>oe.renderLoadingIndicator);if(H!=null&&H.renderLoadingIndicator)return H.renderLoadingIndicator;if((Fe=o.loadingIndicator)!=null&&Fe.render)return o.loadingIndicator.render})(),N=(H,Fe)=>Fe==null?!1:typeof Fe=="string"?(H.textContent=Fe,!0):(H.appendChild(Fe),!0),q=new Set,F=new Set,ke=r.some(H=>H.renderAskUserQuestion),ge=[],ee=[],Ae=o.enableComponentStreaming!==!1,Ie=r.some(H=>H.renderApproval)&&o.approval!==!1,$e=[];if(g.forEach(H=>{var Ct,Qn,rn,mo,Jn,wr,Qr,Jr,Yt,Cr,sr,ar,zo,Sr;q.add(H.id);let Fe=ke&&Hr(H),oe=Ie&&H.variant==="approval"&&!!H.approval,tt=!Fe&&H.role==="assistant"&&!H.variant&&Ae&&wg(H);if(!oe&&xo.has(H.id)){let nt=c.querySelector(`#wrapper-${H.id}`);nt==null||nt.removeAttribute("data-preserve-runtime"),xo.delete(H.id)}if(!tt&&lo.has(H.id)){let nt=c.querySelector(`#wrapper-${H.id}`);nt==null||nt.removeAttribute("data-preserve-runtime"),lo.delete(H.id)}let _t=Hr(H)?`:${(Ct=H.agentMetadata)!=null&&Ct.askUserQuestionAnswered?"a":"u"}:${(Qn=H.agentMetadata)!=null&&Qn.askUserQuestionAnswers?Object.keys(H.agentMetadata.askUserQuestionAnswers).length:0}`:"",Nt=Sm(H,xs)+_t,qt=Fe||oe||tt?null:Tm(xe,H.id,Nt);if(qt){y.appendChild(qt.cloneNode(!0)),Hr(H)&&((rn=H.toolCall)!=null&&rn.id)&&((mo=H.agentMetadata)==null?void 0:mo.awaitingLocalTool)===!0&&!((Jn=H.agentMetadata)!=null&&Jn.askUserQuestionAnswered)&&(F.add(H.toolCall.id),Gi(H,o,Be.composerOverlay));return}let it=null,cn=r.find(nt=>!!(H.variant==="reasoning"&&nt.renderReasoning||H.variant==="tool"&&nt.renderToolCall||!H.variant&&nt.renderMessage)),Xn=(wr=o.layout)==null?void 0:wr.messages;if(Hr(H)&&((Qr=H.agentMetadata)==null?void 0:Qr.askUserQuestionAnswered)===!0){Gn.delete(H.id);let nt=c.querySelector(`#wrapper-${H.id}`);nt==null||nt.removeAttribute("data-preserve-runtime");return}if(Hr(H)&&((Yt=(Jr=o.features)==null?void 0:Jr.askUserQuestion)==null?void 0:Yt.enabled)!==!1){let nt=r.find(vn=>typeof vn.renderAskUserQuestion=="function");if(nt&&Lt.current){let vn=Gn.get(H.id),fn=vn!==Nt,dn=null;if(fn){let{payload:Et,complete:Hn}=ps(H),en=H.id,Po=()=>{var sn;return(sn=Lt.current)==null?void 0:sn.getMessages().find(Ln=>Ln.id===en)};dn=nt.renderAskUserQuestion({message:H,payload:Et,complete:Hn,resolve:sn=>{var go;let Ln=Po();Ln&&((go=Lt.current)==null||go.resolveAskUserQuestion(Ln,sn))},dismiss:()=>{var Ln,go,Ar;let sn=Po();(Ln=sn==null?void 0:sn.agentMetadata)!=null&&Ln.awaitingLocalTool&&((go=Lt.current)==null||go.markAskUserQuestionResolved(sn),(Ar=Lt.current)==null||Ar.resolveAskUserQuestion(sn,"(dismissed)"))},config:o})}let ft=vn!=null;if(fn&&dn===null&&!ft){((Cr=H.agentMetadata)==null?void 0:Cr.awaitingLocalTool)===!0&&!((sr=H.agentMetadata)!=null&&sr.askUserQuestionAnswered)&&(F.add(H.toolCall.id),Gi(H,o,Be.composerOverlay));return}let lt=document.createElement("div");lt.className="persona-flex",lt.id=`wrapper-${H.id}`,lt.setAttribute("data-wrapper-id",H.id),lt.setAttribute("data-ask-plugin-stub","true"),lt.setAttribute("data-preserve-runtime","true"),y.appendChild(lt),ge.push({messageId:H.id,fingerprint:Nt,bubble:dn});return}else{((ar=H.agentMetadata)==null?void 0:ar.awaitingLocalTool)===!0&&!((zo=H.agentMetadata)!=null&&zo.askUserQuestionAnswered)&&(F.add(H.toolCall.id),Gi(H,o,Be.composerOverlay));return}}else if(oe){let nt=r.find(ft=>typeof ft.renderApproval=="function"),fn=xo.get(H.id)!==Nt,dn=null;if(fn&&(nt!=null&&nt.renderApproval)){let ft=H.id,lt=(Et,Hn)=>{var Po,sn,Ln;let en=(Po=Lt.current)==null?void 0:Po.getMessages().find(go=>go.id===ft);en!=null&&en.approval&&(en.approval.toolType==="webmcp"?(sn=Lt.current)==null||sn.resolveWebMcpApproval(en.id,Et):(Ln=Lt.current)==null||Ln.resolveApproval(en.approval,Et,Hn))};dn=nt.renderApproval({message:H,defaultRenderer:()=>Qi(H,o),config:o,approve:Et=>lt("approved",Et),deny:Et=>lt("denied",Et)})}if(fn&&dn===null){let ft=c.querySelector(`#wrapper-${H.id}`);ft==null||ft.removeAttribute("data-preserve-runtime"),xo.delete(H.id),it=Qi(H,o)}else{let ft=document.createElement("div");ft.className="persona-flex",ft.id=`wrapper-${H.id}`,ft.setAttribute("data-wrapper-id",H.id),ft.setAttribute("data-approval-plugin-stub","true"),ft.setAttribute("data-preserve-runtime","true"),y.appendChild(ft),$e.push({messageId:H.id,fingerprint:Nt,bubble:dn});return}}else if(cn)if(H.variant==="reasoning"&&H.reasoning&&cn.renderReasoning){if(!fe)return;it=cn.renderReasoning({message:H,defaultRenderer:()=>Ql(H,o),config:o})}else if(H.variant==="tool"&&H.toolCall&&cn.renderToolCall){if(!ae)return;it=cn.renderToolCall({message:H,defaultRenderer:()=>Jl(H,o),config:o})}else cn.renderMessage&&(it=cn.renderMessage({message:H,defaultRenderer:()=>{let nt=Xl(H,h,Xn,o.messageActions,te,{loadingIndicatorRenderer:O,widgetConfig:o});return H.role!=="user"&&cc(nt,H,o,$),nt},config:o}));if(!it&&tt){let nt=Cg(H);if(nt){let vn=lo.get(H.id),fn=vn!==Nt,dn=o.wrapComponentDirectiveInBubble!==!1,ft=null;if(fn){let lt=vg(nt,{config:o,message:H,transform:h});if(lt)if(dn){let Et=document.createElement("div");if(Et.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Et.id=`bubble-${H.id}`,Et.setAttribute("data-message-id",H.id),H.content&&H.content.trim()){let Hn=document.createElement("div");Hn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Hn.innerHTML=h({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),Et.appendChild(Hn)}Et.appendChild(lt),ft=Et}else{let Et=document.createElement("div");if(Et.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Et.id=`bubble-${H.id}`,Et.setAttribute("data-message-id",H.id),Et.setAttribute("data-persona-component-directive","true"),H.content&&H.content.trim()){let Hn=document.createElement("div");Hn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Hn.innerHTML=h({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),Et.appendChild(Hn)}Et.appendChild(lt),ft=Et}}if(ft||vn!=null){let lt=document.createElement("div");lt.className="persona-flex",lt.id=`wrapper-${H.id}`,lt.setAttribute("data-wrapper-id",H.id),lt.setAttribute("data-component-directive-stub","true"),lt.setAttribute("data-preserve-runtime","true"),dn||lt.classList.add("persona-w-full"),y.appendChild(lt),ee.push({messageId:H.id,fingerprint:Nt,bubble:ft});return}}}if(!it)if(H.variant==="reasoning"&&H.reasoning){if(!fe)return;it=Ql(H,o)}else if(H.variant==="tool"&&H.toolCall){if(!ae)return;it=Jl(H,o)}else if(H.variant==="approval"&&H.approval){if(o.approval===!1)return;it=Qi(H,o)}else{let nt=(Sr=o.layout)==null?void 0:Sr.messages;nt!=null&&nt.renderUserMessage&&H.role==="user"?it=nt.renderUserMessage({message:H,config:o,streaming:!!H.streaming}):nt!=null&&nt.renderAssistantMessage&&H.role==="assistant"?it=nt.renderAssistantMessage({message:H,config:o,streaming:!!H.streaming}):it=Xl(H,h,nt,o.messageActions,te,{loadingIndicatorRenderer:O,widgetConfig:o}),H.role!=="user"&&it&&cc(it,H,o,$)}let Ge=document.createElement("div");Ge.className="persona-flex",Ge.id=`wrapper-${H.id}`,Ge.setAttribute("data-wrapper-id",H.id),H.role==="user"&&Ge.classList.add("persona-justify-end"),(it==null?void 0:it.getAttribute("data-persona-component-directive"))==="true"&&Ge.classList.add("persona-w-full"),Ge.appendChild(it),km(xe,H.id,Nt,Ge),y.appendChild(Ge)}),Be.composerOverlay&&Be.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Fe=>{let oe=Fe.getAttribute("data-persona-ask-sheet-for");oe&&!F.has(oe)&&ms(Be.composerOverlay,oe)}),(We=(pt=o.features)==null?void 0:pt.toolCallDisplay)!=null&&We.grouped){let H=[],Fe=[];g.forEach(oe=>{if(oe.variant==="tool"&&oe.toolCall&&ae){Fe.push(oe);return}Fe.length>1&&H.push(Fe),Fe=[]}),Fe.length>1&&H.push(Fe),H.forEach((oe,tt)=>{var Ct,Qn;let _t=oe.map(rn=>Array.from(y.children).find(mo=>mo instanceof HTMLElement&&mo.getAttribute("data-wrapper-id")===rn.id)).filter(rn=>!!rn);if(_t.length<2)return;let Nt=document.createElement("div");Nt.className="persona-flex",Nt.id=`wrapper-tool-group-${tt}-${oe[0].id}`,Nt.setAttribute("data-wrapper-id",`tool-group-${tt}-${oe[0].id}`);let qt=document.createElement("div");qt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",qt.setAttribute("data-persona-tool-group","true");let it=document.createElement("div");it.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let cn=`Called ${oe.length} tools`,Xn=(Qn=(Ct=o.toolCall)==null?void 0:Ct.renderGroupedSummary)==null?void 0:Qn.call(Ct,{messages:oe,toolCalls:oe.map(rn=>rn.toolCall).filter(rn=>!!rn),defaultSummary:cn,config:o});N(it,Xn)||(it.textContent=cn);let Ge=document.createElement("div");Ge.className="persona-tool-group-stack persona-flex persona-flex-col",qt.append(it,Ge),Nt.appendChild(qt),_t[0].before(Nt),_t.forEach((rn,mo)=>{let Jn=document.createElement("div");Jn.className="persona-tool-group-item persona-relative",Jn.setAttribute("data-persona-tool-group-item","true"),mo<_t.length-1&&Jn.setAttribute("data-persona-tool-group-connector","true"),Jn.appendChild(rn),Ge.appendChild(Jn)})})}Em(xe,q);let rt=g.some(H=>H.role==="assistant"&&H.streaming),Ke=g[g.length-1],gt=(Ke==null?void 0:Ke.role)==="assistant"&&!Ke.streaming&&Ke.variant!=="approval";if(io&&g.some(H=>H.role==="user")&&!rt&&!gt){let H={config:o,streaming:!0,location:"standalone",defaultRenderer:xa},Fe=r.find(tt=>tt.renderLoadingIndicator),oe=null;if(Fe!=null&&Fe.renderLoadingIndicator&&(oe=Fe.renderLoadingIndicator(H)),oe===null&&((Pe=o.loadingIndicator)!=null&&Pe.render)&&(oe=o.loadingIndicator.render(H)),oe===null&&(oe=xa()),oe){let tt=document.createElement("div"),_t=((je=o.loadingIndicator)==null?void 0:je.showBubble)!==!1;tt.className=_t?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),tt.setAttribute("data-typing-indicator","true"),tt.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",tt.appendChild(oe);let Nt=document.createElement("div");Nt.className="persona-flex",Nt.id="wrapper-typing-indicator",Nt.setAttribute("data-wrapper-id","typing-indicator"),Nt.appendChild(tt),y.appendChild(Nt)}}if(!io&&g.length>0){let H=g[g.length-1],Fe={config:o,lastMessage:H,messageCount:g.length},oe=r.find(_t=>_t.renderIdleIndicator),tt=null;if(oe!=null&&oe.renderIdleIndicator&&(tt=oe.renderIdleIndicator(Fe)),tt===null&&((Je=o.loadingIndicator)!=null&&Je.renderIdle)&&(tt=o.loadingIndicator.renderIdle(Fe)),tt){let _t=document.createElement("div"),Nt=((xt=o.loadingIndicator)==null?void 0:xt.showBubble)!==!1;_t.className=Nt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),_t.setAttribute("data-idle-indicator","true"),_t.appendChild(tt);let qt=document.createElement("div");qt.className="persona-flex",qt.id="wrapper-idle-indicator",qt.setAttribute("data-wrapper-id","idle-indicator"),qt.appendChild(_t),y.appendChild(qt)}}if(Mi(c,y),ge.length>0)for(let{messageId:H,fingerprint:Fe,bubble:oe}of ge){let tt=c.querySelector(`#wrapper-${H}`);tt&&oe!==null&&(tt.replaceChildren(oe),tt.setAttribute("data-bubble-fp",Fe),Gn.set(H,Fe))}if(Gn.size>0)for(let H of Gn.keys())q.has(H)||Gn.delete(H);if(ee.length>0)for(let{messageId:H,fingerprint:Fe,bubble:oe}of ee){let tt=c.querySelector(`#wrapper-${H}`);tt&&oe!==null&&(tt.replaceChildren(oe),tt.setAttribute("data-bubble-fp",Fe),lo.set(H,Fe))}if(lo.size>0)for(let H of lo.keys())q.has(H)||lo.delete(H);if($e.length>0)for(let{messageId:H,fingerprint:Fe,bubble:oe}of $e){let tt=c.querySelector(`#wrapper-${H}`);tt&&oe!==null&&(tt.replaceChildren(oe),tt.setAttribute("data-bubble-fp",Fe),xo.set(H,Fe))}if(xo.size>0)for(let H of xo.keys())q.has(H)||xo.delete(H)},er=null,Ua=()=>{var h;if(er)return;let c=y=>{let L=y.composedPath();L.includes(Te)||Ue&&L.includes(Ue)||Ot(!1,"user")};er=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},Ts=()=>{var g;if(!er)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("pointerdown",er,!0),er=null};vt.push(()=>Ts());let tr=null,za=()=>{var h;if(tr)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Ot(!1,"user"))};tr=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},ks=()=>{var g;if(!tr)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("keydown",tr,!0),tr=null};vt.push(()=>ks());let nr=!1,Es=new Set,qa=()=>{var g,h,y,L;let c=(y=(h=(g=o.launcher)==null?void 0:g.composerBar)==null?void 0:h.peek)==null?void 0:y.streamAnimation;return c||((L=o.features)==null?void 0:L.streamAnimation)},$o=()=>{var gt,pt,We,Pe;if(!E())return;let c=Be.peekBanner,g=Be.peekTextNode;if(!c||!g)return;if(T){c.classList.remove("persona-pill-peek--visible");return}let h=(gt=$==null?void 0:$.getMessages())!=null?gt:[],y;for(let je=h.length-1;je>=0;je--){let Je=h[je];if(Je.role==="assistant"&&Je.content){y=Je;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let L=y.content,O=!!y.streaming,N=qa(),q=Wi(N),F=q.type!=="none"?ma(q.type,N==null?void 0:N.plugins):null,ke=((pt=F==null?void 0:F.isAnimating)==null?void 0:pt.call(F,y))===!0,ge=F!==null&&(O||ke);ge&&F&&!Es.has(F.name)&&(zl(F,e),Es.add(F.name));let ee=ge&&(F!=null&&F.containerClass)?F.containerClass:null,Ae=(We=g.dataset.personaPeekStreamClass)!=null?We:null;Ae&&Ae!==ee&&(g.classList.remove(Ae),delete g.dataset.personaPeekStreamClass),ee&&Ae!==ee&&(g.classList.add(ee),g.dataset.personaPeekStreamClass=ee),ge?(g.style.setProperty("--persona-stream-step",`${q.speed}ms`),g.style.setProperty("--persona-stream-duration",`${q.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ie=ge?Bi(L,q.buffer,F,y,O):L;if(ge&&q.placeholder==="skeleton"&&O&&(!Ie||!Ie.trim())){let je=document.createElement("div"),Je=fa();Je.classList.add("persona-pill-peek__skeleton"),je.appendChild(Je),Mi(g,je)}else{let je=Math.max(0,Ie.length-100),Je=Ie.length>100?Ie.slice(-100):Ie,xt=ta(Je);if(!ge||!F){let H=Ie.length>100?`\u2026${Je}`:Je;g.textContent!==H&&(g.textContent=H)}else{let H=xt;(F.wrap==="char"||F.wrap==="word")&&(H=ga(xt,F.wrap,`peek-${y.id}`,{skipTags:F.skipTags,startIndex:je}));let Fe=document.createElement("div");if(Fe.innerHTML=H,F.useCaret&&Je.length>0){let oe=Hi(),tt=Fe.querySelectorAll(".persona-stream-char, .persona-stream-word"),_t=tt[tt.length-1];_t!=null&&_t.parentNode?_t.parentNode.insertBefore(oe,_t.nextSibling):Fe.appendChild(oe)}Mi(g,Fe),(Pe=F.onAfterRender)==null||Pe.call(F,{container:g,bubble:c,messageId:y.id,message:y,speed:q.speed,duration:q.duration})}}let Ke=io||nr;c.classList.toggle("persona-pill-peek--visible",Ke)};if(E()){let c=Be.peekBanner;if(c){let y=L=>{L.preventDefault(),L.stopPropagation(),Ot(!0,"user")};c.addEventListener("pointerdown",y),vt.push(()=>{c.removeEventListener("pointerdown",y)})}let g=()=>{nr||(nr=!0,$o())},h=()=>{nr&&(nr=!1,$o())};ue.addEventListener("pointerenter",g),ue.addEventListener("pointerleave",h),vt.push(()=>{ue.removeEventListener("pointerenter",g),ue.removeEventListener("pointerleave",h)}),Ue&&(Ue.addEventListener("pointerenter",g),Ue.addEventListener("pointerleave",h),vt.push(()=>{Ue.removeEventListener("pointerenter",g),Ue.removeEventListener("pointerleave",h)}))}let ja=c=>{var Ae,Ie,$e,rt,Ke,gt,pt,We;let g=(Ie=(Ae=o.launcher)==null?void 0:Ae.composerBar)!=null?Ie:{},h=($e=g.expandedSize)!=null?$e:"anchored",y=(rt=g.bottomOffset)!=null?rt:"16px",L=g.collapsedMaxWidth,O=(Ke=g.expandedMaxWidth)!=null?Ke:"880px",N=(gt=g.expandedTopOffset)!=null?gt:"5vh",q=(pt=g.modalMaxWidth)!=null?pt:"880px",F=(We=g.modalMaxHeight)!=null?We:"min(90vh, 800px)",ke="calc(100vw - 32px)",ge="var(--persona-pill-area-height, 80px)",ee=Te.style;if(ee.left="",ee.right="",ee.top="",ee.bottom="",ee.transform="",ee.width="",ee.maxWidth="",ee.height="",ee.maxHeight="",Ue){let Pe=Ue.style;Pe.bottom=y,Pe.width=L!=null?L:""}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=q,ee.maxWidth=ke,ee.maxHeight=F,ee.height=F;return}ee.left="50%",ee.transform="translateX(-50%)",ee.bottom=`calc(${y} + ${ge})`,ee.top=N,ee.width=O,ee.maxWidth=ke}},or=()=>{var F,ke,ge,ee,Ae,Ie,$e,rt;if(!S())return;if(E()){let gt=(ge=((ke=(F=o.launcher)==null?void 0:F.composerBar)!=null?ke:{}).expandedSize)!=null?ge:"anchored",pt=T?"expanded":"collapsed";Te.dataset.state=pt,Te.dataset.expandedSize=gt,Ue&&(Ue.dataset.state=pt,Ue.dataset.expandedSize=gt),Te.style.removeProperty("display"),Te.classList.remove("persona-pointer-events-none","persona-opacity-0"),ue.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ja(T),me.style.display=T?"flex":"none",yo(),T?(Ua(),za()):(Ts(),ks()),$o();return}let c=bn(o),g=(ee=e.ownerDocument.defaultView)!=null?ee:window,h=(Ie=(Ae=o.launcher)==null?void 0:Ae.mobileBreakpoint)!=null?Ie:640,y=(rt=($e=o.launcher)==null?void 0:$e.mobileFullscreen)!=null?rt:!0,L=g.innerWidth<=h,O=y&&L&&I,N=Bo(o).reveal;T?(Te.style.removeProperty("display"),Te.style.display=c?"flex":"",Te.classList.remove("persona-pointer-events-none","persona-opacity-0"),ue.classList.remove("persona-scale-95","persona-opacity-0"),ue.classList.add("persona-scale-100","persona-opacity-100"),Qe?Qe.element.style.display="none":et&&(et.style.display="none")):(c?c&&(N==="overlay"||N==="push")&&!O?(Te.style.removeProperty("display"),Te.style.display="flex",Te.classList.remove("persona-pointer-events-none","persona-opacity-0"),ue.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Te.style.setProperty("display","none","important"),Te.classList.remove("persona-pointer-events-none","persona-opacity-0"),ue.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Te.style.display="",Te.classList.add("persona-pointer-events-none","persona-opacity-0"),ue.classList.remove("persona-scale-100","persona-opacity-100"),ue.classList.add("persona-scale-95","persona-opacity-0")),Qe?Qe.element.style.display=c?"none":"":et&&(et.style.display=c?"none":""))},Ot=(c,g="user")=>{var O,N;if(!S()||T===c)return;let h=T;T=c,or();let y=(()=>{var $e,rt,Ke,gt,pt,We,Pe,je,Je,xt;let q=(rt=($e=o.launcher)==null?void 0:$e.sidebarMode)!=null?rt:!1,F=(Ke=e.ownerDocument.defaultView)!=null?Ke:window,ke=(pt=(gt=o.launcher)==null?void 0:gt.mobileFullscreen)!=null?pt:!0,ge=(Pe=(We=o.launcher)==null?void 0:We.mobileBreakpoint)!=null?Pe:640,ee=F.innerWidth<=ge,Ae=bn(o)&&ke&&ee,Ie=E()&&((xt=(Je=(je=o.launcher)==null?void 0:je.composerBar)==null?void 0:Je.expandedSize)!=null?xt:"fullscreen")==="fullscreen";return q||ke&&ee&&I||Ae||Ie})();if(T&&y){if(!Xt){let q=e.getRootNode(),F=q instanceof ShadowRoot?q.host:e.closest(".persona-host");F&&(Xt=ql(F,(N=(O=o.launcher)==null?void 0:O.zIndex)!=null?N:Cn))}Qt||(Qt=jl(e.ownerDocument))}else T||(Xt==null||Xt(),Xt=null,Qt==null||Qt(),Qt=null);T&&(Jt(),Zo(!0));let L={open:T,source:g,timestamp:Date.now()};T&&!h?s.emit("widget:opened",L):!T&&h&&s.emit("widget:closed",L),s.emit("widget:state",{open:T,launcherEnabled:I,voiceActive:yt.active,streaming:$.isStreaming()})},qr=c=>{jt(c?"stop":"send"),j&&(j.disabled=c),vo.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)})},jr=()=>{yt.active||be&&be.focus()};s.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>jr(),200)});let Ms=()=>{var h,y,L,O,N,q,F,ke,ge,ee,Ae;Fn.textContent=(y=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",to.textContent=(O=(L=o.copy)==null?void 0:L.welcomeSubtitle)!=null?O:"Ask anything about your account or products.",be.placeholder=(q=(N=o.copy)==null?void 0:N.inputPlaceholder)!=null?q:"How can I help...";let c=Q.querySelector("[data-persona-intro-card]");if(c){let Ie=((F=o.copy)==null?void 0:F.showWelcomeCard)!==!1;c.style.display=Ie?"":"none",Ie?(Q.classList.remove("persona-gap-3"),Q.classList.add("persona-gap-6")):(Q.classList.remove("persona-gap-6"),Q.classList.add("persona-gap-3"))}!((ge=(ke=o.sendButton)==null?void 0:ke.useIcon)!=null&&ge)&&!($!=null&&$.isStreaming())&&(de.textContent=(Ae=(ee=o.copy)==null?void 0:ee.sendButtonLabel)!=null?Ae:"Send"),be.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',be.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 Ro=null,Ka=()=>{Ro==null&&(Ro=setInterval(()=>{let c=_e.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Ro),Ro=null;return}let g=Date.now();c.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=hi(g-y))})},100))};if($=new ki(o,{onMessagesChanged(c){yr(_e,c,he),Ka(),$&&(c.some(L=>L.role==="user")?vo.render([],$,be,c):vo.render(o.suggestionChips,$,be,c,o.suggestionChipsConfig)),Zo(!io),$a(c);let g=[...c].reverse().find(y=>y.role==="user"),h=yt.lastUserMessageId;g&&g.id!==h&&(yt.lastUserMessageId=g.id,s.emit("user:message",g)),yt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),zr(c),$o()},onStatusChanged(c){var y;let g=(y=o.statusIndicator)!=null?y:{};st(gn,(L=>{var O,N,q,F;return L==="idle"?(O=g.idleText)!=null?O:wn.idle:L==="connecting"?(N=g.connectingText)!=null?N:wn.connecting:L==="connected"?(q=g.connectedText)!=null?q:wn.connected:L==="error"?(F=g.errorText)!=null?F:wn.error:wn[L]})(c),g,c)},onStreamingChanged(c){io=c,qr(c),$&&yr(_e,$.getMessages(),he),c||Zo(!0),$o()},onVoiceStatusChanged(c){var g,h;if(((h=(g=o.voiceRecognition)==null?void 0:g.provider)==null?void 0:h.type)==="runtype")switch(c){case"listening":break;case"processing":X(),Z();break;case"speaking":X(),le();break;default:c==="idle"&&$.isBargeInActive()?(X(),P(),j==null||j.setAttribute("aria-label","End voice session")):(yt.active=!1,X(),co("system"),Bn());break}},onArtifactsState(c){$n=c,qn(),zr()}}),Lt.current=$,((Ad=(Sd=o.voiceRecognition)==null?void 0:Sd.provider)==null?void 0:Ad.type)==="runtype")try{$.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}o.clientToken&&$.initClientSession().catch(c=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(G||o.onSSEEvent)&&$.setSSEEventCallback((c,g)=>{var h;(h=o.onSSEEvent)==null||h.call(o,c,g),ve==null||ve.processEvent(c,g),G==null||G.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=hc(c.metadata),M.syncFromMetadata()),(g=c.messages)!=null&&g.length&&$.hydrateMessages(c.messages),(h=c.artifacts)!=null&&h.length&&$.hydrateArtifacts(c.artifacts,(y=c.selectedArtifactId)!=null?y:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let Ls=()=>{var g,h,y;!E()||T||!((y=(h=(g=o.launcher)==null?void 0:g.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||Ot(!0,"auto")},Is=c=>{var L;if(c.preventDefault(),$.isStreaming()){$.cancel(),ve==null||ve.reset(),ce==null||ce.update();return}let g=be.value.trim(),h=(L=ot==null?void 0:ot.hasAttachments())!=null?L:!1;if(!g&&!h)return;Ls();let y;h&&(y=[],y.push(...ot.getContentParts()),g&&y.push(_l(g))),be.value="",be.style.height="auto",vr(),$.sendMessage(g,{contentParts:y}),h&&ot.clearAttachments()},Ga=()=>{var c;return((c=o.features)==null?void 0:c.composerHistory)!==!1},Kr={...Li},Gr=!1,vr=()=>{Kr={...Li}},Ya=()=>$.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),Xa=c=>{if(!be)return;Gr=!0,be.value=c,be.dispatchEvent(new Event("input",{bubbles:!0})),Gr=!1;let g=be.value.length;be.setSelectionRange(g,g)},Rs=()=>{Gr||vr()},Ps=c=>{if(be){if(Ga()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=be.selectionStart===0&&be.selectionEnd===0,h=Cm({direction:c.key==="ArrowUp"?"up":"down",history:Ya(),currentValue:be.value,atStart:g,state:Kr});if(Kr=h.state,h.handled){c.preventDefault(),h.value!==void 0&&Xa(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if($.isStreaming()){c.preventDefault();return}vr(),c.preventDefault(),de.click()}}},Ws=c=>{c.key!=="Escape"||c.isComposing||$.isStreaming()&&c.composedPath().includes(me)&&($.cancel(),ve==null||ve.reset(),ce==null||ce.update(),vr(),c.preventDefault(),c.stopImmediatePropagation())},Bs=async c=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!ot)return;let g=Ty(c.clipboardData);g.length!==0&&(c.preventDefault(),await ot.handleFiles(g))},Mn=null,Yn=!1,Uo=null,ct=null,Hs=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,xr=(c="user")=>{var O,N,q,F,ke,ge,ee;if(Yn||$.isStreaming())return;let g=Hs();if(!g)return;Mn=new g;let y=(N=((O=o.voiceRecognition)!=null?O:{}).pauseDuration)!=null?N:2e3;Mn.continuous=!0,Mn.interimResults=!0,Mn.lang="en-US";let L=be.value;Mn.onresult=Ae=>{let Ie="",$e="";for(let Ke=0;Ke<Ae.results.length;Ke++){let gt=Ae.results[Ke],pt=gt[0].transcript;gt.isFinal?Ie+=pt+" ":$e=pt}let rt=L+Ie+$e;be.value=rt,Uo&&clearTimeout(Uo),(Ie||$e)&&(Uo=window.setTimeout(()=>{let Ke=be.value.trim();Ke&&Mn&&Yn&&(Ao(),be.value="",be.style.height="auto",$.sendMessage(Ke,{viaVoice:!0}))},y))},Mn.onerror=Ae=>{Ae.error!=="no-speech"&&Ao()},Mn.onend=()=>{if(Yn){let Ae=be.value.trim();Ae&&Ae!==L.trim()&&(be.value="",be.style.height="auto",$.sendMessage(Ae,{viaVoice:!0})),Ao()}};try{if(Mn.start(),Yn=!0,yt.active=!0,c!=="system"&&(yt.manuallyDeactivated=!1),co(c),Bn(),j){let Ae=(q=o.voiceRecognition)!=null?q:{};ct={backgroundColor:j.style.backgroundColor,color:j.style.color,borderColor:j.style.borderColor,iconName:(F=Ae.iconName)!=null?F:"mic",iconSize:parseFloat((ee=(ge=Ae.iconSize)!=null?ge:(ke=o.sendButton)==null?void 0:ke.size)!=null?ee:"40")||24};let Ie=Ae.recordingBackgroundColor,$e=Ae.recordingIconColor,rt=Ae.recordingBorderColor;if(j.classList.add("persona-voice-recording"),j.style.backgroundColor=Ie!=null?Ie:"var(--persona-voice-recording-bg, #ef4444)",j.style.color=$e!=null?$e:"var(--persona-voice-recording-indicator, #ffffff)",$e){let Ke=j.querySelector("svg");Ke&&Ke.setAttribute("stroke",$e)}rt&&(j.style.borderColor=rt),j.setAttribute("aria-label","Stop voice recognition")}}catch{Ao("system")}},Ao=(c="user")=>{if(Yn){if(Yn=!1,Uo&&(clearTimeout(Uo),Uo=null),Mn){try{Mn.stop()}catch{}Mn=null}if(yt.active=!1,co(c),Bn(),j){if(j.classList.remove("persona-voice-recording"),ct){j.style.backgroundColor=ct.backgroundColor,j.style.color=ct.color,j.style.borderColor=ct.borderColor;let g=j.querySelector("svg");g&&g.setAttribute("stroke",ct.color||"currentColor"),ct=null}j.setAttribute("aria-label","Start voice recognition")}}},Yr=(c,g)=>{var gt,pt,We,Pe,je,Je,xt,H;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((gt=c==null?void 0:c.provider)==null?void 0:gt.type)==="runtype";if(!(h||y))return null;let O=b("div","persona-send-button-wrapper"),N=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");N.type="button",N.setAttribute("aria-label","Start voice recognition");let q=(pt=c==null?void 0:c.iconName)!=null?pt:"mic",F=(We=g==null?void 0:g.size)!=null?We:"40px",ke=(Pe=c==null?void 0:c.iconSize)!=null?Pe:F,ge=parseFloat(ke)||24,ee=(je=c==null?void 0:c.backgroundColor)!=null?je:g==null?void 0:g.backgroundColor,Ae=(Je=c==null?void 0:c.iconColor)!=null?Je:g==null?void 0:g.textColor;N.style.width=ke,N.style.height=ke,N.style.minWidth=ke,N.style.minHeight=ke,N.style.fontSize="18px",N.style.lineHeight="1",Ae?N.style.color=Ae:N.style.color="var(--persona-text, #111827)";let $e=Me(q,ge,Ae||"currentColor",1.5);$e?N.appendChild($e):N.textContent="\u{1F3A4}",ee?N.style.backgroundColor=ee:N.style.backgroundColor="",c!=null&&c.borderWidth&&(N.style.borderWidth=c.borderWidth,N.style.borderStyle="solid"),c!=null&&c.borderColor&&(N.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(N.style.paddingLeft=c.paddingX,N.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(N.style.paddingTop=c.paddingY,N.style.paddingBottom=c.paddingY),O.appendChild(N);let rt=(xt=c==null?void 0:c.tooltipText)!=null?xt:"Start voice recognition";if(((H=c==null?void 0:c.showTooltip)!=null?H:!1)&&rt){let Fe=b("div","persona-send-button-tooltip");Fe.textContent=rt,O.appendChild(Fe)}return{micButton:N,micButtonWrapper:O}},Ye=()=>{var g,h,y,L,O;if(!j||ct)return;let c=(g=o.voiceRecognition)!=null?g:{};ct={backgroundColor:j.style.backgroundColor,color:j.style.color,borderColor:j.style.borderColor,iconName:(h=c.iconName)!=null?h:"mic",iconSize:parseFloat((O=(L=c.iconSize)!=null?L:(y=o.sendButton)==null?void 0:y.size)!=null?O:"40")||24}},k=(c,g)=>{var O,N,q,F,ke;if(!j)return;let h=j.querySelector("svg");h&&h.remove();let y=(ke=ct==null?void 0:ct.iconSize)!=null?ke:parseFloat((F=(q=(O=o.voiceRecognition)==null?void 0:O.iconSize)!=null?q:(N=o.sendButton)==null?void 0:N.size)!=null?F:"40")||24,L=Me(c,y,g,1.5);L&&j.appendChild(L)},z=()=>{j&&j.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},P=()=>{var L;if(!j)return;Ye();let c=(L=o.voiceRecognition)!=null?L:{},g=c.recordingBackgroundColor,h=c.recordingIconColor,y=c.recordingBorderColor;if(z(),j.classList.add("persona-voice-recording"),j.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",j.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let O=j.querySelector("svg");O&&O.setAttribute("stroke",h)}y&&(j.style.borderColor=y),j.setAttribute("aria-label","Stop voice recognition")},Z=()=>{var q,F,ke,ge,ee,Ae,Ie,$e;if(!j)return;Ye();let c=(q=o.voiceRecognition)!=null?q:{},g=$.getVoiceInterruptionMode(),h=(F=c.processingIconName)!=null?F:"loader",y=(ge=(ke=c.processingIconColor)!=null?ke:ct==null?void 0:ct.color)!=null?ge:"",L=(Ae=(ee=c.processingBackgroundColor)!=null?ee:ct==null?void 0:ct.backgroundColor)!=null?Ae:"",O=($e=(Ie=c.processingBorderColor)!=null?Ie:ct==null?void 0:ct.borderColor)!=null?$e:"";z(),j.classList.add("persona-voice-processing"),j.style.backgroundColor=L,j.style.borderColor=O;let N=y||"currentColor";j.style.color=N,k(h,N),j.setAttribute("aria-label","Processing voice input"),g==="none"&&(j.style.cursor="default")},le=()=>{var ke,ge,ee,Ae,Ie,$e,rt,Ke,gt,pt,We,Pe;if(!j)return;Ye();let c=(ke=o.voiceRecognition)!=null?ke:{},g=$.getVoiceInterruptionMode(),h=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",y=(ge=c.speakingIconName)!=null?ge:h,L=($e=c.speakingIconColor)!=null?$e:g==="barge-in"?(Ae=(ee=c.recordingIconColor)!=null?ee:ct==null?void 0:ct.color)!=null?Ae:"":(Ie=ct==null?void 0:ct.color)!=null?Ie:"",O=(gt=c.speakingBackgroundColor)!=null?gt:g==="barge-in"?(rt=c.recordingBackgroundColor)!=null?rt:"var(--persona-voice-recording-bg, #ef4444)":(Ke=ct==null?void 0:ct.backgroundColor)!=null?Ke:"",N=(Pe=c.speakingBorderColor)!=null?Pe:g==="barge-in"?(pt=c.recordingBorderColor)!=null?pt:"":(We=ct==null?void 0:ct.borderColor)!=null?We:"";z(),j.classList.add("persona-voice-speaking"),j.style.backgroundColor=O,j.style.borderColor=N;let q=L||"currentColor";j.style.color=q,k(y,q);let F=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";j.setAttribute("aria-label",F),g==="none"&&(j.style.cursor="default"),g==="barge-in"&&j.classList.add("persona-voice-recording")},X=()=>{var c,g,h;j&&(z(),ct&&(j.style.backgroundColor=(c=ct.backgroundColor)!=null?c:"",j.style.color=(g=ct.color)!=null?g:"",j.style.borderColor=(h=ct.borderColor)!=null?h:"",k(ct.iconName,ct.color||"currentColor"),ct=null),j.style.cursor="",j.setAttribute("aria-label","Start voice recognition"))},Re=()=>{var c,g;if(((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let h=$.getVoiceStatus(),y=$.getVoiceInterruptionMode();if(y==="none"&&(h==="processing"||h==="speaking"))return;if(y==="cancel"&&(h==="processing"||h==="speaking")){$.stopVoicePlayback();return}if($.isBargeInActive()){$.stopVoicePlayback(),$.deactivateBargeIn().then(()=>{yt.active=!1,yt.manuallyDeactivated=!0,Bn(),co("user"),X()});return}$.toggleVoice().then(()=>{yt.active=$.isVoiceActive(),yt.manuallyDeactivated=!$.isVoiceActive(),Bn(),co("user"),$.isVoiceActive()?P():X()});return}if(Yn){let h=be.value.trim();yt.manuallyDeactivated=!0,Bn(),Ao("user"),h&&(be.value="",be.style.height="auto",$.sendMessage(h))}else yt.manuallyDeactivated=!1,Bn(),xr("user")};On=Re,j&&(j.addEventListener("click",Re),vt.push(()=>{var c,g;((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?($.isVoiceActive()&&$.toggleVoice(),X()):Ao("system"),j&&j.removeEventListener("click",Re)}));let Ne=s.on("assistant:complete",()=>{Cs&&(yt.active||yt.manuallyDeactivated||Cs==="assistant"&&!yt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!yt.active&&!yt.manuallyDeactivated&&(((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?$.toggleVoice().then(()=>{yt.active=$.isVoiceActive(),co("auto"),$.isVoiceActive()&&P()}):xr("auto"))},600))});vt.push(Ne);let dt=s.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});vt.push(dt);let Xe=()=>{Ot(!T,"user")},Qe=null,et=null;if(I&&!E()){let c=r.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:o,defaultRenderer:()=>ya(o,Xe).element,onToggle:Xe});g&&(et=g)}et||(Qe=ya(o,Xe))}Qe?e.appendChild(Qe.element):et&&e.appendChild(et),or(),vo.render(o.suggestionChips,$,be,void 0,o.suggestionChipsConfig),Ms(),qr($.isStreaming()),Zo(!0),Oa(),W&&(!I||E()?setTimeout(()=>jr(),0):T&&setTimeout(()=>jr(),200));let Jt=()=>{var F,ke,ge,ee,Ae,Ie,$e,rt,Ke,gt,pt,We,Pe,je,Je,xt,H,Fe,oe,tt,_t,Nt;if(E()){St(),or();return}let c=bn(o),g=(ke=(F=o.launcher)==null?void 0:F.sidebarMode)!=null?ke:!1,h=c||g||((ee=(ge=o.launcher)==null?void 0:ge.fullHeight)!=null?ee:!1),y=(Ae=e.ownerDocument.defaultView)!=null?Ae:window,L=($e=(Ie=o.launcher)==null?void 0:Ie.mobileFullscreen)!=null?$e:!0,O=(Ke=(rt=o.launcher)==null?void 0:rt.mobileBreakpoint)!=null?Ke:640,N=y.innerWidth<=O,q=L&&N&&I;try{if(q){yo(),es(e,o);return}if(w&&(w=!1,yo(),es(e,o)),!I&&!c){ue.style.height="",ue.style.width="";return}if(!g&&!c){let qt=(pt=(gt=o==null?void 0:o.launcher)==null?void 0:gt.width)!=null?pt:o==null?void 0:o.launcherWidth,it=qt!=null?qt:fo;ue.style.width=it,ue.style.maxWidth=it}if(Io(),!h){let qt=y.innerHeight,it=64,cn=(Pe=(We=o.launcher)==null?void 0:We.heightOffset)!=null?Pe:0,Xn=Math.max(200,qt-it),Ge=Math.min(640,Xn),Ct=Math.max(200,Ge-cn);ue.style.height=`${Ct}px`}}finally{if(St(),or(),T&&I){let it=((je=e.ownerDocument.defaultView)!=null?je:window).innerWidth<=((xt=(Je=o.launcher)==null?void 0:Je.mobileBreakpoint)!=null?xt:640),cn=(Fe=(H=o.launcher)==null?void 0:H.sidebarMode)!=null?Fe:!1,Xn=(tt=(oe=o.launcher)==null?void 0:oe.mobileFullscreen)!=null?tt:!0,Ge=bn(o)&&Xn&&it,Ct=cn||Xn&&it&&I||Ge;if(Ct&&!Qt){let Qn=e.getRootNode(),rn=Qn instanceof ShadowRoot?Qn.host:e.closest(".persona-host");rn&&!Xt&&(Xt=ql(rn,(Nt=(_t=o.launcher)==null?void 0:_t.zIndex)!=null?Nt:Cn)),Qt=jl(e.ownerDocument)}else Ct||(Xt==null||Xt(),Xt=null,Qt==null||Qt(),Qt=null)}}};Jt();let It=(Td=e.ownerDocument.defaultView)!=null?Td:window;if(It.addEventListener("resize",Jt),vt.push(()=>It.removeEventListener("resize",Jt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{St()});c.observe(Ve),vt.push(()=>c.disconnect())}Co=Q.scrollTop;let Dt=Q.scrollHeight,ln=()=>{let c=Q.scrollTop,g=Q.scrollHeight,h=g<Dt;Dt=g;let{action:y,nextLastScrollTop:L}=Ri({following:wo.isFollowing(),currentScrollTop:c,lastScrollTop:Co,nearBottom:pa(Q,ws),userScrollThreshold:Da,isAutoScrolling:No||hr||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Co=L,y==="resume"){Jo();return}y==="pause"&&As()};Q.addEventListener("scroll",ln,{passive:!0}),vt.push(()=>Q.removeEventListener("scroll",ln));let yn=c=>{let g=Pi({following:wo.isFollowing(),deltaY:c.deltaY,nearBottom:pa(Q,ws),resumeWhenNearBottom:!0});g==="pause"?As():g==="resume"&&Jo()};Q.addEventListener("wheel",yn,{passive:!0}),vt.push(()=>Q.removeEventListener("wheel",yn)),Wt.addEventListener("click",()=>{Q.scrollTop=Q.scrollHeight,Co=Q.scrollTop,Jo(),Zo(!0)}),vt.push(()=>Wt.remove()),vt.push(()=>{Ss()});let hn=()=>{qe&&(Kn&&(qe.removeEventListener("click",Kn),Kn=null),S()?(qe.style.display="",Kn=()=>{Ot(!1,"user")},qe.addEventListener("click",Kn)):qe.style.display="none")};hn(),(()=>{let{clearChatButton:c}=Be;c&&c.addEventListener("click",()=>{$.clearMessages(),xe.clear(),Jo(),ms(Be.composerOverlay);try{localStorage.removeItem(fs),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${fs}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==fs)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(),G==null||G.clear(),ve==null||ve.reset(),ce==null||ce.update()})})(),Ut&&Ut.addEventListener("submit",Is),be==null||be.addEventListener("keydown",Ps),be==null||be.addEventListener("input",Rs),be==null||be.addEventListener("paste",Bs);let po=(kd=e.ownerDocument)!=null?kd:document;po.addEventListener("keydown",Ws,!0);let Pc="persona-attachment-drop-active",Ds=0,hl=()=>{Ds=0,me.classList.remove(Pc)},Xr=()=>{var c;return((c=o.attachments)==null?void 0:c.enabled)===!0&&ot!==null},Wc=c=>{!tl(c.dataTransfer)||!Xr()||(Ds++,Ds===1&&me.classList.add(Pc))},Bc=c=>{!tl(c.dataTransfer)||!Xr()||(Ds--,Ds<=0&&hl())},Hc=c=>{!tl(c.dataTransfer)||!Xr()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Dc=c=>{var h;if(!tl(c.dataTransfer)||!Xr())return;c.preventDefault(),c.stopPropagation(),hl();let g=Array.from((h=c.dataTransfer.files)!=null?h:[]);g.length!==0&&ot.handleFiles(g)},rr=!0;me.addEventListener("dragenter",Wc,rr),me.addEventListener("dragleave",Bc,rr),e.addEventListener("dragover",Hc,rr),e.addEventListener("drop",Dc,rr);let Qa=e.ownerDocument,Fc=c=>{Xr()&&c.preventDefault()},Oc=c=>{Xr()&&c.preventDefault()};Qa.addEventListener("dragover",Fc),Qa.addEventListener("drop",Oc),vt.push(()=>{Ut&&Ut.removeEventListener("submit",Is),be==null||be.removeEventListener("keydown",Ps),be==null||be.removeEventListener("input",Rs),be==null||be.removeEventListener("paste",Bs),po.removeEventListener("keydown",Ws,!0)}),vt.push(()=>{me.removeEventListener("dragenter",Wc,rr),me.removeEventListener("dragleave",Bc,rr),e.removeEventListener("dragover",Hc,rr),e.removeEventListener("drop",Dc,rr),Qa.removeEventListener("dragover",Fc),Qa.removeEventListener("drop",Oc),hl()}),vt.push(()=>{$.cancel()}),Qe?vt.push(()=>{Qe==null||Qe.destroy()}):et&&vt.push(()=>{et==null||et.remove()});let on={update(c){var en,Po,sn,Ln,go,Ar,Tr,Ja,Fs,Wd,Bd,Hd,Dd,Fd,Od,Nd,_d,Vd,$d,Ud,zd,qd,jd,Kd,Gd,Yd,Xd,Qd,Jd,Zd,ep,tp,np,op,rp,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,bp,yp,vp,xp,wp,Cp,Sp,Ap,Tp,kp,Ep,Mp,Lp,Ip,Rp,Pp,Wp,Bp,Hp,Dp,Fp,Op,Np,_p,Vp,$p,Up,zp,qp,jp,Kp,Gp,Yp,Xp,Qp,Jp,Zp,eu,tu,nu,ou,ru,su,au,iu,lu,cu,du,pu,uu,mu,gu,fu,hu,bu,yu,vu,xu,wu,Cu,Su,Au,Tu,ku,Eu,Mu;let g=o.toolCall,h=o.messageActions,y=(en=o.layout)==null?void 0:en.messages,L=o.colorScheme,O=o.loadingIndicator,N=o.iterationDisplay,q=(Po=o.features)==null?void 0:Po.showReasoning,F=(sn=o.features)==null?void 0:sn.showToolCalls,ke=(Ln=o.features)==null?void 0:Ln.toolCallDisplay,ge=(go=o.features)==null?void 0:go.reasoningDisplay;o={...o,...c},yo(),es(e,o),Zi(e,o),el(e,o),qn(),o.colorScheme!==L&&Qo();let ee=pc.getForInstance(o.plugins);r.length=0,r.push(...ee),I=(Tr=(Ar=o.launcher)==null?void 0:Ar.enabled)!=null?Tr:!0,R=(Fs=(Ja=o.launcher)==null?void 0:Ja.autoExpand)!=null?Fs:!1,fe=(Bd=(Wd=o.features)==null?void 0:Wd.showReasoning)!=null?Bd:!0,ae=(Dd=(Hd=o.features)==null?void 0:Hd.showToolCalls)!=null?Dd:!0,ye=(Od=(Fd=o.features)==null?void 0:Fd.scrollToBottom)!=null?Od:{},Gt(),Vo();let Ae=Ee;if(Ee=(_d=(Nd=o.features)==null?void 0:Nd.showEventStreamToggle)!=null?_d:!1,Ee&&!Ae){if(G||(K=new Sa(we),G=new Ca(pe,K),ve=ve!=null?ve:new Aa,K.open().then(()=>G==null?void 0:G.restore()).catch(()=>{}),$.setSSEEventCallback((J,Tt)=>{var $t;($t=o.onSSEEvent)==null||$t.call(o,J,Tt),ve==null||ve.processEvent(J,Tt),G.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:J,timestamp:Date.now(),payload:JSON.stringify(Tt)})})),!bt&&De){let J=($d=(Vd=o.features)==null?void 0:Vd.eventStream)==null?void 0:$d.classNames,Tt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(J!=null&&J.toggleButton?" "+J.toggleButton:"");bt=b("button",Tt),bt.style.width="28px",bt.style.height="28px",bt.style.color=Rn.actionIconColor,bt.type="button",bt.setAttribute("aria-label","Event Stream"),bt.title="Event Stream";let $t=Me("activity","18px","currentColor",1.5);$t&&bt.appendChild($t);let ut=Be.clearChatButtonWrapper,Bt=Be.closeButtonWrapper,pn=ut||Bt;pn&&pn.parentNode===De?De.insertBefore(bt,pn):De.appendChild(bt),bt.addEventListener("click",()=>{ne?Nn():Tn()})}}else!Ee&&Ae&&(Nn(),bt&&(bt.remove(),bt=null),G==null||G.clear(),K==null||K.destroy(),G=null,K=null,ve==null||ve.reset(),ve=null);if(((Ud=o.launcher)==null?void 0:Ud.enabled)===!1&&Qe&&(Qe.destroy(),Qe=null),((zd=o.launcher)==null?void 0:zd.enabled)===!1&&et&&(et.remove(),et=null),((qd=o.launcher)==null?void 0:qd.enabled)!==!1&&!Qe&&!et){let J=r.find(Tt=>Tt.renderLauncher);if(J!=null&&J.renderLauncher){let Tt=J.renderLauncher({config:o,defaultRenderer:()=>ya(o,Xe).element,onToggle:Xe});Tt&&(et=Tt,e.appendChild(et))}et||(Qe=ya(o,Xe),e.appendChild(Qe.element))}Qe&&Qe.update(o),Le&&((jd=o.launcher)==null?void 0:jd.title)!==void 0&&(Le.textContent=o.launcher.title),He&&((Kd=o.launcher)==null?void 0:Kd.subtitle)!==void 0&&(He.textContent=o.launcher.subtitle);let Ie=(Gd=o.layout)==null?void 0:Gd.header;if((Ie==null?void 0:Ie.layout)!==x&&De){let J=Ie?Ni(o,Ie,{showClose:S(),onClose:()=>Ot(!1,"user")}):Br({config:o,showClose:S(),onClose:()=>Ot(!1,"user")});De.replaceWith(J.header),De=J.header,V=J.iconHolder,Le=J.headerTitle,He=J.headerSubtitle,qe=J.closeButton,x=Ie==null?void 0:Ie.layout}else if(Ie&&(V&&(V.style.display=Ie.showIcon===!1?"none":""),Le&&(Le.style.display=Ie.showTitle===!1?"none":""),He&&(He.style.display=Ie.showSubtitle===!1?"none":""),qe&&(qe.style.display=Ie.showCloseButton===!1?"none":""),Be.clearChatButtonWrapper)){let J=Ie.showClearChat;if(J!==void 0){Be.clearChatButtonWrapper.style.display=J?"":"none";let{closeButtonWrapper:Tt}=Be;Tt&&!Tt.classList.contains("persona-absolute")&&(J?Tt.classList.remove("persona-ml-auto"):Tt.classList.add("persona-ml-auto"))}}let rt=((Yd=o.layout)==null?void 0:Yd.showHeader)!==!1;De&&(De.style.display=rt?"":"none");let Ke=((Xd=o.layout)==null?void 0:Xd.showFooter)!==!1;Ve&&(Ve.style.display=Ke?"":"none"),St(),Vo(),I!==B?I?Ot(R,"auto"):(T=!0,or()):R!==D&&Ot(R,"auto"),D=R,B=I,Jt(),hn();let We=JSON.stringify(c.toolCall)!==JSON.stringify(g),Pe=JSON.stringify(o.messageActions)!==JSON.stringify(h),je=JSON.stringify((Qd=o.layout)==null?void 0:Qd.messages)!==JSON.stringify(y),Je=((Jd=o.loadingIndicator)==null?void 0:Jd.render)!==(O==null?void 0:O.render)||((Zd=o.loadingIndicator)==null?void 0:Zd.renderIdle)!==(O==null?void 0:O.renderIdle)||((ep=o.loadingIndicator)==null?void 0:ep.showBubble)!==(O==null?void 0:O.showBubble),xt=o.iterationDisplay!==N,H=((np=(tp=o.features)==null?void 0:tp.showReasoning)!=null?np:!0)!==(q!=null?q:!0)||((rp=(op=o.features)==null?void 0:op.showToolCalls)!=null?rp:!0)!==(F!=null?F:!0)||JSON.stringify((sp=o.features)==null?void 0:sp.toolCallDisplay)!==JSON.stringify(ke)||JSON.stringify((ap=o.features)==null?void 0:ap.reasoningDisplay)!==JSON.stringify(ge);(We||Pe||je||Je||xt||H)&&$&&(xs++,yr(_e,$.getMessages(),he));let oe=(ip=o.launcher)!=null?ip:{},tt=(lp=oe.headerIconHidden)!=null?lp:!1,_t=(dp=(cp=o.layout)==null?void 0:cp.header)==null?void 0:dp.showIcon,Nt=tt||_t===!1,qt=oe.headerIconName,it=(pp=oe.headerIconSize)!=null?pp:"48px";if(V){let J=me.querySelector(".persona-border-b-persona-divider"),Tt=J==null?void 0:J.querySelector(".persona-flex-col");if(Nt)V.style.display="none",J&&Tt&&!J.contains(Tt)&&J.insertBefore(Tt,J.firstChild);else{if(V.style.display="",V.style.height=it,V.style.width=it,J&&Tt&&(J.contains(V)?V.nextSibling!==Tt&&(V.remove(),J.insertBefore(V,Tt)):J.insertBefore(V,Tt)),qt){let ut=parseFloat(it)||24,Bt=Me(qt,ut*.6,"#ffffff",2);Bt?V.replaceChildren(Bt):V.textContent=(up=oe.agentIconText)!=null?up:"\u{1F4AC}"}else if(oe.iconUrl){let ut=V.querySelector("img");if(ut)ut.src=oe.iconUrl,ut.style.height=it,ut.style.width=it;else{let Bt=document.createElement("img");Bt.src=oe.iconUrl,Bt.alt="",Bt.className="persona-rounded-xl persona-object-cover",Bt.style.height=it,Bt.style.width=it,V.replaceChildren(Bt)}}else{let ut=V.querySelector("svg"),Bt=V.querySelector("img");(ut||Bt)&&V.replaceChildren(),V.textContent=(mp=oe.agentIconText)!=null?mp:"\u{1F4AC}"}let $t=V.querySelector("img");$t&&($t.style.height=it,$t.style.width=it)}}let cn=(fp=(gp=o.layout)==null?void 0:gp.header)==null?void 0:fp.showTitle,Xn=(bp=(hp=o.layout)==null?void 0:hp.header)==null?void 0:bp.showSubtitle;if(Le&&(Le.style.display=cn===!1?"none":""),He&&(He.style.display=Xn===!1?"none":""),qe){((vp=(yp=o.layout)==null?void 0:yp.header)==null?void 0:vp.showCloseButton)===!1?qe.style.display="none":qe.style.display="";let Tt=(xp=oe.closeButtonSize)!=null?xp:"32px",$t=(wp=oe.closeButtonPlacement)!=null?wp:"inline";qe.style.height=Tt,qe.style.width=Tt;let{closeButtonWrapper:ut}=Be,Bt=$t==="top-right",pn=ut==null?void 0:ut.classList.contains("persona-absolute");if(ut&&Bt!==pn)if(ut.remove(),Bt)ut.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",me.style.position="relative",me.appendChild(ut);else{let ht=(Sp=(Cp=oe.clearChat)==null?void 0:Cp.placement)!=null?Sp:"inline",un=(Tp=(Ap=oe.clearChat)==null?void 0:Ap.enabled)!=null?Tp:!0;ut.className=un&&ht==="inline"?"":"persona-ml-auto";let Dn=me.querySelector(".persona-border-b-persona-divider");Dn&&Dn.appendChild(ut)}if(qe.style.color=oe.closeButtonColor||Rn.actionIconColor,oe.closeButtonBackgroundColor?(qe.style.backgroundColor=oe.closeButtonBackgroundColor,qe.classList.remove("hover:persona-bg-gray-100")):(qe.style.backgroundColor="",qe.classList.add("hover:persona-bg-gray-100")),oe.closeButtonBorderWidth||oe.closeButtonBorderColor){let ht=oe.closeButtonBorderWidth||"0px",un=oe.closeButtonBorderColor||"transparent";qe.style.border=`${ht} solid ${un}`,qe.classList.remove("persona-border-none")}else qe.style.border="",qe.classList.add("persona-border-none");oe.closeButtonBorderRadius?(qe.style.borderRadius=oe.closeButtonBorderRadius,qe.classList.remove("persona-rounded-full")):(qe.style.borderRadius="",qe.classList.add("persona-rounded-full")),oe.closeButtonPaddingX?(qe.style.paddingLeft=oe.closeButtonPaddingX,qe.style.paddingRight=oe.closeButtonPaddingX):(qe.style.paddingLeft="",qe.style.paddingRight=""),oe.closeButtonPaddingY?(qe.style.paddingTop=oe.closeButtonPaddingY,qe.style.paddingBottom=oe.closeButtonPaddingY):(qe.style.paddingTop="",qe.style.paddingBottom="");let xn=(kp=oe.closeButtonIconName)!=null?kp:"x",To=(Ep=oe.closeButtonIconText)!=null?Ep:"\xD7";qe.innerHTML="";let In=Me(xn,"28px","currentColor",1);In?qe.appendChild(In):qe.textContent=To;let Zt=(Mp=oe.closeButtonTooltipText)!=null?Mp:"Close chat",Zn=(Lp=oe.closeButtonShowTooltip)!=null?Lp:!0;if(qe.setAttribute("aria-label",Zt),ut&&(ut._cleanupTooltip&&(ut._cleanupTooltip(),delete ut._cleanupTooltip),Zn&&Zt)){let ht=null,un=()=>{if(ht||!qe)return;let kr=qe.ownerDocument,Os=kr.body;if(!Os)return;ht=Wo(kr,"div","persona-clear-chat-tooltip"),ht.textContent=Zt;let Ns=Wo(kr,"div");Ns.className="persona-clear-chat-tooltip-arrow",ht.appendChild(Ns);let Er=qe.getBoundingClientRect();ht.style.position="fixed",ht.style.zIndex=String(lr),ht.style.left=`${Er.left+Er.width/2}px`,ht.style.top=`${Er.top-8}px`,ht.style.transform="translate(-50%, -100%)",Os.appendChild(ht)},Dn=()=>{ht&&ht.parentNode&&(ht.parentNode.removeChild(ht),ht=null)};ut.addEventListener("mouseenter",un),ut.addEventListener("mouseleave",Dn),qe.addEventListener("focus",un),qe.addEventListener("blur",Dn),ut._cleanupTooltip=()=>{Dn(),ut&&(ut.removeEventListener("mouseenter",un),ut.removeEventListener("mouseleave",Dn)),qe&&(qe.removeEventListener("focus",un),qe.removeEventListener("blur",Dn))}}}let{clearChatButton:Ge,clearChatButtonWrapper:Ct}=Be;if(Ge){let J=(Ip=oe.clearChat)!=null?Ip:{},Tt=(Rp=J.enabled)!=null?Rp:!0,$t=(Wp=(Pp=o.layout)==null?void 0:Pp.header)==null?void 0:Wp.showClearChat,ut=$t!==void 0?$t:Tt,Bt=(Bp=J.placement)!=null?Bp:"inline";if(Ct){Ct.style.display=ut?"":"none";let{closeButtonWrapper:pn}=Be;!E()&&pn&&!pn.classList.contains("persona-absolute")&&(ut?pn.classList.remove("persona-ml-auto"):pn.classList.add("persona-ml-auto"));let xn=Bt==="top-right",To=Ct.classList.contains("persona-absolute");if(!E()&&xn!==To&&ut){if(Ct.remove(),xn)Ct.className="persona-absolute persona-top-4 persona-z-50",Ct.style.right="48px",me.style.position="relative",me.appendChild(Ct);else{Ct.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ct.style.right="";let Zt=me.querySelector(".persona-border-b-persona-divider"),Zn=Be.closeButtonWrapper;Zt&&Zn&&Zn.parentElement===Zt?Zt.insertBefore(Ct,Zn):Zt&&Zt.appendChild(Ct)}let In=Be.closeButtonWrapper;In&&!In.classList.contains("persona-absolute")&&(xn?In.classList.add("persona-ml-auto"):In.classList.remove("persona-ml-auto"))}}if(ut){if(!E()){let ht=(Hp=J.size)!=null?Hp:"32px";Ge.style.height=ht,Ge.style.width=ht}let pn=(Dp=J.iconName)!=null?Dp:"refresh-cw",xn=(Fp=J.iconColor)!=null?Fp:"";Ge.style.color=xn||Rn.actionIconColor,Ge.innerHTML="";let To=E()?"14px":"20px",In=Me(pn,To,"currentColor",2);if(In&&Ge.appendChild(In),J.backgroundColor?(Ge.style.backgroundColor=J.backgroundColor,Ge.classList.remove("hover:persona-bg-gray-100")):(Ge.style.backgroundColor="",Ge.classList.add("hover:persona-bg-gray-100")),J.borderWidth||J.borderColor){let ht=J.borderWidth||"0px",un=J.borderColor||"transparent";Ge.style.border=`${ht} solid ${un}`,Ge.classList.remove("persona-border-none")}else Ge.style.border="",Ge.classList.add("persona-border-none");J.borderRadius?(Ge.style.borderRadius=J.borderRadius,Ge.classList.remove("persona-rounded-full")):(Ge.style.borderRadius="",Ge.classList.add("persona-rounded-full")),J.paddingX?(Ge.style.paddingLeft=J.paddingX,Ge.style.paddingRight=J.paddingX):(Ge.style.paddingLeft="",Ge.style.paddingRight=""),J.paddingY?(Ge.style.paddingTop=J.paddingY,Ge.style.paddingBottom=J.paddingY):(Ge.style.paddingTop="",Ge.style.paddingBottom="");let Zt=(Op=J.tooltipText)!=null?Op:"Clear chat",Zn=(Np=J.showTooltip)!=null?Np:!0;if(Ge.setAttribute("aria-label",Zt),Ct&&(Ct._cleanupTooltip&&(Ct._cleanupTooltip(),delete Ct._cleanupTooltip),Zn&&Zt)){let ht=null,un=()=>{if(ht||!Ge)return;let kr=Ge.ownerDocument,Os=kr.body;if(!Os)return;ht=Wo(kr,"div","persona-clear-chat-tooltip"),ht.textContent=Zt;let Ns=Wo(kr,"div");Ns.className="persona-clear-chat-tooltip-arrow",ht.appendChild(Ns);let Er=Ge.getBoundingClientRect();ht.style.position="fixed",ht.style.zIndex=String(lr),ht.style.left=`${Er.left+Er.width/2}px`,ht.style.top=`${Er.top-8}px`,ht.style.transform="translate(-50%, -100%)",Os.appendChild(ht)},Dn=()=>{ht&&ht.parentNode&&(ht.parentNode.removeChild(ht),ht=null)};Ct.addEventListener("mouseenter",un),Ct.addEventListener("mouseleave",Dn),Ge.addEventListener("focus",un),Ge.addEventListener("blur",Dn),Ct._cleanupTooltip=()=>{Dn(),Ct&&(Ct.removeEventListener("mouseenter",un),Ct.removeEventListener("mouseleave",Dn)),Ge&&(Ge.removeEventListener("focus",un),Ge.removeEventListener("blur",Dn))}}}}let Qn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[mc],rn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Ta.message,Ta.messageAndClick];M=gc({parsers:Qn,handlers:rn,getSessionMetadata:f,updateSessionMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),he=kg(o,M,Y),$.updateConfig(o),yr(_e,$.getMessages(),he),vo.render(o.suggestionChips,$,be,void 0,o.suggestionChipsConfig),Ms(),qr($.isStreaming());let mo=((_p=o.voiceRecognition)==null?void 0:_p.enabled)===!0,Jn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),wr=(($p=(Vp=o.voiceRecognition)==null?void 0:Vp.provider)==null?void 0:$p.type)==="runtype";if(mo&&(Jn||wr))if(!j||!zt){let J=Yr(o.voiceRecognition,o.sendButton);J&&(j=J.micButton,zt=J.micButtonWrapper,Pt.insertBefore(zt,Pn),j.addEventListener("click",Re),j.disabled=$.isStreaming())}else{let J=(Up=o.voiceRecognition)!=null?Up:{},Tt=(zp=o.sendButton)!=null?zp:{},$t=(qp=J.iconName)!=null?qp:"mic",ut=(jp=Tt.size)!=null?jp:"40px",Bt=(Kp=J.iconSize)!=null?Kp:ut,pn=parseFloat(Bt)||24;j.style.width=Bt,j.style.height=Bt,j.style.minWidth=Bt,j.style.minHeight=Bt;let xn=(Yp=(Gp=J.iconColor)!=null?Gp:Tt.textColor)!=null?Yp:"currentColor";j.innerHTML="";let To=Me($t,pn,xn,2);To?j.appendChild(To):j.textContent="\u{1F3A4}";let In=(Xp=J.backgroundColor)!=null?Xp:Tt.backgroundColor;In?j.style.backgroundColor=In:j.style.backgroundColor="",xn?j.style.color=xn:j.style.color="var(--persona-text, #111827)",J.borderWidth?(j.style.borderWidth=J.borderWidth,j.style.borderStyle="solid"):(j.style.borderWidth="",j.style.borderStyle=""),J.borderColor?j.style.borderColor=J.borderColor:j.style.borderColor="",J.paddingX?(j.style.paddingLeft=J.paddingX,j.style.paddingRight=J.paddingX):(j.style.paddingLeft="",j.style.paddingRight=""),J.paddingY?(j.style.paddingTop=J.paddingY,j.style.paddingBottom=J.paddingY):(j.style.paddingTop="",j.style.paddingBottom="");let Zt=zt==null?void 0:zt.querySelector(".persona-send-button-tooltip"),Zn=(Qp=J.tooltipText)!=null?Qp:"Start voice recognition";if(((Jp=J.showTooltip)!=null?Jp:!1)&&Zn)if(Zt)Zt.textContent=Zn,Zt.style.display="";else{let un=document.createElement("div");un.className="persona-send-button-tooltip",un.textContent=Zn,zt==null||zt.insertBefore(un,j)}else Zt&&(Zt.style.display="none");zt.style.display="",j.disabled=$.isStreaming()}else j&&zt&&(zt.style.display="none",((eu=(Zp=o.voiceRecognition)==null?void 0:Zp.provider)==null?void 0:eu.type)==="runtype"?$.isVoiceActive()&&$.toggleVoice():Yn&&Ao());if(((tu=o.attachments)==null?void 0:tu.enabled)===!0)if(!Vt||!Ze){let J=(nu=o.attachments)!=null?nu:{},$t=(ru=((ou=o.sendButton)!=null?ou:{}).size)!=null?ru:"40px";Ce||(Ce=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ce.style.display="none",Ut.insertBefore(Ce,be)),se||(se=document.createElement("input"),se.type="file",se.accept=((su=J.allowedTypes)!=null?su:qo).join(","),se.multiple=((au=J.maxFiles)!=null?au:4)>1,se.style.display="none",se.setAttribute("aria-label","Attach files"),Ut.insertBefore(se,be)),Vt=b("div","persona-send-button-wrapper"),Ze=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Ze.type="button",Ze.setAttribute("aria-label",(iu=J.buttonTooltipText)!=null?iu:"Attach file");let ut=(lu=J.buttonIconName)!=null?lu:"paperclip",Bt=$t,pn=parseFloat(Bt)||40,xn=Math.round(pn*.6);Ze.style.width=Bt,Ze.style.height=Bt,Ze.style.minWidth=Bt,Ze.style.minHeight=Bt,Ze.style.fontSize="18px",Ze.style.lineHeight="1",Ze.style.backgroundColor="transparent",Ze.style.color="var(--persona-primary, #111827)",Ze.style.border="none",Ze.style.borderRadius="6px",Ze.style.transition="background-color 0.15s ease",Ze.addEventListener("mouseenter",()=>{Ze.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Ze.addEventListener("mouseleave",()=>{Ze.style.backgroundColor="transparent"});let To=Me(ut,xn,"currentColor",1.5);To?Ze.appendChild(To):Ze.textContent="\u{1F4CE}",Ze.addEventListener("click",Zn=>{Zn.preventDefault(),se==null||se.click()}),Vt.appendChild(Ze);let In=(cu=J.buttonTooltipText)!=null?cu:"Attach file",Zt=b("div","persona-send-button-tooltip");Zt.textContent=In,Vt.appendChild(Zt),at.append(Vt),!ot&&se&&Ce&&(ot=ca.fromConfig(J),ot.setPreviewsContainer(Ce),se.addEventListener("change",async()=>{ot&&(se!=null&&se.files)&&(await ot.handleFileSelect(se.files),se.value="")})),me.querySelector(".persona-attachment-drop-overlay")||me.appendChild(Eg(J.dropOverlay))}else{Vt.style.display="";let J=(du=o.attachments)!=null?du:{};se&&(se.accept=((pu=J.allowedTypes)!=null?pu:qo).join(","),se.multiple=((uu=J.maxFiles)!=null?uu:4)>1),ot&&ot.updateConfig({allowedTypes:J.allowedTypes,maxFileSize:J.maxFileSize,maxFiles:J.maxFiles})}else Vt&&(Vt.style.display="none"),ot&&ot.clearAttachments(),(mu=me.querySelector(".persona-attachment-drop-overlay"))==null||mu.remove();let Yt=(gu=o.sendButton)!=null?gu:{},Cr=(fu=Yt.useIcon)!=null?fu:!1,sr=(hu=Yt.iconText)!=null?hu:"\u2191",ar=Yt.iconName,zo=(bu=Yt.tooltipText)!=null?bu:"Send message",Sr=(yu=Yt.showTooltip)!=null?yu:!1,nt=(vu=Yt.size)!=null?vu:"40px",vn=Yt.backgroundColor,fn=Yt.textColor;if(Cr){if(de.style.width=nt,de.style.height=nt,de.style.minWidth=nt,de.style.minHeight=nt,de.style.fontSize="18px",de.style.lineHeight="1",de.innerHTML="",fn?de.style.color=fn:de.style.color="var(--persona-button-primary-fg, #ffffff)",ar){let J=parseFloat(nt)||24,Tt=(fn==null?void 0:fn.trim())||"currentColor",$t=Me(ar,J,Tt,2);$t?de.appendChild($t):de.textContent=sr}else de.textContent=sr;de.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",vn?(de.style.backgroundColor=vn,de.classList.remove("persona-bg-persona-primary")):(de.style.backgroundColor="",de.classList.add("persona-bg-persona-primary"))}else de.textContent=(wu=(xu=o.copy)==null?void 0:xu.sendButtonLabel)!=null?wu:"Send",de.style.width="",de.style.height="",de.style.minWidth="",de.style.minHeight="",de.style.fontSize="",de.style.lineHeight="",de.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",vn?(de.style.backgroundColor=vn,de.classList.remove("persona-bg-persona-accent")):de.classList.add("persona-bg-persona-accent"),fn?de.style.color=fn:de.classList.add("persona-text-white");Yt.borderWidth?(de.style.borderWidth=Yt.borderWidth,de.style.borderStyle="solid"):(de.style.borderWidth="",de.style.borderStyle=""),Yt.borderColor?de.style.borderColor=Yt.borderColor:de.style.borderColor="",Yt.paddingX?(de.style.paddingLeft=Yt.paddingX,de.style.paddingRight=Yt.paddingX):(de.style.paddingLeft="",de.style.paddingRight=""),Yt.paddingY?(de.style.paddingTop=Yt.paddingY,de.style.paddingBottom=Yt.paddingY):(de.style.paddingTop="",de.style.paddingBottom="");let dn=Pn==null?void 0:Pn.querySelector(".persona-send-button-tooltip");if(Sr&&zo)if(dn)dn.textContent=zo,dn.style.display="";else{let J=document.createElement("div");J.className="persona-send-button-tooltip",J.textContent=zo,Pn==null||Pn.insertBefore(J,de)}else dn&&(dn.style.display="none");let ft=(ku=(Cu=o.layout)==null?void 0:Cu.contentMaxWidth)!=null?ku:E()?(Tu=(Au=(Su=o.launcher)==null?void 0:Su.composerBar)==null?void 0:Au.contentMaxWidth)!=null?Tu:"720px":void 0;ft?(_e.style.maxWidth=ft,_e.style.marginLeft="auto",_e.style.marginRight="auto",_e.style.width="100%",Ut&&(Ut.style.maxWidth=ft,Ut.style.marginLeft="auto",Ut.style.marginRight="auto"),Ht&&(Ht.style.maxWidth=ft,Ht.style.marginLeft="auto",Ht.style.marginRight="auto")):(_e.style.maxWidth="",_e.style.marginLeft="",_e.style.marginRight="",_e.style.width="",Ut&&(Ut.style.maxWidth="",Ut.style.marginLeft="",Ut.style.marginRight=""),Ht&&(Ht.style.maxWidth="",Ht.style.marginLeft="",Ht.style.marginRight=""));let lt=(Eu=o.statusIndicator)!=null?Eu:{},Et=(Mu=lt.visible)!=null?Mu:!0;if(gn.style.display=Et?"":"none",$){let J=$.getStatus();st(gn,($t=>{var ut,Bt,pn,xn;return $t==="idle"?(ut=lt.idleText)!=null?ut:wn.idle:$t==="connecting"?(Bt=lt.connectingText)!=null?Bt:wn.connecting:$t==="connected"?(pn=lt.connectedText)!=null?pn:wn.connected:$t==="error"?(xn=lt.errorText)!=null?xn:wn.error:wn[$t]})(J),lt,J)}gn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Hn=lt.align==="left"?"persona-text-left":lt.align==="center"?"persona-text-center":"persona-text-right";gn.classList.add(Hn)},open(){S()&&Ot(!0,"api")},close(){S()&&Ot(!1,"api")},toggle(){S()&&Ot(!T,"api")},clearChat(){kn=!1,$.clearMessages(),xe.clear(),Jo();try{localStorage.removeItem(fs),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${fs}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==fs)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(),G==null||G.clear(),ve==null||ve.reset(),ce==null||ce.update()},setMessage(c){return!be||$.isStreaming()?!1:(!T&&S()&&Ot(!0,"system"),be.value=c,be.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if($.isStreaming())return!1;let g=(c==null?void 0:c.trim())||be.value.trim();return g?(!T&&S()&&Ot(!0,"system"),be.value="",be.style.height="auto",$.sendMessage(g),!0):!1},startVoiceRecognition(){var g,h;return $.isStreaming()?!1:((h=(g=o.voiceRecognition)==null?void 0:g.provider)==null?void 0:h.type)==="runtype"?($.isVoiceActive()||(!T&&S()&&Ot(!0,"system"),yt.manuallyDeactivated=!1,Bn(),$.toggleVoice().then(()=>{yt.active=$.isVoiceActive(),co("user"),$.isVoiceActive()&&P()})),!0):Yn?!0:Hs()?(!T&&S()&&Ot(!0,"system"),yt.manuallyDeactivated=!1,Bn(),xr("user"),!0):!1},stopVoiceRecognition(){var c,g;return((g=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?$.isVoiceActive()?($.toggleVoice().then(()=>{yt.active=!1,yt.manuallyDeactivated=!0,Bn(),co("user"),X()}),!0):!1:Yn?(yt.manuallyDeactivated=!0,Bn(),Ao("user"),!0):!1},injectMessage(c){return!T&&S()&&Ot(!0,"system"),$.injectMessage(c)},injectAssistantMessage(c){!T&&S()&&Ot(!0,"system");let g=$.injectAssistantMessage(c);return _&&(_=!1,U&&(clearTimeout(U),U=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),g},injectUserMessage(c){return!T&&S()&&Ot(!0,"system"),$.injectUserMessage(c)},injectSystemMessage(c){return!T&&S()&&Ot(!0,"system"),$.injectSystemMessage(c)},injectMessageBatch(c){return!T&&S()&&Ot(!0,"system"),$.injectMessageBatch(c)},injectComponentDirective(c){return!T&&S()&&Ot(!0,"system"),$.injectComponentDirective(c)},injectTestMessage(c){!T&&S()&&Ot(!0,"system"),$.injectTestEvent(c)},async connectStream(c,g){return $.connectStream(c,g)},__pushEventStreamEvent(c){G&&(ve==null||ve.processEvent(c.type,c.payload),G.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!Ee||!G||Tn()},hideEventStream(){ne&&Nn()},isEventStreamVisible(){return ne},showArtifacts(){bo(o)&&(kn=!1,qn(),At==null||At.setMobileOpen(!0))},hideArtifacts(){bo(o)&&(kn=!0,qn())},upsertArtifact(c){return bo(o)?(kn=!1,$.upsertArtifact(c)):null},selectArtifact(c){bo(o)&&$.selectArtifact(c)},clearArtifacts(){bo(o)&&$.clearArtifacts()},getArtifacts(){var c;return(c=$==null?void 0:$.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=$==null?void 0:$.getSelectedArtifactId())!=null?c:null},focusInput(){return I&&!T&&!E()||!be?!1:(be.focus(),!0)},async resolveApproval(c,g,h){let L=$.getMessages().find(O=>{var N;return O.variant==="approval"&&((N=O.approval)==null?void 0:N.id)===c});if(!(L!=null&&L.approval))throw new Error(`Approval not found: ${c}`);if(L.approval.toolType==="webmcp"){$.resolveWebMcpApproval(L.id,g);return}return $.resolveApproval(L.approval,g,h)},getMessages(){return $.getMessages()},getStatus(){return $.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()&&T},isVoiceActive(){return yt.active},getState(){return{open:S()&&T,launcherEnabled:I,voiceActive:yt.active,streaming:$.isStreaming()}},showCSATFeedback(c){!T&&S()&&Ot(!0,"system");let g=_e.querySelector(".persona-feedback-container");g&&g.remove();let h=Sg({onSubmit:async(y,L)=>{var O;$.isClientTokenMode()&&await $.submitCSATFeedback(y,L),(O=c==null?void 0:c.onSubmit)==null||O.call(c,y,L)},onDismiss:c==null?void 0:c.onDismiss,...c});_e.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!T&&S()&&Ot(!0,"system");let g=_e.querySelector(".persona-feedback-container");g&&g.remove();let h=Ag({onSubmit:async(y,L)=>{var O;$.isClientTokenMode()&&await $.submitNPSFeedback(y,L),(O=c==null?void 0:c.onSubmit)==null||O.call(c,y,L)},onDismiss:c==null?void 0:c.onDismiss,...c});_e.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,g){return $.submitCSATFeedback(c,g)},async submitNPSFeedback(c,g){return $.submitNPSFeedback(c,g)},destroy(){Ro!=null&&(clearInterval(Ro),Ro=null),vt.forEach(c=>c()),Te.remove(),Ue==null||Ue.remove(),Qe==null||Qe.destroy(),et==null||et.remove(),Kn&&qe.removeEventListener("click",Kn)}};if((((Ed=n==null?void 0:n.debugTools)!=null?Ed:!1)||!!o.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:on,getMessages:on.getMessages,getStatus:on.getStatus,getMetadata:on.getPersistentMetadata,updateMetadata:on.updatePersistentMetadata,clearHistory:()=>on.clearChat(),setVoiceActive:h=>h?on.startVoiceRecognition():on.stopVoiceRecognition()};window.AgentWidgetBrowser=g,vt.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=q=>{let F=q.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&on.focusInput()};if(window.addEventListener("persona:focusInput",g),vt.push(()=>{window.removeEventListener("persona:focusInput",g)}),Ee){let q=ke=>{let ge=ke.detail;(!(ge!=null&&ge.instanceId)||ge.instanceId===c)&&on.showEventStream()},F=ke=>{let ge=ke.detail;(!(ge!=null&&ge.instanceId)||ge.instanceId===c)&&on.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",F),vt.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",F)})}let h=q=>{let F=q.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&on.showArtifacts()},y=q=>{let F=q.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&on.hideArtifacts()},L=q=>{let F=q.detail;F!=null&&F.instanceId&&F.instanceId!==c||F!=null&&F.artifact&&on.upsertArtifact(F.artifact)},O=q=>{let F=q.detail;F!=null&&F.instanceId&&F.instanceId!==c||typeof(F==null?void 0:F.id)=="string"&&on.selectArtifact(F.id)},N=q=>{let F=q.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&on.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",L),window.addEventListener("persona:selectArtifact",O),window.addEventListener("persona:clearArtifacts",N),vt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",L),window.removeEventListener("persona:selectArtifact",O),window.removeEventListener("persona:clearArtifacts",N)})}let uo=ky(o.persistState);if(uo&&S()){let c=Ey(uo.storage),g=`${uo.keyPrefix}widget-open`,h=`${uo.keyPrefix}widget-voice`,y=`${uo.keyPrefix}widget-voice-mode`;if(c){let L=((Md=uo.persist)==null?void 0:Md.openState)&&c.getItem(g)==="true",O=((Ld=uo.persist)==null?void 0:Ld.voiceState)&&c.getItem(h)==="true",N=((Id=uo.persist)==null?void 0:Id.voiceState)&&c.getItem(y)==="true";if(L&&setTimeout(()=>{on.open(),setTimeout(()=>{var q;if(O||N)on.startVoiceRecognition();else if((q=uo.persist)!=null&&q.focusInput){let F=e.querySelector("textarea");F&&F.focus()}},100)},0),(Rd=uo.persist)!=null&&Rd.openState&&(s.on("widget:opened",()=>{c.setItem(g,"true")}),s.on("widget:closed",()=>{c.setItem(g,"false")})),(Pd=uo.persist)!=null&&Pd.voiceState&&(s.on("voice:state",q=>{c.setItem(h,q.active?"true":"false")}),s.on("user:message",q=>{c.setItem(y,q.viaVoice?"true":"false")})),uo.clearOnChatClear){let q=()=>{c.removeItem(g),c.removeItem(h),c.removeItem(y)},F=()=>q();window.addEventListener("persona:clear-chat",F),vt.push(()=>{window.removeEventListener("persona:clear-chat",F)})}}}return m&&S()&&setTimeout(()=>{on.open()},0),$o(),on};var My=(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},Lg=(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"},xc=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=""},Ig=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",xc(e)},bc=e=>{e.style.transition=""},yc=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=""},vc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},nl=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Ly=(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))},Iy=(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)},Rg=(e,t,n,o,r,s,a)=>{var C,v,M,I,R,W;let i=Bo(s),d=i.reveal==="push";Ly(e,t,n,o,d),Iy(e,t,n,o,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,m=(v=(C=s==null?void 0:s.launcher)==null?void 0:C.mobileFullscreen)!=null?v:!0,p=(I=(M=s==null?void 0:s.launcher)==null?void 0:M.mobileBreakpoint)!=null?I:640,f=l!=null?l.innerWidth<=p:!1;if(m&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),yc(t),bc(o),Ig(o),vc(n),nl(r,o),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String((W=(R=s==null?void 0:s.launcher)==null?void 0:R.zIndex)!=null?W:Cn),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"),Ig(o),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",yc(t),bc(o),vc(n),nl(r,o);let D=i.animate?"transform 180ms ease":"none",B=i.side==="right"?"translateX(100%)":"translateX(-100%)",x=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=x,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",i.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",bc(o),xc(o),nl(r,o);let D=My(i.width,e.clientWidth),B=Math.max(0,e.clientWidth),x=i.animate?"transform 180ms ease":"none",w=i.side==="right"?a?`translateX(-${D}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${D}px)`;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${B+D}px`,t.style.transition=x,t.style.transform=w,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${B}px`,n.style.maxWidth=`${B}px`,n.style.minWidth=`${B}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.position="relative",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",yc(t),xc(o),vc(n),nl(r,o);let D=i.reveal==="emerge";D?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let B=a?i.width:"0px",x=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",w=!a;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${B}`,o.style.width=B,o.style.maxWidth=B,o.style.minWidth=B,o.style.minHeight="0",o.style.position="relative",o.style.overflow=D||w?"hidden":"visible",o.style.transition=x,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")}},Ry=(e,t)=>{let n=e.ownerDocument.createElement("div");return Lg(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Lg(n,o)},destroy(){n.remove()}}},Py=(e,t)=>{var R,W,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"),m=n.createElement("div"),p=(W=(R=t==null?void 0:t.launcher)==null?void 0:R.enabled)==null||W?(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",m.dataset.personaDockRole="host",l.appendChild(m),o.insertBefore(a,e),d.appendChild(e);let f=null,u=()=>{f==null||f.disconnect(),f=null},C=()=>{u(),Bo(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Rg(a,i,d,l,m,t,p)}),f.observe(a))},v=()=>{Rg(a,i,d,l,m,t,p),C()},M=a.ownerDocument.defaultView,I=()=>{v()};return M==null||M.addEventListener("resize",I),Bo(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),v(),{mode:"docked",host:m,shell:a,syncWidgetState(x){let w=x.launcherEnabled?x.open:!0;p!==w&&(p=w,v())},updateConfig(x){var w,E;t=x,((E=(w=t==null?void 0:t.launcher)==null?void 0:w.enabled)!=null?E:!0)===!1&&(p=!0),v()},destroy(){M==null||M.removeEventListener("resize",I),u(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},Pg=(e,t)=>bn(t)?Py(e,t):Ry(e,t);var Nr={desktop:{w:1280,h:800},mobile:{w:390,h:844}},ol=.15,rl=1.5,ka="persona-preview-shell-theme",wc={load:()=>null,save:()=>{},clear:()=>{}},Cc=["How do I get started?","Pricing & plans","Talk to support"];function Ea(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Sc(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 sl(e){let t=Sc(e);return`* { box-sizing: border-box; }
|
|
107
|
+
`}if(!y&&!c){let ut="max-height: -moz-available !important; max-height: stretch !important;",yt=p?"":"padding-top: 1.25em !important;",mt=p?"":`z-index: ${(sn=(Wn=o.launcher)==null?void 0:Wn.zIndex)!=null?sn:Mn} !important;`;Le.style.cssText+=ut+yt+mt}Ye()};vo(),ds(e,o),il(e,o),ll(e,o);let bt=[];bt.push(()=>{document.removeEventListener("keydown",tr)});let Zt=null,en=null;bt.push(()=>{Zt==null||Zt(),Zt=null,en==null||en(),en=null}),qn&&bt.push(()=>{qn==null||qn.disconnect(),qn=null}),bt.push(()=>{Pn==null||Pn(),Pn=null,zo(),Ft&&(Ft.remove(),Ft=null),Tt==null||Tt.element.style.removeProperty("width"),Tt==null||Tt.element.style.removeProperty("maxWidth")}),Ee&&bt.push(()=>{Re!==null&&(cancelAnimationFrame(Re),Re=null),K==null||K.destroy(),K=null,ye==null||ye.destroy(),ye=null,J=null});let Xn=null,rr=()=>{Xn&&(Xn(),Xn=null),o.colorScheme==="auto"&&(Xn=lm(()=>{ds(e,o)}))};rr(),bt.push(()=>{Xn&&(Xn(),Xn=null)});let we=(Vd=o.features)==null?void 0:Vd.streamAnimation;if(we!=null&&we.type&&we.type!=="none"){let c=wa(we.type,we.plugins);c&&(tc(c,e),bt.push(()=>rf(e)))}let io=Rf(Mt),lo=null,$,Po=!1,qo=Ym(),jo=new Map,Wo=new Map,xo=new Map,Is=0,Jn=Oi(),Qn=0,wo=null,Co=!1,Ar=!1,Ko=0,An=null,Bo=null,Jr=!1,Tr=!1,Qr=null,za=4,Zr=24,qa=80,es=new Map,vt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Rs=(Ud=($d=o.voiceRecognition)==null?void 0:$d.autoResume)!=null?Ud:!1,co=c=>{s.emit("voice:state",{active:vt.active,source:c,timestamp:Date.now()})},Nn=()=>{m(c=>({...c,voiceState:{active:vt.active,timestamp:Date.now(),manuallyDeactivated:vt.manuallyDeactivated}}))},ja=()=>{var y,L;if(((y=o.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=Ec(d.voiceState),p=!!c.active,h=Number((L=c.timestamp)!=null?L:0);vt.manuallyDeactivated=!!c.manuallyDeactivated,p&&Date.now()-h<nv&&setTimeout(()=>{var N,_;vt.active||(vt.manuallyDeactivated=!1,((_=(N=o.voiceRecognition)==null?void 0:N.provider)==null?void 0:_.type)==="runtype"?$.toggleVoice().then(()=>{vt.active=$.isVoiceActive(),co("restore"),$.isVoiceActive()&&zs()}):fn("restore"))},1e3)},Ka=()=>$?eg($.getMessages()).filter(c=>!c.__skipPersist):[];function ts(c){if(!(i!=null&&i.save))return;let h={messages:c?eg(c):$?Ka():[],metadata:d,artifacts:jn.artifacts,selectedArtifactId:jn.selectedId};try{let y=i.save(h);y instanceof Promise&&y.catch(L=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",L)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let Go=null,Ps=()=>Le.querySelector("#persona-scroll-container")||fe,sr=()=>{Go!==null&&(cancelAnimationFrame(Go),Go=null),Co=!1},Ws=()=>{wo!==null&&(cancelAnimationFrame(wo),wo=null),Ar=!1,sr()},Bs=()=>{Ko>0?(Cn.textContent=String(Ko),Cn.style.display="",Qe.setAttribute("aria-label",`${Gt()||"Jump to latest"} (${Ko} new)`)):(Cn.textContent="",Cn.style.display="none",Qe.setAttribute("aria-label",Gt()||"Jump to latest"))},Hs=()=>{Ko!==0&&(Ko=0,Bs())},Ds=()=>gt()==="follow"?!Jn.isFollowing():!Vr(fe,Zr),_n=()=>{if(!vn()||ae){Qe.parentNode&&Qe.remove(),Qe.style.display="none";return}Qe.parentNode!==j&&j.appendChild(Qe),yn();let p=Qo(fe)>0&&Ds();p||Hs(),Qe.style.display=p?"":"none"},ns=()=>{Jn.pause()&&(Ws(),_n())},Ho=()=>{Jn.resume(),Hs(),_n()},Do=(c=!1)=>{gt()==="follow"&&Jn.isFollowing()&&(!c&&!Po||(wo!==null&&(cancelAnimationFrame(wo),wo=null),Ar=!0,wo=requestAnimationFrame(()=>{wo=null,Ar=!1,Jn.isFollowing()&&Ga(Ps(),c?220:140)})))},Fs=(c,p,h,y=()=>!0)=>{let L=c.scrollTop,N=p(),_=N-L;sr();let q=performance.now();Co=!0;let O=ge=>1-Math.pow(1-ge,3),Ce=ge=>{if(!y()){sr();return}let ne=p();ne!==N&&(N=ne,_=N-L);let ke=ge-q,Ve=Math.min(ke/h,1),Te=O(Ve),nt=L+_*Te;c.scrollTop=nt,Qn=c.scrollTop,Ve<1?Go=requestAnimationFrame(Ce):(c.scrollTop=N,Qn=c.scrollTop,Go=null,Co=!1)};Go=requestAnimationFrame(Ce)},Ga=(c,p=500)=>{let h=Qo(c)-c.scrollTop;if(Math.abs(h)<1){Qn=c.scrollTop;return}if(Math.abs(h)>=qa){sr(),Co=!0,c.scrollTop=Qo(c),Qn=c.scrollTop,Co=!1;return}Fs(c,()=>Qo(c),p,()=>Jn.isFollowing())},Os=()=>{let c=Ps();Co=!0,c.scrollTop=Qo(c),Qn=c.scrollTop,Co=!1,_n()},Ns=c=>{Sn.style.height=`${Math.max(0,Math.round(c))}px`,An&&(An.spacerHeight=Math.max(0,c))},kr=()=>{Bo!==null&&(cancelAnimationFrame(Bo),Bo=null),sr(),An=null,Sn.style.height="0px"},Ya=c=>{Bo!==null&&cancelAnimationFrame(Bo),Bo=requestAnimationFrame(()=>{var Ce;Bo=null;let p=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(c):c.replace(/"/g,'\\"'),h=fe.querySelector(`[data-message-id="${p}"]`);if(!h)return;let y=0,L=h;for(;L&&L!==fe;)y+=L.offsetTop,L=L.offsetParent;let N=(Ce=An==null?void 0:An.spacerHeight)!=null?Ce:0,_=fe.scrollHeight-N,{targetScrollTop:q,spacerHeight:O}=ef({anchorOffsetTop:y,topOffset:Lt(),viewportHeight:fe.clientHeight,contentHeight:_});An={initialSpacerHeight:O,contentHeightAtAnchor:_,spacerHeight:O},Ns(O),Fs(fe,()=>q,220)})},Xa=()=>{if(gt()==="follow"){if(!Jn.isFollowing()||Vr(fe,1))return;Do(!Po);return}if(An&&An.initialSpacerHeight>0){let c=fe.scrollHeight-An.spacerHeight,p=tf({initialSpacerHeight:An.initialSpacerHeight,contentHeightAtAnchor:An.contentHeightAtAnchor,currentContentHeight:c});p!==An.spacerHeight&&Ns(p)}_n()},Ja=c=>{let p=gt();p==="follow"?(Ho(),Do(!0)):p==="anchor-top"&&Ya(c)},Qa=c=>{let p=new Map;c.forEach(h=>{let y=es.get(h.id);p.set(h.id,{streaming:h.streaming,role:h.role}),!y&&h.role==="assistant"&&(s.emit("assistant:message",h),!Tr&>()!=="anchor-top"&&Ds()&&(Ko+=1,Bs(),_n())),h.role==="assistant"&&(y!=null&&y.streaming)&&h.streaming===!1&&s.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(y?h.approval.status!=="pending"&&s.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):s.emit("approval:requested",{approval:h.approval,message:h}))}),es.clear(),p.forEach((h,y)=>{es.set(y,h)})},Er=(c,p,h)=>{var pt,We,Ie,ze,Ye,Ct;let y=document.createElement("div"),N=(()=>{var He;let H=r.find(Oe=>Oe.renderLoadingIndicator);if(H!=null&&H.renderLoadingIndicator)return H.renderLoadingIndicator;if((He=o.loadingIndicator)!=null&&He.render)return o.loadingIndicator.render})(),_=(H,He)=>He==null?!1:typeof He=="string"?(H.textContent=He,!0):(H.appendChild(He),!0),q=new Set,O=new Set,Ce=r.some(H=>H.renderAskUserQuestion),ge=[],ne=[],ke=o.enableComponentStreaming!==!1,Ve=r.some(H=>H.renderApproval)&&o.approval!==!1,Te=[];if(p.forEach(H=>{var Xe,Wt,dn,mo,eo,Mr,Lr,is,ls,Xt,Ir,ur,mr,Xo;q.add(H.id);let He=Ce&&Ur(H),Oe=Ve&&H.variant==="approval"&&!!H.approval,ve=!He&&H.role==="assistant"&&!H.variant&&ke&&Xf(H);if(!Oe&&xo.has(H.id)){let rt=c.querySelector(`#wrapper-${H.id}`);rt==null||rt.removeAttribute("data-preserve-runtime"),xo.delete(H.id)}if(!ve&&Wo.has(H.id)){let rt=c.querySelector(`#wrapper-${H.id}`);rt==null||rt.removeAttribute("data-preserve-runtime"),Wo.delete(H.id)}let Vt=Ur(H)?`:${(Xe=H.agentMetadata)!=null&&Xe.askUserQuestionAnswered?"a":"u"}:${(Wt=H.agentMetadata)!=null&&Wt.askUserQuestionAnswers?Object.keys(H.agentMetadata.askUserQuestionAnswers).length:0}`:"",Nt=Gm(H,Is)+Vt,Yt=He||Oe||ve?null:Xm(qo,H.id,Nt);if(Yt){y.appendChild(Yt.cloneNode(!0)),Ur(H)&&((dn=H.toolCall)!=null&&dn.id)&&((mo=H.agentMetadata)==null?void 0:mo.awaitingLocalTool)===!0&&!((eo=H.agentMetadata)!=null&&eo.askUserQuestionAnswered)&&(O.add(H.toolCall.id),nl(H,o,Be.composerOverlay));return}let St=null,jt=r.find(rt=>!!(H.variant==="reasoning"&&rt.renderReasoning||H.variant==="tool"&&rt.renderToolCall||!H.variant&&rt.renderMessage)),Zn=(Mr=o.layout)==null?void 0:Mr.messages;if(Ur(H)&&((Lr=H.agentMetadata)==null?void 0:Lr.askUserQuestionAnswered)===!0){jo.delete(H.id);let rt=c.querySelector(`#wrapper-${H.id}`);rt==null||rt.removeAttribute("data-preserve-runtime");return}if(Ur(H)&&((ls=(is=o.features)==null?void 0:is.askUserQuestion)==null?void 0:ls.enabled)!==!1){let rt=r.find(xn=>typeof xn.renderAskUserQuestion=="function");if(rt&&Rt.current){let xn=jo.get(H.id),Wn=xn!==Nt,sn=null;if(Wn){let{payload:mt,complete:Vn}=ws(H),pn=H.id,Fo=()=>{var un;return(un=Rt.current)==null?void 0:un.getMessages().find(Bn=>Bn.id===pn)};sn=rt.renderAskUserQuestion({message:H,payload:mt,complete:Vn,resolve:un=>{var fo;let Bn=Fo();Bn&&((fo=Rt.current)==null||fo.resolveAskUserQuestion(Bn,un))},dismiss:()=>{var Bn,fo,Rr;let un=Fo();(Bn=un==null?void 0:un.agentMetadata)!=null&&Bn.awaitingLocalTool&&((fo=Rt.current)==null||fo.markAskUserQuestionResolved(un),(Rr=Rt.current)==null||Rr.resolveAskUserQuestion(un,"(dismissed)"))},config:o})}let ut=xn!=null;if(Wn&&sn===null&&!ut){((Xt=H.agentMetadata)==null?void 0:Xt.awaitingLocalTool)===!0&&!((Ir=H.agentMetadata)!=null&&Ir.askUserQuestionAnswered)&&(O.add(H.toolCall.id),nl(H,o,Be.composerOverlay));return}let yt=document.createElement("div");yt.className="persona-flex",yt.id=`wrapper-${H.id}`,yt.setAttribute("data-wrapper-id",H.id),yt.setAttribute("data-ask-plugin-stub","true"),yt.setAttribute("data-preserve-runtime","true"),y.appendChild(yt),ge.push({messageId:H.id,fingerprint:Nt,bubble:sn});return}else{((ur=H.agentMetadata)==null?void 0:ur.awaitingLocalTool)===!0&&!((mr=H.agentMetadata)!=null&&mr.askUserQuestionAnswered)&&(O.add(H.toolCall.id),nl(H,o,Be.composerOverlay));return}}else if(Oe){let rt=r.find(ut=>typeof ut.renderApproval=="function"),Wn=xo.get(H.id)!==Nt,sn=null;if(Wn&&(rt!=null&&rt.renderApproval)){let ut=H.id,yt=(mt,Vn)=>{var Fo,un,Bn;let pn=(Fo=Rt.current)==null?void 0:Fo.getMessages().find(fo=>fo.id===ut);pn!=null&&pn.approval&&(pn.approval.toolType==="webmcp"?(un=Rt.current)==null||un.resolveWebMcpApproval(pn.id,mt):(Bn=Rt.current)==null||Bn.resolveApproval(pn.approval,mt,Vn))};sn=rt.renderApproval({message:H,defaultRenderer:()=>sl(H,o),config:o,approve:mt=>yt("approved",mt),deny:mt=>yt("denied",mt)})}if(Wn&&sn===null){let ut=c.querySelector(`#wrapper-${H.id}`);ut==null||ut.removeAttribute("data-preserve-runtime"),xo.delete(H.id),St=sl(H,o)}else{let ut=document.createElement("div");ut.className="persona-flex",ut.id=`wrapper-${H.id}`,ut.setAttribute("data-wrapper-id",H.id),ut.setAttribute("data-approval-plugin-stub","true"),ut.setAttribute("data-preserve-runtime","true"),y.appendChild(ut),Te.push({messageId:H.id,fingerprint:Nt,bubble:sn});return}}else if(jt)if(H.variant==="reasoning"&&H.reasoning&&jt.renderReasoning){if(!me)return;St=jt.renderReasoning({message:H,defaultRenderer:()=>lc(H,o),config:o})}else if(H.variant==="tool"&&H.toolCall&&jt.renderToolCall){if(!de)return;St=jt.renderToolCall({message:H,defaultRenderer:()=>cc(H,o),config:o})}else jt.renderMessage&&(St=jt.renderMessage({message:H,defaultRenderer:()=>{let rt=ic(H,h,Zn,o.messageActions,ee,{loadingIndicatorRenderer:N,widgetConfig:o});return H.role!=="user"&&xc(rt,H,o,$),rt},config:o}));if(!St&&ve){let rt=Jf(H);if(rt){let xn=Wo.get(H.id),Wn=xn!==Nt,sn=o.wrapComponentDirectiveInBubble!==!1,ut=null;if(Wn){let yt=Gf(rt,{config:o,message:H,transform:h});if(yt)if(sn){let mt=document.createElement("div");if(mt.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(" "),mt.id=`bubble-${H.id}`,mt.setAttribute("data-message-id",H.id),H.content&&H.content.trim()){let Vn=document.createElement("div");Vn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Vn.innerHTML=h({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),mt.appendChild(Vn)}mt.appendChild(yt),ut=mt}else{let mt=document.createElement("div");if(mt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",mt.id=`bubble-${H.id}`,mt.setAttribute("data-message-id",H.id),mt.setAttribute("data-persona-component-directive","true"),H.content&&H.content.trim()){let Vn=document.createElement("div");Vn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Vn.innerHTML=h({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),mt.appendChild(Vn)}mt.appendChild(yt),ut=mt}}if(ut||xn!=null){let yt=document.createElement("div");yt.className="persona-flex",yt.id=`wrapper-${H.id}`,yt.setAttribute("data-wrapper-id",H.id),yt.setAttribute("data-component-directive-stub","true"),yt.setAttribute("data-preserve-runtime","true"),sn||yt.classList.add("persona-w-full"),y.appendChild(yt),ne.push({messageId:H.id,fingerprint:Nt,bubble:ut});return}}}if(!St)if(H.variant==="reasoning"&&H.reasoning){if(!me)return;St=lc(H,o)}else if(H.variant==="tool"&&H.toolCall){if(!de)return;St=cc(H,o)}else if(H.variant==="approval"&&H.approval){if(o.approval===!1)return;St=sl(H,o)}else{let rt=(Xo=o.layout)==null?void 0:Xo.messages;rt!=null&&rt.renderUserMessage&&H.role==="user"?St=rt.renderUserMessage({message:H,config:o,streaming:!!H.streaming}):rt!=null&&rt.renderAssistantMessage&&H.role==="assistant"?St=rt.renderAssistantMessage({message:H,config:o,streaming:!!H.streaming}):St=ic(H,h,rt,o.messageActions,ee,{loadingIndicatorRenderer:N,widgetConfig:o}),H.role!=="user"&&St&&xc(St,H,o,$)}let rn=document.createElement("div");rn.className="persona-flex",rn.id=`wrapper-${H.id}`,rn.setAttribute("data-wrapper-id",H.id),H.role==="user"&&rn.classList.add("persona-justify-end"),(St==null?void 0:St.getAttribute("data-persona-component-directive"))==="true"&&rn.classList.add("persona-w-full"),rn.appendChild(St),Jm(qo,H.id,Nt,rn),y.appendChild(rn)}),Be.composerOverlay&&Be.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(He=>{let Oe=He.getAttribute("data-persona-ask-sheet-for");Oe&&!O.has(Oe)&&Ss(Be.composerOverlay,Oe)}),(We=(pt=o.features)==null?void 0:pt.toolCallDisplay)!=null&&We.grouped){let H=[],He=[];p.forEach(Oe=>{if(Oe.variant==="tool"&&Oe.toolCall&&de){He.push(Oe);return}He.length>1&&H.push(He),He=[]}),He.length>1&&H.push(He),H.forEach((Oe,ve)=>{var Xe,Wt;let Vt=Oe.map(dn=>Array.from(y.children).find(mo=>mo instanceof HTMLElement&&mo.getAttribute("data-wrapper-id")===dn.id)).filter(dn=>!!dn);if(Vt.length<2)return;let Nt=document.createElement("div");Nt.className="persona-flex",Nt.id=`wrapper-tool-group-${ve}-${Oe[0].id}`,Nt.setAttribute("data-wrapper-id",`tool-group-${ve}-${Oe[0].id}`);let Yt=document.createElement("div");Yt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Yt.setAttribute("data-persona-tool-group","true");let St=document.createElement("div");St.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let jt=`Called ${Oe.length} tools`,Zn=(Wt=(Xe=o.toolCall)==null?void 0:Xe.renderGroupedSummary)==null?void 0:Wt.call(Xe,{messages:Oe,toolCalls:Oe.map(dn=>dn.toolCall).filter(dn=>!!dn),defaultSummary:jt,config:o});_(St,Zn)||(St.textContent=jt);let rn=document.createElement("div");rn.className="persona-tool-group-stack persona-flex persona-flex-col",Yt.append(St,rn),Nt.appendChild(Yt),Vt[0].before(Nt),Vt.forEach((dn,mo)=>{let eo=document.createElement("div");eo.className="persona-tool-group-item persona-relative",eo.setAttribute("data-persona-tool-group-item","true"),mo<Vt.length-1&&eo.setAttribute("data-persona-tool-group-connector","true"),eo.appendChild(dn),rn.appendChild(eo)})})}Qm(qo,q);let nt=p.some(H=>H.role==="assistant"&&H.streaming),je=p[p.length-1],dt=(je==null?void 0:je.role)==="assistant"&&!je.streaming&&je.variant!=="approval";if(Po&&p.some(H=>H.role==="user")&&!nt&&!dt){let H={config:o,streaming:!0,location:"standalone",defaultRenderer:Ma},He=r.find(ve=>ve.renderLoadingIndicator),Oe=null;if(He!=null&&He.renderLoadingIndicator&&(Oe=He.renderLoadingIndicator(H)),Oe===null&&((Ie=o.loadingIndicator)!=null&&Ie.render)&&(Oe=o.loadingIndicator.render(H)),Oe===null&&(Oe=Ma()),Oe){let ve=document.createElement("div"),Vt=((ze=o.loadingIndicator)==null?void 0:ze.showBubble)!==!1;ve.className=Vt?["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(" "),ve.setAttribute("data-typing-indicator","true"),ve.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",ve.appendChild(Oe);let Nt=document.createElement("div");Nt.className="persona-flex",Nt.id="wrapper-typing-indicator",Nt.setAttribute("data-wrapper-id","typing-indicator"),Nt.appendChild(ve),y.appendChild(Nt)}}if(!Po&&p.length>0){let H=p[p.length-1],He={config:o,lastMessage:H,messageCount:p.length},Oe=r.find(Vt=>Vt.renderIdleIndicator),ve=null;if(Oe!=null&&Oe.renderIdleIndicator&&(ve=Oe.renderIdleIndicator(He)),ve===null&&((Ye=o.loadingIndicator)!=null&&Ye.renderIdle)&&(ve=o.loadingIndicator.renderIdle(He)),ve){let Vt=document.createElement("div"),Nt=((Ct=o.loadingIndicator)==null?void 0:Ct.showBubble)!==!1;Vt.className=Nt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-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(" "),Vt.setAttribute("data-idle-indicator","true"),Vt.appendChild(ve);let Yt=document.createElement("div");Yt.className="persona-flex",Yt.id="wrapper-idle-indicator",Yt.setAttribute("data-wrapper-id","idle-indicator"),Yt.appendChild(Vt),y.appendChild(Yt)}}if(Di(c,y),ge.length>0)for(let{messageId:H,fingerprint:He,bubble:Oe}of ge){let ve=c.querySelector(`#wrapper-${H}`);ve&&Oe!==null&&(ve.replaceChildren(Oe),ve.setAttribute("data-bubble-fp",He),jo.set(H,He))}if(jo.size>0)for(let H of jo.keys())q.has(H)||jo.delete(H);if(ne.length>0)for(let{messageId:H,fingerprint:He,bubble:Oe}of ne){let ve=c.querySelector(`#wrapper-${H}`);ve&&Oe!==null&&(ve.replaceChildren(Oe),ve.setAttribute("data-bubble-fp",He),Wo.set(H,He))}if(Wo.size>0)for(let H of Wo.keys())q.has(H)||Wo.delete(H);if(Te.length>0)for(let{messageId:H,fingerprint:He,bubble:Oe}of Te){let ve=c.querySelector(`#wrapper-${H}`);ve&&Oe!==null&&(ve.replaceChildren(Oe),ve.setAttribute("data-bubble-fp",He),xo.set(H,He))}if(xo.size>0)for(let H of xo.keys())q.has(H)||xo.delete(H)},ar=null,Za=()=>{var h;if(ar)return;let c=y=>{let L=y.composedPath();L.includes(Le)||Je&&L.includes(Je)||Ot(!1,"user")};ar=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},_s=()=>{var p;if(!ar)return;((p=e.ownerDocument)!=null?p:document).removeEventListener("pointerdown",ar,!0),ar=null};bt.push(()=>_s());let ir=null,ei=()=>{var h;if(ir)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Ot(!1,"user"))};ir=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},Vs=()=>{var p;if(!ir)return;((p=e.ownerDocument)!=null?p:document).removeEventListener("keydown",ir,!0),ir=null};bt.push(()=>Vs());let lr=!1,$s=new Set,ti=()=>{var p,h,y,L;let c=(y=(h=(p=o.launcher)==null?void 0:p.composerBar)==null?void 0:h.peek)==null?void 0:y.streamAnimation;return c||((L=o.features)==null?void 0:L.streamAnimation)},Yo=()=>{var dt,pt,We,Ie;if(!E())return;let c=Be.peekBanner,p=Be.peekTextNode;if(!c||!p)return;if(k){c.classList.remove("persona-pill-peek--visible");return}let h=(dt=$==null?void 0:$.getMessages())!=null?dt:[],y;for(let ze=h.length-1;ze>=0;ze--){let Ye=h[ze];if(Ye.role==="assistant"&&Ye.content){y=Ye;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let L=y.content,N=!!y.streaming,_=ti(),q=Vi(_),O=q.type!=="none"?wa(q.type,_==null?void 0:_.plugins):null,Ce=((pt=O==null?void 0:O.isAnimating)==null?void 0:pt.call(O,y))===!0,ge=O!==null&&(N||Ce);ge&&O&&!$s.has(O.name)&&(tc(O,e),$s.add(O.name));let ne=ge&&(O!=null&&O.containerClass)?O.containerClass:null,ke=(We=p.dataset.personaPeekStreamClass)!=null?We:null;ke&&ke!==ne&&(p.classList.remove(ke),delete p.dataset.personaPeekStreamClass),ne&&ke!==ne&&(p.classList.add(ne),p.dataset.personaPeekStreamClass=ne),ge?(p.style.setProperty("--persona-stream-step",`${q.speed}ms`),p.style.setProperty("--persona-stream-duration",`${q.duration}ms`)):(p.style.removeProperty("--persona-stream-step"),p.style.removeProperty("--persona-stream-duration"));let Ve=ge?$i(L,q.buffer,O,y,N):L;if(ge&&q.placeholder==="skeleton"&&N&&(!Ve||!Ve.trim())){let ze=document.createElement("div"),Ye=Sa();Ye.classList.add("persona-pill-peek__skeleton"),ze.appendChild(Ye),Di(p,ze)}else{let ze=Math.max(0,Ve.length-100),Ye=Ve.length>100?Ve.slice(-100):Ve,Ct=pa(Ye);if(!ge||!O){let H=Ve.length>100?`\u2026${Ye}`:Ye;p.textContent!==H&&(p.textContent=H)}else{let H=Ct;(O.wrap==="char"||O.wrap==="word")&&(H=Ca(Ct,O.wrap,`peek-${y.id}`,{skipTags:O.skipTags,startIndex:ze}));let He=document.createElement("div");if(He.innerHTML=H,O.useCaret&&Ye.length>0){let Oe=Ui(),ve=He.querySelectorAll(".persona-stream-char, .persona-stream-word"),Vt=ve[ve.length-1];Vt!=null&&Vt.parentNode?Vt.parentNode.insertBefore(Oe,Vt.nextSibling):He.appendChild(Oe)}Di(p,He),(Ie=O.onAfterRender)==null||Ie.call(O,{container:p,bubble:c,messageId:y.id,message:y,speed:q.speed,duration:q.duration})}}let je=Po||lr;c.classList.toggle("persona-pill-peek--visible",je)};if(E()){let c=Be.peekBanner;if(c){let y=L=>{L.preventDefault(),L.stopPropagation(),Ot(!0,"user")};c.addEventListener("pointerdown",y),bt.push(()=>{c.removeEventListener("pointerdown",y)})}let p=()=>{lr||(lr=!0,Yo())},h=()=>{lr&&(lr=!1,Yo())};pe.addEventListener("pointerenter",p),pe.addEventListener("pointerleave",h),bt.push(()=>{pe.removeEventListener("pointerenter",p),pe.removeEventListener("pointerleave",h)}),Je&&(Je.addEventListener("pointerenter",p),Je.addEventListener("pointerleave",h),bt.push(()=>{Je.removeEventListener("pointerenter",p),Je.removeEventListener("pointerleave",h)}))}let ni=c=>{var ke,Ve,Te,nt,je,dt,pt,We;let p=(Ve=(ke=o.launcher)==null?void 0:ke.composerBar)!=null?Ve:{},h=(Te=p.expandedSize)!=null?Te:"anchored",y=(nt=p.bottomOffset)!=null?nt:"16px",L=p.collapsedMaxWidth,N=(je=p.expandedMaxWidth)!=null?je:"880px",_=(dt=p.expandedTopOffset)!=null?dt:"5vh",q=(pt=p.modalMaxWidth)!=null?pt:"880px",O=(We=p.modalMaxHeight)!=null?We:"min(90vh, 800px)",Ce="calc(100vw - 32px)",ge="var(--persona-pill-area-height, 80px)",ne=Le.style;if(ne.left="",ne.right="",ne.top="",ne.bottom="",ne.transform="",ne.width="",ne.maxWidth="",ne.height="",ne.maxHeight="",Je){let Ie=Je.style;Ie.bottom=y,Ie.width=L!=null?L:""}if(c&&h!=="fullscreen"){if(h==="modal"){ne.top="50%",ne.left="50%",ne.transform="translate(-50%, -50%)",ne.bottom="auto",ne.right="auto",ne.width=q,ne.maxWidth=Ce,ne.maxHeight=O,ne.height=O;return}ne.left="50%",ne.transform="translateX(-50%)",ne.bottom=`calc(${y} + ${ge})`,ne.top=_,ne.width=N,ne.maxWidth=Ce}},cr=()=>{var O,Ce,ge,ne,ke,Ve,Te,nt;if(!S())return;if(E()){let dt=(ge=((Ce=(O=o.launcher)==null?void 0:O.composerBar)!=null?Ce:{}).expandedSize)!=null?ge:"anchored",pt=k?"expanded":"collapsed";Le.dataset.state=pt,Le.dataset.expandedSize=dt,Je&&(Je.dataset.state=pt,Je.dataset.expandedSize=dt),Le.style.removeProperty("display"),Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ni(k),j.style.display=k?"flex":"none",vo(),k?(Za(),ei()):(_s(),Vs()),Yo();return}let c=wn(o),p=(ne=e.ownerDocument.defaultView)!=null?ne:window,h=(Ve=(ke=o.launcher)==null?void 0:ke.mobileBreakpoint)!=null?Ve:640,y=(nt=(Te=o.launcher)==null?void 0:Te.mobileFullscreen)!=null?nt:!0,L=p.innerWidth<=h,N=y&&L&&I,_=No(o).reveal;k?(Le.style.removeProperty("display"),Le.style.display=c?"flex":"",Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-95","persona-opacity-0"),pe.classList.add("persona-scale-100","persona-opacity-100"),tn?tn.element.style.display="none":nn&&(nn.style.display="none")):(c?c&&(_==="overlay"||_==="push")&&!N?(Le.style.removeProperty("display"),Le.style.display="flex",Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Le.style.setProperty("display","none","important"),Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Le.style.display="",Le.classList.add("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-100","persona-opacity-100"),pe.classList.add("persona-scale-95","persona-opacity-0")),tn?tn.element.style.display=c?"none":"":nn&&(nn.style.display=c?"none":""))},Ot=(c,p="user")=>{var N,_;if(!S()||k===c)return;let h=k;k=c,cr();let y=(()=>{var Te,nt,je,dt,pt,We,Ie,ze,Ye,Ct;let q=(nt=(Te=o.launcher)==null?void 0:Te.sidebarMode)!=null?nt:!1,O=(je=e.ownerDocument.defaultView)!=null?je:window,Ce=(pt=(dt=o.launcher)==null?void 0:dt.mobileFullscreen)!=null?pt:!0,ge=(Ie=(We=o.launcher)==null?void 0:We.mobileBreakpoint)!=null?Ie:640,ne=O.innerWidth<=ge,ke=wn(o)&&Ce&&ne,Ve=E()&&((Ct=(Ye=(ze=o.launcher)==null?void 0:ze.composerBar)==null?void 0:Ye.expandedSize)!=null?Ct:"fullscreen")==="fullscreen";return q||Ce&&ne&&I||ke||Ve})();if(k&&y){if(!Zt){let q=e.getRootNode(),O=q instanceof ShadowRoot?q.host:e.closest(".persona-host");O&&(Zt=nc(O,(_=(N=o.launcher)==null?void 0:N.zIndex)!=null?_:Mn))}en||(en=oc(e.ownerDocument))}else k||(Zt==null||Zt(),Zt=null,en==null||en(),en=null);k&&(qs(),gt()==="follow"?Do(!0):Os());let L={open:k,source:p,timestamp:Date.now()};k&&!h?s.emit("widget:opened",L):!k&&h&&s.emit("widget:closed",L),s.emit("widget:state",{open:k,launcherEnabled:I,voiceActive:vt.active,streaming:$.isStreaming()})},os=c=>{Jt(c?"stop":"send"),G&&(G.disabled=c),io.buttons.forEach(p=>{p.disabled=c}),$e.dataset.personaComposerStreaming=c?"true":"false",$e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(p=>{(p instanceof HTMLButtonElement||p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement||p instanceof HTMLSelectElement)&&(p.disabled=c)})},rs=()=>{vt.active||te&&te.focus()};s.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>rs(),200)});let Us=()=>{var h,y,L,N,_,q,O,Ce,ge,ne,ke;oo.textContent=(y=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",Mo.textContent=(N=(L=o.copy)==null?void 0:L.welcomeSubtitle)!=null?N:"Ask anything about your account or products.",te.placeholder=(q=(_=o.copy)==null?void 0:_.inputPlaceholder)!=null?q:"How can I help...";let c=fe.querySelector("[data-persona-intro-card]");if(c){let Ve=((O=o.copy)==null?void 0:O.showWelcomeCard)!==!1;c.style.display=Ve?"":"none",Ve?(fe.classList.remove("persona-gap-3"),fe.classList.add("persona-gap-6")):(fe.classList.remove("persona-gap-6"),fe.classList.add("persona-gap-3"))}!((ge=(Ce=o.sendButton)==null?void 0:Ce.useIcon)!=null&&ge)&&!($!=null&&$.isStreaming())&&(qe.textContent=(ke=(ne=o.copy)==null?void 0:ne.sendButtonLabel)!=null?ke:"Send"),te.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',te.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{m(p=>({...p,sessionId:c}))}});let po=null,Ge=()=>{po==null&&(po=setInterval(()=>{let c=tt.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(po),po=null;return}let p=Date.now();c.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=Ai(p-y))})},100))};if($=new Bi(o,{onMessagesChanged(c){var y;Er(tt,c,he),Ge(),$&&(c.some(N=>N.role==="user")?io.render([],$,te,c):io.render(o.suggestionChips,$,te,c,o.suggestionChipsConfig)),Do(!Po),Qa(c);let p=[...c].reverse().find(L=>L.role==="user");c.length===0&&kr(),!Jr||Tr?(Jr=!0,Qr=(y=p==null?void 0:p.id)!=null?y:null):p&&p.id!==Qr&&(Qr=p.id,Ja(p.id));let h=vt.lastUserMessageId;p&&p.id!==h&&(vt.lastUserMessageId=p.id,s.emit("user:message",p)),vt.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),ts(c),Yo()},onStatusChanged(c){var y;let p=(y=o.statusIndicator)!=null?y:{};lt(an,(L=>{var N,_,q,O;return L==="idle"?(N=p.idleText)!=null?N:En.idle:L==="connecting"?(_=p.connectingText)!=null?_:En.connecting:L==="connected"?(q=p.connectedText)!=null?q:En.connected:L==="error"?(O=p.errorText)!=null?O:En.error:En[L]})(c),p,c)},onStreamingChanged(c){Po=c,os(c),$&&Er(tt,$.getMessages(),he),c||Do(!0),Yo()},onVoiceStatusChanged(c){var p,h;if(((h=(p=o.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype")switch(c){case"listening":break;case"processing":dr(),Ag();break;case"speaking":dr(),Tg();break;default:c==="idle"&&$.isBargeInActive()?(dr(),zs(),G==null||G.setAttribute("aria-label","End voice session")):(vt.active=!1,dr(),co("system"),Nn());break}},onArtifactsState(c){jn=c,Yn(),ts()}}),Rt.current=$,Jr=!0,((qd=(zd=o.voiceRecognition)==null?void 0:zd.provider)==null?void 0:qd.type)==="runtype")try{$.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}o.clientToken&&$.initClientSession().catch(c=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(ye||o.onSSEEvent)&&$.setSSEEventCallback((c,p)=>{var h;(h=o.onSSEEvent)==null||h.call(o,c,p),be==null||be.processEvent(c,p),ye==null||ye.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(p)})}),l&&l.then(c=>{var p,h,y;if(c){if(c.metadata&&(d=Ec(c.metadata),M.syncFromMetadata()),(p=c.messages)!=null&&p.length){Tr=!0;try{$.hydrateMessages(c.messages)}finally{Tr=!1}}(h=c.artifacts)!=null&&h.length&&$.hydrateArtifacts(c.artifacts,(y=c.selectedArtifactId)!=null?y:null)}}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let T=()=>{var p,h,y;!E()||k||!((y=(h=(p=o.launcher)==null?void 0:p.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||Ot(!0,"auto")},U=c=>{var L;if(c.preventDefault(),$.isStreaming()){$.cancel(),be==null||be.reset(),K==null||K.update();return}let p=te.value.trim(),h=(L=At==null?void 0:At.hasAttachments())!=null?L:!1;if(!p&&!h)return;T();let y;h&&(y=[],y.push(...At.getContentParts()),p&&y.push(Jl(p))),te.value="",te.style.height="auto",X(),$.sendMessage(p,{contentParts:y}),h&&At.clearAttachments()},B=()=>{var c;return((c=o.features)==null?void 0:c.composerHistory)!==!1},Z={...Fi},ie=!1,X=()=>{Z={...Fi}},Pe=()=>$.getMessages().filter(c=>c.role==="user").map(c=>{var p;return(p=c.content)!=null?p:""}).filter(c=>c.length>0),Ne=c=>{if(!te)return;ie=!0,te.value=c,te.dispatchEvent(new Event("input",{bubbles:!0})),ie=!1;let p=te.value.length;te.setSelectionRange(p,p)},at=()=>{ie||X()},Ze=c=>{if(te){if(B()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let p=te.selectionStart===0&&te.selectionEnd===0,h=Km({direction:c.key==="ArrowUp"?"up":"down",history:Pe(),currentValue:te.value,atStart:p,state:Z});if(Z=h.state,h.handled){c.preventDefault(),h.value!==void 0&&Ne(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if($.isStreaming()){c.preventDefault();return}X(),c.preventDefault(),qe.click()}}},Ht=c=>{c.key!=="Escape"||c.isComposing||$.isStreaming()&&c.composedPath().includes(j)&&($.cancel(),be==null||be.reset(),K==null||K.update(),X(),c.preventDefault(),c.stopImmediatePropagation())},$t=async c=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!At)return;let p=rv(c.clipboardData);p.length!==0&&(c.preventDefault(),await At.handleFiles(p))},_t=null,ct=!1,kt=null,Ue=null,Tn=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,fn=(c="user")=>{var N,_,q,O,Ce,ge,ne;if(ct||$.isStreaming())return;let p=Tn();if(!p)return;_t=new p;let y=(_=((N=o.voiceRecognition)!=null?N:{}).pauseDuration)!=null?_:2e3;_t.continuous=!0,_t.interimResults=!0,_t.lang="en-US";let L=te.value;_t.onresult=ke=>{let Ve="",Te="";for(let je=0;je<ke.results.length;je++){let dt=ke.results[je],pt=dt[0].transcript;dt.isFinal?Ve+=pt+" ":Te=pt}let nt=L+Ve+Te;te.value=nt,kt&&clearTimeout(kt),(Ve||Te)&&(kt=window.setTimeout(()=>{let je=te.value.trim();je&&_t&&ct&&(Ut(),te.value="",te.style.height="auto",$.sendMessage(je,{viaVoice:!0}))},y))},_t.onerror=ke=>{ke.error!=="no-speech"&&Ut()},_t.onend=()=>{if(ct){let ke=te.value.trim();ke&&ke!==L.trim()&&(te.value="",te.style.height="auto",$.sendMessage(ke,{viaVoice:!0})),Ut()}};try{if(_t.start(),ct=!0,vt.active=!0,c!=="system"&&(vt.manuallyDeactivated=!1),co(c),Nn(),G){let ke=(q=o.voiceRecognition)!=null?q:{};Ue={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:(O=ke.iconName)!=null?O:"mic",iconSize:parseFloat((ne=(ge=ke.iconSize)!=null?ge:(Ce=o.sendButton)==null?void 0:Ce.size)!=null?ne:"40")||24};let Ve=ke.recordingBackgroundColor,Te=ke.recordingIconColor,nt=ke.recordingBorderColor;if(G.classList.add("persona-voice-recording"),G.style.backgroundColor=Ve!=null?Ve:"var(--persona-voice-recording-bg, #ef4444)",G.style.color=Te!=null?Te:"var(--persona-voice-recording-indicator, #ffffff)",Te){let je=G.querySelector("svg");je&&je.setAttribute("stroke",Te)}nt&&(G.style.borderColor=nt),G.setAttribute("aria-label","Stop voice recognition")}}catch{Ut("system")}},Ut=(c="user")=>{if(ct){if(ct=!1,kt&&(clearTimeout(kt),kt=null),_t){try{_t.stop()}catch{}_t=null}if(vt.active=!1,co(c),Nn(),G){if(G.classList.remove("persona-voice-recording"),Ue){G.style.backgroundColor=Ue.backgroundColor,G.style.color=Ue.color,G.style.borderColor=Ue.borderColor;let p=G.querySelector("svg");p&&p.setAttribute("stroke",Ue.color||"currentColor"),Ue=null}G.setAttribute("aria-label","Start voice recognition")}}},So=(c,p)=>{var dt,pt,We,Ie,ze,Ye,Ct,H;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((dt=c==null?void 0:c.provider)==null?void 0:dt.type)==="runtype";if(!(h||y))return null;let N=b("div","persona-send-button-wrapper"),_=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");_.type="button",_.setAttribute("aria-label","Start voice recognition");let q=(pt=c==null?void 0:c.iconName)!=null?pt:"mic",O=(We=p==null?void 0:p.size)!=null?We:"40px",Ce=(Ie=c==null?void 0:c.iconSize)!=null?Ie:O,ge=parseFloat(Ce)||24,ne=(ze=c==null?void 0:c.backgroundColor)!=null?ze:p==null?void 0:p.backgroundColor,ke=(Ye=c==null?void 0:c.iconColor)!=null?Ye:p==null?void 0:p.textColor;_.style.width=Ce,_.style.height=Ce,_.style.minWidth=Ce,_.style.minHeight=Ce,_.style.fontSize="18px",_.style.lineHeight="1",ke?_.style.color=ke:_.style.color="var(--persona-text, #111827)";let Te=Me(q,ge,ke||"currentColor",1.5);Te?_.appendChild(Te):_.textContent="\u{1F3A4}",ne?_.style.backgroundColor=ne:_.style.backgroundColor="",c!=null&&c.borderWidth&&(_.style.borderWidth=c.borderWidth,_.style.borderStyle="solid"),c!=null&&c.borderColor&&(_.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(_.style.paddingLeft=c.paddingX,_.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(_.style.paddingTop=c.paddingY,_.style.paddingBottom=c.paddingY),N.appendChild(_);let nt=(Ct=c==null?void 0:c.tooltipText)!=null?Ct:"Start voice recognition";if(((H=c==null?void 0:c.showTooltip)!=null?H:!1)&&nt){let He=b("div","persona-send-button-tooltip");He.textContent=nt,N.appendChild(He)}return{micButton:_,micButtonWrapper:N}},Al=()=>{var p,h,y,L,N;if(!G||Ue)return;let c=(p=o.voiceRecognition)!=null?p:{};Ue={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:(h=c.iconName)!=null?h:"mic",iconSize:parseFloat((N=(L=c.iconSize)!=null?L:(y=o.sendButton)==null?void 0:y.size)!=null?N:"40")||24}},Tl=(c,p)=>{var N,_,q,O,Ce;if(!G)return;let h=G.querySelector("svg");h&&h.remove();let y=(Ce=Ue==null?void 0:Ue.iconSize)!=null?Ce:parseFloat((O=(q=(N=o.voiceRecognition)==null?void 0:N.iconSize)!=null?q:(_=o.sendButton)==null?void 0:_.size)!=null?O:"40")||24,L=Me(c,y,p,1.5);L&&G.appendChild(L)},oi=()=>{G&&G.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},zs=()=>{var L;if(!G)return;Al();let c=(L=o.voiceRecognition)!=null?L:{},p=c.recordingBackgroundColor,h=c.recordingIconColor,y=c.recordingBorderColor;if(oi(),G.classList.add("persona-voice-recording"),G.style.backgroundColor=p!=null?p:"var(--persona-voice-recording-bg, #ef4444)",G.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let N=G.querySelector("svg");N&&N.setAttribute("stroke",h)}y&&(G.style.borderColor=y),G.setAttribute("aria-label","Stop voice recognition")},Ag=()=>{var q,O,Ce,ge,ne,ke,Ve,Te;if(!G)return;Al();let c=(q=o.voiceRecognition)!=null?q:{},p=$.getVoiceInterruptionMode(),h=(O=c.processingIconName)!=null?O:"loader",y=(ge=(Ce=c.processingIconColor)!=null?Ce:Ue==null?void 0:Ue.color)!=null?ge:"",L=(ke=(ne=c.processingBackgroundColor)!=null?ne:Ue==null?void 0:Ue.backgroundColor)!=null?ke:"",N=(Te=(Ve=c.processingBorderColor)!=null?Ve:Ue==null?void 0:Ue.borderColor)!=null?Te:"";oi(),G.classList.add("persona-voice-processing"),G.style.backgroundColor=L,G.style.borderColor=N;let _=y||"currentColor";G.style.color=_,Tl(h,_),G.setAttribute("aria-label","Processing voice input"),p==="none"&&(G.style.cursor="default")},Tg=()=>{var Ce,ge,ne,ke,Ve,Te,nt,je,dt,pt,We,Ie;if(!G)return;Al();let c=(Ce=o.voiceRecognition)!=null?Ce:{},p=$.getVoiceInterruptionMode(),h=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",y=(ge=c.speakingIconName)!=null?ge:h,L=(Te=c.speakingIconColor)!=null?Te:p==="barge-in"?(ke=(ne=c.recordingIconColor)!=null?ne:Ue==null?void 0:Ue.color)!=null?ke:"":(Ve=Ue==null?void 0:Ue.color)!=null?Ve:"",N=(dt=c.speakingBackgroundColor)!=null?dt:p==="barge-in"?(nt=c.recordingBackgroundColor)!=null?nt:"var(--persona-voice-recording-bg, #ef4444)":(je=Ue==null?void 0:Ue.backgroundColor)!=null?je:"",_=(Ie=c.speakingBorderColor)!=null?Ie:p==="barge-in"?(pt=c.recordingBorderColor)!=null?pt:"":(We=Ue==null?void 0:Ue.borderColor)!=null?We:"";oi(),G.classList.add("persona-voice-speaking"),G.style.backgroundColor=N,G.style.borderColor=_;let q=L||"currentColor";G.style.color=q,Tl(y,q);let O=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";G.setAttribute("aria-label",O),p==="none"&&(G.style.cursor="default"),p==="barge-in"&&G.classList.add("persona-voice-recording")},dr=()=>{var c,p,h;G&&(oi(),Ue&&(G.style.backgroundColor=(c=Ue.backgroundColor)!=null?c:"",G.style.color=(p=Ue.color)!=null?p:"",G.style.borderColor=(h=Ue.borderColor)!=null?h:"",Tl(Ue.iconName,Ue.color||"currentColor"),Ue=null),G.style.cursor="",G.setAttribute("aria-label","Start voice recognition"))},ri=()=>{var c,p;if(((p=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:p.type)==="runtype"){let h=$.getVoiceStatus(),y=$.getVoiceInterruptionMode();if(y==="none"&&(h==="processing"||h==="speaking"))return;if(y==="cancel"&&(h==="processing"||h==="speaking")){$.stopVoicePlayback();return}if($.isBargeInActive()){$.stopVoicePlayback(),$.deactivateBargeIn().then(()=>{vt.active=!1,vt.manuallyDeactivated=!0,Nn(),co("user"),dr()});return}$.toggleVoice().then(()=>{vt.active=$.isVoiceActive(),vt.manuallyDeactivated=!$.isVoiceActive(),Nn(),co("user"),$.isVoiceActive()?zs():dr()});return}if(ct){let h=te.value.trim();vt.manuallyDeactivated=!0,Nn(),Ut("user"),h&&(te.value="",te.style.height="auto",$.sendMessage(h))}else vt.manuallyDeactivated=!1,Nn(),fn("user")};Un=ri,G&&(G.addEventListener("click",ri),bt.push(()=>{var c,p;((p=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:p.type)==="runtype"?($.isVoiceActive()&&$.toggleVoice(),dr()):Ut("system"),G&&G.removeEventListener("click",ri)}));let kg=s.on("assistant:complete",()=>{Rs&&(vt.active||vt.manuallyDeactivated||Rs==="assistant"&&!vt.lastUserMessageWasVoice||setTimeout(()=>{var c,p;!vt.active&&!vt.manuallyDeactivated&&(((p=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:p.type)==="runtype"?$.toggleVoice().then(()=>{vt.active=$.isVoiceActive(),co("auto"),$.isVoiceActive()&&zs()}):fn("auto"))},600))});bt.push(kg);let Eg=s.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});bt.push(Eg);let ss=()=>{Ot(!k,"user")},tn=null,nn=null;if(I&&!E()){let c=r.find(p=>p.renderLauncher);if(c!=null&&c.renderLauncher){let p=c.renderLauncher({config:o,defaultRenderer:()=>ka(o,ss).element,onToggle:ss});p&&(nn=p)}nn||(tn=ka(o,ss))}tn?e.appendChild(tn.element):nn&&e.appendChild(nn),cr(),io.render(o.suggestionChips,$,te,void 0,o.suggestionChipsConfig),Us(),os($.isStreaming()),gt()==="follow"?Do(!0):Os(),ja(),P&&(!I||E()?setTimeout(()=>rs(),0):k&&setTimeout(()=>rs(),200));let qs=()=>{var O,Ce,ge,ne,ke,Ve,Te,nt,je,dt,pt,We,Ie,ze,Ye,Ct,H,He,Oe,ve,Vt,Nt;if(E()){yn(),cr();return}let c=wn(o),p=(Ce=(O=o.launcher)==null?void 0:O.sidebarMode)!=null?Ce:!1,h=c||p||((ne=(ge=o.launcher)==null?void 0:ge.fullHeight)!=null?ne:!1),y=(ke=e.ownerDocument.defaultView)!=null?ke:window,L=(Te=(Ve=o.launcher)==null?void 0:Ve.mobileFullscreen)!=null?Te:!0,N=(je=(nt=o.launcher)==null?void 0:nt.mobileBreakpoint)!=null?je:640,_=y.innerWidth<=N,q=L&&_&&I;try{if(q){vo(),ds(e,o);return}if(x&&(x=!1,vo(),ds(e,o)),!I&&!c){pe.style.height="",pe.style.width="";return}if(!p&&!c){let Yt=(pt=(dt=o==null?void 0:o.launcher)==null?void 0:dt.width)!=null?pt:o==null?void 0:o.launcherWidth,St=Yt!=null?Yt:go;pe.style.width=St,pe.style.maxWidth=St}if(Ro(),!h){let Yt=y.innerHeight,St=64,jt=(Ie=(We=o.launcher)==null?void 0:We.heightOffset)!=null?Ie:0,Zn=Math.max(200,Yt-St),rn=Math.min(640,Zn),Xe=Math.max(200,rn-jt);pe.style.height=`${Xe}px`}}finally{if(yn(),cr(),k&&I){let St=((ze=e.ownerDocument.defaultView)!=null?ze:window).innerWidth<=((Ct=(Ye=o.launcher)==null?void 0:Ye.mobileBreakpoint)!=null?Ct:640),jt=(He=(H=o.launcher)==null?void 0:H.sidebarMode)!=null?He:!1,Zn=(ve=(Oe=o.launcher)==null?void 0:Oe.mobileFullscreen)!=null?ve:!0,rn=wn(o)&&Zn&&St,Xe=jt||Zn&&St&&I||rn;if(Xe&&!en){let Wt=e.getRootNode(),dn=Wt instanceof ShadowRoot?Wt.host:e.closest(".persona-host");dn&&!Zt&&(Zt=nc(dn,(Nt=(Vt=o.launcher)==null?void 0:Vt.zIndex)!=null?Nt:Mn)),en=oc(e.ownerDocument)}else Xe||(Zt==null||Zt(),Zt=null,en==null||en(),en=null)}}};qs();let Uc=(jd=e.ownerDocument.defaultView)!=null?jd:window;if(Uc.addEventListener("resize",qs),bt.push(()=>Uc.removeEventListener("resize",qs)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{yn()});c.observe($e),bt.push(()=>c.disconnect())}Qn=fe.scrollTop;let zc=Qo(fe),Mg=()=>{let c=fe.getRootNode(),p=typeof c.getSelection=="function"?c.getSelection():null;return p!=null?p:fe.ownerDocument.getSelection()},kl=()=>Zm(Mg(),fe),qc=()=>{let c=fe.scrollTop,p=Qo(fe),h=p<zc;if(zc=p,gt()!=="follow"){Qn=c,_n();return}let{action:y,nextLastScrollTop:L}=Ni({following:Jn.isFollowing(),currentScrollTop:c,lastScrollTop:Qn,nearBottom:Vr(fe,Zr),userScrollThreshold:za,isAutoScrolling:Co||Ar||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Qn=L,y==="resume"){kl()||Ho();return}y==="pause"&&ns()};if(fe.addEventListener("scroll",qc,{passive:!0}),bt.push(()=>fe.removeEventListener("scroll",qc)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Xa()});c.observe(tt),c.observe(fe),bt.push(()=>c.disconnect())}let jc=()=>{gt()==="follow"&&Jn.isFollowing()&&kl()&&ns()},Kc=fe.ownerDocument;Kc.addEventListener("selectionchange",jc),bt.push(()=>{Kc.removeEventListener("selectionchange",jc)});let Gc=c=>{if(gt()!=="follow")return;let p=_i({following:Jn.isFollowing(),deltaY:c.deltaY,nearBottom:Vr(fe,Zr),resumeWhenNearBottom:!0});p==="pause"?ns():p==="resume"&&!kl()&&Ho()};fe.addEventListener("wheel",Gc,{passive:!0}),bt.push(()=>fe.removeEventListener("wheel",Gc)),Qe.addEventListener("click",()=>{kr(),fe.scrollTop=fe.scrollHeight,Qn=fe.scrollTop,Ho(),Do(!0),_n()}),bt.push(()=>Qe.remove()),bt.push(()=>{Ws(),kr()});let Yc=()=>{F&&(lo&&(F.removeEventListener("click",lo),lo=null),S()?(F.style.display="",lo=()=>{Ot(!1,"user")},F.addEventListener("click",lo)):F.style.display="none")};Yc(),(()=>{let{clearChatButton:c}=Be;c&&c.addEventListener("click",()=>{$.clearMessages(),qo.clear(),Ho(),Ss(Be.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 p=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}d={},M.syncFromMetadata(),ye==null||ye.clear(),be==null||be.reset(),K==null||K.update()})})(),Dt&&Dt.addEventListener("submit",U),te==null||te.addEventListener("keydown",Ze),te==null||te.addEventListener("input",at),te==null||te.addEventListener("paste",$t);let Xc=(Kd=e.ownerDocument)!=null?Kd:document;Xc.addEventListener("keydown",Ht,!0);let Jc="persona-attachment-drop-active",js=0,El=()=>{js=0,j.classList.remove(Jc)},as=()=>{var c;return((c=o.attachments)==null?void 0:c.enabled)===!0&&At!==null},Qc=c=>{!cl(c.dataTransfer)||!as()||(js++,js===1&&j.classList.add(Jc))},Zc=c=>{!cl(c.dataTransfer)||!as()||(js--,js<=0&&El())},ed=c=>{!cl(c.dataTransfer)||!as()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},td=c=>{var h;if(!cl(c.dataTransfer)||!as())return;c.preventDefault(),c.stopPropagation(),El();let p=Array.from((h=c.dataTransfer.files)!=null?h:[]);p.length!==0&&At.handleFiles(p)},pr=!0;j.addEventListener("dragenter",Qc,pr),j.addEventListener("dragleave",Zc,pr),e.addEventListener("dragover",ed,pr),e.addEventListener("drop",td,pr);let si=e.ownerDocument,nd=c=>{as()&&c.preventDefault()},od=c=>{as()&&c.preventDefault()};si.addEventListener("dragover",nd),si.addEventListener("drop",od),bt.push(()=>{Dt&&Dt.removeEventListener("submit",U),te==null||te.removeEventListener("keydown",Ze),te==null||te.removeEventListener("input",at),te==null||te.removeEventListener("paste",$t),Xc.removeEventListener("keydown",Ht,!0)}),bt.push(()=>{j.removeEventListener("dragenter",Qc,pr),j.removeEventListener("dragleave",Zc,pr),e.removeEventListener("dragover",ed,pr),e.removeEventListener("drop",td,pr),si.removeEventListener("dragover",nd),si.removeEventListener("drop",od),El()}),bt.push(()=>{$.cancel()}),tn?bt.push(()=>{tn==null||tn.destroy()}):nn&&bt.push(()=>{nn==null||nn.remove()});let cn={update(c){var Fo,un,Bn,fo,Rr,Pr,ai,Ks,ep,tp,np,op,rp,sp,ap,ip,lp,cp,dp,pp,up,mp,fp,gp,hp,bp,yp,vp,xp,wp,Cp,Sp,Ap,Tp,kp,Ep,Mp,Lp,Ip,Rp,Pp,Wp,Bp,Hp,Dp,Fp,Op,Np,_p,Vp,$p,Up,zp,qp,jp,Kp,Gp,Yp,Xp,Jp,Qp,Zp,eu,tu,nu,ou,ru,su,au,iu,lu,cu,du,pu,uu,mu,fu,gu,hu,bu,yu,vu,xu,wu,Cu,Su,Au,Tu,ku,Eu,Mu,Lu,Iu,Ru,Pu,Wu,Bu,Hu,Du,Fu,Ou,Nu,_u,Vu,$u,Uu,zu,qu,ju,Ku,Gu,Yu,Xu,Ju,Qu;let p=o.toolCall,h=o.messageActions,y=(Fo=o.layout)==null?void 0:Fo.messages,L=o.colorScheme,N=o.loadingIndicator,_=o.iterationDisplay,q=(un=o.features)==null?void 0:un.showReasoning,O=(Bn=o.features)==null?void 0:Bn.showToolCalls,Ce=(fo=o.features)==null?void 0:fo.toolCallDisplay,ge=(Rr=o.features)==null?void 0:Rr.reasoningDisplay;o={...o,...c},vo(),ds(e,o),il(e,o),ll(e,o),Yn(),o.colorScheme!==L&&rr();let ne=Cc.getForInstance(o.plugins);r.length=0,r.push(...ne),I=(ai=(Pr=o.launcher)==null?void 0:Pr.enabled)!=null?ai:!0,R=(ep=(Ks=o.launcher)==null?void 0:Ks.autoExpand)!=null?ep:!1,me=(np=(tp=o.features)==null?void 0:tp.showReasoning)!=null?np:!0,de=(rp=(op=o.features)==null?void 0:op.showToolCalls)!=null?rp:!0,xe=(ap=(sp=o.features)==null?void 0:sp.scrollToBottom)!=null?ap:{};let ke=gt();De=(lp=(ip=o.features)==null?void 0:ip.scrollBehavior)!=null?lp:{},ke!==gt()&&(kr(),Ho()),Lo(),_n();let Ve=Ee;if(Ee=(dp=(cp=o.features)==null?void 0:cp.showEventStreamToggle)!=null?dp:!1,Ee&&!Ve){if(ye||(J=new Ra(le),ye=new Ia(se,J),be=be!=null?be:new Pa,J.open().then(()=>ye==null?void 0:ye.restore()).catch(()=>{}),$.setSSEEventCallback((Q,Et)=>{var zt;(zt=o.onSSEEvent)==null||zt.call(o,Q,Et),be==null||be.processEvent(Q,Et),ye.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Q,timestamp:Date.now(),payload:JSON.stringify(Et)})})),!wt&&_e){let Q=(up=(pp=o.features)==null?void 0:pp.eventStream)==null?void 0:up.classNames,Et="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:"");wt=b("button",Et),wt.style.width="28px",wt.style.height="28px",wt.style.color=Dn.actionIconColor,wt.type="button",wt.setAttribute("aria-label","Event Stream"),wt.title="Event Stream";let zt=Me("activity","18px","currentColor",1.5);zt&&wt.appendChild(zt);let ft=Be.clearChatButtonWrapper,Bt=Be.closeButtonWrapper,gn=ft||Bt;gn&&gn.parentNode===_e?_e.insertBefore(wt,gn):_e.appendChild(wt),wt.addEventListener("click",()=>{ae?yo():Vo()})}}else!Ee&&Ve&&(yo(),wt&&(wt.remove(),wt=null),ye==null||ye.clear(),J==null||J.destroy(),ye=null,J=null,be==null||be.reset(),be=null);if(((mp=o.launcher)==null?void 0:mp.enabled)===!1&&tn&&(tn.destroy(),tn=null),((fp=o.launcher)==null?void 0:fp.enabled)===!1&&nn&&(nn.remove(),nn=null),((gp=o.launcher)==null?void 0:gp.enabled)!==!1&&!tn&&!nn){let Q=r.find(Et=>Et.renderLauncher);if(Q!=null&&Q.renderLauncher){let Et=Q.renderLauncher({config:o,defaultRenderer:()=>ka(o,ss).element,onToggle:ss});Et&&(nn=Et,e.appendChild(nn))}nn||(tn=ka(o,ss),e.appendChild(tn.element))}tn&&tn.update(o),Fe&&((hp=o.launcher)==null?void 0:hp.title)!==void 0&&(Fe.textContent=o.launcher.title),Ke&&((bp=o.launcher)==null?void 0:bp.subtitle)!==void 0&&(Ke.textContent=o.launcher.subtitle);let Te=(yp=o.layout)==null?void 0:yp.header;if((Te==null?void 0:Te.layout)!==w&&_e){let Q=Te?Ki(o,Te,{showClose:S(),onClose:()=>Ot(!1,"user")}):$r({config:o,showClose:S(),onClose:()=>Ot(!1,"user")});_e.replaceWith(Q.header),_e=Q.header,ue=Q.iconHolder,Fe=Q.headerTitle,Ke=Q.headerSubtitle,F=Q.closeButton,w=Te==null?void 0:Te.layout}else if(Te&&(ue&&(ue.style.display=Te.showIcon===!1?"none":""),Fe&&(Fe.style.display=Te.showTitle===!1?"none":""),Ke&&(Ke.style.display=Te.showSubtitle===!1?"none":""),F&&(F.style.display=Te.showCloseButton===!1?"none":""),Be.clearChatButtonWrapper)){let Q=Te.showClearChat;if(Q!==void 0){Be.clearChatButtonWrapper.style.display=Q?"":"none";let{closeButtonWrapper:Et}=Be;Et&&!Et.classList.contains("persona-absolute")&&(Q?Et.classList.remove("persona-ml-auto"):Et.classList.add("persona-ml-auto"))}}let je=((vp=o.layout)==null?void 0:vp.showHeader)!==!1;_e&&(_e.style.display=je?"":"none");let dt=((xp=o.layout)==null?void 0:xp.showFooter)!==!1;$e&&($e.style.display=dt?"":"none"),yn(),_n(),I!==W?I?Ot(R,"auto"):(k=!0,cr()):R!==D&&Ot(R,"auto"),D=R,W=I,qs(),Yc();let Ie=JSON.stringify(c.toolCall)!==JSON.stringify(p),ze=JSON.stringify(o.messageActions)!==JSON.stringify(h),Ye=JSON.stringify((wp=o.layout)==null?void 0:wp.messages)!==JSON.stringify(y),Ct=((Cp=o.loadingIndicator)==null?void 0:Cp.render)!==(N==null?void 0:N.render)||((Sp=o.loadingIndicator)==null?void 0:Sp.renderIdle)!==(N==null?void 0:N.renderIdle)||((Ap=o.loadingIndicator)==null?void 0:Ap.showBubble)!==(N==null?void 0:N.showBubble),H=o.iterationDisplay!==_,He=((kp=(Tp=o.features)==null?void 0:Tp.showReasoning)!=null?kp:!0)!==(q!=null?q:!0)||((Mp=(Ep=o.features)==null?void 0:Ep.showToolCalls)!=null?Mp:!0)!==(O!=null?O:!0)||JSON.stringify((Lp=o.features)==null?void 0:Lp.toolCallDisplay)!==JSON.stringify(Ce)||JSON.stringify((Ip=o.features)==null?void 0:Ip.reasoningDisplay)!==JSON.stringify(ge);(Ie||ze||Ye||Ct||H||He)&&$&&(Is++,Er(tt,$.getMessages(),he));let ve=(Rp=o.launcher)!=null?Rp:{},Vt=(Pp=ve.headerIconHidden)!=null?Pp:!1,Nt=(Bp=(Wp=o.layout)==null?void 0:Wp.header)==null?void 0:Bp.showIcon,Yt=Vt||Nt===!1,St=ve.headerIconName,jt=(Hp=ve.headerIconSize)!=null?Hp:"48px";if(ue){let Q=j.querySelector(".persona-border-b-persona-divider"),Et=Q==null?void 0:Q.querySelector(".persona-flex-col");if(Yt)ue.style.display="none",Q&&Et&&!Q.contains(Et)&&Q.insertBefore(Et,Q.firstChild);else{if(ue.style.display="",ue.style.height=jt,ue.style.width=jt,Q&&Et&&(Q.contains(ue)?ue.nextSibling!==Et&&(ue.remove(),Q.insertBefore(ue,Et)):Q.insertBefore(ue,Et)),St){let ft=parseFloat(jt)||24,Bt=Me(St,ft*.6,"#ffffff",2);Bt?ue.replaceChildren(Bt):ue.textContent=(Dp=ve.agentIconText)!=null?Dp:"\u{1F4AC}"}else if(ve.iconUrl){let ft=ue.querySelector("img");if(ft)ft.src=ve.iconUrl,ft.style.height=jt,ft.style.width=jt;else{let Bt=document.createElement("img");Bt.src=ve.iconUrl,Bt.alt="",Bt.className="persona-rounded-xl persona-object-cover",Bt.style.height=jt,Bt.style.width=jt,ue.replaceChildren(Bt)}}else{let ft=ue.querySelector("svg"),Bt=ue.querySelector("img");(ft||Bt)&&ue.replaceChildren(),ue.textContent=(Fp=ve.agentIconText)!=null?Fp:"\u{1F4AC}"}let zt=ue.querySelector("img");zt&&(zt.style.height=jt,zt.style.width=jt)}}let Zn=(Np=(Op=o.layout)==null?void 0:Op.header)==null?void 0:Np.showTitle,rn=(Vp=(_p=o.layout)==null?void 0:_p.header)==null?void 0:Vp.showSubtitle;if(Fe&&(Fe.style.display=Zn===!1?"none":""),Ke&&(Ke.style.display=rn===!1?"none":""),F){((Up=($p=o.layout)==null?void 0:$p.header)==null?void 0:Up.showCloseButton)===!1?F.style.display="none":F.style.display="";let Et=(zp=ve.closeButtonSize)!=null?zp:"32px",zt=(qp=ve.closeButtonPlacement)!=null?qp:"inline";F.style.height=Et,F.style.width=Et;let{closeButtonWrapper:ft}=Be,Bt=zt==="top-right",gn=ft==null?void 0:ft.classList.contains("persona-absolute");if(ft&&Bt!==gn)if(ft.remove(),Bt)ft.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",j.style.position="relative",j.appendChild(ft);else{let ht=(Kp=(jp=ve.clearChat)==null?void 0:jp.placement)!=null?Kp:"inline",hn=(Yp=(Gp=ve.clearChat)==null?void 0:Gp.enabled)!=null?Yp:!0;ft.className=hn&&ht==="inline"?"":"persona-ml-auto";let $n=j.querySelector(".persona-border-b-persona-divider");$n&&$n.appendChild(ft)}if(F.style.color=ve.closeButtonColor||Dn.actionIconColor,ve.closeButtonBackgroundColor?(F.style.backgroundColor=ve.closeButtonBackgroundColor,F.classList.remove("hover:persona-bg-gray-100")):(F.style.backgroundColor="",F.classList.add("hover:persona-bg-gray-100")),ve.closeButtonBorderWidth||ve.closeButtonBorderColor){let ht=ve.closeButtonBorderWidth||"0px",hn=ve.closeButtonBorderColor||"transparent";F.style.border=`${ht} solid ${hn}`,F.classList.remove("persona-border-none")}else F.style.border="",F.classList.add("persona-border-none");ve.closeButtonBorderRadius?(F.style.borderRadius=ve.closeButtonBorderRadius,F.classList.remove("persona-rounded-full")):(F.style.borderRadius="",F.classList.add("persona-rounded-full")),ve.closeButtonPaddingX?(F.style.paddingLeft=ve.closeButtonPaddingX,F.style.paddingRight=ve.closeButtonPaddingX):(F.style.paddingLeft="",F.style.paddingRight=""),ve.closeButtonPaddingY?(F.style.paddingTop=ve.closeButtonPaddingY,F.style.paddingBottom=ve.closeButtonPaddingY):(F.style.paddingTop="",F.style.paddingBottom="");let kn=(Xp=ve.closeButtonIconName)!=null?Xp:"x",Ao=(Jp=ve.closeButtonIconText)!=null?Jp:"\xD7";F.innerHTML="";let Hn=Me(kn,"28px","currentColor",1);Hn?F.appendChild(Hn):F.textContent=Ao;let on=(Qp=ve.closeButtonTooltipText)!=null?Qp:"Close chat",to=(Zp=ve.closeButtonShowTooltip)!=null?Zp:!0;if(F.setAttribute("aria-label",on),ft&&(ft._cleanupTooltip&&(ft._cleanupTooltip(),delete ft._cleanupTooltip),to&&on)){let ht=null,hn=()=>{if(ht||!F)return;let Wr=F.ownerDocument,Gs=Wr.body;if(!Gs)return;ht=Oo(Wr,"div","persona-clear-chat-tooltip"),ht.textContent=on;let Ys=Oo(Wr,"div");Ys.className="persona-clear-chat-tooltip-arrow",ht.appendChild(Ys);let Br=F.getBoundingClientRect();ht.style.position="fixed",ht.style.zIndex=String(gr),ht.style.left=`${Br.left+Br.width/2}px`,ht.style.top=`${Br.top-8}px`,ht.style.transform="translate(-50%, -100%)",Gs.appendChild(ht)},$n=()=>{ht&&ht.parentNode&&(ht.parentNode.removeChild(ht),ht=null)};ft.addEventListener("mouseenter",hn),ft.addEventListener("mouseleave",$n),F.addEventListener("focus",hn),F.addEventListener("blur",$n),ft._cleanupTooltip=()=>{$n(),ft&&(ft.removeEventListener("mouseenter",hn),ft.removeEventListener("mouseleave",$n)),F&&(F.removeEventListener("focus",hn),F.removeEventListener("blur",$n))}}}let{clearChatButton:Xe,clearChatButtonWrapper:Wt}=Be;if(Xe){let Q=(eu=ve.clearChat)!=null?eu:{},Et=(tu=Q.enabled)!=null?tu:!0,zt=(ou=(nu=o.layout)==null?void 0:nu.header)==null?void 0:ou.showClearChat,ft=zt!==void 0?zt:Et,Bt=(ru=Q.placement)!=null?ru:"inline";if(Wt){Wt.style.display=ft?"":"none";let{closeButtonWrapper:gn}=Be;!E()&&gn&&!gn.classList.contains("persona-absolute")&&(ft?gn.classList.remove("persona-ml-auto"):gn.classList.add("persona-ml-auto"));let kn=Bt==="top-right",Ao=Wt.classList.contains("persona-absolute");if(!E()&&kn!==Ao&&ft){if(Wt.remove(),kn)Wt.className="persona-absolute persona-top-4 persona-z-50",Wt.style.right="48px",j.style.position="relative",j.appendChild(Wt);else{Wt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Wt.style.right="";let on=j.querySelector(".persona-border-b-persona-divider"),to=Be.closeButtonWrapper;on&&to&&to.parentElement===on?on.insertBefore(Wt,to):on&&on.appendChild(Wt)}let Hn=Be.closeButtonWrapper;Hn&&!Hn.classList.contains("persona-absolute")&&(kn?Hn.classList.add("persona-ml-auto"):Hn.classList.remove("persona-ml-auto"))}}if(ft){if(!E()){let ht=(su=Q.size)!=null?su:"32px";Xe.style.height=ht,Xe.style.width=ht}let gn=(au=Q.iconName)!=null?au:"refresh-cw",kn=(iu=Q.iconColor)!=null?iu:"";Xe.style.color=kn||Dn.actionIconColor,Xe.innerHTML="";let Ao=E()?"14px":"20px",Hn=Me(gn,Ao,"currentColor",2);if(Hn&&Xe.appendChild(Hn),Q.backgroundColor?(Xe.style.backgroundColor=Q.backgroundColor,Xe.classList.remove("hover:persona-bg-gray-100")):(Xe.style.backgroundColor="",Xe.classList.add("hover:persona-bg-gray-100")),Q.borderWidth||Q.borderColor){let ht=Q.borderWidth||"0px",hn=Q.borderColor||"transparent";Xe.style.border=`${ht} solid ${hn}`,Xe.classList.remove("persona-border-none")}else Xe.style.border="",Xe.classList.add("persona-border-none");Q.borderRadius?(Xe.style.borderRadius=Q.borderRadius,Xe.classList.remove("persona-rounded-full")):(Xe.style.borderRadius="",Xe.classList.add("persona-rounded-full")),Q.paddingX?(Xe.style.paddingLeft=Q.paddingX,Xe.style.paddingRight=Q.paddingX):(Xe.style.paddingLeft="",Xe.style.paddingRight=""),Q.paddingY?(Xe.style.paddingTop=Q.paddingY,Xe.style.paddingBottom=Q.paddingY):(Xe.style.paddingTop="",Xe.style.paddingBottom="");let on=(lu=Q.tooltipText)!=null?lu:"Clear chat",to=(cu=Q.showTooltip)!=null?cu:!0;if(Xe.setAttribute("aria-label",on),Wt&&(Wt._cleanupTooltip&&(Wt._cleanupTooltip(),delete Wt._cleanupTooltip),to&&on)){let ht=null,hn=()=>{if(ht||!Xe)return;let Wr=Xe.ownerDocument,Gs=Wr.body;if(!Gs)return;ht=Oo(Wr,"div","persona-clear-chat-tooltip"),ht.textContent=on;let Ys=Oo(Wr,"div");Ys.className="persona-clear-chat-tooltip-arrow",ht.appendChild(Ys);let Br=Xe.getBoundingClientRect();ht.style.position="fixed",ht.style.zIndex=String(gr),ht.style.left=`${Br.left+Br.width/2}px`,ht.style.top=`${Br.top-8}px`,ht.style.transform="translate(-50%, -100%)",Gs.appendChild(ht)},$n=()=>{ht&&ht.parentNode&&(ht.parentNode.removeChild(ht),ht=null)};Wt.addEventListener("mouseenter",hn),Wt.addEventListener("mouseleave",$n),Xe.addEventListener("focus",hn),Xe.addEventListener("blur",$n),Wt._cleanupTooltip=()=>{$n(),Wt&&(Wt.removeEventListener("mouseenter",hn),Wt.removeEventListener("mouseleave",$n)),Xe&&(Xe.removeEventListener("focus",hn),Xe.removeEventListener("blur",$n))}}}}let dn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Ac],mo=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Wa.message,Wa.messageAndClick];M=Tc({parsers:dn,handlers:mo,getSessionMetadata:g,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),he=tg(o,M,Y),$.updateConfig(o),Er(tt,$.getMessages(),he),io.render(o.suggestionChips,$,te,void 0,o.suggestionChipsConfig),Us(),os($.isStreaming());let eo=((du=o.voiceRecognition)==null?void 0:du.enabled)===!0,Mr=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Lr=((uu=(pu=o.voiceRecognition)==null?void 0:pu.provider)==null?void 0:uu.type)==="runtype";if(eo&&(Mr||Lr))if(!G||!xt){let Q=So(o.voiceRecognition,o.sendButton);Q&&(G=Q.micButton,xt=Q.micButtonWrapper,Kt.insertBefore(xt,Fn),G.addEventListener("click",ri),G.disabled=$.isStreaming())}else{let Q=(mu=o.voiceRecognition)!=null?mu:{},Et=(fu=o.sendButton)!=null?fu:{},zt=(gu=Q.iconName)!=null?gu:"mic",ft=(hu=Et.size)!=null?hu:"40px",Bt=(bu=Q.iconSize)!=null?bu:ft,gn=parseFloat(Bt)||24;G.style.width=Bt,G.style.height=Bt,G.style.minWidth=Bt,G.style.minHeight=Bt;let kn=(vu=(yu=Q.iconColor)!=null?yu:Et.textColor)!=null?vu:"currentColor";G.innerHTML="";let Ao=Me(zt,gn,kn,2);Ao?G.appendChild(Ao):G.textContent="\u{1F3A4}";let Hn=(xu=Q.backgroundColor)!=null?xu:Et.backgroundColor;Hn?G.style.backgroundColor=Hn:G.style.backgroundColor="",kn?G.style.color=kn:G.style.color="var(--persona-text, #111827)",Q.borderWidth?(G.style.borderWidth=Q.borderWidth,G.style.borderStyle="solid"):(G.style.borderWidth="",G.style.borderStyle=""),Q.borderColor?G.style.borderColor=Q.borderColor:G.style.borderColor="",Q.paddingX?(G.style.paddingLeft=Q.paddingX,G.style.paddingRight=Q.paddingX):(G.style.paddingLeft="",G.style.paddingRight=""),Q.paddingY?(G.style.paddingTop=Q.paddingY,G.style.paddingBottom=Q.paddingY):(G.style.paddingTop="",G.style.paddingBottom="");let on=xt==null?void 0:xt.querySelector(".persona-send-button-tooltip"),to=(wu=Q.tooltipText)!=null?wu:"Start voice recognition";if(((Cu=Q.showTooltip)!=null?Cu:!1)&&to)if(on)on.textContent=to,on.style.display="";else{let hn=document.createElement("div");hn.className="persona-send-button-tooltip",hn.textContent=to,xt==null||xt.insertBefore(hn,G)}else on&&(on.style.display="none");xt.style.display="",G.disabled=$.isStreaming()}else G&&xt&&(xt.style.display="none",((Au=(Su=o.voiceRecognition)==null?void 0:Su.provider)==null?void 0:Au.type)==="runtype"?$.isVoiceActive()&&$.toggleVoice():ct&&Ut());if(((Tu=o.attachments)==null?void 0:Tu.enabled)===!0)if(!Se||!st){let Q=(ku=o.attachments)!=null?ku:{},zt=(Mu=((Eu=o.sendButton)!=null?Eu:{}).size)!=null?Mu:"40px";et||(et=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),et.style.display="none",Dt.insertBefore(et,te)),ce||(ce=document.createElement("input"),ce.type="file",ce.accept=((Lu=Q.allowedTypes)!=null?Lu:Jo).join(","),ce.multiple=((Iu=Q.maxFiles)!=null?Iu:4)>1,ce.style.display="none",ce.setAttribute("aria-label","Attach files"),Dt.insertBefore(ce,te)),Se=b("div","persona-send-button-wrapper"),st=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),st.type="button",st.setAttribute("aria-label",(Ru=Q.buttonTooltipText)!=null?Ru:"Attach file");let ft=(Pu=Q.buttonIconName)!=null?Pu:"paperclip",Bt=zt,gn=parseFloat(Bt)||40,kn=Math.round(gn*.6);st.style.width=Bt,st.style.height=Bt,st.style.minWidth=Bt,st.style.minHeight=Bt,st.style.fontSize="18px",st.style.lineHeight="1",st.style.backgroundColor="transparent",st.style.color="var(--persona-primary, #111827)",st.style.border="none",st.style.borderRadius="6px",st.style.transition="background-color 0.15s ease",st.addEventListener("mouseenter",()=>{st.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),st.addEventListener("mouseleave",()=>{st.style.backgroundColor="transparent"});let Ao=Me(ft,kn,"currentColor",1.5);Ao?st.appendChild(Ao):st.textContent="\u{1F4CE}",st.addEventListener("click",to=>{to.preventDefault(),ce==null||ce.click()}),Se.appendChild(st);let Hn=(Wu=Q.buttonTooltipText)!=null?Wu:"Attach file",on=b("div","persona-send-button-tooltip");on.textContent=Hn,Se.appendChild(on),Pt.append(Se),!At&&ce&&et&&(At=va.fromConfig(Q),At.setPreviewsContainer(et),ce.addEventListener("change",async()=>{At&&(ce!=null&&ce.files)&&(await At.handleFileSelect(ce.files),ce.value="")})),j.querySelector(".persona-attachment-drop-overlay")||j.appendChild(ng(Q.dropOverlay))}else{Se.style.display="";let Q=(Bu=o.attachments)!=null?Bu:{};ce&&(ce.accept=((Hu=Q.allowedTypes)!=null?Hu:Jo).join(","),ce.multiple=((Du=Q.maxFiles)!=null?Du:4)>1),At&&At.updateConfig({allowedTypes:Q.allowedTypes,maxFileSize:Q.maxFileSize,maxFiles:Q.maxFiles})}else Se&&(Se.style.display="none"),At&&At.clearAttachments(),(Fu=j.querySelector(".persona-attachment-drop-overlay"))==null||Fu.remove();let Xt=(Ou=o.sendButton)!=null?Ou:{},Ir=(Nu=Xt.useIcon)!=null?Nu:!1,ur=(_u=Xt.iconText)!=null?_u:"\u2191",mr=Xt.iconName,Xo=(Vu=Xt.tooltipText)!=null?Vu:"Send message",rt=($u=Xt.showTooltip)!=null?$u:!1,xn=(Uu=Xt.size)!=null?Uu:"40px",Wn=Xt.backgroundColor,sn=Xt.textColor;if(Ir){if(qe.style.width=xn,qe.style.height=xn,qe.style.minWidth=xn,qe.style.minHeight=xn,qe.style.fontSize="18px",qe.style.lineHeight="1",qe.innerHTML="",sn?qe.style.color=sn:qe.style.color="var(--persona-button-primary-fg, #ffffff)",mr){let Q=parseFloat(xn)||24,Et=(sn==null?void 0:sn.trim())||"currentColor",zt=Me(mr,Q,Et,2);zt?qe.appendChild(zt):qe.textContent=ur}else qe.textContent=ur;qe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Wn?(qe.style.backgroundColor=Wn,qe.classList.remove("persona-bg-persona-primary")):(qe.style.backgroundColor="",qe.classList.add("persona-bg-persona-primary"))}else qe.textContent=(qu=(zu=o.copy)==null?void 0:zu.sendButtonLabel)!=null?qu:"Send",qe.style.width="",qe.style.height="",qe.style.minWidth="",qe.style.minHeight="",qe.style.fontSize="",qe.style.lineHeight="",qe.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?(qe.style.backgroundColor=Wn,qe.classList.remove("persona-bg-persona-accent")):qe.classList.add("persona-bg-persona-accent"),sn?qe.style.color=sn:qe.classList.add("persona-text-white");Xt.borderWidth?(qe.style.borderWidth=Xt.borderWidth,qe.style.borderStyle="solid"):(qe.style.borderWidth="",qe.style.borderStyle=""),Xt.borderColor?qe.style.borderColor=Xt.borderColor:qe.style.borderColor="",Xt.paddingX?(qe.style.paddingLeft=Xt.paddingX,qe.style.paddingRight=Xt.paddingX):(qe.style.paddingLeft="",qe.style.paddingRight=""),Xt.paddingY?(qe.style.paddingTop=Xt.paddingY,qe.style.paddingBottom=Xt.paddingY):(qe.style.paddingTop="",qe.style.paddingBottom="");let ut=Fn==null?void 0:Fn.querySelector(".persona-send-button-tooltip");if(rt&&Xo)if(ut)ut.textContent=Xo,ut.style.display="";else{let Q=document.createElement("div");Q.className="persona-send-button-tooltip",Q.textContent=Xo,Fn==null||Fn.insertBefore(Q,qe)}else ut&&(ut.style.display="none");let yt=(Xu=(ju=o.layout)==null?void 0:ju.contentMaxWidth)!=null?Xu:E()?(Yu=(Gu=(Ku=o.launcher)==null?void 0:Ku.composerBar)==null?void 0:Gu.contentMaxWidth)!=null?Yu:"720px":void 0;yt?(tt.style.maxWidth=yt,tt.style.marginLeft="auto",tt.style.marginRight="auto",tt.style.width="100%",Dt&&(Dt.style.maxWidth=yt,Dt.style.marginLeft="auto",Dt.style.marginRight="auto"),Mt&&(Mt.style.maxWidth=yt,Mt.style.marginLeft="auto",Mt.style.marginRight="auto")):(tt.style.maxWidth="",tt.style.marginLeft="",tt.style.marginRight="",tt.style.width="",Dt&&(Dt.style.maxWidth="",Dt.style.marginLeft="",Dt.style.marginRight=""),Mt&&(Mt.style.maxWidth="",Mt.style.marginLeft="",Mt.style.marginRight=""));let mt=(Ju=o.statusIndicator)!=null?Ju:{},Vn=(Qu=mt.visible)!=null?Qu:!0;if(an.style.display=Vn?"":"none",$){let Q=$.getStatus();lt(an,(zt=>{var ft,Bt,gn,kn;return zt==="idle"?(ft=mt.idleText)!=null?ft:En.idle:zt==="connecting"?(Bt=mt.connectingText)!=null?Bt:En.connecting:zt==="connected"?(gn=mt.connectedText)!=null?gn:En.connected:zt==="error"?(kn=mt.errorText)!=null?kn:En.error:En[zt]})(Q),mt,Q)}an.classList.remove("persona-text-left","persona-text-center","persona-text-right");let pn=mt.align==="left"?"persona-text-left":mt.align==="center"?"persona-text-center":"persona-text-right";an.classList.add(pn)},open(){S()&&Ot(!0,"api")},close(){S()&&Ot(!1,"api")},toggle(){S()&&Ot(!k,"api")},clearChat(){Rn=!1,$.clearMessages(),qo.clear(),Ho();try{localStorage.removeItem(Ts),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ts}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ts)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let p=i.clear();p instanceof Promise&&p.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}d={},M.syncFromMetadata(),ye==null||ye.clear(),be==null||be.reset(),K==null||K.update()},setMessage(c){return!te||$.isStreaming()?!1:(!k&&S()&&Ot(!0,"system"),te.value=c,te.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if($.isStreaming())return!1;let p=(c==null?void 0:c.trim())||te.value.trim();return p?(!k&&S()&&Ot(!0,"system"),te.value="",te.style.height="auto",$.sendMessage(p),!0):!1},startVoiceRecognition(){var p,h;return $.isStreaming()?!1:((h=(p=o.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype"?($.isVoiceActive()||(!k&&S()&&Ot(!0,"system"),vt.manuallyDeactivated=!1,Nn(),$.toggleVoice().then(()=>{vt.active=$.isVoiceActive(),co("user"),$.isVoiceActive()&&zs()})),!0):ct?!0:Tn()?(!k&&S()&&Ot(!0,"system"),vt.manuallyDeactivated=!1,Nn(),fn("user"),!0):!1},stopVoiceRecognition(){var c,p;return((p=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:p.type)==="runtype"?$.isVoiceActive()?($.toggleVoice().then(()=>{vt.active=!1,vt.manuallyDeactivated=!0,Nn(),co("user"),dr()}),!0):!1:ct?(vt.manuallyDeactivated=!0,Nn(),Ut("user"),!0):!1},injectMessage(c){return!k&&S()&&Ot(!0,"system"),$.injectMessage(c)},injectAssistantMessage(c){!k&&S()&&Ot(!0,"system");let p=$.injectAssistantMessage(c);return V&&(V=!1,z&&(clearTimeout(z),z=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),p},injectUserMessage(c){return!k&&S()&&Ot(!0,"system"),$.injectUserMessage(c)},injectSystemMessage(c){return!k&&S()&&Ot(!0,"system"),$.injectSystemMessage(c)},injectMessageBatch(c){return!k&&S()&&Ot(!0,"system"),$.injectMessageBatch(c)},injectComponentDirective(c){return!k&&S()&&Ot(!0,"system"),$.injectComponentDirective(c)},injectTestMessage(c){!k&&S()&&Ot(!0,"system"),$.injectTestEvent(c)},async connectStream(c,p){return $.connectStream(c,p)},__pushEventStreamEvent(c){ye&&(be==null||be.processEvent(c.type,c.payload),ye.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!Ee||!ye||Vo()},hideEventStream(){ae&&yo()},isEventStreamVisible(){return ae},showArtifacts(){bo(o)&&(Rn=!1,Yn(),Tt==null||Tt.setMobileOpen(!0))},hideArtifacts(){bo(o)&&(Rn=!0,Yn())},upsertArtifact(c){return bo(o)?(Rn=!1,$.upsertArtifact(c)):null},selectArtifact(c){bo(o)&&$.selectArtifact(c)},clearArtifacts(){bo(o)&&$.clearArtifacts()},getArtifacts(){var c;return(c=$==null?void 0:$.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=$==null?void 0:$.getSelectedArtifactId())!=null?c:null},focusInput(){return I&&!k&&!E()||!te?!1:(te.focus(),!0)},async resolveApproval(c,p,h){let L=$.getMessages().find(N=>{var _;return N.variant==="approval"&&((_=N.approval)==null?void 0:_.id)===c});if(!(L!=null&&L.approval))throw new Error(`Approval not found: ${c}`);if(L.approval.toolType==="webmcp"){$.resolveWebMcpApproval(L.id,p);return}return $.resolveApproval(L.approval,p,h)},getMessages(){return $.getMessages()},getStatus(){return $.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){m(c)},on(c,p){return s.on(c,p)},off(c,p){s.off(c,p)},isOpen(){return S()&&k},isVoiceActive(){return vt.active},getState(){return{open:S()&&k,launcherEnabled:I,voiceActive:vt.active,streaming:$.isStreaming()}},showCSATFeedback(c){!k&&S()&&Ot(!0,"system");let p=tt.querySelector(".persona-feedback-container");p&&p.remove();let h=Qf({onSubmit:async(y,L)=>{var N;$.isClientTokenMode()&&await $.submitCSATFeedback(y,L),(N=c==null?void 0:c.onSubmit)==null||N.call(c,y,L)},onDismiss:c==null?void 0:c.onDismiss,...c});tt.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!k&&S()&&Ot(!0,"system");let p=tt.querySelector(".persona-feedback-container");p&&p.remove();let h=Zf({onSubmit:async(y,L)=>{var N;$.isClientTokenMode()&&await $.submitNPSFeedback(y,L),(N=c==null?void 0:c.onSubmit)==null||N.call(c,y,L)},onDismiss:c==null?void 0:c.onDismiss,...c});tt.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,p){return $.submitCSATFeedback(c,p)},async submitNPSFeedback(c,p){return $.submitNPSFeedback(c,p)},destroy(){po!=null&&(clearInterval(po),po=null),bt.forEach(c=>c()),Le.remove(),Je==null||Je.remove(),tn==null||tn.destroy(),nn==null||nn.remove(),lo&&F.removeEventListener("click",lo)}};if((((Gd=n==null?void 0:n.debugTools)!=null?Gd:!1)||!!o.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,p={controller:cn,getMessages:cn.getMessages,getStatus:cn.getStatus,getMetadata:cn.getPersistentMetadata,updateMetadata:cn.updatePersistentMetadata,clearHistory:()=>cn.clearChat(),setVoiceActive:h=>h?cn.startVoiceRecognition():cn.stopVoiceRecognition()};window.AgentWidgetBrowser=p,bt.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),p=q=>{let O=q.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&cn.focusInput()};if(window.addEventListener("persona:focusInput",p),bt.push(()=>{window.removeEventListener("persona:focusInput",p)}),Ee){let q=Ce=>{let ge=Ce.detail;(!(ge!=null&&ge.instanceId)||ge.instanceId===c)&&cn.showEventStream()},O=Ce=>{let ge=Ce.detail;(!(ge!=null&&ge.instanceId)||ge.instanceId===c)&&cn.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",O),bt.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",O)})}let h=q=>{let O=q.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&cn.showArtifacts()},y=q=>{let O=q.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&cn.hideArtifacts()},L=q=>{let O=q.detail;O!=null&&O.instanceId&&O.instanceId!==c||O!=null&&O.artifact&&cn.upsertArtifact(O.artifact)},N=q=>{let O=q.detail;O!=null&&O.instanceId&&O.instanceId!==c||typeof(O==null?void 0:O.id)=="string"&&cn.selectArtifact(O.id)},_=q=>{let O=q.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&cn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",L),window.addEventListener("persona:selectArtifact",N),window.addEventListener("persona:clearArtifacts",_),bt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",L),window.removeEventListener("persona:selectArtifact",N),window.removeEventListener("persona:clearArtifacts",_)})}let uo=sv(o.persistState);if(uo&&S()){let c=av(uo.storage),p=`${uo.keyPrefix}widget-open`,h=`${uo.keyPrefix}widget-voice`,y=`${uo.keyPrefix}widget-voice-mode`;if(c){let L=((Yd=uo.persist)==null?void 0:Yd.openState)&&c.getItem(p)==="true",N=((Xd=uo.persist)==null?void 0:Xd.voiceState)&&c.getItem(h)==="true",_=((Jd=uo.persist)==null?void 0:Jd.voiceState)&&c.getItem(y)==="true";if(L&&setTimeout(()=>{cn.open(),setTimeout(()=>{var q;if(N||_)cn.startVoiceRecognition();else if((q=uo.persist)!=null&&q.focusInput){let O=e.querySelector("textarea");O&&O.focus()}},100)},0),(Qd=uo.persist)!=null&&Qd.openState&&(s.on("widget:opened",()=>{c.setItem(p,"true")}),s.on("widget:closed",()=>{c.setItem(p,"false")})),(Zd=uo.persist)!=null&&Zd.voiceState&&(s.on("voice:state",q=>{c.setItem(h,q.active?"true":"false")}),s.on("user:message",q=>{c.setItem(y,q.viaVoice?"true":"false")})),uo.clearOnChatClear){let q=()=>{c.removeItem(p),c.removeItem(h),c.removeItem(y)},O=()=>q();window.addEventListener("persona:clear-chat",O),bt.push(()=>{window.removeEventListener("persona:clear-chat",O)})}}}return f&&S()&&setTimeout(()=>{cn.open()},0),Yo(),cn};var iv=(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},rg=(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"},Rc=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=""},sg=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Rc(e)},Mc=e=>{e.style.transition=""},Lc=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform=""},Ic=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},dl=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},lv=(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))},cv=(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)},ag=(e,t,n,o,r,s,a)=>{var C,v,M,I,R,P;let i=No(s),d=i.reveal==="push";lv(e,t,n,o,d),cv(e,t,n,o,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,f=(v=(C=s==null?void 0:s.launcher)==null?void 0:C.mobileFullscreen)!=null?v:!0,u=(I=(M=s==null?void 0:s.launcher)==null?void 0:M.mobileBreakpoint)!=null?I:640,g=l!=null?l.innerWidth<=u:!1;if(f&&g&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Lc(t),Mc(o),sg(o),Ic(n),dl(r,o),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String((P=(R=s==null?void 0:s.launcher)==null?void 0:R.zIndex)!=null?P:Mn),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"),sg(o),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Lc(t),Mc(o),Ic(n),dl(r,o);let D=i.animate?"transform 180ms ease":"none",W=i.side==="right"?"translateX(100%)":"translateX(-100%)",w=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=w,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",i.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Mc(o),Rc(o),dl(r,o);let D=iv(i.width,e.clientWidth),W=Math.max(0,e.clientWidth),w=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=w,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="",Lc(t),Rc(o),Ic(n),dl(r,o);let D=i.reveal==="emerge";D?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let W=a?i.width:"0px",w=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",x=!a;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${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=w,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")}},dv=(e,t)=>{let n=e.ownerDocument.createElement("div");return rg(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){rg(n,o)},destroy(){n.remove()}}},pv=(e,t)=>{var R,P,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"),f=n.createElement("div"),u=(P=(R=t==null?void 0:t.launcher)==null?void 0:R.enabled)==null||P?(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",f.dataset.personaDockRole="host",l.appendChild(f),o.insertBefore(a,e),d.appendChild(e);let g=null,m=()=>{g==null||g.disconnect(),g=null},C=()=>{m(),No(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{ag(a,i,d,l,f,t,u)}),g.observe(a))},v=()=>{ag(a,i,d,l,f,t,u),C()},M=a.ownerDocument.defaultView,I=()=>{v()};return M==null||M.addEventListener("resize",I),No(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),v(),{mode:"docked",host:f,shell:a,syncWidgetState(w){let x=w.launcherEnabled?w.open:!0;u!==x&&(u=x,v())},updateConfig(w){var x,E;t=w,((E=(x=t==null?void 0:t.launcher)==null?void 0:x.enabled)!=null?E:!0)===!1&&(u=!0),v()},destroy(){M==null||M.removeEventListener("resize",I),m(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},ig=(e,t)=>wn(t)?pv(e,t):dv(e,t);var Kr={desktop:{w:1280,h:800},mobile:{w:390,h:844}},pl=.15,ul=1.5,Ba="persona-preview-shell-theme",Pc={load:()=>null,save:()=>{},clear:()=>{}},Wc=["How do I get started?","Pricing & plans","Talk to support"];function Ha(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Bc(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 ml(e){let t=Bc(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 la=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
128
128
|
.preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
|
|
129
129
|
.preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
|
|
130
130
|
.preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${t.cardBg}; box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
|
|
131
|
-
.preview-workspace-card.short { height: 96px; }`}function
|
|
131
|
+
.preview-workspace-card.short { height: 96px; }`}function fl(e,t){let n=e.contentDocument;if(!(n!=null&&n.documentElement))return;let o=n.getElementById(Ba);o||(o=n.createElement("style"),o.id=Ba,n.head.appendChild(o)),o.textContent=ml(t)}var Hc=`
|
|
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 la=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
147
147
|
<div class="preview-iframe-line body"></div>
|
|
148
148
|
<div class="preview-iframe-line body"></div>
|
|
149
149
|
</div>
|
|
150
|
-
</div>`,
|
|
150
|
+
</div>`,Dc=`
|
|
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 la=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
160
160
|
<div class="preview-workspace-card short"></div>
|
|
161
161
|
<div class="preview-workspace-card short"></div>
|
|
162
162
|
</div>
|
|
163
|
-
</div>`;function
|
|
164
|
-
${
|
|
163
|
+
</div>`;function gl(e,t,n,o){let r=`
|
|
164
|
+
${Hc}
|
|
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 la=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
173
173
|
</div>
|
|
174
174
|
<div class="preview-workspace-body">
|
|
175
175
|
<div id="preview-content-${e}" class="preview-workspace-content" data-mount-id="${e}">
|
|
176
|
-
${
|
|
176
|
+
${Dc}
|
|
177
177
|
</div>
|
|
178
178
|
</div>
|
|
179
179
|
</div>`;return`<!DOCTYPE html>
|
|
@@ -181,19 +181,19 @@ _Details: ${n.message}_`:o}var la=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
181
181
|
<head>
|
|
182
182
|
<meta charset="UTF-8">
|
|
183
183
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
184
|
-
<link rel="stylesheet" href="${
|
|
185
|
-
<style id="${
|
|
184
|
+
<link rel="stylesheet" href="${Ha(o)}">
|
|
185
|
+
<style id="${Ba}">${ml(t)}</style>
|
|
186
186
|
</head>
|
|
187
187
|
<body>
|
|
188
188
|
${n?s:r}
|
|
189
189
|
</body>
|
|
190
|
-
</html>`}var
|
|
190
|
+
</html>`}var uv={"user-message":"User message","assistant-message":"Assistant message","assistant-code-block":"Assistant \u2014 code block","assistant-markdown-table":"Assistant \u2014 markdown table","assistant-image":"Assistant \u2014 image","reasoning-streaming":"Reasoning (streaming)","reasoning-complete":"Reasoning (complete)","tool-running":"Tool call (running)","tool-complete":"Tool call (complete)","approval-request":"Approval request"};function lg(e){return uv[e]}function hl(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"approval-request":{let r=`preview-approval-${o}`;return{id:`approval-${r}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"approval",approval:{id:r,status:"pending",agentId:"preview-agent",executionId:`preview-exec-${o}`,toolName:"add_to_cart",description:"Add the selected item to the shopping cart. Approve to let the assistant continue.",parameters:{items:[{productEntityId:129,quantity:1}]}}}}case"tool-complete":return{id:`preview-seq-tool-complete-${o}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"tool",toolCall:{id:`preview-tool-complete-${o}`,name:"Create build instructions",status:"complete",chunks:["Prepared the build instructions and validated the inputs."],result:{ok:!0},duration:420}};default:return{id:`preview-seq-tool-running-${o}`,role:"assistant",content:"",createdAt:n,streaming:!0,variant:"tool",toolCall:{id:`preview-tool-running-${o}`,name:"Get platform documentation",status:"running",chunks:["Fetching the relevant platform documentation..."]}}}}function
|
|
194
|
-
${
|
|
195
|
-
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${
|
|
196
|
-
</div>`,
|
|
193
|
+
`),createdAt:n};case"reasoning-streaming":return{id:`preview-seq-reasoning-stream-${o}`,role:"assistant",content:"",createdAt:n,streaming:!0,variant:"reasoning",reasoning:{id:`preview-reasoning-stream-${o}`,status:"streaming",chunks:["Thinking through the next step in the workflow..."]}};case"reasoning-complete":return{id:`preview-seq-reasoning-complete-${o}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"reasoning",reasoning:{id:`preview-reasoning-complete-${o}`,status:"complete",chunks:["Reviewed the requirements and finalized the reasoning output."],durationMs:1200}};case"approval-request":{let r=`preview-approval-${o}`;return{id:`approval-${r}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"approval",approval:{id:r,status:"pending",agentId:"preview-agent",executionId:`preview-exec-${o}`,toolName:"add_to_cart",description:"Add the selected item to the shopping cart. Approve to let the assistant continue.",parameters:{items:[{productEntityId:129,quantity:1}]}}}}case"tool-complete":return{id:`preview-seq-tool-complete-${o}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"tool",toolCall:{id:`preview-tool-complete-${o}`,name:"Create build instructions",status:"complete",chunks:["Prepared the build instructions and validated the inputs."],result:{ok:!0},duration:420}};default:return{id:`preview-seq-tool-running-${o}`,role:"assistant",content:"",createdAt:n,streaming:!0,variant:"tool",toolCall:{id:`preview-tool-running-${o}`,name:"Get platform documentation",status:"running",chunks:["Fetching the relevant platform documentation..."]}}}}function cg(e,t){return[...e,hl(t,e.length)]}function Fc(e){return e==="assistant-message"||e==="assistant-code-block"||e==="assistant-markdown-table"||e==="assistant-image"}function dg(e,t,n){var d,l;let o=hl(e,t);if(!Fc(e)||typeof o.content!="string")return[{message:o,delayMs:0,done:!0}];let r=Math.max(1,(d=n==null?void 0:n.chunkSize)!=null?d:24),s=Math.max(0,(l=n==null?void 0:n.delayMs)!=null?l:42),a=o.content,i=[];i.push({message:{...o,content:"",streaming:!0},delayMs:0,done:!1});for(let f=r;f<a.length;f+=r)i.push({message:{...o,content:a.slice(0,f),streaming:!0},delayMs:s,done:!1});return i.push({message:{...o,content:a,streaming:!1},delayMs:s,done:!0}),i}var mv=()=>[{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()}],fv=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 Oc(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"&&fv(t)?[...mv(),...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 bl(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:Wc:e.suggestionChips,initialMessages:Oc(t,e,n),storageAdapter:Pc};return t==="artifact"&&(r.features={...r.features,artifacts:{...(a=r.features)==null?void 0:a.artifacts,enabled:!0}}),r}function xr(e,t){var s,a,i,d;let n=e.theme?mn(e.theme,{validate:!1}):mn(),o=(s=e.scene)!=null?s:"conversation",r={...It,...e.config,theme:n,darkTheme:e.darkTheme,colorScheme:(i=t!=null?t:(a=e.config)==null?void 0:a.colorScheme)!=null?i:"light"};return bl(r,o,(d=e.appendedMessages)!=null?d:[])}function pg(e,t,n){var a,i,d;let o=e.theme?mn(e.theme,{validate:!1}):mn(),r=(a=e.scene)!=null?a:"conversation",s={...It,...e.config,theme:o,darkTheme:e.darkTheme,colorScheme:(d=n!=null?n:(i=e.config)==null?void 0:i.colorScheme)!=null?d:"light"};return bl(s,r,t)}function ug(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:xr(e,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:xr(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:xr(d,n),shellMode:n},{mountId:"preview-current",label:"Current",config:xr(e,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:xr(e,n),shellMode:n}]}function mg(e,t){let n={...t},o=[],r=[],s=null,a=!1,i=1,d=1,l=0;function f(){var R;return(R=n.device)!=null?R:"desktop"}function u(){var R;return(R=n.zoom)!=null?R:i}function g(){var k,V;let R=getComputedStyle(e),P=parseFloat(R.paddingLeft)+parseFloat(R.paddingRight),D=parseFloat(R.paddingTop)+parseFloat(R.paddingBottom),W=40,w=((k=n.compareMode)!=null?k:"off")!=="off",x=(e.clientWidth-P-W)/(w?2:1),E=e.clientHeight-D-W;if(x<=0||E<=0)return 1;let S=(V=Kr[f()])!=null?V:Kr.desktop;return Math.min(x/S.w,E/S.h,1)}function m(){var D,W,w;i=g();let R=Math.max(pl,Math.min(ul,u()));d=R;let P=Array.from(e.querySelectorAll(".preview-iframe-wrapper"));for(let x of P){let E=(D=x.dataset.device)!=null?D:"desktop",S=(W=Kr[E])!=null?W:Kr.desktop;x.style.width=`${S.w*R}px`,x.style.height=`${S.h*R}px`,E==="mobile"&&(x.style.borderRadius=`${32*R}px`);let k=x.querySelector("iframe");k&&(k.style.width=`${S.w}px`,k.style.height=`${S.h}px`,k.style.transformOrigin="top left",k.style.transition="none",k.style.transform=`scale(${R})`)}(w=n.onScaleChange)==null||w.call(n,R)}function C(){var R;(R=n.onBeforeDestroy)==null||R.call(n);for(let P of o)P.destroy();for(let P of r)P();o=[],r=[]}function v(){return Array.from(e.querySelectorAll("iframe[data-mount-id]"))}function M(){var de,Ee,xe,De;if(a)return;C();let R=++l,P=ug(n),D=f(),W=((de=n.compareMode)!=null?de:"off")!=="off",w=((Ee=n.scene)!=null?Ee:"conversation")==="minimized",x=(xe=n.widgetCssPath)!=null?xe:"/widget-dist/widget.css",E=(De=n.buildSrcdoc)!=null?De:gl,S=D==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",k=Ae=>`<div class="${S}" data-mount-id="${Ae.mountId}" data-device="${D}" data-shell-mode="${Ae.shellMode}">
|
|
194
|
+
${W?`<div class="preview-frame-meta"><span class="preview-frame-label">${Ha(Ae.label)}</span></div>`:""}
|
|
195
|
+
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${Ae.mountId}"></iframe>
|
|
196
|
+
</div>`,V=W?`<div class="preview-compare-grid">${P.map(Ae=>`<div class="preview-compare-cell">${k(Ae)}</div>`).join("")}</div>`:`<div class="preview-single">${k(P[0])}</div>`;n.morphContainer?n.morphContainer(e,V):e.innerHTML=V,m();let z=v(),Y=0,he=z.length,me=()=>{var le,J,se,ye,be;if(a||R!==l)return;for(let K of z){let ae=K.dataset.mountId;if(!ae||!K.contentDocument)continue;let Re=P.find(lt=>lt.mountId===ae);if(!Re)continue;let oe=()=>{},ee=wn(Re.config),re=ee?(()=>{var j;let lt=(j=K.contentDocument)==null?void 0:j.getElementById(`preview-content-${ae}`);if(!lt)return null;let Le=ig(lt,Re.config),pe=K.contentDocument.createElement("div");pe.id=ae,pe.style.height="100%",pe.style.display="flex",pe.style.flexDirection="column",pe.style.flex="1",pe.style.minHeight="0",Le.host.appendChild(pe);let Je=()=>Le.syncWidgetState(it.getState()),Be=oe;return oe=()=>{Le.destroy(),Be()},pe.__syncDock=Je,pe.__hostLayout=Le,pe})():K.contentDocument.getElementById(ae);if(!re)continue;let it=og(re,Re.config);if(o.push(it),ee&&re.__syncDock){let lt=re.__syncDock,Le=it.on("widget:opened",lt),pe=it.on("widget:closed",lt),Je=oe;oe=()=>{Le(),pe(),Je()},lt()}r.push(oe),w&&it.close()}if(((le=n.scene)!=null?le:"conversation")==="artifact"||(ye=(se=(J=n.config)==null?void 0:J.features)==null?void 0:se.artifacts)!=null&&ye.enabled)for(let K of o)K.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`});(ce=n.onAfterMount)==null||ce.call(n,{iframes:U,controllers:[...o]})};for(let we of U){let K=we.dataset.mountId;if(!K)continue;let pe=W.find(G=>G.mountId===K);pe&&(we.addEventListener("load",()=>{Y++,Y>=he&&fe()},{once:!0}),we.srcdoc=E(K,pe.shellMode,bn(pe.config),w))}he===0&&fe()}function I(){var D;if(a)return;let R=Fg(n);if(o.length!==R.length){M();return}if(R.some(B=>{let x=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${B.mountId}"]`);return!x||x.dataset.shellMode!==B.shellMode})){M();return}o.forEach((B,x)=>{var w;B.update(R[x].config),((w=n.scene)!=null?w:"conversation")==="minimized"&&B.close()});for(let B of R){let x=e.querySelector(`iframe[data-mount-id="${B.mountId}"]`);x&&al(x,B.shellMode)}(D=n.onAfterUpdate)==null||D.call(n,{iframes:v(),controllers:[...o]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||u()}),s.observe(e)),M(),{update(R){if(a)return;let W=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},W?M():I()},destroy(){a||(a=!0,C(),s==null||s.disconnect(),e.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},u())},getIframes(){return v()},getScale(){return d},setZoom(R){a||(n={...n,zoom:R},u())}}}function Ho(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}var Ia={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"},Dy=/^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 Fy(e){return Dy.test(e)}function _r(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=Ia[t];if(n)return n;let o=ts(t);if(si(o)||o==="transparent"||Fy(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(Ia).slice(0,6).join(", ")}).`)}var pl=$s.map(e=>e==="gray"?"neutral":e),Oy={...Object.fromEntries(pl.map(e=>[e,e])),gray:"neutral",grey:"neutral"};function Ra(e,t=!0){let n=String(e!=null?e:"").trim().toLowerCase(),o=Oy[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 Pa(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 Wa(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 Ny={sharp:"sharp",square:"sharp",none:"sharp",default:"default",normal:"default",rounded:"rounded",round:"rounded",soft:"rounded",pill:"pill",circle:"pill",full:"pill"};function Ba(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=Ny[t];if(!n)throw new Error(`Unknown roundness "${e}". Valid: sharp, default, rounded, pill.`);return n}function Ha(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=oi(t);return ri(n.value,n.unit)}throw new Error('Radius must be a number (px) or a CSS length string like "0.5rem".')}function ul(e){for(let t of Ir){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 Ng=ul("typo-font-family"),Ma=ul("typo-font-size"),La=ul("typo-font-weight"),dl=ul("typo-line-height"),_g={...Ng,monospace:Ng.mono},Vg={...Ma,small:Ma.sm,md:Ma.base,medium:Ma.base,large:Ma.lg},$g={...La,400:La.normal,500:La.medium,600:La.semibold,700:La.bold},Ug={...dl,"1.25":dl.tight,"1.5":dl.normal,"1.625":dl.relaxed};function zg(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 qg="theme.palette.radius.";function _y(){var t;let e={pill:{sm:"9999px",md:"9999px",lg:"9999px",xl:"9999px",full:"9999px"}};for(let n of Ir)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(qg)&&typeof i=="string"&&(s[a.slice(qg.length)]=i);e[r[1]]=s}return e}var bs=_y(),jg=["sm","md","lg","xl","full"];function gl(e,t,n="theme",o=0){if(o>6)return null;let r=e.get(`${n}.${t}`);return typeof r!="string"||r===""?n==="darkTheme"?gl(e,t,"theme",o):null:r.startsWith("#")||r.startsWith("rgb")||r==="transparent"?r:r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components.")?gl(e,r,n,o+1):null}function ml(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 ys(e){return e.replace(/^role-/,"")}function Vy(e){for(let[t,n]of Object.entries(bs))if(jg.every(o=>e[o]===n[o]))return t;return"custom"}function gr(e){var o,r;let t={};for(let s of jg)t[s]=String((o=e.get(`theme.palette.radius.${s}`))!=null?o:"");let n={};for(let s of ir)n[ys(s.roleId)]=ci(a=>e.get(`theme.${a}`),s);return{brand:{primary:Mc(e.get("theme.palette.colors.primary.500")),secondary:Mc(e.get("theme.palette.colors.secondary.500")),accent:Mc(e.get("theme.palette.colors.accent.500"))},roles:n,typography:{fontFamily:ml(e,"theme.semantic.typography.fontFamily"),fontSize:ml(e,"theme.semantic.typography.fontSize"),fontWeight:ml(e,"theme.semantic.typography.fontWeight"),lineHeight:ml(e,"theme.semantic.typography.lineHeight")},roundness:{style:Vy(t),radius:t},colorScheme:String((r=e.get("colorScheme"))!=null?r:"light"),history:{index:e.getHistoryIndex(),canUndo:e.canUndo(),canRedo:e.canRedo()}}}function Mc(e){return typeof e=="string"&&e!==""?e:null}var hs=[{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 Kg(e){let t=new Set(e.targets.map(n=>n.path));return hs.filter(n=>t.has(n.fg)||t.has(n.bg)).map(n=>n.key)}var $y={AA:4.5,AAA:7};function Uy(e){return Math.round(e*100)/100}function zy(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=Lr.indexOf(a[2]),l=null,m=1/0;return Lr.forEach((p,f)=>{let u=e.get(`${r}.palette.colors.${i}.${p}`);if(!(typeof u!="string"||!(u.startsWith("#")||u.startsWith("rgb")))&&Vs(u,n)>=o){let C=d>=0?Math.abs(f-d):f;C<m&&(m=C,l=`palette.colors.${i}.${p}`)}}),l}function vs(e,t="AA",n="both",o){let r=$y[t],s=n==="both"?["light","dark"]:[n],a=o?hs.filter(d=>o.includes(d.key)):hs,i=[];for(let d of s){let l=d==="light"?"theme":"darkTheme";for(let m of a){let p=gl(e,m.fg,l),f=gl(e,m.bg,l);if(!p||!f)continue;let u=Uy(Vs(p,f)),C=u>=r,v={pair:m.key,label:m.label,variant:d,fg:p,bg:f,ratio:u,threshold:r,passes:C};if(!C){let M=zy(e,m.fg,f,r,l);M&&(v.suggestion=M)}i.push(v)}}return{level:t,checks:i,failures:i.filter(d=>!d.passes)}}function Vr(e,t,n="light",o="AA"){return t.length===0?[]:vs(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 mn={};for(let e of ir){let t=ys(e.roleId);mn[t]=e,mn[e.roleId]=e}Object.assign(mn,{surface:mn.surfaces,background:mn.surfaces,backgrounds:mn.surfaces,user:mn["user-messages"],"user-message":mn["user-messages"],assistant:mn["assistant-messages"],"assistant-message":mn["assistant-messages"],actions:mn["primary-actions"],buttons:mn["primary-actions"],composer:mn.input,links:mn["links-focus"],focus:mn["links-focus"],border:mn.borders,dividers:mn.borders,scroll:mn["scroll-to-bottom"]});function qy(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=mn[t];if(!n){let o=ir.map(r=>ys(r.roleId)).join(", ");throw new Error(`Unknown role "${e}". Valid roles: ${o}.`)}return n}function Gg(){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 di)t(n.sections);for(let n of ea)t(n.sections);return e}var jy={voice:"voiceRecognition.enabled",artifacts:"features.artifacts.enabled",attachments:"attachments.enabled",toolCalls:"features.showToolCalls",reasoning:"features.showReasoning",feedback:"messageActions.enabled"},Ky={avatars:"layout.messages.avatar.show",timestamps:"layout.messages.timestamp.show",showHeader:"layout.showHeader",messageStyle:"layout.messages.layout"},Lc=["bottom-right","bottom-left","top-right","top-left"],Ic=["bubble","flat","minimal"],Gy={title:"copy.welcomeTitle",subtitle:"copy.welcomeSubtitle",placeholder:"copy.inputPlaceholder",sendLabel:"copy.sendButtonLabel"};function Rc(e,t){var B;let n=(B=t==null?void 0:t.editTarget)!=null?B:"both",o=null,r=x=>x&&typeof x=="object"?x:{},s=(x,w,E=n)=>{let S={};return(E==="light"||E==="both")&&(S[`theme.${x}`]=w),(E==="dark"||E==="both")&&(S[`darkTheme.${x}`]=w),S},a=x=>{if(n==="both")return x;let w={};for(let[E,S]of Object.entries(x))(n==="light"&&E.startsWith("theme.")||n==="dark"&&E.startsWith("darkTheme."))&&(w[E]=S);return w},i=()=>n==="dark"?"dark":"light",d=(x,w=[])=>Ho({ok:!0,summary:gr(e),warnings:w,applied:x});return[{name:"get_theme_overview",title:"Get current theme & what is editable",description:"Read the current widget theme (brand colors, per-role color assignments, typography, roundness, color scheme, undo/redo state), the available presets, and the high-level levers you can change. Call this FIRST before editing.",annotations:{readOnlyHint:!0},inputSchema:{type:"object",properties:{verbosity:{type:"string",enum:["summary","full"],description:"Use 'full' to also include the field-id index for set_theme_fields."}},additionalProperties:!1},execute(x){let{verbosity:w}=r(x),E={summary:gr(e),availableRoles:ir.map(S=>({role:ys(S.roleId),helper:S.helper})),availableFamilies:pl,presets:os.map(S=>{var T;return{id:S.id,name:S.name,description:S.description,tags:(T=S.tags)!=null?T:[]}}),tools:[{tool:"set_brand_colors",hint:"Recolor the palette (primary/secondary/accent) \u2014 auto-generates shade scales."},{tool:"assign_color_role",hint:"Recolor a region (header, user/assistant messages, actions, input, links, borders, surfaces, scroll) with a family + intensity."},{tool:"set_typography",hint:"Set font family, size, weight, line height."},{tool:"set_roundness",hint:"Set corner roundness (sharp/default/rounded/pill) or granular radii."},{tool:"set_color_scheme",hint:"Set light/dark/auto and which variant edits target."},{tool:"apply_preset",hint:"Apply a complete built-in preset."},{tool:"configure_widget",hint:"Toggle launcher position, features, and layout."},{tool:"set_copy_and_suggestions",hint:"Set welcome copy, placeholder, and suggestion chips."},{tool:"set_theme_fields",hint:"Advanced escape hatch: set any field by id or dot-path."},{tool:"check_contrast",hint:"Audit WCAG contrast across key text/background pairs."},{tool:"manage_session",hint:"Undo, redo, reset, or export the theme."}]};return w==="full"&&(o!=null||(o=Gg()),E.fieldIndex=Array.from(o.values()).map(S=>{var T;return{id:S.id,path:S.path,type:S.type,label:S.label,options:(T=S.options)==null?void 0:T.map(_=>_.value)}})),Ho(E)}},{name:"set_brand_colors",title:"Set brand colors",description:'Set one or more brand colors (primary, secondary, accent). Each color auto-generates a full 50\u2013950 shade scale and applies to the light and dark themes (per the current edit target). Accepts hex ("#2563eb", "2563eb", "#18f"), rgb()/rgba() ("rgb(37, 99, 235)"), or CSS color names ("blue", "slateblue").',inputSchema:{type:"object",properties:{primary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},secondary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},accent:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."}},additionalProperties:!1},execute(x){let w=r(x),E=["primary","secondary","accent"],S={},T={};for(let U of E){if(w[U]===void 0)continue;let Y=_r(w[U]);T[U]=Y;let he=ii(Y);for(let fe of Lr){let ae=he[fe];ae!==void 0&&Object.assign(S,s(`palette.colors.${U}.${fe}`,ae))}}if(Object.keys(T).length===0)throw new Error("Provide at least one of: primary, secondary, accent.");e.setBatch(S);let _=Vr(e,["primary-button","user-message"],i());return d(T,_)}},{name:"assign_color_role",title:"Assign a color family to an interface role",description:"Recolor a semantic region of the widget by choosing a palette family and intensity. One call writes all related tokens (background, text, border, icon) consistently. Roles: header, user-messages, assistant-messages, primary-actions, input, links, borders, surfaces, scroll-to-bottom. Families: primary, secondary, accent, neutral. Intensity: solid (bold) or soft (tinted).",inputSchema:{type:"object",properties:{role:{type:"string",description:'Interface role, e.g. "header" or "user-messages".'},family:{type:"string",enum:pl},intensity:{type:"string",enum:["solid","soft"],description:"Defaults to 'solid'."}},required:["role","family"],additionalProperties:!1},execute(x){let w=r(x),E=qy(w.role),S=Ra(w.family,!0),T=Pa(w.intensity),_=a(Js(S,T,E)),U=Object.keys(_).length;e.setBatch(_);let Y=Vr(e,Kg(E),i());return d({role:ys(E.roleId),family:S,intensity:T,tokensWritten:U},Y)}},{name:"set_typography",title:"Set typography",description:"Set font family, base size, weight, and line height in one call. fontFamily: sans|serif|mono. fontSize: xs|sm|base|lg|xl. fontWeight: normal|medium|semibold|bold (or 400\u2013700). lineHeight: tight|normal|relaxed (or 1.25/1.5/1.625).",inputSchema:{type:"object",properties:{fontFamily:{type:"string"},fontSize:{type:"string"},fontWeight:{type:["string","number"]},lineHeight:{type:["string","number"]}},additionalProperties:!1},execute(x){let w=r(x),E={},S={},T=(_,U)=>{var he;if(w[_]===void 0)return;let Y=zg(w[_],U,_);S[_]=(he=Y.split(".").pop())!=null?he:Y,Object.assign(E,s(`semantic.typography.${_}`,Y))};if(T("fontFamily",_g),T("fontSize",Vg),T("fontWeight",$g),T("lineHeight",Ug),Object.keys(S).length===0)throw new Error("Provide at least one of: fontFamily, fontSize, fontWeight, lineHeight.");return e.setBatch(E),d(S)}},{name:"set_roundness",title:"Set corner roundness",description:"Set overall corner roundness with a keyword (sharp, default, rounded, pill) which maps the full radius scale, OR pass granular radius values. Provide at least one of `style` or `radius`.",inputSchema:{type:"object",properties:{style:{type:"string",enum:["sharp","default","rounded","pill"]},radius:{type:"object",description:"Granular overrides (px number or CSS length).",properties:{sm:{type:["string","number"]},md:{type:["string","number"]},lg:{type:["string","number"]},xl:{type:["string","number"]},full:{type:["string","number"]}},additionalProperties:!1}},additionalProperties:!1},execute(x){let w=r(x),E={},S={};if(w.style!==void 0){let T=Ba(w.style);S.style=T;for(let[_,U]of Object.entries(bs[T]))Object.assign(E,s(`palette.radius.${_}`,U))}if(w.radius!==void 0){let T=r(w.radius),_={};for(let U of["sm","md","lg","xl","full"]){if(T[U]===void 0)continue;let Y=Ha(T[U]);_[U]=Y,Object.assign(E,s(`palette.radius.${U}`,Y))}S.radius=_}if(Object.keys(E).length===0)throw new Error("Provide `style` (sharp|default|rounded|pill) or a `radius` object.");return e.setBatch(E),d(S)}},{name:"set_color_scheme",title:"Set color scheme",description:"Set the shipped widget color scheme (light, dark, or auto/follow-system). Optionally set `editTarget` to choose which theme variant subsequent styling edits write to (light, dark, or both \u2014 default both).",inputSchema:{type:"object",properties:{scheme:{type:"string",enum:["light","dark","auto"]},editTarget:{type:"string",enum:["light","dark","both"]}},additionalProperties:!1},execute(x){let w=r(x),E={};if(w.scheme!==void 0){let S=Wa(w.scheme);e.set("colorScheme",S),E.scheme=S}if(w.editTarget!==void 0){let S=String(w.editTarget).trim().toLowerCase();if(S!=="light"&&S!=="dark"&&S!=="both")throw new Error(`Unknown editTarget "${w.editTarget}". Valid: light, dark, both.`);n=S,E.editTarget=S}if(Object.keys(E).length===0)throw new Error("Provide `scheme` and/or `editTarget`.");return Ho({ok:!0,summary:gr(e),warnings:[],applied:E,editTarget:n})}},{name:"apply_preset",title:"Apply a built-in theme preset",description:"Apply a complete built-in preset, replacing theme tokens. Call get_theme_overview to list preset ids.",inputSchema:{type:"object",properties:{presetId:{type:"string"}},required:["presetId"],additionalProperties:!1},execute(x){let{presetId:w}=r(x),E=pi(String(w!=null?w:""));if(!E){let U=os.map(Y=>Y.id).join(", ");throw new Error(`Unknown preset "${w}". Valid presets: ${U}.`)}let S=an(E.theme,{validate:!1}),T={...e.getConfig()};E.darkTheme&&(T.darkTheme=an(E.darkTheme,{validate:!1})),E.toolCall&&(T.toolCall=E.toolCall),e.setFullConfig(T,S);let _=Vr(e,["body","assistant-message"],"light");return d({appliedPreset:{id:E.id,name:E.name}},_)}},{name:"configure_widget",title:"Configure launcher, features, and layout",description:"Toggle non-theme widget configuration. launcherPosition: bottom-right|bottom-left|top-right|top-left. features: { voice, artifacts, attachments, toolCalls, reasoning, feedback } booleans. layout: { avatars, timestamps, showHeader } booleans and messageStyle: bubble|flat|minimal.",inputSchema:{type:"object",properties:{launcherPosition:{type:"string",enum:Lc},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:Ic}},additionalProperties:!1}},additionalProperties:!1},execute(x){var U,Y,he;let w=r(x),E={},S={};if(w.launcherPosition!==void 0){let fe=String(w.launcherPosition);if(!Lc.includes(fe))throw new Error(`Unknown launcherPosition "${fe}". Valid: ${Lc.join(", ")}.`);E["launcher.position"]=fe,S.launcherPosition=fe}let T=r(w.features);for(let[fe,ae]of Object.entries(jy))T[fe]!==void 0&&(E[ae]=!!T[fe],(U=S.features)!=null||(S.features={}),S.features[fe]=!!T[fe]);let _=r(w.layout);for(let[fe,ae]of Object.entries(Ky))if(_[fe]!==void 0)if(fe==="messageStyle"){let Ee=String(_[fe]);if(!Ic.includes(Ee))throw new Error(`Unknown messageStyle "${Ee}". Valid: ${Ic.join(", ")}.`);E[ae]=Ee,(Y=S.layout)!=null||(S.layout={}),S.layout[fe]=Ee}else E[ae]=!!_[fe],(he=S.layout)!=null||(S.layout={}),S.layout[fe]=!!_[fe];if(Object.keys(E).length===0)throw new Error("Provide launcherPosition, features, and/or layout.");return e.setBatch(E),d(S)}},{name:"set_copy_and_suggestions",title:"Set welcome copy and suggestion chips",description:"Set the widget welcome copy and suggestion chips. title/subtitle are the welcome card text; placeholder is the input placeholder; sendLabel is the send button label; suggestions is an array of suggestion-chip strings (replaces the existing list).",inputSchema:{type:"object",properties:{title:{type:"string"},subtitle:{type:"string"},placeholder:{type:"string"},sendLabel:{type:"string"},suggestions:{type:"array",items:{type:"string"}}},additionalProperties:!1},execute(x){let w=r(x),E={},S={};for(let[T,_]of Object.entries(Gy))w[T]!==void 0&&(E[_]=String(w[T]),S[T]=String(w[T]));if(w.suggestions!==void 0){if(!Array.isArray(w.suggestions))throw new Error("`suggestions` must be an array of strings.");let T=w.suggestions.filter(_=>typeof _=="string");E.suggestionChips=T,S.suggestions=T}if(Object.keys(E).length===0)throw new Error("Provide at least one of: title, subtitle, placeholder, sendLabel, suggestions.");return e.setBatch(E),d(S)}},{name:"set_theme_fields",title:"Set theme fields by id or path (advanced)",description:'Advanced escape hatch: set individual editor fields by field id (see get_theme_overview verbosity:"full") \u2014 theme field ids follow the current edit target (light/dark/both) \u2014 or by raw dot-path (theme.* / darkTheme.* / a config path), which is written as-is. Use only when a higher-level tool does not cover the need. Values are validated against the field metadata.',inputSchema:{type:"object",properties:{updates:{type:"array",items:{type:"object",properties:{field:{type:"string",description:"Field id or dot-path."},value:{type:["string","number","boolean"]}},required:["field","value"],additionalProperties:!1}}},required:["updates"],additionalProperties:!1},execute(x){var _;let{updates:w}=r(x);if(!Array.isArray(w)||w.length===0)throw new Error("`updates` must be a non-empty array of { field, value }.");o!=null||(o=Gg());let E={},S=[];for(let U of w){let Y=r(U),he=String((_=Y.field)!=null?_:"");try{let fe=o.get(he),ae=fe?fe.path:he;if(!fe&&!/^(theme|darkTheme)\.|\./.test(ae))throw new Error(`Unknown field "${he}". Pass a known field id or a dot-path (e.g. theme.palette.radius.md).`);let Ee=Yy(fe,Y.value);if(fe&&ae.startsWith("theme.")){let ye=s(ae.slice(6),Ee);Object.assign(E,ye),S.push({field:he,resolvedPath:Object.keys(ye),ok:!0})}else E[ae]=Ee,S.push({field:he,resolvedPath:ae,ok:!0})}catch(fe){S.push({field:he,ok:!1,error:fe.message})}}let T=S.filter(U=>U.ok);return Object.keys(E).length>0&&e.setBatch(E),Ho({ok:T.length>0,summary:gr(e),warnings:[],applied:{updates:S}})}},{name:"check_contrast",title:"Check accessibility contrast",description:"Run WCAG contrast checks over the key text/background pairs (message text, header title, input/body text, primary button). Returns each ratio, whether it passes, and a suggested foreground shade for failures.",annotations:{readOnlyHint:!0},inputSchema:{type:"object",properties:{level:{type:"string",enum:["AA","AAA"],description:"Defaults to 'AA'."},variant:{type:"string",enum:["light","dark","both"],description:"Defaults to 'both'."}},additionalProperties:!1},execute(x){let w=r(x),E=w.level==="AAA"?"AAA":"AA",S=w.variant==="light"||w.variant==="dark"?w.variant:"both",T=vs(e,E,S);return Ho({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(x){let{action:w}=r(x);switch(w){case"undo":return e.undo(),d({action:"undo"});case"redo":return e.redo(),d({action:"redo"});case"reset":return e.resetToDefaults(),d({action:"reset"});case"export":return Ho({ok:!0,snapshot:e.exportSnapshot()});default:throw new Error(`Unknown action "${w}". Valid: undo, redo, reset, export.`)}}}]}function Yy(e,t){if(!e)return t;switch(e.type){case"color":return e.parseValue?e.parseValue(_r(t)):_r(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}}0&&(module.exports={ADVANCED_TOKENS_SECTION,ALL_ROLES,ALL_TABS,BRAND_PALETTE_SECTION,BUILT_IN_PRESETS,COLORS_SECTIONS,COLOR_FAMILIES,COMPONENTS_SECTIONS,COMPONENT_COLOR_SECTIONS,COMPONENT_SHAPE_SECTIONS,CONFIGURE_SECTIONS,CONFIGURE_SUB_GROUPS,CONTRAST_PAIRS,CSS_NAMED_COLORS,DEVICE_DIMENSIONS,HOME_SUGGESTION_CHIPS,INTERFACE_ROLES_SECTION,MOCK_BROWSER_CONTENT,MOCK_WORKSPACE_CONTENT,PALETTE_SECTION,PREVIEW_STORAGE_ADAPTER,RADIUS_PRESETS,ROLE_ASSISTANT_MESSAGES,ROLE_BORDERS,ROLE_FAMILIES,ROLE_FAMILY_LABELS,ROLE_HEADER,ROLE_INPUT,ROLE_INTENSITIES,ROLE_LINKS_FOCUS,ROLE_PRIMARY_ACTIONS,ROLE_SCROLL_TO_BOTTOM,ROLE_SURFACES,ROLE_USER_MESSAGES,SEMANTIC_COLORS_SECTION,SHADE_KEYS,SHELL_STYLE_ID,STATUS_COLORS_SECTION,STATUS_PALETTE_SECTION,STYLE_SECTIONS,STYLE_SECTIONS_V2,THEME_EDITOR_PRESETS,THEME_SECTION,ThemeEditorState,ZOOM_MAX,ZOOM_MIN,appendPreviewTranscriptEntry,applySceneConfig,applyShellTheme,buildPreviewConfig,buildPreviewConfigWithMessages,buildShellCss,buildSrcdoc,buildSummary,buildTranscriptStreamFrames,coerceColor,coerceFamily,coerceIntensity,coerceRadius,coerceRoundnessStyle,coerceScheme,convertFromPx,convertToPx,createPreviewMessages,createPreviewTranscriptEntry,createThemeEditorTools,createThemePreview,detectRoleAssignment,escapeHtml,findSection,formatCssValue,generateColorScale,getPreviewTranscriptPresetLabel,getShellPalette,getThemeEditorPreset,hexToHsl,hslToHex,isValidHex,normalizeColorValue,paletteColorPath,parseCssValue,presetStreamsText,quickContrastWarnings,resolveRoleAssignment,resolveThemeColorPath,rgbToHex,runContrastChecks,scopeSection,tokenRefDisplayName,toolResult,wcagContrastRatio});
|
|
204
|
+
- Resizable panes`});(be=n.onAfterMount)==null||be.call(n,{iframes:z,controllers:[...o]})};for(let Ae of z){let le=Ae.dataset.mountId;if(!le)continue;let J=P.find(se=>se.mountId===le);J&&(Ae.addEventListener("load",()=>{Y++,Y>=he&&me()},{once:!0}),Ae.srcdoc=E(le,J.shellMode,wn(J.config),x))}he===0&&me()}function I(){var D;if(a)return;let R=ug(n);if(o.length!==R.length){M();return}if(R.some(W=>{let w=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${W.mountId}"]`);return!w||w.dataset.shellMode!==W.shellMode})){M();return}o.forEach((W,w)=>{var x;W.update(R[w].config),((x=n.scene)!=null?x:"conversation")==="minimized"&&W.close()});for(let W of R){let w=e.querySelector(`iframe[data-mount-id="${W.mountId}"]`);w&&fl(w,W.shellMode)}(D=n.onAfterUpdate)==null||D.call(n,{iframes:v(),controllers:[...o]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||m()}),s.observe(e)),M(),{update(R){if(a)return;let P=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},P?M():I()},destroy(){a||(a=!0,C(),s==null||s.disconnect(),e.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},m())},getIframes(){return v()},getScale(){return d},setZoom(R){a||(n={...n,zoom:R},m())}}}function _o(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}var Oa={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"},gv=/^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 hv(e){return gv.test(e)}function Gr(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=Oa[t];if(n)return n;let o=ps(t);if(mi(o)||o==="transparent"||hv(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(Oa).slice(0,6).join(", ")}).`)}var vl=Qs.map(e=>e==="gray"?"neutral":e),bv={...Object.fromEntries(vl.map(e=>[e,e])),gray:"neutral",grey:"neutral"};function Na(e,t=!0){let n=String(e!=null?e:"").trim().toLowerCase(),o=bv[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 _a(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 Va(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 yv={sharp:"sharp",square:"sharp",none:"sharp",default:"default",normal:"default",rounded:"rounded",round:"rounded",soft:"rounded",pill:"pill",circle:"pill",full:"pill"};function $a(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=yv[t];if(!n)throw new Error(`Unknown roundness "${e}". Valid: sharp, default, rounded, pill.`);return n}function Ua(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=pi(t);return ui(n.value,n.unit)}throw new Error('Radius must be a number (px) or a CSS length string like "0.5rem".')}function xl(e){for(let t of Fr){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 fg=xl("typo-font-family"),Da=xl("typo-font-size"),Fa=xl("typo-font-weight"),yl=xl("typo-line-height"),gg={...fg,monospace:fg.mono},hg={...Da,small:Da.sm,md:Da.base,medium:Da.base,large:Da.lg},bg={...Fa,400:Fa.normal,500:Fa.medium,600:Fa.semibold,700:Fa.bold},yg={...yl,"1.25":yl.tight,"1.5":yl.normal,"1.625":yl.relaxed};function vg(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 xg="theme.palette.radius.";function vv(){var t;let e={pill:{sm:"9999px",md:"9999px",lg:"9999px",xl:"9999px",full:"9999px"}};for(let n of Fr)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(xg)&&typeof i=="string"&&(s[a.slice(xg.length)]=i);e[r[1]]=s}return e}var Es=vv(),wg=["sm","md","lg","xl","full"];function Cl(e,t,n="theme",o=0){if(o>6)return null;let r=e.get(`${n}.${t}`);return typeof r!="string"||r===""?n==="darkTheme"?Cl(e,t,"theme",o):null:r.startsWith("#")||r.startsWith("rgb")||r==="transparent"?r:r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components.")?Cl(e,r,n,o+1):null}function wl(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 Ms(e){return e.replace(/^role-/,"")}function xv(e){for(let[t,n]of Object.entries(Es))if(wg.every(o=>e[o]===n[o]))return t;return"custom"}function wr(e){var o,r;let t={};for(let s of wg)t[s]=String((o=e.get(`theme.palette.radius.${s}`))!=null?o:"");let n={};for(let s of fr)n[Ms(s.roleId)]=bi(a=>e.get(`theme.${a}`),s);return{brand:{primary:Nc(e.get("theme.palette.colors.primary.500")),secondary:Nc(e.get("theme.palette.colors.secondary.500")),accent:Nc(e.get("theme.palette.colors.accent.500"))},roles:n,typography:{fontFamily:wl(e,"theme.semantic.typography.fontFamily"),fontSize:wl(e,"theme.semantic.typography.fontSize"),fontWeight:wl(e,"theme.semantic.typography.fontWeight"),lineHeight:wl(e,"theme.semantic.typography.lineHeight")},roundness:{style:xv(t),radius:t},colorScheme:String((r=e.get("colorScheme"))!=null?r:"light"),history:{index:e.getHistoryIndex(),canUndo:e.canUndo(),canRedo:e.canRedo()}}}function Nc(e){return typeof e=="string"&&e!==""?e:null}var ks=[{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 Cg(e){let t=new Set(e.targets.map(n=>n.path));return ks.filter(n=>t.has(n.fg)||t.has(n.bg)).map(n=>n.key)}var wv={AA:4.5,AAA:7};function Cv(e){return Math.round(e*100)/100}function Sv(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=Dr.indexOf(a[2]),l=null,f=1/0;return Dr.forEach((u,g)=>{let m=e.get(`${r}.palette.colors.${i}.${u}`);if(!(typeof m!="string"||!(m.startsWith("#")||m.startsWith("rgb")))&&Js(m,n)>=o){let C=d>=0?Math.abs(g-d):g;C<f&&(f=C,l=`palette.colors.${i}.${u}`)}}),l}function Ls(e,t="AA",n="both",o){let r=wv[t],s=n==="both"?["light","dark"]:[n],a=o?ks.filter(d=>o.includes(d.key)):ks,i=[];for(let d of s){let l=d==="light"?"theme":"darkTheme";for(let f of a){let u=Cl(e,f.fg,l),g=Cl(e,f.bg,l);if(!u||!g)continue;let m=Cv(Js(u,g)),C=m>=r,v={pair:f.key,label:f.label,variant:d,fg:u,bg:g,ratio:m,threshold:r,passes:C};if(!C){let M=Sv(e,f.fg,g,r,l);M&&(v.suggestion=M)}i.push(v)}}return{level:t,checks:i,failures:i.filter(d=>!d.passes)}}function Yr(e,t,n="light",o="AA"){return t.length===0?[]:Ls(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 bn={};for(let e of fr){let t=Ms(e.roleId);bn[t]=e,bn[e.roleId]=e}Object.assign(bn,{surface:bn.surfaces,background:bn.surfaces,backgrounds:bn.surfaces,user:bn["user-messages"],"user-message":bn["user-messages"],assistant:bn["assistant-messages"],"assistant-message":bn["assistant-messages"],actions:bn["primary-actions"],buttons:bn["primary-actions"],composer:bn.input,links:bn["links-focus"],focus:bn["links-focus"],border:bn.borders,dividers:bn.borders,scroll:bn["scroll-to-bottom"]});function Av(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=bn[t];if(!n){let o=fr.map(r=>Ms(r.roleId)).join(", ");throw new Error(`Unknown role "${e}". Valid roles: ${o}.`)}return n}function Sg(){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 yi)t(n.sections);for(let n of da)t(n.sections);return e}var Tv={voice:"voiceRecognition.enabled",artifacts:"features.artifacts.enabled",attachments:"attachments.enabled",toolCalls:"features.showToolCalls",reasoning:"features.showReasoning",feedback:"messageActions.enabled"},kv={avatars:"layout.messages.avatar.show",timestamps:"layout.messages.timestamp.show",showHeader:"layout.showHeader",messageStyle:"layout.messages.layout"},_c=["bottom-right","bottom-left","top-right","top-left"],Vc=["bubble","flat","minimal"],Ev={title:"copy.welcomeTitle",subtitle:"copy.welcomeSubtitle",placeholder:"copy.inputPlaceholder",sendLabel:"copy.sendButtonLabel"};function $c(e,t){var W;let n=(W=t==null?void 0:t.editTarget)!=null?W:"both",o=null,r=w=>w&&typeof w=="object"?w:{},s=(w,x,E=n)=>{let S={};return(E==="light"||E==="both")&&(S[`theme.${w}`]=x),(E==="dark"||E==="both")&&(S[`darkTheme.${w}`]=x),S},a=w=>{if(n==="both")return w;let x={};for(let[E,S]of Object.entries(w))(n==="light"&&E.startsWith("theme.")||n==="dark"&&E.startsWith("darkTheme."))&&(x[E]=S);return x},i=()=>n==="dark"?"dark":"light",d=(w,x=[])=>_o({ok:!0,summary:wr(e),warnings:x,applied:w});return[{name:"get_theme_overview",title:"Get current theme & what is editable",description:"Read the current widget theme (brand colors, per-role color assignments, typography, roundness, color scheme, undo/redo state), the available presets, and the high-level levers you can change. Call this FIRST before editing.",annotations:{readOnlyHint:!0},inputSchema:{type:"object",properties:{verbosity:{type:"string",enum:["summary","full"],description:"Use 'full' to also include the field-id index for set_theme_fields."}},additionalProperties:!1},execute(w){let{verbosity:x}=r(w),E={summary:wr(e),availableRoles:fr.map(S=>({role:Ms(S.roleId),helper:S.helper})),availableFamilies:vl,presets:ms.map(S=>{var k;return{id:S.id,name:S.name,description:S.description,tags:(k=S.tags)!=null?k:[]}}),tools:[{tool:"set_brand_colors",hint:"Recolor the palette (primary/secondary/accent) \u2014 auto-generates shade scales."},{tool:"assign_color_role",hint:"Recolor a region (header, user/assistant messages, actions, input, links, borders, surfaces, scroll) with a family + intensity."},{tool:"set_typography",hint:"Set font family, size, weight, line height."},{tool:"set_roundness",hint:"Set corner roundness (sharp/default/rounded/pill) or granular radii."},{tool:"set_color_scheme",hint:"Set light/dark/auto and which variant edits target."},{tool:"apply_preset",hint:"Apply a complete built-in preset."},{tool:"configure_widget",hint:"Toggle launcher position, features, and layout."},{tool:"set_copy_and_suggestions",hint:"Set welcome copy, placeholder, and suggestion chips."},{tool:"set_theme_fields",hint:"Advanced escape hatch: set any field by id or dot-path."},{tool:"check_contrast",hint:"Audit WCAG contrast across key text/background pairs."},{tool:"manage_session",hint:"Undo, redo, reset, or export the theme."}]};return x==="full"&&(o!=null||(o=Sg()),E.fieldIndex=Array.from(o.values()).map(S=>{var k;return{id:S.id,path:S.path,type:S.type,label:S.label,options:(k=S.options)==null?void 0:k.map(V=>V.value)}})),_o(E)}},{name:"set_brand_colors",title:"Set brand colors",description:'Set one or more brand colors (primary, secondary, accent). Each color auto-generates a full 50\u2013950 shade scale and applies to the light and dark themes (per the current edit target). Accepts hex ("#2563eb", "2563eb", "#18f"), rgb()/rgba() ("rgb(37, 99, 235)"), or CSS color names ("blue", "slateblue").',inputSchema:{type:"object",properties:{primary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},secondary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},accent:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."}},additionalProperties:!1},execute(w){let x=r(w),E=["primary","secondary","accent"],S={},k={};for(let z of E){if(x[z]===void 0)continue;let Y=Gr(x[z]);k[z]=Y;let he=gi(Y);for(let me of Dr){let de=he[me];de!==void 0&&Object.assign(S,s(`palette.colors.${z}.${me}`,de))}}if(Object.keys(k).length===0)throw new Error("Provide at least one of: primary, secondary, accent.");e.setBatch(S);let V=Yr(e,["primary-button","user-message"],i());return d(k,V)}},{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:vl},intensity:{type:"string",enum:["solid","soft"],description:"Defaults to 'solid'."}},required:["role","family"],additionalProperties:!1},execute(w){let x=r(w),E=Av(x.role),S=Na(x.family,!0),k=_a(x.intensity),V=a(la(S,k,E)),z=Object.keys(V).length;e.setBatch(V);let Y=Yr(e,Cg(E),i());return d({role:Ms(E.roleId),family:S,intensity:k,tokensWritten:z},Y)}},{name:"set_typography",title:"Set typography",description:"Set font family, base size, weight, and line height in one call. fontFamily: sans|serif|mono. fontSize: xs|sm|base|lg|xl. fontWeight: normal|medium|semibold|bold (or 400\u2013700). lineHeight: tight|normal|relaxed (or 1.25/1.5/1.625).",inputSchema:{type:"object",properties:{fontFamily:{type:"string"},fontSize:{type:"string"},fontWeight:{type:["string","number"]},lineHeight:{type:["string","number"]}},additionalProperties:!1},execute(w){let x=r(w),E={},S={},k=(V,z)=>{var he;if(x[V]===void 0)return;let Y=vg(x[V],z,V);S[V]=(he=Y.split(".").pop())!=null?he:Y,Object.assign(E,s(`semantic.typography.${V}`,Y))};if(k("fontFamily",gg),k("fontSize",hg),k("fontWeight",bg),k("lineHeight",yg),Object.keys(S).length===0)throw new Error("Provide at least one of: fontFamily, fontSize, fontWeight, lineHeight.");return e.setBatch(E),d(S)}},{name:"set_roundness",title:"Set corner roundness",description:"Set overall corner roundness with a keyword (sharp, default, rounded, pill) which maps the full radius scale, OR pass granular radius values. Provide at least one of `style` or `radius`.",inputSchema:{type:"object",properties:{style:{type:"string",enum:["sharp","default","rounded","pill"]},radius:{type:"object",description:"Granular overrides (px number or CSS length).",properties:{sm:{type:["string","number"]},md:{type:["string","number"]},lg:{type:["string","number"]},xl:{type:["string","number"]},full:{type:["string","number"]}},additionalProperties:!1}},additionalProperties:!1},execute(w){let x=r(w),E={},S={};if(x.style!==void 0){let k=$a(x.style);S.style=k;for(let[V,z]of Object.entries(Es[k]))Object.assign(E,s(`palette.radius.${V}`,z))}if(x.radius!==void 0){let k=r(x.radius),V={};for(let z of["sm","md","lg","xl","full"]){if(k[z]===void 0)continue;let Y=Ua(k[z]);V[z]=Y,Object.assign(E,s(`palette.radius.${z}`,Y))}S.radius=V}if(Object.keys(E).length===0)throw new Error("Provide `style` (sharp|default|rounded|pill) or a `radius` object.");return e.setBatch(E),d(S)}},{name:"set_color_scheme",title:"Set color scheme",description:"Set the shipped widget color scheme (light, dark, or auto/follow-system). Optionally set `editTarget` to choose which theme variant subsequent styling edits write to (light, dark, or both \u2014 default both).",inputSchema:{type:"object",properties:{scheme:{type:"string",enum:["light","dark","auto"]},editTarget:{type:"string",enum:["light","dark","both"]}},additionalProperties:!1},execute(w){let x=r(w),E={};if(x.scheme!==void 0){let S=Va(x.scheme);e.set("colorScheme",S),E.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,E.editTarget=S}if(Object.keys(E).length===0)throw new Error("Provide `scheme` and/or `editTarget`.");return _o({ok:!0,summary:wr(e),warnings:[],applied:E,editTarget:n})}},{name:"apply_preset",title:"Apply a built-in theme preset",description:"Apply a complete built-in preset, replacing theme tokens. Call get_theme_overview to list preset ids.",inputSchema:{type:"object",properties:{presetId:{type:"string"}},required:["presetId"],additionalProperties:!1},execute(w){let{presetId:x}=r(w),E=vi(String(x!=null?x:""));if(!E){let z=ms.map(Y=>Y.id).join(", ");throw new Error(`Unknown preset "${x}". Valid presets: ${z}.`)}let S=mn(E.theme,{validate:!1}),k={...e.getConfig()};E.darkTheme&&(k.darkTheme=mn(E.darkTheme,{validate:!1})),E.toolCall&&(k.toolCall=E.toolCall),e.setFullConfig(k,S);let V=Yr(e,["body","assistant-message"],"light");return d({appliedPreset:{id:E.id,name:E.name}},V)}},{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:_c},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:Vc}},additionalProperties:!1}},additionalProperties:!1},execute(w){var z,Y,he;let x=r(w),E={},S={};if(x.launcherPosition!==void 0){let me=String(x.launcherPosition);if(!_c.includes(me))throw new Error(`Unknown launcherPosition "${me}". Valid: ${_c.join(", ")}.`);E["launcher.position"]=me,S.launcherPosition=me}let k=r(x.features);for(let[me,de]of Object.entries(Tv))k[me]!==void 0&&(E[de]=!!k[me],(z=S.features)!=null||(S.features={}),S.features[me]=!!k[me]);let V=r(x.layout);for(let[me,de]of Object.entries(kv))if(V[me]!==void 0)if(me==="messageStyle"){let Ee=String(V[me]);if(!Vc.includes(Ee))throw new Error(`Unknown messageStyle "${Ee}". Valid: ${Vc.join(", ")}.`);E[de]=Ee,(Y=S.layout)!=null||(S.layout={}),S.layout[me]=Ee}else E[de]=!!V[me],(he=S.layout)!=null||(S.layout={}),S.layout[me]=!!V[me];if(Object.keys(E).length===0)throw new Error("Provide launcherPosition, features, and/or layout.");return e.setBatch(E),d(S)}},{name:"set_copy_and_suggestions",title:"Set welcome copy and suggestion chips",description:"Set the widget welcome copy and suggestion chips. title/subtitle are the welcome card text; placeholder is the input placeholder; sendLabel is the send button label; suggestions is an array of suggestion-chip strings (replaces the existing list).",inputSchema:{type:"object",properties:{title:{type:"string"},subtitle:{type:"string"},placeholder:{type:"string"},sendLabel:{type:"string"},suggestions:{type:"array",items:{type:"string"}}},additionalProperties:!1},execute(w){let x=r(w),E={},S={};for(let[k,V]of Object.entries(Ev))x[k]!==void 0&&(E[V]=String(x[k]),S[k]=String(x[k]));if(x.suggestions!==void 0){if(!Array.isArray(x.suggestions))throw new Error("`suggestions` must be an array of strings.");let k=x.suggestions.filter(V=>typeof V=="string");E.suggestionChips=k,S.suggestions=k}if(Object.keys(E).length===0)throw new Error("Provide at least one of: title, subtitle, placeholder, sendLabel, suggestions.");return e.setBatch(E),d(S)}},{name:"set_theme_fields",title:"Set theme fields by id or path (advanced)",description:'Advanced escape hatch: set individual editor fields by field id (see get_theme_overview verbosity:"full") \u2014 theme field ids follow the current edit target (light/dark/both) \u2014 or by raw dot-path (theme.* / darkTheme.* / a config path), which is written as-is. Use only when a higher-level tool does not cover the need. Values are validated against the field metadata.',inputSchema:{type:"object",properties:{updates:{type:"array",items:{type:"object",properties:{field:{type:"string",description:"Field id or dot-path."},value:{type:["string","number","boolean"]}},required:["field","value"],additionalProperties:!1}}},required:["updates"],additionalProperties:!1},execute(w){var V;let{updates:x}=r(w);if(!Array.isArray(x)||x.length===0)throw new Error("`updates` must be a non-empty array of { field, value }.");o!=null||(o=Sg());let E={},S=[];for(let z of x){let Y=r(z),he=String((V=Y.field)!=null?V:"");try{let me=o.get(he),de=me?me.path:he;if(!me&&!/^(theme|darkTheme)\.|\./.test(de))throw new Error(`Unknown field "${he}". Pass a known field id or a dot-path (e.g. theme.palette.radius.md).`);let Ee=Mv(me,Y.value);if(me&&de.startsWith("theme.")){let xe=s(de.slice(6),Ee);Object.assign(E,xe),S.push({field:he,resolvedPath:Object.keys(xe),ok:!0})}else E[de]=Ee,S.push({field:he,resolvedPath:de,ok:!0})}catch(me){S.push({field:he,ok:!1,error:me.message})}}let k=S.filter(z=>z.ok);return Object.keys(E).length>0&&e.setBatch(E),_o({ok:k.length>0,summary:wr(e),warnings:[],applied:{updates:S}})}},{name:"check_contrast",title:"Check accessibility contrast",description:"Run WCAG contrast checks over the key text/background pairs (message text, header title, input/body text, primary button). Returns each ratio, whether it passes, and a suggested foreground shade for failures.",annotations:{readOnlyHint:!0},inputSchema:{type:"object",properties:{level:{type:"string",enum:["AA","AAA"],description:"Defaults to 'AA'."},variant:{type:"string",enum:["light","dark","both"],description:"Defaults to 'both'."}},additionalProperties:!1},execute(w){let x=r(w),E=x.level==="AAA"?"AAA":"AA",S=x.variant==="light"||x.variant==="dark"?x.variant:"both",k=Ls(e,E,S);return _o({level:k.level,passing:k.checks.length-k.failures.length,total:k.checks.length,checks:k.checks,failures:k.failures})}},{name:"manage_session",title:"Undo, redo, reset, or export the theme",description:'Session action. "undo"/"redo" step through edit history; "reset" restores defaults; "export" returns the embeddable theme snapshot (config + theme JSON) with no side effects.',inputSchema:{type:"object",properties:{action:{type:"string",enum:["undo","redo","reset","export"]}},required:["action"],additionalProperties:!1},execute(w){let{action:x}=r(w);switch(x){case"undo":return e.undo(),d({action:"undo"});case"redo":return e.redo(),d({action:"redo"});case"reset":return e.resetToDefaults(),d({action:"reset"});case"export":return _o({ok:!0,snapshot:e.exportSnapshot()});default:throw new Error(`Unknown action "${x}". Valid: undo, redo, reset, export.`)}}}]}function Mv(e,t){if(!e)return t;switch(e.type){case"color":return e.parseValue?e.parseValue(Gr(t)):Gr(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}}0&&(module.exports={ADVANCED_TOKENS_SECTION,ALL_ROLES,ALL_TABS,BRAND_PALETTE_SECTION,BUILT_IN_PRESETS,COLORS_SECTIONS,COLOR_FAMILIES,COMPONENTS_SECTIONS,COMPONENT_COLOR_SECTIONS,COMPONENT_SHAPE_SECTIONS,CONFIGURE_SECTIONS,CONFIGURE_SUB_GROUPS,CONTRAST_PAIRS,CSS_NAMED_COLORS,DEVICE_DIMENSIONS,HOME_SUGGESTION_CHIPS,INTERFACE_ROLES_SECTION,MOCK_BROWSER_CONTENT,MOCK_WORKSPACE_CONTENT,PALETTE_SECTION,PREVIEW_STORAGE_ADAPTER,RADIUS_PRESETS,ROLE_ASSISTANT_MESSAGES,ROLE_BORDERS,ROLE_FAMILIES,ROLE_FAMILY_LABELS,ROLE_HEADER,ROLE_INPUT,ROLE_INTENSITIES,ROLE_LINKS_FOCUS,ROLE_PRIMARY_ACTIONS,ROLE_SCROLL_TO_BOTTOM,ROLE_SURFACES,ROLE_USER_MESSAGES,SEMANTIC_COLORS_SECTION,SHADE_KEYS,SHELL_STYLE_ID,STATUS_COLORS_SECTION,STATUS_PALETTE_SECTION,STYLE_SECTIONS,STYLE_SECTIONS_V2,THEME_EDITOR_PRESETS,THEME_SECTION,ThemeEditorState,ZOOM_MAX,ZOOM_MIN,appendPreviewTranscriptEntry,applySceneConfig,applyShellTheme,buildPreviewConfig,buildPreviewConfigWithMessages,buildShellCss,buildSrcdoc,buildSummary,buildTranscriptStreamFrames,coerceColor,coerceFamily,coerceIntensity,coerceRadius,coerceRoundnessStyle,coerceScheme,convertFromPx,convertToPx,createPreviewMessages,createPreviewTranscriptEntry,createThemeEditorTools,createThemePreview,detectRoleAssignment,escapeHtml,findSection,formatCssValue,generateColorScale,getPreviewTranscriptPresetLabel,getShellPalette,getThemeEditorPreset,hexToHsl,hslToHex,isValidHex,normalizeColorValue,paletteColorPath,parseCssValue,presetStreamsText,quickContrastWarnings,resolveRoleAssignment,resolveThemeColorPath,rgbToHex,runContrastChecks,scopeSection,tokenRefDisplayName,toolResult,wcagContrastRatio});
|