@runtypelabs/persona 3.34.0 → 3.35.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -11
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/{types-CthJFfNx.d.cts → types-DgYsuwXL.d.cts} +15 -14
- package/dist/animations/{types-CthJFfNx.d.ts → types-DgYsuwXL.d.ts} +15 -14
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/codegen.cjs +11 -11
- package/dist/codegen.js +10 -10
- package/dist/index.cjs +46 -44
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +514 -158
- package/dist/index.d.ts +514 -158
- package/dist/index.global.js +41 -89
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +46 -44
- package/dist/index.js.map +1 -1
- package/dist/install.global.js +1 -1
- package/dist/install.global.js.map +1 -1
- package/dist/launcher.global.js +2 -2
- package/dist/launcher.global.js.map +1 -1
- package/dist/markdown-parsers.js +53 -0
- package/dist/plugin-kit.d.cts +4 -4
- package/dist/plugin-kit.d.ts +4 -4
- package/dist/runtype-tts.js +1 -0
- package/dist/smart-dom-reader.cjs +1 -1
- package/dist/smart-dom-reader.d.cts +352 -103
- package/dist/smart-dom-reader.d.ts +352 -103
- package/dist/smart-dom-reader.js +1 -1
- package/dist/theme-editor-preview.cjs +203 -0
- package/dist/theme-editor-preview.d.cts +5748 -0
- package/dist/theme-editor-preview.d.ts +5748 -0
- package/dist/theme-editor-preview.js +203 -0
- package/dist/theme-editor.cjs +14 -131
- package/dist/theme-editor.d.cts +362 -574
- package/dist/theme-editor.d.ts +362 -574
- package/dist/theme-editor.js +14 -131
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.d.cts +1 -1
- package/dist/theme-reference.d.ts +1 -1
- package/dist/theme-reference.js +1 -1
- package/dist/voice-worklet-player.cjs +80 -0
- package/dist/voice-worklet-player.d.cts +215 -0
- package/dist/voice-worklet-player.d.ts +215 -0
- package/dist/voice-worklet-player.js +80 -0
- package/dist/widget.css +54 -36
- package/package.json +16 -2
- package/src/animations/glyph-cycle.ts +11 -14
- package/src/animations/wipe.ts +1 -1
- package/src/ask-user-question-tool.test.ts +1 -1
- package/src/ask-user-question-tool.ts +6 -8
- package/src/client.test.ts +67 -12
- package/src/client.ts +40 -32
- package/src/codegen.test.ts +1 -1
- package/src/codegen.ts +1 -1
- package/src/components/approval-bubble.test.ts +1 -1
- package/src/components/approval-bubble.ts +3 -3
- package/src/components/artifact-pane.ts +3 -3
- package/src/components/ask-user-question-bubble.test.ts +14 -14
- package/src/components/ask-user-question-bubble.ts +10 -10
- package/src/components/composer-builder.ts +17 -16
- package/src/components/composer-parts.test.ts +54 -0
- package/src/components/composer-parts.ts +95 -126
- package/src/components/demo-carousel.ts +1 -1
- package/src/components/event-stream-view.test.ts +7 -7
- package/src/components/event-stream-view.ts +5 -5
- package/src/components/header-builder.ts +33 -27
- package/src/components/header-layouts.ts +1 -1
- package/src/components/header-parts.test.ts +90 -0
- package/src/components/header-parts.ts +62 -93
- package/src/components/launcher.test.ts +11 -0
- package/src/components/launcher.ts +1 -1
- package/src/components/message-bubble.test.ts +74 -2
- package/src/components/message-bubble.ts +25 -11
- package/src/components/messages.ts +2 -2
- package/src/components/panel.test.ts +1 -1
- package/src/components/panel.ts +92 -97
- package/src/components/pill-composer-builder.ts +28 -24
- package/src/components/reasoning-bubble.ts +2 -2
- package/src/components/suggestions.ts +1 -1
- package/src/components/tool-bubble.ts +1 -1
- package/src/components/widget-view.test.ts +181 -0
- package/src/components/widget-view.ts +234 -0
- package/src/defaults.ts +54 -51
- package/src/generated/runtype-openapi-contract.ts +5 -0
- package/src/index-core.ts +30 -4
- package/src/index-global.ts +73 -6
- package/src/index.ts +7 -1
- package/src/install.test.ts +11 -11
- package/src/install.ts +28 -18
- package/src/launcher-global.ts +25 -14
- package/src/markdown-parsers-eager.ts +20 -0
- package/src/markdown-parsers-entry.ts +4 -0
- package/src/markdown-parsers-loader.ts +49 -0
- package/src/plugin-kit.test.ts +1 -1
- package/src/plugin-kit.ts +7 -7
- package/src/plugins/types.ts +5 -5
- package/src/postprocessors.ts +27 -14
- package/src/runtime/host-layout.test.ts +1 -1
- package/src/runtime/host-layout.ts +4 -5
- package/src/runtime/init.ts +2 -2
- package/src/session.test.ts +5 -6
- package/src/session.ts +333 -227
- package/src/session.voice.test.ts +146 -0
- package/src/session.webmcp.test.ts +24 -25
- package/src/smart-dom-reader.ts +3 -4
- package/src/styles/widget.css +54 -36
- package/src/suggest-replies-tool.test.ts +3 -3
- package/src/suggest-replies-tool.ts +5 -5
- package/src/testing/index.ts +1 -1
- package/src/theme-editor/color-utils.ts +2 -2
- package/src/theme-editor/index.ts +4 -13
- package/src/theme-editor/presets.ts +1 -1
- package/src/theme-editor/preview-utils.ts +22 -20
- package/src/theme-editor/preview.ts +4 -1
- package/src/theme-editor/role-mappings.ts +3 -3
- package/src/theme-editor/sections.ts +21 -20
- package/src/theme-editor/types.ts +1 -1
- package/src/theme-editor/webmcp/index.ts +1 -1
- package/src/theme-editor/webmcp/summary.ts +1 -2
- package/src/theme-editor/webmcp/tools.ts +30 -30
- package/src/theme-editor/webmcp/types.ts +2 -2
- package/src/theme-editor-preview.ts +10 -0
- package/src/theme-reference.ts +26 -26
- package/src/types.ts +368 -99
- package/src/ui.approval-plugin.test.ts +3 -3
- package/src/ui.ask-user-question-plugin.test.ts +9 -9
- package/src/ui.component-directive.test.ts +4 -4
- package/src/ui.composer-bar.test.ts +10 -11
- package/src/ui.composer-keyboard.test.ts +5 -5
- package/src/ui.header-icon-color.test.ts +59 -0
- package/src/ui.scroll.test.ts +5 -6
- package/src/ui.stop-button.test.ts +3 -4
- package/src/ui.suggest-replies.test.ts +2 -2
- package/src/ui.ts +292 -131
- package/src/utils/buttons.ts +1 -1
- package/src/utils/code-generators.ts +1 -1
- package/src/utils/composer-history.ts +3 -3
- package/src/utils/dom-context.test.ts +2 -2
- package/src/utils/dom-context.ts +7 -7
- package/src/utils/dom.test.ts +67 -0
- package/src/utils/dom.ts +75 -0
- package/src/utils/dropdown.ts +2 -2
- package/src/utils/event-stream-buffer.test.ts +2 -2
- package/src/utils/message-fingerprint.test.ts +9 -0
- package/src/utils/message-fingerprint.ts +5 -0
- package/src/utils/morph.ts +1 -1
- package/src/utils/sanitize.ts +32 -16
- package/src/utils/sequence-buffer.test.ts +8 -8
- package/src/utils/sequence-buffer.ts +4 -4
- package/src/utils/smart-dom-adapter.test.ts +1 -1
- package/src/utils/smart-dom-adapter.ts +4 -5
- package/src/utils/speech-text.test.ts +122 -0
- package/src/utils/speech-text.ts +101 -0
- package/src/utils/stream-animation.test.ts +3 -3
- package/src/utils/stream-animation.ts +6 -6
- package/src/utils/theme.test.ts +1 -1
- package/src/utils/throughput-tracker.test.ts +11 -11
- package/src/utils/throughput-tracker.ts +9 -9
- package/src/utils/tokens.ts +13 -13
- package/src/utils/virtual-scroller.ts +1 -1
- package/src/vendor/smart-dom-reader/README.md +4 -4
- package/src/vendor/smart-dom-reader/index.d.ts +1 -1
- package/src/vendor/smart-dom-reader/index.js +2 -2
- package/src/version.ts +1 -1
- package/src/voice/audio-playback-manager.test.ts +159 -0
- package/src/voice/audio-playback-manager.ts +145 -30
- package/src/voice/browser-speech-engine.ts +130 -0
- package/src/voice/fallback-speech-engine.ts +89 -0
- package/src/voice/index.ts +21 -0
- package/src/voice/read-aloud-controller.test.ts +143 -0
- package/src/voice/read-aloud-controller.ts +136 -0
- package/src/voice/runtype-speech-engine.test.ts +280 -0
- package/src/voice/runtype-speech-engine.ts +211 -0
- package/src/voice/runtype-tts-entry.ts +10 -0
- package/src/voice/runtype-tts-loader.test.ts +47 -0
- package/src/voice/runtype-tts-loader.ts +42 -0
- package/src/voice/runtype-voice-provider.ts +332 -537
- package/src/voice/voice-factory.ts +26 -4
- package/src/voice/voice.test.ts +321 -7
- package/src/voice/worklet-playback-engine.ts +272 -0
- package/src/voice-worklet-player.ts +39 -0
- package/src/webmcp-bridge.test.ts +6 -6
- package/src/webmcp-bridge.ts +24 -25
- package/src/webmcp-polyfill.ts +1 -1
- package/src/voice/voice-activity-detector.ts +0 -90
package/dist/theme-editor.cjs
CHANGED
|
@@ -1,110 +1,4 @@
|
|
|
1
|
-
"use strict";var Nf=Object.create;var di=Object.defineProperty;var _f=Object.getOwnPropertyDescriptor;var Vf=Object.getOwnPropertyNames;var $f=Object.getPrototypeOf,Uf=Object.prototype.hasOwnProperty;var zf=(e,t)=>{for(var n in t)di(e,n,{get:t[n],enumerable:!0})},rm=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Vf(t))!Uf.call(e,r)&&r!==n&&di(e,r,{get:()=>t[r],enumerable:!(o=_f(t,r))||o.enumerable});return e};var sm=(e,t,n)=>(n=e!=null?Nf($f(e)):{},rm(t||!e||!e.__esModule?di(n,"default",{value:e,enumerable:!0}):n,e)),qf=e=>rm(di({},"__esModule",{value:!0}),e);var Kv={};zf(Kv,{ADVANCED_TOKENS_SECTION:()=>jl,ALL_ROLES:()=>fr,ALL_TABS:()=>wi,BRAND_PALETTE_SECTION:()=>$l,BUILT_IN_PRESETS:()=>Kl,COLORS_SECTIONS:()=>Am,COLOR_FAMILIES:()=>vi,COMPONENTS_SECTIONS:()=>Fl,COMPONENT_COLOR_SECTIONS:()=>Ol,COMPONENT_SHAPE_SECTIONS:()=>Dl,CONFIGURE_SECTIONS:()=>_l,CONFIGURE_SUB_GROUPS:()=>pa,CONTRAST_PAIRS:()=>Ms,CSS_NAMED_COLORS:()=>$a,DEVICE_DIMENSIONS:()=>Yr,HOME_SUGGESTION_CHIPS:()=>Fc,INTERFACE_ROLES_SECTION:()=>zl,MOCK_BROWSER_CONTENT:()=>_c,MOCK_WORKSPACE_CONTENT:()=>Vc,PALETTE_SECTION:()=>Cm,PREVIEW_STORAGE_ADAPTER:()=>Oc,RADIUS_PRESETS:()=>Ls,ROLE_ASSISTANT_MESSAGES:()=>oa,ROLE_BORDERS:()=>la,ROLE_FAMILIES:()=>Zs,ROLE_FAMILY_LABELS:()=>ym,ROLE_HEADER:()=>ta,ROLE_INPUT:()=>aa,ROLE_INTENSITIES:()=>To,ROLE_LINKS_FOCUS:()=>ia,ROLE_PRIMARY_ACTIONS:()=>ra,ROLE_SCROLL_TO_BOTTOM:()=>sa,ROLE_SURFACES:()=>ea,ROLE_USER_MESSAGES:()=>na,SEMANTIC_COLORS_SECTION:()=>Sm,SHADE_KEYS:()=>Fr,SHELL_STYLE_ID:()=>Fa,STATUS_COLORS_SECTION:()=>ql,STATUS_PALETTE_SECTION:()=>Ul,STYLE_SECTIONS:()=>Nr,STYLE_SECTIONS_V2:()=>Tm,THEME_EDITOR_PRESETS:()=>hs,THEME_SECTION:()=>Vl,ThemeEditorState:()=>mi,ZOOM_MAX:()=>gl,ZOOM_MIN:()=>ml,appendPreviewTranscriptEntry:()=>yf,applySceneConfig:()=>vl,applyShellTheme:()=>hl,buildPreviewConfig:()=>wr,buildPreviewConfigWithMessages:()=>xf,buildShellCss:()=>fl,buildSrcdoc:()=>bl,buildSummary:()=>Cr,buildTranscriptStreamFrames:()=>vf,coerceColor:()=>Qr,coerceFamily:()=>Ua,coerceIntensity:()=>za,coerceRadius:()=>Ka,coerceRoundnessStyle:()=>ja,coerceScheme:()=>qa,convertFromPx:()=>fm,convertToPx:()=>gm,createPreviewMessages:()=>Uc,createPreviewTranscriptEntry:()=>yl,createThemeEditorTools:()=>Kc,createThemePreview:()=>Cf,detectRoleAssignment:()=>xi,escapeHtml:()=>Na,findSection:()=>Em,formatCssValue:()=>fi,generateColorScale:()=>yi,getPreviewTranscriptPresetLabel:()=>bf,getShellPalette:()=>Nc,getThemeEditorPreset:()=>Ci,hexToHsl:()=>Pl,hslToHex:()=>Wl,isValidHex:()=>hi,normalizeColorValue:()=>gs,paletteColorPath:()=>hm,parseCssValue:()=>gi,presetStreamsText:()=>$c,quickContrastWarnings:()=>Xr,resolveRoleAssignment:()=>ca,resolveThemeColorPath:()=>Bl,rgbToHex:()=>bi,runContrastChecks:()=>Rs,scopeSection:()=>Mm,tokenRefDisplayName:()=>bm,toolResult:()=>_o,wcagContrastRatio:()=>Js});module.exports=qf(Kv);var am=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];am(s)&&am(r)?n[o]=Xs(s,r):n[o]=r}return n}var go="min(440px, calc(100vw - 24px))",pi="440px",Lt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width: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 im(e,t){if(!(!e&&!t))return e?t?Xs(e,t):e:t}function lm(e){var t,n,o,r,s,a,i,d,l,u,g,f,m,x,v,M,I,R,B,D,P;return e?{...Lt,...e,theme:im(Lt.theme,e.theme),darkTheme:im(Lt.darkTheme,e.darkTheme),launcher:{...Lt.launcher,...e.launcher,dock:{...(t=Lt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(o=Lt.launcher)==null?void 0:o.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...Lt.copy,...e.copy},sendButton:{...Lt.sendButton,...e.sendButton},statusIndicator:{...Lt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Lt.voiceRecognition,...e.voiceRecognition},features:(()=>{var le,X,se,ye,be,K,ae,Pe,oe,ee;let w=(le=Lt.features)==null?void 0:le.artifacts,C=(X=e.features)==null?void 0:X.artifacts,E=(se=Lt.features)==null?void 0:se.scrollToBottom,A=(ye=e.features)==null?void 0:ye.scrollToBottom,S=(be=Lt.features)==null?void 0:be.scrollBehavior,V=(K=e.features)==null?void 0:K.scrollBehavior,$=(ae=Lt.features)==null?void 0:ae.streamAnimation,G=(Pe=e.features)==null?void 0:Pe.streamAnimation,he=(oe=Lt.features)==null?void 0:oe.askUserQuestion,me=(ee=e.features)==null?void 0:ee.askUserQuestion,de=w===void 0&&C===void 0?void 0:{...w,...C,layout:{...w==null?void 0:w.layout,...C==null?void 0:C.layout}},Ee=E===void 0&&A===void 0?void 0:{...E,...A},xe=S===void 0&&V===void 0?void 0:{...S,...V},De=$===void 0&&G===void 0?void 0:{...$,...G},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{...Lt.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:Lt.suggestionChips,suggestionChipsConfig:{...Lt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Lt.layout,...e.layout,header:{...(a=Lt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Lt.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(g=(u=Lt.layout)==null?void 0:u.messages)==null?void 0:g.avatar,...(m=(f=e.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(v=(x=Lt.layout)==null?void 0:x.messages)==null?void 0:v.timestamp,...(I=(M=e.layout)==null?void 0:M.messages)==null?void 0:I.timestamp}},slots:{...(R=Lt.layout)==null?void 0:R.slots,...(B=e.layout)==null?void 0:B.slots}},markdown:{...Lt.markdown,...e.markdown,options:{...(D=Lt.markdown)==null?void 0:D.options,...(P=e.markdown)==null?void 0:P.options}},messageActions:{...Lt.messageActions,...e.messageActions}}:Lt}var jf={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"}},Kf={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"}},Gf={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:pi,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 us(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."))?us(e,o):o}function cm(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=us(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 Yf(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 dm(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]=dm(s,r):n[o]=r}return n}function Qf(e,t){return t?dm(e,t):e}function un(e,t={}){var r,s,a,i,d,l,u,g,f,m,x,v,M;let n={palette:jf,semantic:Kf,components:Gf},o={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(u=e==null?void 0:e.semantic)==null?void 0:u.colors,interactive:{...n.semantic.colors.interactive,...(f=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(x=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:x.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:Qf(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let I=Yf(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 pm(e){var v,M,I,R,B,D,P,w,C,E,A,S,V,$,G,he,me,de,Ee,xe,De,Ae,le,X,se,ye,be,K,ae,Pe,oe,ee,re,it,lt,Ie,pe,Xe,Be,j,ge,nt,kt,ne,qe,_n,Ht,ln,so,Lo,O,ue,Oe,Ge,_e,$e,rt,Rt,jt,Jt,Y,vt,at,Se,ce,et,en,Kt,Pn,wn,mt,Et,Je,zt,cn,An,Tn,yn,Io,St,qn,jn,Vo,bo,xt,Sr,Ro,Ar,Vn,Jr,er,$o,At,Kn,Gn,Wn,It,ao,io,Yn,tr,Uo,nr,Qn,Dt,Bn,lo,or,zo,rr,Po,Xn,yo,ft,tn,nn,Jn,sr;let t=cm(e),n={};for(let[we,vo]of Object.entries(t)){let co=we.replace(/\./g,"-");n[`--persona-${co}`]=vo.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"]=(B=n["--persona-semantic-colors-background"])!=null?B: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"]=(P=n["--persona-semantic-colors-text"])!=null?P:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(w=n["--persona-semantic-colors-text-muted"])!=null?w:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(C=n["--persona-semantic-colors-text-inverse"])!=null?C:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(E=n["--persona-semantic-colors-border"])!=null?E:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(A=n["--persona-semantic-colors-divider"])!=null?A:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(S=n["--persona-components-voice-recording-indicator"])!=null?S: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"]=($=n["--persona-components-voice-processing-icon"])!=null?$:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(G=n["--persona-components-voice-speaking-icon"])!=null?G:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(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"]=(X=n["--persona-semantic-typography-fontFamily"])!=null?X: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"]=(Pe=n["--persona-palette-radius-lg"])!=null?Pe:"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"]=(Ie=n["--persona-components-launcher-foreground"])!=null?Ie:n["--persona-text-inverse"],n["--persona-launcher-border"]=(pe=n["--persona-components-launcher-border"])!=null?pe:n["--persona-border"],n["--persona-button-primary-bg"]=(Xe=n["--persona-components-button-primary-background"])!=null?Xe:n["--persona-primary"],n["--persona-button-primary-fg"]=(Be=n["--persona-components-button-primary-foreground"])!=null?Be:n["--persona-text-inverse"],n["--persona-button-radius"]=(ge=(j=n["--persona-components-button-primary-borderRadius"])!=null?j:n["--persona-palette-radius-full"])!=null?ge:"9999px",n["--persona-panel-radius"]=(kt=(nt=n["--persona-components-panel-borderRadius"])!=null?nt:n["--persona-radius-xl"])!=null?kt:"0.75rem",n["--persona-panel-border"]=(ne=n["--persona-components-panel-border"])!=null?ne:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(_n=(qe=n["--persona-components-panel-shadow"])!=null?qe:n["--persona-palette-shadows-xl"])!=null?_n:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(Ht=n["--persona-components-launcher-shadow"])!=null?Ht:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(so=(ln=n["--persona-components-input-borderRadius"])!=null?ln:n["--persona-radius-lg"])!=null?so:"0.5rem",n["--persona-message-user-radius"]=(O=(Lo=n["--persona-components-message-user-borderRadius"])!=null?Lo:n["--persona-radius-lg"])!=null?O:"0.5rem",n["--persona-message-assistant-radius"]=(Oe=(ue=n["--persona-components-message-assistant-borderRadius"])!=null?ue:n["--persona-radius-lg"])!=null?Oe:"0.5rem",n["--persona-header-bg"]=(Ge=n["--persona-components-header-background"])!=null?Ge: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"]=(rt=n["--persona-components-header-iconForeground"])!=null?rt:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(Rt=n["--persona-components-header-titleForeground"])!=null?Rt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(jt=n["--persona-components-header-subtitleForeground"])!=null?jt:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Jt=n["--persona-components-header-actionIconForeground"])!=null?Jt:n["--persona-muted"];let o=(Y=e.components)==null?void 0:Y.header;o!=null&&o.shadow&&(n["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom);let r=(vt=e.components)==null?void 0:vt.introCard;n["--persona-intro-card-bg"]=(at=n["--persona-components-introCard-background"])!=null?at: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"]=(en=(et=r==null?void 0:r.shadow)!=null?et:n["--persona-components-introCard-shadow"])!=null?en:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Kt=n["--persona-components-input-background"])!=null?Kt:n["--persona-surface"],n["--persona-input-placeholder"]=(Pn=n["--persona-components-input-placeholder"])!=null?Pn:n["--persona-text-muted"],n["--persona-message-user-bg"]=(wn=n["--persona-components-message-user-background"])!=null?wn: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"]=(Et=n["--persona-components-message-user-shadow"])!=null?Et:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Je=n["--persona-components-message-assistant-background"])!=null?Je:n["--persona-surface"],n["--persona-message-assistant-text"]=(zt=n["--persona-components-message-assistant-text"])!=null?zt:n["--persona-text"],n["--persona-message-assistant-border"]=(cn=n["--persona-components-message-assistant-border"])!=null?cn:n["--persona-border"],n["--persona-message-assistant-shadow"]=(An=n["--persona-components-message-assistant-shadow"])!=null?An:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(yn=(Tn=n["--persona-components-scrollToBottom-background"])!=null?Tn:n["--persona-button-primary-bg"])!=null?yn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(St=(Io=n["--persona-components-scrollToBottom-foreground"])!=null?Io:n["--persona-button-primary-fg"])!=null?St:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(qn=n["--persona-components-scrollToBottom-border"])!=null?qn:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(jn=n["--persona-components-scrollToBottom-size"])!=null?jn:"40px",n["--persona-scroll-to-bottom-radius"]=(xt=(bo=(Vo=n["--persona-components-scrollToBottom-borderRadius"])!=null?Vo:n["--persona-button-radius"])!=null?bo:n["--persona-radius-full"])!=null?xt:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Ro=(Sr=n["--persona-components-scrollToBottom-shadow"])!=null?Sr:n["--persona-palette-shadows-sm"])!=null?Ro:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(Ar=n["--persona-components-scrollToBottom-padding"])!=null?Ar:"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"]=(er=(Jr=n["--persona-components-scrollToBottom-fontSize"])!=null?Jr:n["--persona-palette-typography-fontSize-sm"])!=null?er:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=($o=n["--persona-components-scrollToBottom-iconSize"])!=null?$o:"14px",n["--persona-tool-bubble-shadow"]=(At=n["--persona-components-toolBubble-shadow"])!=null?At:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Kn=n["--persona-components-reasoningBubble-shadow"])!=null?Kn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Gn=n["--persona-components-composer-shadow"])!=null?Gn:"none",n["--persona-md-inline-code-bg"]=(Wn=n["--persona-components-markdown-inlineCode-background"])!=null?Wn:n["--persona-container"],n["--persona-md-inline-code-color"]=(It=n["--persona-components-markdown-inlineCode-foreground"])!=null?It:n["--persona-text"],n["--persona-md-link-color"]=(io=(ao=n["--persona-components-markdown-link-foreground"])!=null?ao:n["--persona-accent"])!=null?io:"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let l=n["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(n["--persona-md-prose-font-family"]=l),n["--persona-md-code-block-bg"]=(Yn=n["--persona-components-markdown-codeBlock-background"])!=null?Yn:n["--persona-container"],n["--persona-md-code-block-border-color"]=(tr=n["--persona-components-markdown-codeBlock-borderColor"])!=null?tr: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"]=(nr=n["--persona-components-markdown-table-headerBackground"])!=null?nr:n["--persona-container"],n["--persona-md-table-border-color"]=(Qn=n["--persona-components-markdown-table-borderColor"])!=null?Qn:n["--persona-border"],n["--persona-md-hr-color"]=(Dt=n["--persona-components-markdown-hr-color"])!=null?Dt:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Bn=n["--persona-components-markdown-blockquote-borderColor"])!=null?Bn:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(lo=n["--persona-components-markdown-blockquote-background"])!=null?lo:"transparent",n["--persona-md-blockquote-text-color"]=(or=n["--persona-components-markdown-blockquote-textColor"])!=null?or:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(zo=n["--persona-components-collapsibleWidget-container"])!=null?zo:n["--persona-surface"],n["--cw-surface"]=(rr=n["--persona-components-collapsibleWidget-surface"])!=null?rr:n["--persona-surface"],n["--cw-border"]=(Po=n["--persona-components-collapsibleWidget-border"])!=null?Po:n["--persona-border"],n["--persona-message-border"]=(Xn=n["--persona-components-message-border"])!=null?Xn:n["--persona-border"];let u=e.components,g=u==null?void 0:u.iconButton;g&&(g.background&&(n["--persona-icon-btn-bg"]=g.background),g.border&&(n["--persona-icon-btn-border"]=g.border),g.color&&(n["--persona-icon-btn-color"]=g.color),g.padding&&(n["--persona-icon-btn-padding"]=g.padding),g.borderRadius&&(n["--persona-icon-btn-radius"]=g.borderRadius),g.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=g.hoverBackground),g.hoverColor&&(n["--persona-icon-btn-hover-color"]=g.hoverColor),g.activeBackground&&(n["--persona-icon-btn-active-bg"]=g.activeBackground),g.activeBorder&&(n["--persona-icon-btn-active-border"]=g.activeBorder));let f=u==null?void 0:u.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let m=u==null?void 0:u.toggleGroup;m&&(m.gap&&(n["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(n["--persona-toggle-group-radius"]=m.borderRadius));let x=u==null?void 0:u.artifact;if(x!=null&&x.toolbar){let we=x.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"]=(yo=n["--persona-dropdown-bg"])!=null?yo:we.copyMenuBackground),we.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=we.copyMenuBorder,n["--persona-dropdown-border"]=(ft=n["--persona-dropdown-border"])!=null?ft:we.copyMenuBorder),we.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=we.copyMenuShadow,n["--persona-dropdown-shadow"]=(tn=n["--persona-dropdown-shadow"])!=null?tn:we.copyMenuShadow),we.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=we.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(nn=n["--persona-dropdown-radius"])!=null?nn:we.copyMenuBorderRadius),we.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=we.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(Jn=n["--persona-dropdown-item-hover-bg"])!=null?Jn:we.copyMenuItemHoverBackground),we.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=we.iconBackground),we.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=we.toolbarBorder)}if(x!=null&&x.tab){let we=x.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(x!=null&&x.pane){let we=x.pane;if(we.toolbarBackground){let vo=(sr=us(e,we.toolbarBackground))!=null?sr:we.toolbarBackground;n["--persona-artifact-toolbar-bg"]=vo}}return n}var Xf={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"}}},um=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Il=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Jf=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Il()},Zf=e=>Jf(e),eh=e=>un(e),th=e=>{var n;let t=un(void 0,{validate:!1});return un({...e,palette:{...t.palette,colors:{...Xf.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},ui=e=>{let t=Zf(e),n=um(e==null?void 0:e.theme),o=um(e==null?void 0:e.darkTheme);return t==="dark"?th(Xs(n!=null?n:{},o!=null?o:{})):eh(n)},nh=e=>pm(e),ms=(e,t)=>{let n=ui(t),o=nh(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s)},mm=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Il())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(Il());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};function Rl(e,t){let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return o}function Or(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]:Or((i=a==null?void 0:a[r])!=null?i:{},s.join("."),n)}}var mi=class{constructor(t,n,o){this.listeners=[];this.history=[];this.historyIndex=-1;this.suppressHistory=!1;var s;let r=(s=o==null?void 0:o.mergeDefaults)!=null?s:!0;this.config=r?{...Lt,...n}:n!=null?n:Lt,this.theme=un(t,{validate:!1}),this.syncThemeIntoConfig(),this.pushHistorySnapshot(this.exportSnapshot(),!0)}get(t){var n;return t.startsWith("theme.")?Rl(this.theme,t.replace("theme.","")):t.startsWith("darkTheme.")?Rl((n=this.config.darkTheme)!=null?n:{},t.replace("darkTheme.","")):Rl(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=Or(this.theme,r,n),this.syncThemeIntoConfig()}else if(t.startsWith("darkTheme.")){let r=t.replace("darkTheme.",""),s=(o=this.config.darkTheme)!=null?o:un();this.config={...this.config,darkTheme:Or(s,r,n)}}else this.config=Or(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=Or(this.theme,d,i),n=!0}else if(a.startsWith("darkTheme.")){let d=a.replace("darkTheme.",""),l=(s=this.config.darkTheme)!=null?s:un();this.config={...this.config,darkTheme:Or(l,d,i)},o=!0}else this.config=Or(this.config,a,i),r=!0;n&&this.syncThemeIntoConfig(),(n||o||r)&&(this.recordHistory(),this.notifyListeners())}setTheme(t){this.theme=t,this.syncThemeIntoConfig(),this.recordHistory(),this.notifyListeners()}setFullConfig(t,n){this.config={...t},n&&(this.theme=n),this.syncThemeIntoConfig(),this.recordHistory(),this.notifyListeners()}importSnapshot(t){var r,s;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Snapshot must be a JSON object");let n=t;if("config"in n||"theme"in n||n.version===2){let a=(r=n.config)!=null?r:this.config,i=un((s=n.theme)!=null?s:this.theme,{validate:!1});this.setFullConfig(a,i);return}let o=un(n,{validate:!1});this.setTheme(o)}resetToDefaults(){this.config={...Lt},this.theme=un(),this.syncThemeIntoConfig(),this.history=[],this.historyIndex=-1,this.pushHistorySnapshot(this.exportSnapshot()),this.notifyListeners()}canUndo(){return this.historyIndex>0}canRedo(){return this.historyIndex>=0&&this.historyIndex<this.history.length-1}getHistoryLength(){return this.history.length}getHistoryIndex(){return this.historyIndex}undo(){this.canUndo()&&(this.historyIndex-=1,this.restoreSnapshot(this.history[this.historyIndex]))}redo(){this.canRedo()&&(this.historyIndex+=1,this.restoreSnapshot(this.history[this.historyIndex]))}exportSnapshot(){return{version:2,config:{...this.config,theme:void 0},theme:this.theme}}onChange(t){return this.listeners.push(t),()=>{let n=this.listeners.indexOf(t);n>=0&&this.listeners.splice(n,1)}}syncThemeIntoConfig(){this.config={...this.config,theme:this.theme}}notifyListeners(){for(let t of this.listeners)t(this.config,this.theme)}recordHistory(){this.pushHistorySnapshot(this.exportSnapshot())}pushHistorySnapshot(t,n=!1){if(this.suppressHistory)return;let o=JSON.stringify(t),r=this.historyIndex>=0&&this.history[this.historyIndex]?JSON.stringify(this.history[this.historyIndex]):null;if(n&&this.historyIndex>=0){this.history[this.historyIndex]=t;return}o!==r&&(this.history=this.history.slice(0,this.historyIndex+1),this.history.push(t),this.historyIndex=this.history.length-1)}restoreSnapshot(t){this.suppressHistory=!0,this.config=t.config,this.theme=un(t.theme,{validate:!1}),this.syncThemeIntoConfig(),this.suppressHistory=!1,this.notifyListeners()}};function gi(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 fi(e,t){return t==="rem"?`${e}rem`:`${e}px`}function gm(e,t){return t==="rem"?e*16:e}function fm(e,t){return t==="rem"?e/16:e}function gs(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 hi(e){return/^#[0-9A-Fa-f]{6}$/.test(e)}function bi(e){let t=e.trim().toLowerCase().match(/^rgba?\(([^)]+)\)$/);if(!t)return null;let n=t[1].split(",").map(d=>d.trim());if(n.length<3)return null;let o=d=>{let l=d.endsWith("%"),u=parseFloat(l?d.slice(0,-1):d);return Number.isFinite(u)?Math.max(0,Math.min(255,Math.round(l?u/100*255:u))):NaN},r=o(n[0]),s=o(n[1]),a=o(n[2]);if(!Number.isFinite(r)||!Number.isFinite(s)||!Number.isFinite(a))return null;let i=d=>d.toString(16).padStart(2,"0");return`#${i(r)}${i(s)}${i(a)}`}function Js(e,t){let n=s=>{var l;let a=gs(s),i=a.startsWith("rgb")?(l=bi(a))!=null?l:"#000000":a,d=[1,3,5].map(u=>{let g=parseInt(i.slice(u,u+2),16)/255;return g<=.03928?g/12.92:Math.pow((g+.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 Pl(e){var f;let t=gs(e),n=t.startsWith("rgb")?(f=bi(t))!=null?f:"#000000":t,o=parseInt(n.slice(1,3),16)/255,r=parseInt(n.slice(3,5),16)/255,s=parseInt(n.slice(5,7),16)/255,a=Math.max(o,r,s),i=Math.min(o,r,s),d=(a+i)/2;if(a===i)return{h:0,s:0,l:d};let l=a-i,u=d>.5?l/(2-a-i):l/(a+i),g;switch(a){case o:g=((r-s)/l+(r<s?6:0))/6;break;case r:g=((s-o)/l+2)/6;break;default:g=((o-r)/l+4)/6;break}return{h:g*360,s:u,l:d}}function Wl(e,t,n){let o=(e%360+360)%360,r=(1-Math.abs(2*n-1))*t,s=r*(1-Math.abs(o/60%2-1)),a=n-r/2,i,d,l;o<60?[i,d,l]=[r,s,0]:o<120?[i,d,l]=[s,r,0]:o<180?[i,d,l]=[0,r,s]:o<240?[i,d,l]=[0,s,r]:o<300?[i,d,l]=[s,0,r]:[i,d,l]=[r,0,s];let u=g=>{let f=Math.round((g+a)*255).toString(16);return f.length===1?"0"+f:f};return`#${u(i)}${u(d)}${u(l)}`}function yi(e){let{h:t,s:n,l:o}=Pl(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]=Wl(t,l,d)}return a}var Fr=["50","100","200","300","400","500","600","700","800","900","950"],vi=["primary","secondary","accent","gray","success","warning","error","info"];function hm(e,t){return`palette.colors.${e}.${t}`}function Bl(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.")?Bl(e,`theme.${o}`,n+1):"#cbd5e1"}function bm(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"}],Zs=["primary","secondary","accent","gray"],ym={primary:"Primary",secondary:"Secondary",accent:"Accent",gray:"Neutral"},ea={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"}]},ta={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"}]},na={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"}]},oa={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"}]},ra={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"}]},sa={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"}]},aa={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"}]},ia={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"}]},la={roleId:"role-borders",helper:"Borders, dividers, and separators",intensities:To,targets:[{path:"semantic.colors.border",kind:"border"},{path:"semantic.colors.divider",kind:"border"}]},fr=[ea,ta,na,oa,ra,sa,aa,ia,la];function ca(e,t,n){let o={},r=e==="neutral"?"gray":e;for(let s of n.targets){let a=oh(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 oh(e,t,n,o){let r=t==="solid";if(o==="role-header")return rh(e,r,n);if(o==="role-input")return sh(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 rh(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 sh(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 ah=/^palette\.colors\.(\w+)\.(\d+)$/;function xi(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(ah);if(!r)return null;let s=r[1],a=Zs.includes(s)?s:null;if(!a)return null;for(let l of["solid","soft"]){let u=ca(a,l,t);if(t.targets.every(f=>{var x;return String((x=e(f.path))!=null?x:"")===u[`theme.${f.path}`]}))return{family:a,intensity:l}}return null}var ih={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"}]}]},lh={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"}]},ch={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"}}]},dh={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)"}]}]},ph={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"}]}]},uh={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"}}]},mh={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)"}]},gh={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"}]}]},Nr=[lh,ch,ph,dh,ih,uh,mh,gh];function xm(){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:vi.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 wm={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"}}]},Cm=xm(),Sm=wm,Am=[xm(),wm],fh={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:pi},{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"}]}]},hh={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"}]}]},bh={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"}]}]},yh={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"}]}]},vh={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"}]}]},xh={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"}}]},wh={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"}}]},Ch={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"}}]},Sh={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"}}]},Ah={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"}]},fs=[{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"}],Hl="0 5px 15px rgba(15, 23, 42, 0.08)",vm=[{value:Hl,label:"Default"},...fs],Th={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:fs},{id:"shadow-msg-assistant",label:"Assistant Message",type:"select",path:"theme.components.message.assistant.shadow",defaultValue:"palette.shadows.sm",options:fs},{id:"shadow-tool-bubble",label:"Tool Call Bubble",type:"select",path:"theme.components.toolBubble.shadow",defaultValue:"palette.shadows.sm",options:fs},{id:"shadow-reasoning-bubble",label:"Reasoning Bubble",type:"select",path:"theme.components.reasoningBubble.shadow",defaultValue:"palette.shadows.sm",options:fs},{id:"shadow-approval",label:"Approval Bubble",type:"select",path:"theme.components.approval.requested.shadow",defaultValue:Hl,options:vm},{id:"shadow-intro-card",label:"Intro Card",type:"select",path:"theme.components.introCard.shadow",defaultValue:Hl,options:vm},{id:"shadow-composer",label:"Composer",type:"select",path:"theme.components.composer.shadow",defaultValue:"palette.shadows.none",options:fs}]},Dl=[fh,hh,bh,yh,vh,Th],Ol=[xh,wh,Ch,Sh,Ah],Fl=[...Dl,...Ol],Nl=1024*1024,kh=["What can you help me with?","Tell me about your features","How does this work?"],da={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 Eh(e){return Number(e)*Nl}function Mh(e){let t=Number(e);return Number.isFinite(t)?t>1024?String(Math.round(t/Nl)):String(t):"10"}function Lh(e){var t;return(t=da[String(e)])!=null?t:da.images}function Ih(e){let t=Array.isArray(e)?e:da.images,n=[...new Set(t)].sort();for(let[o,r]of Object.entries(da)){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 Rh={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"}]},Ph={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:kh}]},Wh={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:""}]},Bh={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}]},Hh={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"}]}]},Dh={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"}]}]},Oh={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"}]},Fh={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:""}]},Nh={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"}]},_h={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"}]},Vh={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"}]},$h={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"}]},Uh={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:""}]},zh={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)}]},qh={id:"attachments-config",title:"Attachments",collapsed:!0,fields:[{id:"attach-enabled",label:"Enabled",type:"toggle",path:"attachments.enabled",defaultValue:!1},{id:"attach-max-files",label:"Max Files",type:"select",path:"attachments.maxFiles",defaultValue:4,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"4",label:"4"},{value:"6",label:"6"},{value:"8",label:"8"},{value:"10",label:"10"}],formatValue:e=>String(e!=null?e:4),parseValue:e=>Number(e)},{id:"attach-max-size",label:"Max File Size (MB)",type:"select",path:"attachments.maxFileSize",defaultValue:10*Nl,options:[{value:"1",label:"1 MB"},{value:"5",label:"5 MB"},{value:"10",label:"10 MB"},{value:"25",label:"25 MB"},{value:"50",label:"50 MB"}],formatValue:Mh,parseValue:Eh},{id:"attach-types",label:"Allowed File Types",type:"select",path:"attachments.allowedTypes",defaultValue:da.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:Ih,parseValue:Lh}]},jh={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"}]}]},Kh={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}]},Gh={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"}]}]},Yh={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}]},Qh={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}]},pa=[{label:"Content",sections:[Rh,Ph]},{label:"Layout",sections:[Wh,Bh,Hh,Dh]},{label:"Widget",sections:[Oh,Fh,Nh,_h,Vh,$h]},{label:"Features",sections:[Uh,zh,qh,jh,Kh]},{label:"Developer",collapsedByDefault:!0,sections:[Gh,Yh,Qh]}],_l=pa.flatMap(e=>e.sections),Vl={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"}]},Ul={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"}]},zl={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:ea},{id:"role-header",label:"Header",type:"role-assignment",path:"theme.components.header.background",roleAssignment:ta},{id:"role-user-messages",label:"User Messages",type:"role-assignment",path:"theme.components.message.user.background",roleAssignment:na},{id:"role-assistant-messages",label:"Assistant Messages",type:"role-assignment",path:"theme.components.message.assistant.background",roleAssignment:oa},{id:"role-primary-actions",label:"Primary Actions",type:"role-assignment",path:"theme.components.button.primary.background",roleAssignment:ra},{id:"role-scroll-to-bottom",label:"Scroll To Bottom",type:"role-assignment",path:"theme.components.scrollToBottom.background",roleAssignment:sa},{id:"role-input",label:"Input Field",type:"role-assignment",path:"theme.components.input.background",roleAssignment:aa},{id:"role-links-focus",label:"Links & Focus",type:"role-assignment",path:"theme.semantic.colors.accent",roleAssignment:ia},{id:"role-borders",label:"Borders & Dividers",type:"role-assignment",path:"theme.semantic.colors.border",roleAssignment:la}]},ql={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"}}]},jl={id:"advanced-tokens",title:"Advanced Tokens",description:"Override individual semantic and component values when you need precise control.",collapsed:!0,fields:[]},Tm=[Vl,$l,Ul,zl,ql,jl],wi=[{id:"style",label:"Style",sections:Nr},{id:"design-system",label:"Design System",sections:Fl},{id:"configure",label:"Configure",sections:_l}];function km(e,t){return e.startsWith("theme.")?e.replace(/^theme\./,`${t}.`):e}function Xh(e,t,n){return{...e,id:`${n}-${e.id}`,path:km(e.path,t)}}function Em(e,t){let n=e.find(o=>o.id===t);if(!n)throw new Error(`Section "${t}" not found in definitions`);return n}function Mm(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=>Xh(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])=>[km(d,t),l]))}))}}var Kl=[{id:"default-light",name:"Default Light",description:"Clean monochrome light theme",theme:{components:{artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}}},preview:{primary:"#171717",surface:"#ffffff",accent:"#0f0f0f"},tags:["light"]},{id:"default-dark",name:"Default Dark",description:"Monochrome dark theme",theme:{palette:{colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},semantic:{colors:{primary:"palette.colors.primary.400",secondary:"palette.colors.gray.400",accent:"palette.colors.primary.500",surface:"palette.colors.gray.800",background:"palette.colors.gray.900",container:"palette.colors.gray.800",text:"palette.colors.gray.100",textMuted:"palette.colors.gray.400",textInverse:"palette.colors.gray.900",border:"palette.colors.gray.700",divider:"palette.colors.gray.700",interactive:{default:"palette.colors.primary.400",hover:"palette.colors.primary.300",focus:"palette.colors.primary.500",active:"palette.colors.primary.600",disabled:"palette.colors.gray.600"},feedback:{success:"palette.colors.success.400",warning:"palette.colors.warning.400",error:"palette.colors.error.400",info:"palette.colors.primary.400"}}}},preview:{primary:"#171717",surface:"#1f2937",accent:"#0f0f0f"},tags:["dark"]},{id:"high-contrast",name:"High Contrast",description:"Maximum contrast for accessibility",theme:{semantic:{colors:{primary:"palette.colors.primary.700",secondary:"palette.colors.gray.700",accent:"palette.colors.primary.800",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.200",text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.400",divider:"palette.colors.gray.400",interactive:{default:"palette.colors.primary.700",hover:"palette.colors.primary.800",focus:"palette.colors.primary.900",active:"palette.colors.primary.950",disabled:"palette.colors.gray.400"},feedback:{success:"palette.colors.success.700",warning:"palette.colors.warning.700",error:"palette.colors.error.700",info:"palette.colors.primary.700"}}}},preview:{primary:"#0a0a0a",surface:"#f9fafb",accent:"#050505"},tags:["light","high-contrast","accessibility"]}],hs=[...Kl];function Ci(e){return hs.find(t=>t.id===e)}var Lm=require("marked"),Jh=e=>{if(e)return e},Gl=e=>{var r,s;let t=e==null?void 0:e.markedOptions,n=new Lm.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=Jh(e==null?void 0:e.renderer);return o&&n.use({renderer:o}),a=>n.parse(a)},Si=e=>e?Gl({markedOptions:e.options,renderer:e.renderer}):Gl(),fx=Gl();var ua=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");var Im=sm(require("dompurify"),1),Zh={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"]},eb=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,tb=()=>{let e=(0,Im.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:")&&!eb.test(o)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,Zh)},Ai=e=>e===!1?null:typeof e=="function"?e:tb();var _r="webmcp:",Yl=new Map,Rm=e=>{var t;Yl.clear();for(let n of e){let o=(t=n.title)==null?void 0:t.trim();o&&Yl.set(n.name,o)}},Ql=e=>Yl.get(Hm(e)),Ti={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Pm=null;function Bm(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}:${nb(t.join(""))}`}function Wm(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 nb(e){let t=Wm(e,0).toString(36),n=Wm(e,2654435761).toString(36);return`${t}.${n}`}var ki=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 Ti.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",r),[]}Rm(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=rb(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 x=typeof document!="undefined"&&!!document.modelContext;return ko(x?"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=Hm(t),a;try{a=await r.getTools()}catch(x){let v=x instanceof Error?x.message:String(x);return ko(`Failed to read WebMCP registry: ${v}`)}Rm(a);let i=a.find(x=>x.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=Ql(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 u=new AbortController,g=!1,f=setTimeout(()=>{g=!0,u.abort()},this.timeoutMs),m=()=>u.abort();o&&(o.aborted?u.abort():o.addEventListener("abort",m,{once:!0}));try{let x=await r.executeTool(i,lb(n),{signal:u.signal});return sb(x)}catch(x){if(g)return ko(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return ko("Aborted by cancel()");let v=x instanceof Error?x.message:String(x);return ko(v)}finally{clearTimeout(f),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}(Pm?await Pm():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Ti.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,Ti.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:ab;try{return await n(t)}catch(r){return Ti.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=>ob(t,o))}},Hm=e=>e.startsWith(_r)?e.slice(_r.length):e,ma=e=>e.startsWith(_r),ob=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},rb=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},sb=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:cb(t)}]}},ko=e=>({isError:!0,content:[{type:"text",text:e}]}),ab=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=ib(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
2
|
-
|
|
3
|
-
Arguments:
|
|
4
|
-
${t}`:"")+(e.description?`
|
|
5
|
-
|
|
6
|
-
${e.description}`:"");return window.confirm(n)},ib=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)}},lb=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},cb=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var hr=require("partial-json");var b=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},No=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o};var Xl="ask_user_question",ga=8,bs="data-persona-ask-sheet-for",db="Other",pb="Other\u2026",Om="Type your own answer here",Fm="Send",ub="Next",mb="Back",gb="Submit all",fb="Skip",hb=3,Jl="data-ask-current-index",Zl="data-ask-question-count",Nm="data-ask-answers",ec="data-ask-grouped",_m="data-ask-layout",bb=e=>e.layout==="pills"?"pills":"rows",yb=e=>e.getAttribute(_m)==="pills"?"pills":"rows",Dm=!1,Vm=e=>e.replace(/["\\]/g,"\\$&"),Vr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Xl,tc=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},ys=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,hr.parse)(r,hr.STR|hr.OBJ|hr.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},fa=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>ga&&!Dm&&(Dm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${ga}.`)),t.slice(0,ga)},vb=e=>{var t;return(t=fa(e)[0])!=null?t:null},xb=(e,t)=>{var n;return(n=fa(e)[t])!=null?n:null},wb=(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))},$m=(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},Cb=(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=$m(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Sb=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},Ab=(e,t,n,o)=>{var u,g,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(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!n){for(let m=0;m<hb;m++)s.appendChild(Sb(o));return s}if(d.forEach((m,x)=>{s.appendChild(Cb(m,x,o,a))}),(e==null?void 0:e.allowFreeText)!==!1){let m=o==="rows"?db:pb;if(o==="rows"){let x=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");x.setAttribute("data-ask-user-action","focus-free-text"),x.setAttribute("data-option-index",String(d.length)),x.setAttribute("data-ask-other-row","true");let 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=(u=t.freeTextPlaceholder)!=null?u:Om,M.setAttribute("data-ask-free-text-input","true"),M.setAttribute("aria-label",(g=t.freeTextLabel)!=null?g:m),v.appendChild(M),x.appendChild(v);let I=$m(o,a,d.length);I&&x.appendChild(I),s.appendChild(x)}else{let x=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");x.type="button",x.setAttribute("data-ask-user-action","open-free-text"),x.textContent=(f=t.freeTextLabel)!=null?f:m,s.appendChild(x)}}return s},Um=(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:Om,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:Fm,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},Tb=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:Fm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},kb=(e,t,n)=>{var l,u,g,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:mb,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(u=n.skipLabel)!=null?u:fb,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?(g=n.submitAllLabel)!=null?g:gb:(f=n.nextLabel)!=null?f:ub,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},$r=e=>{let t=e.getAttribute(Nm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},zm=(e,t)=>{e.setAttribute(Nm,JSON.stringify(t))},fo=e=>{var n;let t=Number((n=e.getAttribute(Jl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Eb=(e,t)=>{e.setAttribute(Jl,String(Math.max(0,Math.floor(t))))},vs=e=>{var n;let t=Number((n=e.getAttribute(Zl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},br=e=>e.getAttribute(ec)==="true",Mb=(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},Lb=(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)))},Ei=(e,t)=>{let{payload:n}=ys(t),o=fa(n),r=$r(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},qm=e=>{let t=$r(e),n=fo(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(d=>r.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var g;let l=(g=d.getAttribute("data-option-label"))!=null?g:"",u=r.has(l);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!a.has(o)){i.value=o;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},jm=e=>{if(!br(e))return;let t=$r(e),n=fo(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},nc=(e,t,n)=>{let o=tc(n),r=yb(e),{payload:s,complete:a}=ys(t),i=br(e),d=fo(e),l=vs(e),u=i?xb(s,d):vb(s),g=!!(u!=null&&u.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let R=typeof(u==null?void 0:u.question)=="string"?u.question:"";x.textContent=R,x.classList.toggle("persona-ask-question-skeleton",!R&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let R=Ab(u,o,a,r);v.replaceWith(R)}if(r!=="rows"){let R=e.querySelector('[data-ask-free-text-row="true"]');R&&R.replaceWith(Um(o,r))}let M=e.querySelector('[data-ask-multi-actions="true"]');!i&&g&&!M?e.appendChild(Tb(o)):(!g||i)&&M&&M.remove(),e.setAttribute("data-multi-select",g?"true":"false");let I=e.querySelector('[data-ask-nav-row="true"]');if(i){let R=kb(d,l,o);I?I.replaceWith(R):e.appendChild(R)}else I&&I.remove();qm(e),jm(e)},Ib=(e,t,n)=>{let o=tc(t),r=bb(o),s=e.toolCall.id,a=fa(n),i=Math.max(1,a.length),d=i>1,l=Mb(e,a),u=d?Lb(e,i):0,g=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(bs,s),g.setAttribute("data-tool-call-id",s),g.setAttribute("data-message-id",e.id),g.setAttribute(Zl,String(i)),g.setAttribute(Jl,String(u)),g.setAttribute(ec,d?"true":"false"),g.setAttribute(_m,r),zm(g,l),g.setAttribute("role","group"),g.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&g.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),wb(g,o);let f=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="",f.appendChild(m);let x=b("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",f.appendChild(x),g.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"),g.appendChild(M),r!=="rows"&&g.appendChild(Um(o,r)),nc(g,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},Rb=(e,t,n)=>{let{payload:o}=ys(t),r=Math.max(1,fa(o).length);r>vs(e)&&(e.setAttribute(Zl,String(r)),r>1&&!br(e)&&e.setAttribute(ec,"true")),nc(e,t,n)};var Mi=(e,t,n)=>{if(!n||!Vr(e)||tc(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${bs}]`).forEach(l=>{l.getAttribute(bs)!==r&&l.remove()});let a=n.querySelector(`[${bs}="${Vm(r)}"]`);if(a){Rb(a,e,t);return}let{payload:i}=ys(e),d=Ib(e,t,i);n.appendChild(d)},xs=(e,t)=>{if(!e)return;let n=t?`[${bs}="${Vm(t)}"]`:`[${bs}]`;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)})},oc=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),yr=(e,t)=>{let n=$r(e),o=fo(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,zm(e,n),qm(e),jm(e)},Li=(e,t,n,o)=>{let r=vs(e),s=Math.max(0,Math.min(r-1,o));Eb(e,s),nc(e,t,n)};var Xo="suggest_replies";var Pb={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},Km={name:Xo,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown \u2014 do not add further commentary after calling this tool; end your turn.`,parametersSchema:Pb,origin:"sdk",annotations:{readOnlyHint:!0}},rc=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),sc=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Xo},Wb=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t==null?void 0:t.suggestions;if(!Array.isArray(n))return[];let o=n.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},Gm=e=>{var t;for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return null;if(!sc(o))continue;let r=Wb((t=o.toolCall)==null?void 0:t.args);return r.length>0?r:null}return null},Ym=e=>{var n;let t=(n=e==null?void 0:e.features)==null?void 0:n.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var Bb={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:ga,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option \u2014 free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},Hb={name:Xl,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make \u2014 a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:Bb,origin:"sdk",annotations:{readOnlyHint:!0}},ac=e=>{var o;let t=[],n=(o=e==null?void 0:e.features)==null?void 0:o.askUserQuestion;return(n==null?void 0:n.expose)===!0&&n.enabled!==!1&&t.push(Hb),Ym(e)&&t.push(Km),t};var ws=require("partial-json"),Qm=e=>e.replace(/\\n/g,`
|
|
7
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Cs=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)}},Db=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`},Xm=e=>e.status==="complete"?Db(e):e.status==="pending"?"Waiting":"",Ob=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 Jm=e=>e.status==="complete"?Ob(e):"Using tool...",Ii=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},ba=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 Ii(t)},Ri=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 Ii(t)},ic=(e,t,n)=>{var s;if(!t)return n;let o=((s=e.name)==null?void 0:s.trim())||"tool",r=ba(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},Pi=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&ha(o,n.slice(s,a.index),[]),a[1]!==void 0?ha(o,a[1],["bold"]):a[2]!==void 0?ha(o,a[2],["italic"]):a[3]!==void 0&&ha(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&ha(o,n.slice(s),[]),o},ha=(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})},Fb=()=>{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
|
-
`).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()=>{}}},Ur=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Zm=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},eg=()=>{var t;let e=Fb();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)}},tg=()=>{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,ws.parse)(n,ws.STR|ws.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Qm(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Qm(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var ng=()=>{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 Wi=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 Nb="https://api.runtype.com/v1/dispatch",Bi="https://api.runtype.com";function _b(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 lc=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 Vb(e){switch(e){case"json":return tg;case"regex-json":return eg;case"xml":return ng;default:return Zm}}var og=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function $b(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=og(n);if(!og(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Ur(e);return Ur(t)!==null&&a===null?t:e}var ya=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:Nb,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:Vb(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 ki(t.webmcp):null}updateConfig(t){this.config=t}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$/,""))||Bi}/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$/,""))||Bi}/v1/client/feedback`}async sendFeedback(t){var s,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var r,s,a,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(r=this.config).onSessionExpired)==null||s.call(r);let D=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:D}),D}let l=await this.buildPayload(t.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([D])=>D!=="sessionId"&&D!=="session_id")):void 0,g={sessionId:d.sessionId,messages:t.messages.filter(lc).map(D=>{var P,w,C;return{id:D.id,role:D.role,content:(C=(w=(P=D.contentParts)!=null?P:D.llmContent)!=null?w:D.rawContent)!=null?C:D.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},f=l.clientTools,m=!!(f&&f.length>0),x=m?Bm(f):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,M=m&&v&&this.lastSentClientToolsFingerprint===x,I=!1,R=null,B;for(let D=0;;D++){let w={...g,...m&&(I||!M)&&f?{clientTools:f}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",w),B=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w),signal:o.signal}),B.status===409&&D===0&&m){let C=await B.json().catch(()=>null);if((C==null?void 0:C.error)==="client_tools_resend_required"){I=!0,this.lastSentClientToolsFingerprint=null;continue}R=C!=null?C:{error:"Chat request failed"}}break}if(!B.ok){let D=R!=null?R:await B.json().catch(()=>({error:"Chat request failed"}));if(B.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(B.status===429){let w=new Error(D.hint||"Message limit reached for this session.");throw n({type:"error",error:w}),w}let P=new Error(D.error||"Failed to send message");throw n({type:"error",error:P}),P}if(!B.body){let D=new Error("No response body received");throw n({type:"error",error:D}),D}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(B.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$/,""))||Bi}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,o){var l,u;let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Bi}/resume`,a;r&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(u=o==null?void 0:o.streamResponse)!=null?u:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var s,a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(lc).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,d)=>{let l=new Date(i.createdAt).getTime(),u=new Date(d.createdAt).getTime();return l-u}).map(i=>{var d,l,u;return{role:i.role,content:(u=(l=(d=i.contentParts)!=null?d:i.llmContent)!=null?l:i.rawContent)!=null?u:i.content,createdAt:i.createdAt}}),o={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},r=[...ac(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(r.length>0&&(o.clientTools=r),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let l=await d({messages:t,config:this.config});l&&typeof l=="object"&&Object.assign(i,l)}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",l)}})),Object.keys(i).length&&(o.context=i)}return o}async buildPayload(t){var s,a;let o={messages:t.slice().filter(lc).sort((i,d)=>{let l=new Date(i.createdAt).getTime(),u=new Date(d.createdAt).getTime();return l-u}).map(i=>{var d,l,u;return{role:i.role,content:(u=(l=(d=i.contentParts)!=null?d:i.llmContent)!=null?l:i.rawContent)!=null?u:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},r=[...ac(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(r.length>0&&(o.clientTools=r),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let l=await d({messages:t,config:this.config});l&&typeof l=="object"&&Object.assign(i,l)}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",l)}})),Object.keys(i).length&&(o.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...o},config:this.config});if(i&&typeof i=="object"){let d=i;return o.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=o.clientTools),d}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return o}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=u=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return o.current=g,r(g),g},l=u=>o.current?o.current:d(u);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let u=l(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,r(u)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o){var Ht,ln,so,Lo;let r=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,u=O=>{let ue=O.reasoning?{...O.reasoning,chunks:[...O.reasoning.chunks]}:void 0,Oe=O.toolCall?{...O.toolCall,chunks:O.toolCall.chunks?[...O.toolCall.chunks]:void 0}:void 0,Ge=O.tools?O.tools.map(_e=>({..._e,chunks:_e.chunks?[..._e.chunks]:void 0})):void 0;return{...O,reasoning:ue,toolCall:Oe,tools:Ge}},g=O=>{if(O.role!=="assistant"||O.variant)return!0;let ue=Array.isArray(O.contentParts)&&O.contentParts.length>0,Oe=typeof O.rawContent=="string"&&O.rawContent.trim()!=="";return typeof O.content=="string"&&O.content.trim()!==""||ue||Oe||!!O.stopReason},f=O=>{g(O)&&n({type:"message",message:u(O)})},m=null,x=null,v={current:null},M={current:null},I=!1,R=new Map,B=new Map,D=new Map,P=new Map,w={lastId:null,byStep:new Map},C={lastId:null,byCall:new Map},E=(O,ue,Oe="")=>`${O}::${ue}::${Oe}`,A=(O,ue)=>`${O}::${ue}::`,S=(O,ue,Oe,Ge)=>{let _e=E(O,ue,Oe),$e=D.get(_e);if($e)return $e;let rt=Oe?`-${Oe}`:"",Rt={id:`nested-${O}-${ue}${rt}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Oe?{partId:Oe}:{},agentMetadata:{executionId:Ge,parentToolId:O,parentStepId:ue}};return D.set(_e,Rt),f(Rt),Rt},V=O=>{if(O==null)return null;try{return String(O)}catch{return null}},$=O=>{var ue,Oe,Ge,_e,$e;return V(($e=(_e=(Ge=(Oe=(ue=O.stepId)!=null?ue:O.step_id)!=null?Oe:O.step)!=null?Ge:O.parentId)!=null?_e:O.flowStepId)!=null?$e:O.flow_step_id)},G=O=>{var ue,Oe,Ge,_e,$e,rt,Rt;return V((Rt=(rt=($e=(_e=(Ge=(Oe=(ue=O.callId)!=null?ue:O.call_id)!=null?Oe:O.requestId)!=null?Ge:O.request_id)!=null?_e:O.toolCallId)!=null?$e:O.tool_call_id)!=null?rt:O.stepId)!=null?Rt:O.step_id)},he=o,me=!1,de=()=>{if(m)return m;let O;return!me&&he?(O=he,me=!0):he&&M.current?O=`${he}_${M.current}`:O=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:O,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(m),m},Ee=(O,ue)=>{w.lastId=ue,O&&w.byStep.set(O,ue)},xe=(O,ue)=>{var $e;let Oe=($e=O.reasoningId)!=null?$e:O.id,Ge=$(O);if(Oe){let rt=String(Oe);return Ee(Ge,rt),rt}if(Ge){let rt=w.byStep.get(Ge);if(rt)return w.lastId=rt,rt}if(w.lastId&&!ue)return w.lastId;if(!ue)return null;let _e=`reason-${l()}`;return Ee(Ge,_e),_e},De=O=>{let ue=R.get(O);if(ue)return ue;let Oe={id:`reason-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:O,status:"streaming",chunks:[]}};return R.set(O,Oe),f(Oe),Oe},Ae=(O,ue)=>{C.lastId=ue,O&&C.byCall.set(O,ue)},le=new Set,X=new Map,se=new Set,ye=new Map,be=O=>{if(!O)return!1;let ue=O.replace(/_+/g,"_").replace(/^_|_$/g,"");return ue==="emit_artifact_markdown"||ue==="emit_artifact_component"},K=(O,ue)=>{var $e;let Oe=($e=O.toolId)!=null?$e:O.id,Ge=G(O);if(Oe){let rt=String(Oe);return Ae(Ge,rt),rt}if(Ge){let rt=C.byCall.get(Ge);if(rt)return C.lastId=rt,rt}if(C.lastId&&!ue)return C.lastId;if(!ue)return null;let _e=`tool-${l()}`;return Ae(Ge,_e),_e},ae=O=>{let ue=B.get(O);if(ue)return ue;let Oe={id:`tool-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:O,status:"pending"}};return B.set(O,Oe),f(Oe),Oe},Pe=O=>{if(typeof O=="number"&&Number.isFinite(O))return O;if(typeof O=="string"){let ue=Number(O);if(!Number.isNaN(ue)&&Number.isFinite(ue))return ue;let Oe=Date.parse(O);if(!Number.isNaN(Oe))return Oe}return Date.now()},oe=O=>{if(typeof O=="string")return O;if(O==null)return"";try{return JSON.stringify(O)}catch{return String(O)}},ee=new Map,re=new Map,it=new Map,lt=new Map,Ie=null,pe=(O,ue,Oe)=>{var Rt;let Ge=it.get(O);Ge||(Ge=[],it.set(O,Ge));let _e=0,$e=Ge.length;for(;_e<$e;){let jt=_e+$e>>>1;Ge[jt].seq<ue?_e=jt+1:$e=jt}((Rt=Ge[_e])==null?void 0:Rt.seq)===ue?Ge[_e]={seq:ue,text:Oe}:Ge.splice(_e,0,{seq:ue,text:Oe});let rt="";for(let jt=0;jt<Ge.length;jt++)rt+=Ge[jt].text;return rt},Xe=(O,ue)=>{let Oe=oe(ue),Ge=re.get(O.id),_e=$b(Ge,Oe);O.rawContent=_e;let $e=ee.get(O.id),rt=vt=>{var Se;let at=(Se=O.content)!=null?Se:"";vt.trim()!==""&&(at.trim().length===0||vt.startsWith(at)||vt.trimStart().startsWith(at.trim()))&&(O.content=vt)},Rt=()=>{var vt;if($e){let at=(vt=$e.close)==null?void 0:vt.call($e);at instanceof Promise&&at.catch(()=>{})}ee.delete(O.id),re.delete(O.id),O.streaming=!1,f(O)};if(!$e){rt(Oe),Rt();return}let jt=Ur(_e);if(jt!==null&&jt.trim()!==""){rt(jt),Rt();return}let Jt=vt=>{var ce;let at=typeof vt=="string"?vt:(ce=vt==null?void 0:vt.text)!=null?ce:null;if(at!==null&&at.trim()!=="")return at;let Se=$e.getExtractedText();return Se!==null&&Se.trim()!==""?Se:Oe},Y;try{Y=$e.processChunk(_e)}catch{rt(Oe),Rt();return}if(Y instanceof Promise){Y.then(vt=>{rt(Jt(vt)),Rt()}).catch(()=>{rt(Oe),Rt()});return}rt(Jt(Y)),Rt()},Be=[],j=!1,ge,nt=()=>{j||(j=!0,queueMicrotask(()=>{j=!1,ge()}))},kt=new Wi((O,ue)=>{Be.push({payloadType:O,payload:ue}),nt()}),ne=null,qe=new Map,_n=(Ht=this.config.iterationDisplay)!=null?Ht:"separate";for(ge=()=>{var O,ue,Oe,Ge,_e,$e,rt,Rt,jt,Jt,Y,vt,at,Se,ce,et,en,Kt,Pn,wn,mt,Et,Je,zt,cn,An,Tn,yn,Io,St,qn,jn,Vo,bo,xt,Sr,Ro,Ar,Vn,Jr,er,$o,At,Kn,Gn,Wn,It,ao,io,Yn,tr,Uo,nr,Qn,Dt,Bn,lo,or,zo,rr,Po,Xn,yo,ft,tn,nn,Jn,sr,we,vo,co,U,Zr,Wo,qo,jo,Bo,xo,Ps,Zn,eo,wo,Co,Tr,Ko,kn,Ho,es,kr,ts,Ga,ns,Ya,os,yt,Ws,po,$n,Qa,Xa,rs,Go,Bs,ar,Hs,Ds,Os,Fs,Un,ss,Do,Oo,Ns,Ja,_s,Vs,Er,Za,ei,ti,ni,Tl,Mr,ir,oi,$s,lr,ri,Us,cr,zs,si,Yo,ai,dr,Ot,as,is;for(let Lr=0;Lr<Be.length;Lr++){let Ue=Be[Lr].payloadType,k=Be[Lr].payload;if(Ue==="reason_start"){let z=(O=xe(k,!0))!=null?O:`reason-${l()}`,W=De(z);W.reasoning=(ue=W.reasoning)!=null?ue:{id:z,status:"streaming",chunks:[]},W.reasoning.startedAt=(Ge=W.reasoning.startedAt)!=null?Ge:Pe((Oe=k.startedAt)!=null?Oe:k.timestamp),W.reasoning.completedAt=void 0,W.reasoning.durationMs=void 0,W.streaming=!0,W.reasoning.status="streaming",f(W)}else if(Ue==="reason_delta"||Ue==="reason_chunk"){let z=($e=(_e=xe(k,!1))!=null?_e:xe(k,!0))!=null?$e:`reason-${l()}`,W=De(z);W.reasoning=(rt=W.reasoning)!=null?rt:{id:z,status:"streaming",chunks:[]},W.reasoning.startedAt=(jt=W.reasoning.startedAt)!=null?jt:Pe((Rt=k.startedAt)!=null?Rt:k.timestamp);let Z=(vt=(Y=(Jt=k.reasoningText)!=null?Jt:k.text)!=null?Y:k.delta)!=null?vt:"";if(Z&&k.hidden!==!0){let ie=typeof k.sequenceIndex=="number"?k.sequenceIndex:void 0;if(ie!==void 0){let Q=pe(z,ie,String(Z));W.reasoning.chunks=[Q]}else W.reasoning.chunks.push(String(Z))}if(W.reasoning.status=k.done?"complete":"streaming",k.done){W.reasoning.completedAt=Pe((at=k.completedAt)!=null?at:k.timestamp);let ie=(Se=W.reasoning.startedAt)!=null?Se:Date.now();W.reasoning.durationMs=Math.max(0,((ce=W.reasoning.completedAt)!=null?ce:Date.now())-ie)}W.streaming=W.reasoning.status!=="complete",f(W)}else if(Ue==="reason_complete"){let z=(en=(et=xe(k,!1))!=null?et:xe(k,!0))!=null?en:`reason-${l()}`,W=R.get(z);if(W!=null&&W.reasoning){W.reasoning.status="complete",W.reasoning.completedAt=Pe((Kt=k.completedAt)!=null?Kt:k.timestamp);let ie=(Pn=W.reasoning.startedAt)!=null?Pn:Date.now();W.reasoning.durationMs=Math.max(0,((wn=W.reasoning.completedAt)!=null?wn:Date.now())-ie),W.streaming=!1,f(W)}let Z=$(k);Z&&w.byStep.delete(Z)}else if(Ue==="tool_start"){let z=(mt=K(k,!0))!=null?mt:`tool-${l()}`,W=(Et=k.toolName)!=null?Et:k.name;if(be(W)){le.add(z);continue}let Z=ae(z),ie=(Je=Z.toolCall)!=null?Je:{id:z,status:"pending"};ie.name=W!=null?W:ie.name,ie.status="running",k.args!==void 0?ie.args=k.args:k.parameters!==void 0&&(ie.args=k.parameters),ie.startedAt=(cn=ie.startedAt)!=null?cn:Pe((zt=k.startedAt)!=null?zt:k.timestamp),ie.completedAt=void 0,ie.durationMs=void 0,Z.toolCall=ie,Z.streaming=!0;let Q=k.agentContext;(Q||k.executionId)&&(Z.agentMetadata={executionId:(An=Q==null?void 0:Q.executionId)!=null?An:k.executionId,iteration:(Tn=Q==null?void 0:Q.iteration)!=null?Tn:k.iteration}),f(Z)}else if(Ue==="tool_chunk"||Ue==="tool_delta"){let z=(Io=(yn=K(k,!1))!=null?yn:K(k,!0))!=null?Io:`tool-${l()}`;if(le.has(z))continue;let W=ae(z),Z=(St=W.toolCall)!=null?St:{id:z,status:"running"};Z.startedAt=(jn=Z.startedAt)!=null?jn:Pe((qn=k.startedAt)!=null?qn:k.timestamp);let ie=(xt=(bo=(Vo=k.text)!=null?Vo:k.delta)!=null?bo:k.message)!=null?xt:"";ie&&(Z.chunks=(Sr=Z.chunks)!=null?Sr:[],Z.chunks.push(String(ie))),Z.status="running",W.toolCall=Z,W.streaming=!0;let Q=k.agentContext;(Q||k.executionId)&&(W.agentMetadata=(Vn=W.agentMetadata)!=null?Vn:{executionId:(Ro=Q==null?void 0:Q.executionId)!=null?Ro:k.executionId,iteration:(Ar=Q==null?void 0:Q.iteration)!=null?Ar:k.iteration}),f(W)}else if(Ue==="tool_complete"){let z=(er=(Jr=K(k,!1))!=null?Jr:K(k,!0))!=null?er:`tool-${l()}`;if(le.has(z)){le.delete(z);continue}let W=ae(z),Z=($o=W.toolCall)!=null?$o:{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=Pe((At=k.completedAt)!=null?At:k.timestamp);let ie=(Kn=k.duration)!=null?Kn:k.executionTime;if(typeof ie=="number")Z.durationMs=ie;else{let Ne=(Gn=Z.startedAt)!=null?Gn:Date.now();Z.durationMs=Math.max(0,((Wn=Z.completedAt)!=null?Wn:Date.now())-Ne)}W.toolCall=Z,W.streaming=!1;let Q=k.agentContext;(Q||k.executionId)&&(W.agentMetadata=(io=W.agentMetadata)!=null?io:{executionId:(It=Q==null?void 0:Q.executionId)!=null?It:k.executionId,iteration:(ao=Q==null?void 0:Q.iteration)!=null?ao:k.iteration}),f(W);let Le=G(k);Le&&C.byCall.delete(Le)}else if(Ue==="step_await"&&k.awaitReason==="local_tool_required"&&k.toolName){let z=typeof k.toolCallId=="string"&&k.toolCallId.length>0?k.toolCallId:void 0,W=(Yn=z!=null?z:k.toolId)!=null?Yn:`local-${l()}`,Z=ae(W),ie=k.toolName,Q=ma(ie),Le=(tr=Z.toolCall)!=null?tr:{id:W,status:"pending"};Le.name=ie,Le.args=k.parameters,Le.status=Q?"running":"complete",Le.chunks=(Uo=Le.chunks)!=null?Uo:[],Le.startedAt=(Qn=Le.startedAt)!=null?Qn:Pe((nr=k.startedAt)!=null?nr:k.timestamp),Q?(Le.completedAt=void 0,Le.duration=void 0,Le.durationMs=void 0):Le.completedAt=(Dt=Le.completedAt)!=null?Dt:Le.startedAt,Z.toolCall=Le,Z.streaming=!1,Z.agentMetadata={...Z.agentMetadata,executionId:(lo=k.executionId)!=null?lo:(Bn=Z.agentMetadata)==null?void 0:Bn.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},f(Z)}else if(Ue==="text_start"){if((or=k.toolContext)!=null&&or.toolId)continue;let z=k.partId;if(z!==void 0&&M.current!==null&&z!==M.current){let W=m;W&&(W.streaming=!1,f(W),Ie=W,m=null,I=!0)}z!==void 0&&(M.current=z)}else if(Ue==="text_end"){if((zo=k.toolContext)!=null&&zo.toolId)continue;let z=m;z&&(z.streaming=!1,f(z),Ie=z,m=null,I=!0)}else if(Ue==="step_chunk"||Ue==="step_delta"){let z=k.stepType,W=k.executionType;if(z==="tool"||W==="context")continue;let Z=k.toolContext;if(Z!=null&&Z.toolId){let Ne=String((Po=(rr=k.id)!=null?rr:Z.stepId)!=null?Po:`step-${l()}`),ct=k.partId!==void 0&&k.partId!==null?String(k.partId):"",Ze=`${Z.toolId}::${Ne}`,Bt=P.get(Ze);if(ct!==""&&Bt!==void 0&&Bt!==""&&Bt!==ct){let st=D.get(E(Z.toolId,Ne,Bt));st&&st.streaming!==!1&&(st.streaming=!1,f(st))}ct!==""&&P.set(Ze,ct);let Vt=S(Z.toolId,Ne,ct,Z.executionId),mn=(tn=(ft=(yo=(Xn=k.text)!=null?Xn:k.delta)!=null?yo:k.content)!=null?ft:k.chunk)!=null?tn:"";mn&&(Vt.content+=String(mn),Vt.streaming=!0,f(Vt)),k.isComplete&&(Vt.streaming=!1,f(Vt));continue}let ie=k.partId;if(ie!==void 0&&M.current!==null&&ie!==M.current){let Ne=m;Ne&&(Ne.streaming=!1,f(Ne),Ie=Ne,m=null,I=!0)}ie!==void 0&&(M.current=ie);let Q=ie!==void 0&&(nn=lt.get(ie))!=null?nn:de();ie!==void 0&&(Q.partId||(Q.partId=ie),lt.set(ie,Q));let Le=(vo=(we=(sr=(Jn=k.text)!=null?Jn:k.delta)!=null?sr:k.content)!=null?we:k.chunk)!=null?vo:"";if(Le){let Ne=typeof k.seq=="number"?k.seq:void 0,ct=ie!=null?ie:Q.id,Ze=Ne!==void 0?pe(ct,Ne,String(Le)):((co=re.get(Q.id))!=null?co:"")+Le;Q.rawContent=Ze,ee.has(Q.id)||ee.set(Q.id,this.createStreamParser());let Bt=ee.get(Q.id),Vt=Ze.trim().startsWith("{")||Ze.trim().startsWith("[");if(Vt&&re.set(Q.id,Ze),Bt.__isPlainTextParser===!0){Q.content=Ne!==void 0?Ze:Q.content+Le,re.delete(Q.id),ee.delete(Q.id),Q.rawContent=void 0,f(Q);continue}let st=Bt.processChunk(Ze);if(st instanceof Promise)st.then(ht=>{var Ke;let Zt=typeof ht=="string"?ht:(Ke=ht==null?void 0:ht.text)!=null?Ke:null;if(Zt!==null&&Zt.trim()!=="")Q.content=Zt,f(Q);else if(!Vt&&!Ze.trim().startsWith("<")){let Cn=m,Yt=Cn&&Cn.id===Q.id?Cn:Q;Yt.id===Q.id&&(Yt.content=Ne!==void 0?Ze:Yt.content+Le,re.delete(Yt.id),ee.delete(Yt.id),Yt.rawContent=void 0,f(Yt))}}).catch(()=>{Q.content=Ne!==void 0?Ze:Q.content+Le,re.delete(Q.id),ee.delete(Q.id),Q.rawContent=void 0,f(Q)});else{let ht=typeof st=="string"?st:(U=st==null?void 0:st.text)!=null?U:null;ht!==null&&ht.trim()!==""?(Q.content=ht,f(Q)):!Vt&&!Ze.trim().startsWith("<")&&(Q.content=Ne!==void 0?Ze:Q.content+Le,re.delete(Q.id),ee.delete(Q.id),Q.rawContent=void 0,f(Q))}}if(k.isComplete){let Ne=(Wo=(Zr=k.result)==null?void 0:Zr.response)!=null?Wo:Q.content;if(Ne){let ct=re.get(Q.id),Ze=ct!=null?ct:oe(Ne);Q.rawContent=Ze;let Bt=ee.get(Q.id),Vt=null,mn=!1;if(Bt&&(Vt=Bt.getExtractedText(),Vt===null&&(Vt=Ur(Ze)),Vt===null)){let st=Bt.processChunk(Ze);st instanceof Promise?(mn=!0,st.then(ht=>{var Ke;let Zt=typeof ht=="string"?ht:(Ke=ht==null?void 0:ht.text)!=null?Ke:null;if(Zt!==null){let Cn=m;Cn&&Cn.id===Q.id&&(Cn.content=Zt,Cn.streaming=!1,ee.delete(Cn.id),re.delete(Cn.id),f(Cn))}})):Vt=typeof st=="string"?st:(qo=st==null?void 0:st.text)!=null?qo:null}if(!mn){Vt!==null&&Vt.trim()!==""?Q.content=Vt:re.has(Q.id)||(Q.content=oe(Ne));let st=ee.get(Q.id);if(st){let ht=(jo=st.close)==null?void 0:jo.call(st);ht instanceof Promise&&ht.catch(()=>{}),ee.delete(Q.id)}re.delete(Q.id),Q.streaming=!1,f(Q)}}}}else if(Ue==="step_complete"){let z=k.stepType,W=k.executionType;if(z==="tool"||W==="context")continue;let Z=k.toolContext;if(Z!=null&&Z.toolId){let Ne=String((xo=(Bo=k.id)!=null?Bo:Z.stepId)!=null?xo:"");if(Ne){let ct=A(Z.toolId,Ne);for(let[Ze,Bt]of D)Ze.startsWith(ct)&&Bt.streaming!==!1&&(Bt.streaming=!1,f(Bt));P.delete(`${Z.toolId}::${Ne}`)}continue}let ie=k.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,f(Ze))}let Ne=(Ps=k.result)==null?void 0:Ps.response,ct=Ie;ct&&(ie&&(ct.stopReason=ie),Ne!=null?Xe(ct,Ne):(ee.delete(ct.id),re.delete(ct.id))),Ie=null;continue}let Q=(Zn=k.result)==null?void 0:Zn.response,Le=de();if(ie&&(Le.stopReason=ie),Q!=null){let Ne=ee.get(Le.id),ct=!1,Ze=!1;if(Ne){let Bt=Ne.getExtractedText(),Vt=re.get(Le.id),mn=Vt!=null?Vt:oe(Q);if(Le.rawContent=mn,Bt!==null&&Bt.trim()!=="")Le.content=Bt,ct=!0;else{let st=Ur(mn);if(st!==null)Le.content=st,ct=!0;else{let ht=Ne.processChunk(mn);if(ht instanceof Promise)Ze=!0,ht.then(Zt=>{var Cn;let Ke=typeof Zt=="string"?Zt:(Cn=Zt==null?void 0:Zt.text)!=null?Cn:null;if(Ke!==null&&Ke.trim()!==""){let Yt=m;Yt&&Yt.id===Le.id&&(Yt.content=Ke,Yt.streaming=!1,ee.delete(Yt.id),re.delete(Yt.id),f(Yt))}else{let Yt=Ne.getExtractedText(),vn=m;vn&&vn.id===Le.id&&(Yt!==null&&Yt.trim()!==""?vn.content=Yt:re.has(vn.id)||(vn.content=oe(Q)),vn.streaming=!1,ee.delete(vn.id),re.delete(vn.id),f(vn))}});else{let Zt=typeof ht=="string"?ht:(eo=ht==null?void 0:ht.text)!=null?eo:null;if(Zt!==null&&Zt.trim()!=="")Le.content=Zt,ct=!0;else{let Ke=Ne.getExtractedText();Ke!==null&&Ke.trim()!==""&&(Le.content=Ke,ct=!0)}}}}}if(!Ze){if(!Le.rawContent){let Bt=re.get(Le.id);Le.rawContent=Bt!=null?Bt:oe(Q)}if(!ct&&!re.has(Le.id)&&(Le.content=oe(Q)),Ne){let Bt=(wo=Ne.close)==null?void 0:wo.call(Ne);Bt instanceof Promise&&Bt.catch(()=>{})}ee.delete(Le.id),re.delete(Le.id),Le.streaming=!1,f(Le)}}else ee.delete(Le.id),re.delete(Le.id),Le.streaming=!1,f(Le)}else if(Ue==="flow_complete"){let z=(Co=k.result)==null?void 0:Co.response;if(I){if(m!==null){let W=m;ee.delete(W.id),re.delete(W.id),W.streaming!==!1&&(W.streaming=!1,f(W))}}else if(z!=null){let W=de(),Z=re.get(W.id),ie=Z!=null?Z:oe(z);W.rawContent=ie;let Q=oe(z),Le=ee.get(W.id);if(Le){let Ze=Ur(ie);if(Ze!==null)Q=Ze;else{let Bt=Le.processChunk(ie);Bt instanceof Promise&&Bt.then(mn=>{var ht;let st=typeof mn=="string"?mn:(ht=mn==null?void 0:mn.text)!=null?ht:null;st!==null&&(W.content=st,W.streaming=!1,f(W))});let Vt=Le.getExtractedText();Vt!==null&&(Q=Vt)}}ee.delete(W.id),re.delete(W.id);let Ne=Q!==W.content,ct=W.streaming!==!1;Ne&&(W.content=Q),W.streaming=!1,(Ne||ct)&&f(W)}else if(m!==null){let W=m;ee.delete(W.id),re.delete(W.id),W.streaming!==!1&&(W.streaming=!1,f(W))}n({type:"status",status:"idle"})}else if(Ue==="agent_start")ne={executionId:k.executionId,agentId:(Tr=k.agentId)!=null?Tr:"virtual",agentName:(Ko=k.agentName)!=null?Ko:"",status:"running",currentIteration:0,maxTurns:(kn=k.maxTurns)!=null?kn:1,startedAt:Pe(k.startedAt)};else if(Ue==="agent_iteration_start"){if(ne&&(ne.currentIteration=k.iteration),_n==="separate"&&k.iteration>1){let z=m;z&&(z.streaming=!1,f(z),qe.set(k.iteration-1,z),m=null)}}else if(Ue==="agent_turn_start")x=null;else if(Ue==="agent_turn_delta"){if(k.contentType==="text"){let z=de();z.content+=(Ho=k.delta)!=null?Ho:"",z.agentMetadata={executionId:k.executionId,iteration:k.iteration,turnId:k.turnId,agentName:ne==null?void 0:ne.agentName},x=z,f(z)}else if(k.contentType==="thinking"){let z=(es=k.turnId)!=null?es:`agent-think-${k.iteration}`,W=De(z);W.reasoning=(kr=W.reasoning)!=null?kr:{id:z,status:"streaming",chunks:[]},W.reasoning.chunks.push((ts=k.delta)!=null?ts:""),W.agentMetadata={executionId:k.executionId,iteration:k.iteration,turnId:k.turnId},f(W)}else if(k.contentType==="tool_input"){let z=(Ga=k.toolCallId)!=null?Ga:C.lastId;if(z){let W=B.get(z);W!=null&&W.toolCall&&(W.toolCall.chunks=(ns=W.toolCall.chunks)!=null?ns:[],W.toolCall.chunks.push((Ya=k.delta)!=null?Ya:""),f(W))}}}else if(Ue==="agent_turn_complete"){let z=k.turnId;if(z){let ie=R.get(z);if(ie!=null&&ie.reasoning){ie.reasoning.status="complete",ie.reasoning.completedAt=Pe(k.completedAt);let Q=(os=ie.reasoning.startedAt)!=null?os:Date.now();ie.reasoning.durationMs=Math.max(0,((yt=ie.reasoning.completedAt)!=null?yt:Date.now())-Q),ie.streaming=!1,f(ie)}}let W=k.stopReason,Z=m!=null?m:x;if(W&&Z!==null){let ie=k.turnId;(!ie||((Ws=Z.agentMetadata)==null?void 0:Ws.turnId)===ie)&&(Z.stopReason=W,f(Z))}}else if(Ue==="agent_tool_start"){m&&(m.streaming=!1,f(m),m=null);let z=(po=k.toolCallId)!=null?po:`agent-tool-${l()}`;Ae(G(k),z);let W=ae(z),Z=($n=W.toolCall)!=null?$n:{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=(Xa=(Qa=k.toolName)!=null?Qa:k.name)!=null?Xa:Z.name,Z.status="running",k.parameters!==void 0&&(Z.args=k.parameters),Z.startedAt=Pe((rs=k.startedAt)!=null?rs:k.timestamp),W.toolCall=Z,W.streaming=!0,W.agentMetadata={executionId:k.executionId,iteration:k.iteration},f(W)}else if(Ue==="agent_tool_delta"){let z=(Go=k.toolCallId)!=null?Go:C.lastId;if(z){let W=(Bs=B.get(z))!=null?Bs:ae(z);W.toolCall&&(W.toolCall.chunks=(ar=W.toolCall.chunks)!=null?ar:[],W.toolCall.chunks.push((Hs=k.delta)!=null?Hs:""),W.toolCall.status="running",W.streaming=!0,f(W))}}else if(Ue==="agent_tool_complete"){let z=(Ds=k.toolCallId)!=null?Ds:C.lastId;if(z){let W=(Os=B.get(z))!=null?Os:ae(z);if(W.toolCall){W.toolCall.status="complete",k.result!==void 0&&(W.toolCall.result=k.result),typeof k.executionTime=="number"&&(W.toolCall.durationMs=k.executionTime),W.toolCall.completedAt=Pe((Fs=k.completedAt)!=null?Fs:k.timestamp),W.streaming=!1,f(W);let Z=G(k);Z&&C.byCall.delete(Z)}}}else if(Ue==="agent_media"){let z=Array.isArray(k.media)?k.media:[],W=[];for(let Z of z){if(!Z||typeof Z!="object")continue;let ie=Z,Q=typeof ie.type=="string"?ie.type:void 0,Le=typeof ie.mediaType=="string"?ie.mediaType.toLowerCase():"",Ne=null,ct="";if(Q==="media"){let Ze=typeof ie.data=="string"?ie.data:void 0;if(!Ze)continue;ct=Le.length>0?Le:"application/octet-stream",Ne=`data:${ct};base64,${Ze}`}else if(Q==="image-url"){let Ze=typeof ie.url=="string"?ie.url:void 0;if(!Ze)continue;ct=Le,Ne=Ze}else if(Q==="file-url"){let Ze=typeof ie.url=="string"?ie.url:void 0;if(!Ze)continue;ct=Le,Ne=Ze}else continue;if(Ne)if(Q==="image-url"||ct.startsWith("image/"))W.push({type:"image",image:Ne,...ct?{mimeType:ct}:{}});else if(ct.startsWith("audio/"))W.push({type:"audio",audio:Ne,mimeType:ct});else if(ct.startsWith("video/"))W.push({type:"video",video:Ne,mimeType:ct});else{let Ze=ct||"application/octet-stream";W.push({type:"file",data:Ne,mimeType:Ze,filename:_b(Ze)})}}if(W.length>0){let Z=l(),ie=k.toolCallId,Le={id:`agent-media-${typeof ie=="string"&&ie.length>0?`${ie}-${Z}`:String(Z)}`,role:"assistant",content:"",contentParts:W,createdAt:new Date().toISOString(),streaming:!1,sequence:Z,agentMetadata:{executionId:k.executionId,iteration:k.iteration}};f(Le);let Ne=m;Ne&&(Ne.streaming=!1,f(Ne)),m=null,v.current=null}}else if(Ue!=="agent_iteration_complete"){if(Ue==="agent_reflection"||Ue==="agent_reflect"){let z=`agent-reflection-${k.executionId}-${k.iteration}`,W={id:z,role:"assistant",content:(Un=k.reflection)!=null?Un:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:z,status:"complete",chunks:[(ss=k.reflection)!=null?ss:""]},agentMetadata:{executionId:k.executionId,iteration:k.iteration}};f(W)}else if(Ue==="agent_complete"){ne&&(ne.status=k.success?"complete":"error",ne.completedAt=Pe(k.completedAt),ne.stopReason=k.stopReason);let z=m;z&&(z.streaming=!1,f(z)),n({type:"status",status:"idle"})}else if(Ue==="agent_error"){let z=typeof k.error=="string"?k.error:(Oo=(Do=k.error)==null?void 0:Do.message)!=null?Oo:"Agent execution error";k.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",z):n({type:"error",error:new Error(z)})}else if(Ue!=="agent_ping"){if(Ue==="agent_approval_start"){let z=(Ns=k.approvalId)!=null?Ns:`approval-${l()}`,W={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Ja=ne==null?void 0:ne.agentId)!=null?Ja:"virtual",executionId:(Vs=(_s=k.executionId)!=null?_s:ne==null?void 0:ne.executionId)!=null?Vs:"",toolName:(Er=k.toolName)!=null?Er:"",toolType:k.toolType,description:(ei=k.description)!=null?ei:`Execute ${(Za=k.toolName)!=null?Za:"tool"}`,...typeof k.reason=="string"&&k.reason?{reason:k.reason}:{},parameters:k.parameters}};f(W)}else if(Ue==="step_await"&&k.awaitReason==="approval_required"){let z=(ti=k.approvalId)!=null?ti:`approval-${l()}`,W={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(ni=ne==null?void 0:ne.agentId)!=null?ni:"virtual",executionId:(Mr=(Tl=k.executionId)!=null?Tl:ne==null?void 0:ne.executionId)!=null?Mr:"",toolName:(ir=k.toolName)!=null?ir:"",toolType:k.toolType,description:($s=k.description)!=null?$s:`Execute ${(oi=k.toolName)!=null?oi:"tool"}`,...typeof k.reason=="string"&&k.reason?{reason:k.reason}:{},parameters:k.parameters}};f(W)}else if(Ue==="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:(lr=k.decision)!=null?lr:"approved",agentId:(ri=ne==null?void 0:ne.agentId)!=null?ri:"virtual",executionId:(cr=(Us=k.executionId)!=null?Us:ne==null?void 0:ne.executionId)!=null?cr:"",toolName:(zs=k.toolName)!=null?zs:"",description:(si=k.description)!=null?si:"",resolvedAt:Date.now()}};f(Z)}}else if(Ue==="artifact_start"||Ue==="artifact_delta"||Ue==="artifact_update"||Ue==="artifact_complete"){if(Ue==="artifact_start"){let z=k.artifactType,W=String(k.id),Z=typeof k.title=="string"?k.title:void 0;if(n({type:"artifact_start",id:W,artifactType:z,title:Z,component:typeof k.component=="string"?k.component:void 0}),ye.set(W,{markdown:"",title:Z}),!se.has(W)){se.add(W);let ie={id:`artifact-ref-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:W,title:Z,artifactType:z,status:"streaming"}})};X.set(W,ie),f(ie)}}else if(Ue==="artifact_delta"){let z=String(k.id),W=typeof k.delta=="string"?k.delta:String((Yo=k.delta)!=null?Yo:"");n({type:"artifact_delta",id:z,artDelta:W});let Z=ye.get(z);Z&&(Z.markdown+=W)}else if(Ue==="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(Ue==="artifact_complete"){let z=String(k.id);n({type:"artifact_complete",id:z});let W=X.get(z);if(W){W.streaming=!1;try{let Z=JSON.parse((ai=W.rawContent)!=null?ai:"{}");if(Z.props){Z.props.status="complete";let ie=ye.get(z);ie!=null&&ie.markdown&&(Z.props.markdown=ie.markdown)}W.rawContent=JSON.stringify(Z)}catch{}ye.delete(z),f(W),X.delete(z)}}}else if(Ue==="transcript_insert"){let z=k.message;if(!z||typeof z!="object")continue;let W=String((dr=z.id)!=null?dr:`msg-${l()}`),Z=z.role,Q={id:W,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(Q),Q.rawContent)try{let Le=JSON.parse(Q.rawContent),Ne=(Ot=Le==null?void 0:Le.props)==null?void 0:Ot.artifactId;typeof Ne=="string"&&se.add(Ne)}catch{}m=null,v.current=null,ee.delete(W),re.delete(W)}else if(Ue==="error"||Ue==="step_error"||Ue==="dispatch_error"||Ue==="flow_error"){let z=null;if(k.error instanceof Error)z=k.error;else if(Ue==="dispatch_error"){let W=(as=k.message)!=null?as:k.error;W!=null&&W!==""&&(z=new Error(String(W)))}else if(Ue==="step_error"||Ue==="flow_error"){let W=k.error;typeof W=="string"&&W!==""?z=new Error(W):W!=null&&typeof W=="object"&&"message"in W&&(z=new Error(String((is=W.message)!=null?is:W)))}else Ue==="error"&&k.error!=null&&k.error!==""&&(z=new Error(String(k.error)));if(z){n({type:"error",error:z});let W=m;W&&W.streaming&&(W.streaming=!1,f(W)),n({type:"status",status:"idle"})}}}}}Be.length=0};;){let{done:O,value:ue}=await r.read();if(O)break;a+=s.decode(ue,{stream:!0});let Oe=a.split(`
|
|
10
|
-
|
|
11
|
-
`);a=(ln=Oe.pop())!=null?ln:"";for(let Ge of Oe){let _e=Ge.split(`
|
|
12
|
-
`),$e="message",rt="";for(let Jt of _e)Jt.startsWith("event:")?$e=Jt.replace("event:","").trim():Jt.startsWith("data:")&&(rt+=Jt.replace("data:","").trim());if(!rt)continue;let Rt;try{Rt=JSON.parse(rt)}catch(Jt){n({type:"error",error:Jt instanceof Error?Jt:new Error("Failed to parse chat stream payload")});continue}let jt=$e!=="message"?$e:(so=Rt.type)!=null?so:"message";if((Lo=this.onSSEEvent)==null||Lo.call(this,jt,Rt),this.parseSSEEvent){v.current=m;let Jt=await this.handleCustomSSEEvent(Rt,n,v,f,l,M);if(v.current&&v.current!==m&&(m=v.current),Jt)continue}kt.push(jt,Rt),ge()}}kt.flushPending(),ge(),kt.destroy()}};function Hi(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function va(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Di="[Image]";function cc(e){return{type:"text",text:e}}var rg=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Ub=["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=[...rg,...Ub];function zb(e){return rg.includes(e)||e.startsWith("image/")}function Oi(e){return zb(e.type)}async function sg(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Oi(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 ag(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 qb(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function ig(e,t){let n=qb(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 Fi=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 Ni=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,o,r,s){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(n),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let u=0;u<a.length;u++)i+=a[u]*a[u];let d=Math.sqrt(i/a.length);(o==="silence"?d<r.threshold:d>=r.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=r.duration&&(this.fired=!0,s()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var xa=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 Ni;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,n,o;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let r=this.w;if(!r||!r.location)throw new Error("Window object or location not available");let s=r.location.protocol==="https:"?"wss:":"ws:",a=(t=this.config)==null?void 0:t.host,i=(n=this.config)==null?void 0:n.agentId,d=(o=this.config)==null?void 0:o.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let u=`${s}//${a}/ws/agents/${i}/voice?token=...`,g=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let x=!1,v=I=>{x||(x=!0,clearTimeout(M),m(new Error(I)))},M=setTimeout(()=>v("WebSocket connection timed out."+g),1e4);this.ws.addEventListener("open",()=>{x||(x=!0,clearTimeout(M),f())},{once:!0}),this.ws.addEventListener("error",()=>{v("WebSocket connection failed to "+u+"."+g)},{once:!0}),this.ws.addEventListener("close",I=>{if(!I.wasClean&&!x){let R=I.code!==1006?` (code ${I.code})`:"";v("WebSocket connection failed"+R+"."+g)}},{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 Fi(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,n,o,r;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(r=(o=this.config)==null?void 0:o.silenceThreshold)!=null?r:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let u=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",g=new Blob(this.audioChunks,{type:u});await this.sendAudio(g),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 zr=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 wa(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new xa(e.runtype);case"browser":if(!zr.isSupported())throw new Error("Browser speech recognition not supported");return new zr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function lg(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return wa({type:"runtype",runtype:e.runtype});if(zr.isSupported())return wa({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function dc(e){try{return lg(e),!0}catch{return!1}}var jb=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Kb(e,t){return jb.some(n=>e[n]!==t[n])}function cg(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
|
-
|
|
14
|
-
_Details: ${n.message}_`:o}var Ca=e=>({isError:!0,content:[{type:"text",text:e}]}),dg=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,pg=e=>ma(e)||e===Xo,_i=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,u,g;if(t.type==="message"){this.upsertMessage(t.message);let f=t.message.toolCall,m=!!(f!=null&&f.name)&&(ma(f.name)||f.name===Xo&&((o=(n=this.config.features)==null?void 0:n.suggestReplies)==null?void 0:o.enabled)!==!1);((r=t.message.agentMetadata)==null?void 0:r.awaitingLocalTool)===!0&&m&&this.enqueueWebMcpAwait(t.message),(s=t.message.agentMetadata)!=null&&s.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:(a=t.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i: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;((d=this.agentExecution)==null?void 0:d.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),((l=this.agentExecution)==null?void 0:l.status)==="running"&&(this.agentExecution.status="error"),(g=(u=this.callbacks).onError)==null||g.call(u,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 ya(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 dc((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=wa(s);let a=(n=this.config.voiceRecognition)!=null?n:{},i=(o=a.processingText)!=null?o:"\u{1F3A4} Processing voice...",d=(r=a.processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var u,g,f,m,x,v;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((u=l.transcript)!=null&&u.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(g=l.transcript)!=null&&g.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}):(m=l.text)!=null&&m.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let M=(v=this.pendingVoiceAssistantMessageId)!=null?v:(x=[...this.messages].reverse().find(I=>I.role==="assistant"))==null?void 0:x.id;M&&this.ttsSpokenMessageIds.add(M)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var u,g;this.voiceStatus=l,this.voiceActive=l==="listening",(g=(u=this.callbacks).onVoiceStatusChanged)==null||g.call(u,l)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,o,r,s,a,i,d,l,u;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((o=t.runtype)==null?void 0:o.agentId)||"",clientToken:((r=t.runtype)==null?void 0:r.clientToken)||"",host:(s=t.runtype)==null?void 0:s.host,voiceId:(a=t.runtype)==null?void 0:a.voiceId,pauseDuration:(i=t.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=t.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=t.browser)==null?void 0:l.language)||"en-US",continuous:(u=t.browser)==null?void 0:u.continuous}};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let o=await this.client.initSession();return this.setClientSession(o),o}catch(o){return(n=(t=this.callbacks).onError)==null||n.call(t,o instanceof Error?o:new Error(String(o))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n={...this.config,...t};if(!Kb(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.config=n,this.client=new ya(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:u,rawContent:g}=t,m={id:a!=null?a:n==="user"?Hi():n==="assistant"?va():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...g!==void 0&&{rawContent:g}};return this.upsertMessage(m),m}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:u,streaming:g=!1,voiceProcessing:f,rawContent:m}=o,v={id:d!=null?d:r==="user"?Hi():r==="assistant"?va():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:g,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...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,u,g,f,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=Hi(),s=va(),a={id:r,role:"user",content:o||Di,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(x){let v=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!v){let M=cg(x,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||(x instanceof Error?(g=(u=this.callbacks).onError)==null||g.call(u,x):(m=(f=this.callbacks).onError)==null||m.call(f,new Error(String(x))))}}async continueConversation(){var r,s,a,i,d;if(this.streaming)return;(r=this.abortController)==null||r.abort();let t=va();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(l){let u=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!u){let g=cg(l,this.config.errorMessage);if(g){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:g,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var r,s,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(r=this.abortController)==null||r.abort();let o=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var r,s,a;try{if(((s=(r=this.config.webmcp)==null?void 0:r.autoApprove)==null?void 0:s.call(r,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(o,i)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r!=null&&r.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){var u,g,f,m,x;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:(u=a==null?void 0:a.createdAt)!=null?u:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(g=this.abortController)==null||g.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||(x=(m=this.callbacks).onError)==null||x.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 u,g,f,m,x,v,M,I,R,B,D,P;let o=this.messages.find(w=>w.id===t.id);if(((u=o==null?void 0:o.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let r=(g=t.agentMetadata)==null?void 0:g.executionId,s=(f=t.toolCall)==null?void 0:f.name;if(!r||!s){(x=(m=this.callbacks).onError)==null||x.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,C=Array.isArray(w==null?void 0:w.questions)?w.questions:[];if(C.length===1){let E=typeof((M=C[0])==null?void 0:M.question)=="string"?C[0].question:"";E&&(a={[E]:n})}}this.markAskUserQuestionResolved(t,a),(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(([C,E])=>`${C}: ${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((C,E)=>{let A=typeof(C==null?void 0:C.question)=="string"?C.question:"";if(!A)return;let S=w[A],V=Array.isArray(S)?S.join(", "):typeof S=="string"?S:"";this.appendMessage({id:`ask-user-q-${i}-${E}`,role:"assistant",content:A,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 C=await w.json().catch(()=>null);throw new Error((B=C==null?void 0:C.error)!=null?B:`Resume failed: ${w.status}`)}w.body?await this.connectStream(w.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(w){let C=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));this.setStreaming(!1),this.abortController=null,C||(P=(D=this.callbacks).onError)==null||P.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()}isSuggestRepliesAlreadyResolved(t){var o,r;if(((o=t.toolCall)==null?void 0:o.name)!==Xo)return!1;let n=this.messages.find(s=>s.id===t.id);return((r=(n!=null?n:t).agentMetadata)==null?void 0:r.suggestRepliesResolved)===!0}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(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},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,u,g;let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async f=>{var P,w,C,E,A,S,V;let m=(P=f.toolCall)==null?void 0:P.name,x=(w=f.toolCall)==null?void 0:w.id;if(!m||!x)return null;let v=`${t}:${x}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v)||this.isSuggestRepliesAlreadyResolved(f))return null;this.webMcpInflightKeys.add(v),o.push(v);let M=this.markWebMcpToolRunning(f),I=(E=(C=f.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?E:m;if(m===Xo)return{dedupeKey:v,resumeKey:I,output:rc(),toolMessage:f,startedAt:M,completedAt:Date.now()};let R=new AbortController;this.webMcpResolveControllers.add(R),r.push(R);let B=this.client.executeWebMcpToolCall(m,(A=f.toolCall)==null?void 0:A.args,R.signal),D;if(!B)D={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{D=await B}catch($){let G=$ instanceof Error&&($.name==="AbortError"||$.message.includes("aborted")||$.message.includes("abort"));return G||(V=(S=this.callbacks).onError)==null||V.call(S,$ instanceof Error?$:new Error(String($))),this.markWebMcpToolComplete(f,Ca(G?"Aborted by cancel()":dg($)),M),this.webMcpInflightKeys.delete(v),null}return R.signal.aborted?(this.markWebMcpToolComplete(f,Ca("Aborted by cancel()"),M),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:I,output:D,toolMessage:f,startedAt:M,completedAt:Date.now()}})),i=[];try{if(i=a.filter(x=>x!==null),i.length===0)return;let f={};for(let x of i)f[x.resumeKey]=x.output;let m=await this.client.resumeFlow(t,f,{signal:s.signal});if(!m.ok){let x=await m.json().catch(()=>null);throw new Error((d=x==null?void 0:x.error)!=null?d:`Resume failed: ${m.status}`)}for(let x of i)this.webMcpResolvedKeys.add(x.dedupeKey),this.markWebMcpToolComplete(x.toolMessage,x.output,x.startedAt,x.completedAt,((l=x.toolMessage.toolCall)==null?void 0:l.name)===Xo?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(f){if(!(f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"))))(g=(u=this.callbacks).onError)==null||g.call(u,f instanceof Error?f:new Error(String(f)));else for(let x of i)this.markWebMcpToolComplete(x.toolMessage,Ca("Aborted by cancel()"),x.startedAt)}finally{for(let f of o)this.webMcpInflightKeys.delete(f);for(let f of r)this.webMcpResolveControllers.delete(f);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var x,v,M,I,R,B,D,P,w,C,E,A;let n=(x=t.agentMetadata)==null?void 0:x.executionId,o=(v=t.toolCall)==null?void 0:v.name,r=(M=t.toolCall)==null?void 0:M.id;if(!n){(R=(I=this.callbacks).onError)==null||R.call(I,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(V){(D=(B=this.callbacks).onError)==null||D.call(B,V instanceof Error?V:new Error(String(V)))}finally{this.webMcpInflightKeys.delete(S)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))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=o===Xo,u=(P=t.toolCall)==null?void 0:P.args,g=l?null:this.client.executeWebMcpToolCall(o,u,d),f="execute",m=a;try{let S;if(l?S=rc():g?S=await g:S={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),d.aborted){this.markWebMcpToolComplete(t,Ca("Aborted by cancel()"),a);return}let V=(C=(w=t.agentMetadata)==null?void 0:w.webMcpToolCallId)!=null?C:o;f="resume",await this.resumeWithToolOutput(n,V,S,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,S,a,m,l?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(S){let V=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));(f==="execute"||V||d.aborted)&&this.markWebMcpToolComplete(t,Ca(V||d.aborted?"Aborted by cancel()":dg(S)),a),V||(A=(E=this.callbacks).onError)==null||A.call(E,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 u,g,f,m,x,v,M,I,R,B,D,P,w,C,E;if(s!==o)return r;let a={...r,...n};if(((u=r.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((g=r.agentMetadata)==null?void 0:g.suggestRepliesResolved)===!0&&n.agentMetadata&&(a.agentMetadata={...(f=a.agentMetadata)!=null?f:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let A=r.approval,S=n.approval;a.approval={...A,...S,executionId:S.executionId||A.executionId,toolName:S.toolName||A.toolName,description:S.description||A.description,toolType:(m=S.toolType)!=null?m:A.toolType,reason:(x=S.reason)!=null?x:A.reason,parameters:(v=S.parameters)!=null?v:A.parameters}}let i=(M=n.toolCall)==null?void 0:M.name,d=(I=n.agentMetadata)==null?void 0:I.executionId,l=(R=n.toolCall)==null?void 0:R.id;if(i&&pg(i)&&d&&l&&((B=n.agentMetadata)==null?void 0:B.awaitingLocalTool)===!0){let A=`${d}:${l}`,S=this.webMcpInflightKeys.has(A),V=this.webMcpResolvedKeys.has(A),$=(D=r.toolCall)==null?void 0:D.name,G=((P=r.agentMetadata)==null?void 0:P.executionId)===d&&((w=r.toolCall)==null?void 0:w.id)===l&&$!==void 0&&pg($)&&((C=r.toolCall)==null?void 0:C.status)==="complete";(S||V||G)&&(a.agentMetadata={...(E=a.agentMetadata)!=null?E:{},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 T=require("lucide"),Gb={activity:T.Activity,"arrow-down":T.ArrowDown,"arrow-up":T.ArrowUp,"arrow-up-right":T.ArrowUpRight,bot:T.Bot,"chevron-down":T.ChevronDown,"chevron-up":T.ChevronUp,"chevron-right":T.ChevronRight,"chevron-left":T.ChevronLeft,check:T.Check,clipboard:T.Clipboard,"clipboard-copy":T.ClipboardCopy,copy:T.Copy,file:T.File,"file-code":T.FileCode,"file-spreadsheet":T.FileSpreadsheet,"file-text":T.FileText,"image-plus":T.ImagePlus,loader:T.Loader,"loader-circle":T.LoaderCircle,mic:T.Mic,paperclip:T.Paperclip,"refresh-cw":T.RefreshCw,search:T.Search,send:T.Send,"shield-alert":T.ShieldAlert,"shield-check":T.ShieldCheck,"shield-x":T.ShieldX,square:T.Square,"thumbs-down":T.ThumbsDown,"thumbs-up":T.ThumbsUp,upload:T.Upload,"volume-2":T.Volume2,x:T.X,user:T.User,mail:T.Mail,phone:T.Phone,calendar:T.Calendar,clock:T.Clock,building:T.Building,"map-pin":T.MapPin,lock:T.Lock,key:T.Key,"credit-card":T.CreditCard,"at-sign":T.AtSign,hash:T.Hash,globe:T.Globe,link:T.Link,"circle-check":T.CircleCheck,"circle-x":T.CircleX,"triangle-alert":T.TriangleAlert,info:T.Info,ban:T.Ban,shield:T.Shield,"arrow-left":T.ArrowLeft,"arrow-right":T.ArrowRight,"external-link":T.ExternalLink,ellipsis:T.Ellipsis,"ellipsis-vertical":T.EllipsisVertical,menu:T.Menu,house:T.House,plus:T.Plus,minus:T.Minus,pencil:T.Pencil,trash:T.Trash,"trash-2":T.Trash2,save:T.Save,download:T.Download,share:T.Share,funnel:T.Funnel,settings:T.Settings,"rotate-cw":T.RotateCw,maximize:T.Maximize,minimize:T.Minimize,"shopping-cart":T.ShoppingCart,"shopping-bag":T.ShoppingBag,package:T.Package,truck:T.Truck,tag:T.Tag,gift:T.Gift,receipt:T.Receipt,wallet:T.Wallet,store:T.Store,"dollar-sign":T.DollarSign,percent:T.Percent,play:T.Play,pause:T.Pause,"volume-x":T.VolumeX,camera:T.Camera,image:T.Image,film:T.Film,headphones:T.Headphones,"message-circle":T.MessageCircle,"message-square":T.MessageSquare,bell:T.Bell,heart:T.Heart,star:T.Star,eye:T.Eye,"eye-off":T.EyeOff,bookmark:T.Bookmark,"calendar-days":T.CalendarDays,history:T.History,timer:T.Timer,folder:T.Folder,"folder-open":T.FolderOpen,files:T.Files,sparkles:T.Sparkles,zap:T.Zap,sun:T.Sun,moon:T.Moon,flag:T.Flag,monitor:T.Monitor,smartphone:T.Smartphone},Me=(e,t=24,n="currentColor",o=2)=>{let r=Gb[e];return r?Yb(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 Yb(e,t,n,o){if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,u])=>{l!=="stroke"&&d.setAttribute(l,String(u))}),r.appendChild(d)}),r}var Vi={allowedTypes:Jo,maxFileSize:10*1024*1024,maxFiles:4};function Qb(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Xb(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 Sa=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,o,r;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Vi.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:Vi.maxFileSize,maxFiles:(r=t.maxFiles)!=null?r:Vi.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:Vi.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,o,r,s,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(o=(n=this.config).onFileRejected)==null||o.call(n,l,"count");continue}let u=ag(l,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let g=(r=u.error)!=null&&r.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,g);continue}try{let g=await sg(l),f=Oi(l)?URL.createObjectURL(l):null,m={id:Qb(),file:l,previewUrl:f,contentPart:g};this.attachments.push(m),this.renderPreview(m)}catch(g){console.error("[AttachmentManager] Failed to process file:",g)}}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=Oi(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=Xb(t.file.type),d=Me(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=b("span");l.textContent=ig(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 ug=require("idiomorph"),$i=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;ug.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 Ui={index:-1,draft:""};function mg(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:{...Ui}}}function gg(e,t){var n,o,r,s,a,i,d,l,u,g,f,m,x,v,M,I,R,B,D,P,w,C,E,A,S,V,$,G,he,me,de,Ee,xe,De,Ae,le,X,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,(u=(l=e.llmContent)==null?void 0:l.length)!=null?u:0,(f=(g=e.approval)==null?void 0:g.status)!=null?f:"",(x=(m=e.toolCall)==null?void 0:m.status)!=null?x:"",(M=(v=e.toolCall)==null?void 0:v.name)!=null?M:"",(B=(R=(I=e.toolCall)==null?void 0:I.chunks)==null?void 0:R.length)!=null?B:0,(C=(w=(P=(D=e.toolCall)==null?void 0:D.chunks)==null?void 0:P[e.toolCall.chunks.length-1])==null?void 0:w.slice(-32))!=null?C:"",typeof((E=e.toolCall)==null?void 0:E.args)=="string"?e.toolCall.args.length:(A=e.toolCall)!=null&&A.args?JSON.stringify(e.toolCall.args).length:0,($=(V=(S=e.reasoning)==null?void 0:S.chunks)==null?void 0:V.length)!=null?$:0,(de=(me=(he=(G=e.reasoning)==null?void 0:G.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:"",(X=(le=e.contentParts)==null?void 0:le.length)!=null?X:0,(se=e.stopReason)!=null?se:"",t].join("\0")}function fg(){return new Map}function hg(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function bg(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function yg(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function zi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Zo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function qr(e,t){return Zo(e)-e.scrollTop<=t}function qi(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,u=n-o;return a||Math.abs(u)<s?{action:"none",delta:u,nextLastScrollTop:n}:!t&&r&&(!l||u>0)?{action:"resume",delta:u,nextLastScrollTop:n}:t&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:n}:t&&d&&!r?{action:"pause",delta:u,nextLastScrollTop:n}:{action:"none",delta:u,nextLastScrollTop:n}}function ji(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 vg(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function xg(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 wg(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Ln={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},In=1e5,vr=In+1;var Aa={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Jb=["pre","code","a","script","style"],Ki=e=>{var t,n,o,r,s;return{type:(t=e==null?void 0:e.type)!=null?t:Aa.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:Aa.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:Aa.speed,duration:(r=e==null?void 0:e.duration)!=null?r:Aa.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:Aa.buffer}},Zb=[{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"}],Sg=new Map;for(let e of Zb)Sg.set(e.name,e);var Ta=(e,t)=>{var n,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(o=Sg.get(e))!=null?o:null},Gi=(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},ey=(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},ty=(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},pc=/\s/,ny=(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},oy=(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(pc.test(s[i])){let l=i;for(;l<s.length&&pc.test(s[l]);)l+=1;a.appendChild(o.createTextNode(s.slice(i,l))),i=l}else{let l=o.createElement("span");l.className="persona-stream-word-group";let u=i;for(;u<s.length&&!pc.test(s[u]);)l.appendChild(ey(o,s[u],t,n.value)),n.value+=1,u+=1;a.appendChild(l),i=u}r.replaceChild(a,e)},ry=(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(ty(o,l,t,n.value)),n.value+=1));r.replaceChild(a,e)},ka=(e,t,n,o)=>{var g,f;if(!e||typeof document=="undefined")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set(((g=o==null?void 0:o.skipTags)!=null?g:Jb).map(m=>m.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)ny(d,s)||i.push(d),d=a.nextNode();let l={value:(f=o==null?void 0:o.startIndex)!=null?f:0},u=t==="char"?oy:ry;for(let m of i)u(m,n,l);return r.innerHTML},Yi=(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},Ea=(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},Cg=new WeakMap,sy=(e,t)=>{var s;if(!e.styles)return;let n=Cg.get(t);if(n||(n=new Set,Cg.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)},uc=new WeakMap,ay=(e,t)=>{if(!e.onAttach)return;let n=uc.get(t);if(n||(n=new Map,uc.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},Ag=e=>{let t=uc.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},mc=(e,t)=>{sy(e,t),ay(e,t)};function gc(e,t=In){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 Ma=0,xr=null;function fc(e=document){var n;if(Ma++,Ma===1){let o=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;xr={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,Ma=Math.max(0,Ma-1),Ma===0&&xr)){let r=e.body,s=(o=e.defaultView)!=null?o:window;r.style.overflow=xr.originalOverflow,r.style.position=xr.originalPosition,r.style.top=xr.originalTop,r.style.width=xr.originalWidth,s.scrollTo(0,xr.scrollY),xr=null}}}var La={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Sn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},Ia=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},Eo=e=>{var n,o,r,s,a,i;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:La.side,width:(r=t==null?void 0:t.width)!=null?r:La.width,animate:(s=t==null?void 0:t.animate)!=null?s:La.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:La.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:La.maxHeight}};var Mo={"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 Ra=(e,t)=>{let n=b("button");n.type="button",n.innerHTML=`
|
|
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
|
-
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
18
|
-
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
19
|
-
<span class="persona-block persona-w-full persona-truncate persona-text-sm persona-font-semibold persona-text-persona-primary" data-role="launcher-title"></span>
|
|
20
|
-
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
21
|
-
</span>
|
|
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 B,D,P,w,C,E,A,S,V,$,G,he,me;let a=(B=s.launcher)!=null?B:{},i=Sn(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=(P=a.subtitle)!=null?P:"Get answers fast";l.textContent=de,l.setAttribute("title",de)}let u=n.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let g=n.querySelector("[data-role='launcher-icon']");if(g)if(a.agentIconHidden)g.style.display="none";else{let de=(w=a.agentIconSize)!=null?w:"40px";if(g.style.height=de,g.style.width=de,g.innerHTML="",a.agentIconName){let Ee=parseFloat(de)||24,xe=Me(a.agentIconName,Ee*.6,"var(--persona-text-inverse, #ffffff)",2);xe?(g.appendChild(xe),g.style.display=""):(g.textContent=(C=a.agentIconText)!=null?C:"\u{1F4AC}",g.style.display="")}else a.iconUrl?g.style.display="none":(g.textContent=(E=a.agentIconText)!=null?E:"\u{1F4AC}",g.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let de=(A=a.agentIconSize)!=null?A:"40px";f.style.height=de,f.style.width=de,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let m=n.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let de=(S=a.callToActionIconSize)!=null?S:"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=($=a.callToActionIconText)!=null?$:"\u2197"}let x=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} ${x}`,i||(n.style.zIndex=String((G=a.zIndex)!=null?G:In));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 iy="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Qi=(e,t={})=>{var v,M,I,R,B,D;let{showClose:n=!0,wrapperClassName:o=iy,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 u=(I=a.closeButtonTooltipText)!=null?I:"Close chat",g=(R=a.closeButtonShowTooltip)!=null?R:!0;l.setAttribute("aria-label",u),l.style.display=n?"":"none";let f=(B=a.closeButtonIconName)!=null?B:"x",m=(D=a.closeButtonIconText)!=null?D:"\xD7";l.style.color=a.closeButtonColor||Nn.actionIconColor;let x=Me(f,s,"currentColor",1);if(x?(x.style.display="block",l.appendChild(x)):l.textContent=m,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let P=a.closeButtonBorderWidth||"0px",w=a.closeButtonBorderColor||"transparent";l.style.border=`${P} solid ${w}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),g&&u){let P=null,w=()=>{if(P)return;let E=l.ownerDocument,A=E.body;if(!A)return;P=No(E,"div","persona-clear-chat-tooltip"),P.textContent=u;let S=No(E,"div");S.className="persona-clear-chat-tooltip-arrow",P.appendChild(S);let V=l.getBoundingClientRect();P.style.position="fixed",P.style.zIndex=String(vr),P.style.left=`${V.left+V.width/2}px`,P.style.top=`${V.top-8}px`,P.style.transform="translate(-50%, -100%)",A.appendChild(P)},C=()=>{P&&P.parentNode&&(P.parentNode.removeChild(P),P=null)};d.addEventListener("mouseenter",w),d.addEventListener("mouseleave",C),l.addEventListener("focus",w),l.addEventListener("blur",C),d._cleanupTooltip=()=>{C(),d.removeEventListener("mouseenter",w),d.removeEventListener("mouseleave",C),l.removeEventListener("focus",w),l.removeEventListener("blur",C)}}return{button:l,wrapper:d}},ly="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Xi=(e,t={})=>{var P,w,C,E,A,S,V,$,G,he,me,de,Ee;let{wrapperClassName:n=ly,buttonSize:o,iconSize:r="20px"}=t,a=(w=((P=e==null?void 0:e.launcher)!=null?P:{}).clearChat)!=null?w:{},i=(C=o!=null?o:a.size)!=null?C:"32px",d=(E=a.iconName)!=null?E:"refresh-cw",l=(A=a.iconColor)!=null?A:"",u=(S=a.backgroundColor)!=null?S:"",g=(V=a.borderWidth)!=null?V:"",f=($=a.borderColor)!=null?$:"",m=(G=a.borderRadius)!=null?G:"",x=(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),B=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");B.style.height=i,B.style.width=i,B.type="button",B.setAttribute("aria-label",M),B.style.color=l||Nn.actionIconColor;let D=Me(d,r,"currentColor",1);if(D&&(D.style.display="block",B.appendChild(D)),u&&(B.style.backgroundColor=u,B.classList.remove("hover:persona-bg-gray-100")),g||f){let xe=g||"0px",De=f||"transparent";B.style.border=`${xe} solid ${De}`,B.classList.remove("persona-border-none")}if(m&&(B.style.borderRadius=m,B.classList.remove("persona-rounded-full")),x&&(B.style.paddingLeft=x,B.style.paddingRight=x),v&&(B.style.paddingTop=v,B.style.paddingBottom=v),R.appendChild(B),I&&M){let xe=null,De=()=>{if(xe)return;let le=B.ownerDocument,X=le.body;if(!X)return;xe=No(le,"div","persona-clear-chat-tooltip"),xe.textContent=M;let se=No(le,"div");se.className="persona-clear-chat-tooltip-arrow",xe.appendChild(se);let ye=B.getBoundingClientRect();xe.style.position="fixed",xe.style.zIndex=String(vr),xe.style.left=`${ye.left+ye.width/2}px`,xe.style.top=`${ye.top-8}px`,xe.style.transform="translate(-50%, -100%)",X.appendChild(xe)},Ae=()=>{xe&&xe.parentNode&&(xe.parentNode.removeChild(xe),xe=null)};R.addEventListener("mouseenter",De),R.addEventListener("mouseleave",Ae),B.addEventListener("focus",De),B.addEventListener("blur",Ae),R._cleanupTooltip=()=>{Ae(),R.removeEventListener("mouseenter",De),R.removeEventListener("mouseleave",Ae),B.removeEventListener("focus",De),B.removeEventListener("blur",Ae)}}return{button:B,wrapper:R}};var Nn={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))"},jr=e=>{var P,w,C,E,A,S,V,$,G,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=(P=t==null?void 0:t.launcher)!=null?P:{},s=(w=r.headerIconSize)!=null?w:"48px",a=(C=r.closeButtonPlacement)!=null?C:"inline",i=(E=r.headerIconHidden)!=null?E:!1,d=r.headerIconName,l=b("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let le=parseFloat(s)||24,X=Me(d,le*.6,"currentColor",1);X?l.replaceChildren(X):l.textContent=(S=(A=t==null?void 0:t.launcher)==null?void 0:A.agentIconText)!=null?S:"\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=(G=($=t==null?void 0:t.launcher)==null?void 0:$.agentIconText)!=null?G:"\u{1F4AC}";let u=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=b("span","persona-text-base persona-font-semibold");g.style.color=Nn.titleColor,g.textContent=(me=(he=t==null?void 0:t.launcher)==null?void 0:he.title)!=null?me:"Chat Assistant";let f=b("span","persona-text-xs");f.style.color=Nn.subtitleColor,f.textContent=(Ee=(de=t==null?void 0:t.launcher)==null?void 0:de.subtitle)!=null?Ee:"Here to help you get answers fast",u.append(g,f),i?o.append(u):o.append(l,u);let m=(xe=r.clearChat)!=null?xe:{},x=(De=m.enabled)!=null?De:!0,v=(Ae=m.placement)!=null?Ae:"inline",M=null,I=null;if(x){let X=Xi(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=X.button,I=X.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":x&&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:B,wrapper:D}=Qi(t,{showClose:n,wrapperClassName:R});return a!=="top-right"&&o.appendChild(D),{header:o,iconHolder:l,headerTitle:g,headerSubtitle:f,closeButton:B,closeButtonWrapper:D,clearChatButton:M,clearChatButtonWrapper:I}},Pa=(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 Ss(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(vr)):(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 x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",m.id),m.destructive&&x.setAttribute("data-destructive",""),m.icon){let M=Me(m.icon,16,"currentColor",1.5);M&&x.appendChild(M)}let v=document.createElement("span");v.textContent=m.label,x.appendChild(v),x.addEventListener("click",M=>{M.stopPropagation(),u(),n(m.id)}),a.appendChild(x)}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=x=>{!a.contains(x.target)&&!o.contains(x.target)&&u()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function g(){a.classList.contains("persona-hidden")?l():u()}function f(){u(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:u,toggle:g,destroy:f}}function Rn(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[u,g]of Object.entries(i))d.setAttribute(u,g);return d}function hc(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";o!=="default"&&(l+=" persona-label-btn--"+o),l+=" persona-label-btn--"+r,a&&(l+=" "+a);let u=b("button",l);if(u.type="button",u.setAttribute("aria-label",n),t){let f=Me(t,s!=null?s:14,"currentColor",2);f&&u.appendChild(f)}let g=b("span");if(g.textContent=n,u.appendChild(g),i&&u.addEventListener("click",i),d)for(let[f,m]of Object.entries(d))u.setAttribute(f,m);return u}function Tg(e){var m,x;let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:i,hover:d}=e,l=b("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let u=b("span","persona-combo-btn-label");u.textContent=t,l.appendChild(u);let g=Me(n,14,"currentColor",2);g&&(g.style.marginLeft="4px",g.style.opacity="0.6",l.appendChild(g)),d&&(l.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",l.style.padding=(x=d.padding)!=null?x:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var 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=Ss({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=>{u.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 cy=e=>{var o;let t=jr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(o=e.layoutHeaderConfig)==null?void 0:o.onTitleClick;if(n){let r=t.headerTitle.parentElement;r&&(r.style.cursor="pointer",r.setAttribute("role","button"),r.setAttribute("tabindex","0"),r.addEventListener("click",()=>n()),r.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function dy(e,t,n){var o,r,s;if(t!=null&&t.length)for(let a of t){let i=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(r=(o=a.ariaLabel)!=null?o:a.label)!=null?r:a.id),a.icon){let d=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=Ss({items:a.menuItems,onSelect:u=>n==null?void 0:n(u),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",u=>{u.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var py=e=>{var R,B,D,P,w,C,E,A,S;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,u;if(d)l=Tg({label:(B=a.title)!=null?B:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Nn.titleColor,u=(D=l.querySelector(".persona-combo-btn-label"))!=null?D:l;else{if(l=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=b("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=Nn.titleColor,u.textContent=(P=a.title)!=null?P:"Chat Assistant",l.appendChild(u),dy(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 $=r.onTitleClick;l.addEventListener("click",G=>{G.target.closest("button")||$()}),l.addEventListener("keydown",G=>{(G.key==="Enter"||G.key===" ")&&(G.preventDefault(),$())})}let V=r==null?void 0:r.titleRowHover;V&&(l.style.borderRadius=(C=V.borderRadius)!=null?C:"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 $,G;l.style.backgroundColor=($=V.background)!=null?$:"",l.style.borderColor=(G=V.border)!=null?G:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let g=(A=a.closeButtonSize)!=null?A:"32px",f=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=g,m.style.width=g,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=n?"":"none",m.style.color=a.closeButtonColor||Nn.actionIconColor;let x=(S=a.closeButtonIconName)!=null?S:"x",v=Me(x,"28px","currentColor",1);v?m.appendChild(v):m.textContent="\xD7",o&&m.addEventListener("click",o),f.appendChild(m),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:u,headerSubtitle:I,closeButton:m,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},kg={default:cy,minimal:py},uy=e=>{var t;return(t=kg[e])!=null?t:kg.default},Ji=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),u=b("div");u.style.display="none";let g=b("span"),f=b("span"),m=b("button");m.style.display="none";let x=b("div");return x.style.display="none",{header:l,iconHolder:u,headerTitle:g,headerSubtitle:f,closeButton:m,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let o=(a=t==null?void 0:t.layout)!=null?a:"default",s=uy(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 Zi=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}},el=e=>{var P,w,C,E,A,S,V,$,G,he,me,de;let t=(P=e==null?void 0:e.sendButton)!=null?P:{},n=(w=t.useIcon)!=null?w:!1,o=(C=t.iconText)!=null?C:"\u2191",r=t.iconName,s=(E=t.stopIconName)!=null?E:"square",a=(A=t.tooltipText)!=null?A:"Send message",i=(S=t.stopTooltipText)!=null?S:"Stop generating",d=($=(V=e==null?void 0:e.copy)==null?void 0:V.sendButtonLabel)!=null?$:"Send",l=(he=(G=e==null?void 0:e.copy)==null?void 0:G.stopButtonLabel)!=null?he:"Stop",u=(me=t.showTooltip)!=null?me:!1,g=(de=t.size)!=null?de:"40px",f=t.backgroundColor,m=t.textColor,x=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=g,v.style.height=g,v.style.minWidth=g,v.style.minHeight=g,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(g)||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),f?v.style.backgroundColor=f: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;u&&a&&(R=b("div","persona-send-button-tooltip"),R.textContent=a,x.appendChild(R)),v.setAttribute("aria-label",a),x.appendChild(v);let B="send";return{button:v,wrapper:x,setMode:Ee=>{if(Ee===B)return;B=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}}},tl=e=>{var R,B,D,P,w,C,E,A,S,V,$,G;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=((B=t.provider)==null?void 0:B.type)==="runtype";if(!(o||r))return null;let a=(P=(D=e==null?void 0:e.sendButton)==null?void 0:D.size)!=null?P:"40px",i=b("div","persona-send-button-wrapper"),d=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(w=t.iconName)!=null?w:"mic",u=(C=t.iconSize)!=null?C:a,g=parseFloat(u)||24,f=(A=t.backgroundColor)!=null?A:(E=e==null?void 0:e.sendButton)==null?void 0:E.backgroundColor,m=(V=t.iconColor)!=null?V:(S=e==null?void 0:e.sendButton)==null?void 0:S.textColor;d.style.width=u,d.style.height=u,d.style.minWidth=u,d.style.minHeight=u,d.style.fontSize="18px",d.style.lineHeight="1",m?d.style.color=m:d.style.color="var(--persona-text, #111827)";let v=Me(l,g,m||"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=($=t.tooltipText)!=null?$:"Start voice recognition";if(((G=t.showTooltip)!=null?G:!1)&&M){let he=b("div","persona-send-button-tooltip");he.textContent=M,i.appendChild(he)}return{button:d,wrapper:i}},nl=e=>{var x,v,M,I,R,B,D,P;let t=(x=e==null?void 0:e.attachments)!=null?x:{};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",(B=t.buttonTooltipText)!=null?B:"Attach file");let i=(D=t.buttonIconName)!=null?D:"paperclip",d=n,l=parseFloat(d)||40,u=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let g=Me(i,u,"currentColor",1.5);g?a.appendChild(g):a.textContent="\u{1F4CE}",a.addEventListener("click",w=>{w.preventDefault(),r.click()}),s.appendChild(a);let f=(P=t.buttonTooltipText)!=null?P:"Attach file",m=b("div","persona-send-button-tooltip");return m.textContent=f,s.appendChild(m),{button:a,wrapper:s,input:r,previewsContainer:o}},ol=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},rl=()=>b("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var sl=e=>{var x,v,M,I,R,B;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=rl(),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}=Zi(t);a();let i=el(t),d=tl(t),l=nl(t),u=ol(t);l&&(l.previewsContainer.style.gap="8px",r.append(l.previewsContainer,l.input)),r.append(s);let g=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"),m=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&f.append(l.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),g.append(f,m),r.append(g),r.addEventListener("click",D=>{D.target!==i.button&&D.target!==i.wrapper&&D.target!==(d==null?void 0:d.button)&&D.target!==(d==null?void 0:d.wrapper)&&D.target!==(l==null?void 0:l.button)&&D.target!==(l==null?void 0:l.wrapper)&&s.focus()}),n.append(o,r,u),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:u,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:(B=l==null?void 0:l.previewsContainer)!=null?B:null,actionsRow:g,leftActions:f,rightActions:m,setSendButtonMode:i.setMode}};var Eg=()=>{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}},Mg=e=>{var x,v,M,I,R,B;let{config:t}=e,n=b("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let o=rl();o.style.display="none";let r=ol(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=Zi(t);s.style.maxHeight="100px",a();let i=el(t),d=tl(t),l=nl(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let u=b("form","persona-widget-composer persona-pill-composer");u.setAttribute("data-persona-composer-form",""),u.style.outline="none";let g=b("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&g.append(l.wrapper);let f=b("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),u.addEventListener("click",D=>{D.target!==i.button&&D.target!==i.wrapper&&D.target!==(d==null?void 0:d.button)&&D.target!==(d==null?void 0:d.wrapper)&&D.target!==(l==null?void 0:l.button)&&D.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&u.append(l.input),u.append(g,s,f),l&&n.append(l.previewsContainer),n.append(u,o,r);let m=u;return{footer:n,suggestions:o,composerForm:u,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x: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:(B=l==null?void 0:l.previewsContainer)!=null?B:null,actionsRow:m,leftActions:g,rightActions:f,setSendButtonMode:i.setMode}};var Lg=e=>{var u,g,f,m,x,v,M,I,R,B,D,P,w,C,E,A,S;let t=(g=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?g:!0,n=Sn(e);if(Ia(e)){let V=(m=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?m:{},$=b("div","persona-widget-wrapper persona-fixed persona-transition");$.setAttribute("data-persona-composer-bar",""),$.dataset.state="collapsed",$.dataset.expandedSize=(x=V.expandedSize)!=null?x:"anchored",$.style.zIndex=String((M=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?M:In);let G=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");G.style.width="100%",$.appendChild(G);let 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((B=(R=e==null?void 0:e.launcher)==null?void 0:R.zIndex)!=null?B:In),{wrapper:$,panel:G,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"),$=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($),{wrapper:V,panel:$}}if(!t){let V=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),$=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),G=(P=(D=e==null?void 0:e.launcher)==null?void 0:D.width)!=null?P:"100%";return V.style.width=G,$.style.width="100%",V.appendChild($),{wrapper:V,panel:$}}let r=(w=e==null?void 0:e.launcher)!=null?w:{},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=(C=e==null?void 0:e.launcher)==null?void 0:C.zIndex)!=null?E:In);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(S=(A=e==null?void 0:e.launcher)==null?void 0:A.width)!=null?S: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}},my=(e,t)=>{var D,P,w,C,E,A,S,V,$;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=(P=(D=e==null?void 0:e.launcher)==null?void 0:D.clearChat)==null?void 0:P.enabled)!=null?w:!0,a=null,i=null;if(s){let G=Xi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=G.button,i=G.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=b("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=b("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages"),l.style.setProperty("scrollbar-gutter","stable");let u=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");u.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",u.setAttribute("data-persona-intro-card","");let g=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");g.textContent=(E=(C=e==null?void 0:e.copy)==null?void 0:C.welcomeTitle)!=null?E:"Hello \u{1F44B}";let f=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(S=(A=e==null?void 0:e.copy)==null?void 0:A.welcomeSubtitle)!=null?S:"Ask anything about your account or products.",u.append(g,f);let m=b("div","persona-flex persona-flex-col persona-gap-3"),x=(V=e==null?void 0:e.layout)==null?void 0:V.contentMaxWidth;x&&(m.style.maxWidth=x,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),(($=e==null?void 0:e.copy)==null?void 0:$.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,m);let M=b("div","persona-composer-overlay persona-pointer-events-none");M.setAttribute("data-persona-composer-overlay",""),M.style.position="absolute",M.style.left="0",M.style.right="0",M.style.bottom="0",M.style.zIndex="20";let I=Mg({config:e}),{root:R,textNode:B}=Eg();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:g,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:B}},Ig=(e,t=!0)=>{var M,I,R,B,D,P,w,C,E;if(Ia(e))return my(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?Ji(e,o,{showClose:t}):jr({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=Sn(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=(B=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeTitle)!=null?B:"Hello \u{1F44B}";let l=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(P=(D=e==null?void 0:e.copy)==null?void 0:D.welcomeSubtitle)!=null?P:"Ask anything about your account or products.",i.append(d,l);let u=b("div","persona-flex persona-flex-col persona-gap-3"),g=(w=e==null?void 0:e.layout)==null?void 0:w.contentMaxWidth;g&&(u.style.maxWidth=g,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((C=e==null?void 0:e.copy)==null?void 0:C.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,u);let m=sl({config:e}),x=((E=e==null?void 0:e.layout)==null?void 0:E.showFooter)!==!1;r?Pa(n,s,e):(s.header.style.display="none",Pa(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",x||(m.footer.style.display="none"),n.append(m.footer),n.append(v),{container:n,body:a,messagesWrapper:u,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 gy=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}},fy=(e,t)=>{if(!e)return null;let n=gy(e);if(n===null)return null;let o=t==null?void 0:t[e],r=o!==void 0?o:n;return r||null},hy=(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},by=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},bc=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(":"))},yc=320,Pg=320,yy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),vy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),xy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),wy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Cy=(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 g;let l=b("img");l.alt=((g=i.alt)==null?void 0:g.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=`${yc}px`,l.style.maxHeight=`${Pg}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;r+=1,l.addEventListener("error",()=>{u||(u=!0,r=Math.max(0,r-1),l.remove(),r===0&&a())}),l.addEventListener("load",()=>{u=!0}),by(i.image)?(l.src=i.image,o.appendChild(l)):(u=!0,r=Math.max(0,r-1),l.remove())}),r===0?(a(),null):o}catch{return n==null||n(),null}},Sy=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(!bc(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=`${yc}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Ay=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(!bc(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=`${yc}px`,r.style.maxHeight=`${Pg}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}},Ty=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(!bc(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}},Wa=()=>{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},ky=(e,t,n)=>{let o={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Wa};if(t){let r=t(o);if(r!==null)return r}return Wa()},Ey=(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},Rg=(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},My=(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},Ly=(e,t,n)=>{var m,x,v,M,I,R;let o=(m=t.showCopy)!=null?m:!0,r=(x=t.showUpvote)!=null?x:!0,s=(v=t.showDownvote)!=null?v:!0;if(!o&&!r&&!s){let B=b("div");return B.style.display="none",B.id=`actions-${e.id}`,B.setAttribute("data-actions-for",e.id),B}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],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],g=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${u} ${a==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let f=(B,D,P)=>{let w=Rn({icon:B,label:D,size:14,className:"persona-message-action-btn"});return w.setAttribute("data-action",P),w};return o&&g.appendChild(f("copy","Copy message","copy")),r&&g.appendChild(f("thumbs-up","Upvote","upvote")),s&&g.appendChild(f("thumbs-down","Downvote","downvote")),g},vc=(e,t,n,o,r,s)=>{var le,X,se,ye,be,K,ae,Pe,oe,ee,re,it,lt,Ie,pe,Xe,Be;let a=n!=null?n:{},i=(le=a.layout)!=null?le:"bubble",d=a.avatar,l=a.timestamp,u=(X=d==null?void 0:d.show)!=null?X:!1,g=(se=l==null?void 0:l.show)!=null?se:!1,f=(ye=d==null?void 0:d.position)!=null?ye:"left",m=(be=l==null?void 0:l.position)!=null?be:"below",x=My(e.role,i),v=b("div",x.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=yy(e),I=(ae=(K=e.content)==null?void 0:K.trim())!=null?ae:"",B=M.length>0&&I===Di,D=Ki((oe=(Pe=s==null?void 0:s.widgetConfig)==null?void 0:Pe.features)==null?void 0:oe.streamAnimation),P=(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"?Ta(D.type,P):null,C=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||C);E&&(w!=null&&w.bubbleClass)&&v.classList.add(w.bubbleClass);let A=document.createElement("div");A.classList.add("persona-message-content"),E&&w&&(w.containerClass&&A.classList.add(w.containerClass),A.style.setProperty("--persona-stream-step",`${D.speed}ms`),A.style.setProperty("--persona-stream-duration",`${D.duration}ms`));let S=E?Gi((Ie=e.content)!=null?Ie:"",D.buffer,w,e,!!e.streaming):(pe=e.content)!=null?pe:"",V=t({text:S,message:e,streaming:!!e.streaming,raw:e.rawContent}),$=V;E&&(w==null?void 0:w.wrap)==="char"?$=ka(V,"char",e.id,{skipTags:w.skipTags}):E&&(w==null?void 0:w.wrap)==="word"&&($=ka(V,"word",e.id,{skipTags:w.skipTags}));let G=null;if(B?(G=document.createElement("div"),G.innerHTML=$,G.style.display="none",A.appendChild(G)):A.innerHTML=$,E&&(w!=null&&w.useCaret)&&!B&&I){let j=Yi(),ge=A.querySelectorAll(".persona-stream-char, .persona-stream-word"),nt=ge[ge.length-1];if(nt!=null&&nt.parentNode)nt.parentNode.insertBefore(j,nt.nextSibling);else{let kt=A.lastElementChild;kt?kt.appendChild(j):A.appendChild(j)}}if(g&&m==="inline"&&e.createdAt){let j=Rg(e,l);j.classList.add("persona-ml-2","persona-inline"),A.appendChild(j)}if(M.length>0){let j=Cy(M,!B&&!!I,()=>{B&&G&&(G.style.display="")});j?v.appendChild(j):B&&G&&(G.style.display="")}let he=vy(e);if(he.length>0){let j=Sy(he);j&&v.appendChild(j)}let me=xy(e);if(me.length>0){let j=Ay(me);j&&v.appendChild(j)}let de=wy(e);if(de.length>0){let j=Ty(de);j&&v.appendChild(j)}if(v.appendChild(A),g&&m==="below"&&e.createdAt){let j=Rg(e,l);j.classList.add("persona-mt-1"),v.appendChild(j)}let Ee=e.role==="assistant"?fy(e.stopReason,(Be=(Xe=s==null?void 0:s.widgetConfig)==null?void 0:Xe.copy)==null?void 0:Be.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let j=!!(S&&S.trim()),ge=D.placeholder==="skeleton",nt=ge&&D.buffer==="line"&&j;if(j)nt&&v.appendChild(Ea());else if(ge)v.appendChild(Ea());else{let kt=ky("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);kt&&v.appendChild(kt)}}if(Ee&&e.stopReason&&!e.streaming&&(I||(A.style.display="none"),v.appendChild(hy(e.stopReason,Ee))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let j=Ly(e,o,r);v.appendChild(j)}if(!u||e.role==="system")return v;let De=b("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Ae=Ey(d,e.role);return f==="right"||f==="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 As=new Set,Iy=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Ry=(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
|
-
`):""},Wg=(e,t)=>{let n=As.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")},xc=(e,t)=>{var me,de,Ee,xe,De,Ae,le,X,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&&As.has(e.id),i=n.status!=="complete",d=Ry(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 u=b("div","persona-flex persona-flex-col persona-text-left"),g=b("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",m=(xe=t==null?void 0:t.reasoning)!=null?xe:{},x=String((De=n.startedAt)!=null?De:Date.now()),v=()=>{let K=b("span","");return K.setAttribute("data-tool-elapsed",x),K.textContent=Ri(n),K},M=(Ae=m.renderCollapsedSummary)==null?void 0:Ae.call(m,{message:e,reasoning:n,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Ri(n),createElapsedElement:v});typeof M=="string"&&M.trim()?(g.textContent=M,u.appendChild(g)):M instanceof HTMLElement?u.appendChild(M):(g.textContent=f,u.appendChild(g));let I=b("span","persona-text-xs persona-text-persona-primary");I.textContent=Xm(n),u.appendChild(I);let R=(le=r.loadingAnimation)!=null?le:"none",B=m.activeTextTemplate,D=m.completeTextTemplate,P=i?B:D,w=M instanceof HTMLElement,C=(K,ae,Pe)=>{let oe=Pe;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)=>{g.textContent="";let Pe=Pi(K,""),oe=0;for(let ee of Pe){let re=ee.styles.length>0?(()=>{let it=b("span",ee.styles.map(lt=>`persona-tool-text-${lt}`).join(" "));return g.appendChild(it),it})():g;if(ee.isDuration&&i)re.appendChild(v());else{let it=ee.isDuration?Ri(n):ee.text;ae?oe=C(re,it,oe):re.appendChild(document.createTextNode(it))}}};if(!w&&P)if(I.style.display="none",g.style.display="",i&&R!=="none"){let K=(X=m.loadingAnimationDuration)!=null?X:2e3;g.setAttribute("data-preserve-animation","true"),R==="pulse"?(g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${K}ms`),E(P,!1)):(g.classList.add(`persona-tool-loading-${R}`),g.style.setProperty("--persona-tool-anim-duration",`${K}ms`),R==="shimmer-color"&&(m.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),E(P,!0))}else E(P,!1);else if(!w&&i&&R!=="none"){g.style.display="";let K=(se=m.loadingAnimationDuration)!=null?se:2e3;if(g.setAttribute("data-preserve-animation","true"),R==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${K}ms`);else{g.classList.add(`persona-tool-loading-${R}`),g.style.setProperty("--persona-tool-anim-duration",`${K}ms`),R==="shimmer-color"&&(m.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let ae=g.textContent||f;g.textContent="",C(g,ae,0)}n.status==="complete"&&(g.style.display="none")}else w||(n.status==="complete"?g.style.display="none":g.style.display="");let A=null;if(s){A=b("div","persona-flex persona-items-center");let ae=Me(a?"chevron-up":"chevron-down",16,"currentColor",2);ae?A.appendChild(ae):A.textContent=a?"Hide":"Show";let Pe=b("div","persona-flex persona-items-center persona-ml-auto");Pe.append(A),l.append(u,Pe)}else l.append(u);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","reasoning"),S.style.display="none",S.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:{}});Iy(S,K)||(S.textContent=d),S.style.display=""}if(!a&&i&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(l,S),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 $=n.chunks.join(""),G=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return G.textContent=$||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),V.appendChild(G),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),A){A.innerHTML="";let ae=Me(a?"chevron-up":"chevron-down",16,"currentColor",2);ae?A.appendChild(ae):A.textContent=a?"Hide":"Show"}V.style.display=a?"":"none",S.style.display=a?"none":S.textContent||S.childNodes.length?"":"none"})(),o.append(l,S,V),o};var Ts=new Set,Py=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Wy=(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=Cs(n.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
|
|
26
|
-
`):""},By=(e,t)=>{var u,g,f,m,x;let n=e.toolCall,o=(u=t==null?void 0:t.features)==null?void 0:u.toolCallDisplay,r=(g=o==null?void 0:o.collapsedMode)!=null?g:"tool-call",s=Wy(e,(f=o==null?void 0:o.previewMaxLines)!=null?f:3),a=n?Jm(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=((x=n.name)==null?void 0:x.trim())||a:r==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=ic(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=ic(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},Bg=(e,t,n)=>{var u;let o=Ts.has(e),r=(u=n==null?void 0:n.toolCall)!=null?u:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let g=r.toggleTextColor||r.headerTextColor||"currentColor",f=Me(o?"chevron-up":"chevron-down",16,g,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")},wc=(e,t)=>{var $,G,he,me,de,Ee,xe,De,Ae;let n=e.toolCall,o=($=t==null?void 0:t.toolCall)!=null?$:{},r=b("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=(he=(G=t==null?void 0:t.features)==null?void 0:G.toolCallDisplay)!=null?he:{},a=s.expandable!==!1,i=a&&Ts.has(e.id),{summary:d,previewText:l,isActive:u}=By(e,t),g=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");g.type="button",a&&(g.setAttribute("aria-expanded",i?"true":"false"),g.setAttribute("data-expand-header","true")),g.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(g.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(g.style.paddingLeft=o.headerPaddingX,g.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(g.style.paddingTop=o.headerPaddingY,g.style.paddingBottom=o.headerPaddingY);let f=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 x=String((me=n.startedAt)!=null?me:Date.now()),v=()=>{let le=b("span","");return le.setAttribute("data-tool-elapsed",x),le.textContent=ba(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:u,config:t!=null?t:{},elapsed:ba(n),createElapsedElement:v});typeof M=="string"&&M.trim()?(m.textContent=M,f.appendChild(m)):M instanceof HTMLElement?f.appendChild(M):(m.textContent=d,f.appendChild(m));let I=(xe=s.loadingAnimation)!=null?xe:"none",R=o.activeTextTemplate,B=o.completeTextTemplate,D=u?R:B,P=M instanceof HTMLElement,w=(le,X,se)=>{let ye=se;for(let be of X){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},C=(le,X)=>{var K;m.textContent="";let se=((K=n.name)==null?void 0:K.trim())||"tool",ye=Pi(le,se),be=0;for(let ae of ye){let Pe=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&&u)Pe.appendChild(v());else{let oe=ae.isDuration?ba(n):ae.text;X?be=w(Pe,oe,be):Pe.appendChild(document.createTextNode(oe))}}};if(!P)if(u&&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&&C(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)C(D,!0);else{let X=m.textContent||d;m.textContent="",w(m,X,0)}}else D&&C(D,!1);let E=null;if(a){E=b("div","persona-flex persona-items-center");let le=o.toggleTextColor||o.headerTextColor||"currentColor",X=Me(i?"chevron-up":"chevron-down",16,le,2);X?E.appendChild(X):E.textContent=i?"Hide":"Show";let se=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");se.append(E),g.append(f,se)}else g.append(f);let A=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(A.setAttribute("data-persona-collapsed-preview","tool"),A.style.display="none",A.style.whiteSpace="pre-wrap",!i&&u&&s.activePreview&&l){let le=(Ae=o.renderCollapsedPreview)==null?void 0:Ae.call(o,{message:e,toolCall:n,defaultPreview:l,isActive:u,config:t!=null?t:{}});Py(A,le)||(A.textContent=l),A.style.display=""}if(!i&&u&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(g,A),r;let S=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(S.style.display=i?"":"none",o.contentBackgroundColor&&(S.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(S.style.color=o.contentTextColor),o.contentPaddingX&&(S.style.paddingLeft=o.contentPaddingX,S.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(S.style.paddingTop=o.contentPaddingY,S.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,S.appendChild(le)}if(n.args!==void 0){let le=b("div","persona-space-y-1"),X=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(X.style.color=o.labelTextColor),X.textContent="Arguments";let 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=Cs(n.args),le.append(X,se),S.appendChild(le)}if(n.chunks&&n.chunks.length){let le=b("div","persona-space-y-1"),X=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(X.style.color=o.labelTextColor),X.textContent="Activity";let 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(X,se),S.appendChild(le)}if(n.status==="complete"&&n.result!==void 0){let le=b("div","persona-space-y-1"),X=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(X.style.color=o.labelTextColor),X.textContent="Result";let 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=Cs(n.result),le.append(X,se),S.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`,S.appendChild(le)}return(()=>{if(g.setAttribute("aria-expanded",i?"true":"false"),E){E.innerHTML="";let le=o.toggleTextColor||o.headerTextColor||"currentColor",X=Me(i?"chevron-up":"chevron-down",16,le,2);X?E.appendChild(X):E.textContent=i?"Hide":"Show"}S.style.display=i?"":"none",A.style.display=i?"none":A.textContent||A.childNodes.length?"":"none"})(),r.append(g,A,S),r};var al=new Map,Hy=e=>{let n=(e.startsWith(_r)?e.slice(_r.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)},Hg=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Dg=(e,t)=>{var o,r,s;let n=(r=(o=Hg(t))==null?void 0:o.detailsDisplay)!=null?r:"collapsed";return(s=al.get(e))!=null?s:n==="expanded"},Og=(e,t,n)=>{var a,i;let o=Hg(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)}},Fg=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=Dg(e,n);Og(o,s,n),r.style.display=s?"":"none"};var il=(e,t)=>{var C,E,A,S,V,$,G,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=(C=o==null?void 0:o.backgroundColor)!=null?C:"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)":(A=o==null?void 0:o.titleColor)!=null?A:"currentColor",u=Me(d,20,l,2);u&&i.appendChild(u);let g=b("div","persona-flex-1 persona-min-w-0"),f=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=(S=o==null?void 0:o.title)!=null?S:"Approval Required",f.appendChild(m),!r){let X=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");X.setAttribute("data-approval-status",n.status),n.status==="approved"?(X.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",X.style.color="var(--persona-palette-colors-success-700, #15803d)",X.textContent="Approved"):n.status==="denied"?(X.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",X.style.color="var(--persona-palette-colors-error-700, #b91c1c)",X.textContent="Denied"):n.status==="timeout"&&(X.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",X.style.color="var(--persona-palette-colors-warning-700, #b45309)",X.textContent="Timeout"),f.appendChild(X)}g.appendChild(f);let v=n.toolType==="webmcp"||n.toolName.startsWith(_r)?Ql(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:Hy(n.toolName)}\u201D.`),B=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(B.setAttribute("data-approval-summary","true"),o!=null&&o.descriptionColor&&(B.style.color=o.descriptionColor),B.textContent=R,g.appendChild(B),n.reason){let X=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");X.setAttribute("data-approval-reason","true"),o!=null&&o.reasonColor?X.style.color=o.reasonColor:o!=null&&o.descriptionColor&&(X.style.color=o.descriptionColor);let se=b("span","persona-font-medium");se.textContent=`${($=o==null?void 0:o.reasonLabel)!=null?$:"Agent's stated reason:"} `,X.appendChild(se),X.appendChild(document.createTextNode(n.reason)),g.appendChild(X)}let D=(G=o==null?void 0:o.detailsDisplay)!=null?G:"collapsed",P=!!n.description&&!I,w=P||!!n.parameters;if(D!=="hidden"&&w){let X=Dg(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),Og(se,X,t),g.appendChild(se);let K=b("div");if(K.setAttribute("data-approval-details","true"),K.style.display=X?"":"none",P){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=Cs(n.parameters),K.appendChild(ae)}g.appendChild(K)}if(r){let X=b("div","persona-flex persona-gap-2 persona-mt-2");X.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 Pe=document.createTextNode((le=o==null?void 0:o.denyLabel)!=null?le:"Deny");K.appendChild(Pe),X.append(se,K),g.appendChild(X)}return a.append(i,g),s.appendChild(a),s};var Ng=e=>{let t=[],n=null;return{buttons:t,render:(r,s,a,i,d,l)=>{e.innerHTML="",t.length=0;let u=(l==null?void 0:l.agentPushed)===!0;if(u||(n=null),!r||!r.length||!u&&(i!=null?i:s?s.getMessages():[]).some(M=>M.role==="user"))return;let g=document.createDocumentFragment(),f=s?s.isStreaming():!1,m=x=>{switch(x){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'}};if(r.forEach(x=>{let v=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");v.type="button",v.textContent=x,v.disabled=f,d!=null&&d.fontFamily&&(v.style.fontFamily=m(d.fontFamily)),d!=null&&d.fontWeight&&(v.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(v.style.paddingLeft=d.paddingX,v.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(v.style.paddingTop=d.paddingY,v.style.paddingBottom=d.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",u&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:x},bubbles:!0,composed:!0})),s.sendMessage(x))}),g.appendChild(v),t.push(v)}),e.appendChild(g),u){let x=JSON.stringify(r);x!==n&&(n=x,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...r]},bubbles:!0,composed:!0})))}}}};var Ba=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 Ha=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 Dy=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Oy=new Set(["step_start","execution_start"]),Fy=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Ny=new Set(["step_complete","agent_turn_complete"]),_y=new Set(["flow_complete","agent_complete"]),_g=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),$g=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ro=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Kr=(e,t)=>{let n=e[t];return $g(n)?n:void 0};function Cc(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function ll(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Vy(e,t){return typeof t.type=="string"?t.type:e}function $y(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 Uy(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 Vg(e){var o,r,s,a,i;let t=Kr(e,"result"),n=[Kr(e,"tokens"),Kr(e,"totalTokens"),t?Kr(t,"tokens"):void 0,Kr(e,"usage"),t?Kr(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(r=(o=ro(d.output))!=null?o:ro(d.outputTokens))!=null?r:ro(d.completionTokens);if(l!==void 0)return l}return(i=(s=ro(e.outputTokens))!=null?s:ro(e.completionTokens))!=null?i:t?(a=ro(t.outputTokens))!=null?a:ro(t.completionTokens):void 0}function zy(e){var n,o,r,s,a;let t=Kr(e,"result");return(a=(r=(o=(n=ro(e.executionTime))!=null?n:ro(e.executionTimeMs))!=null?o:ro(e.execution_time))!=null?r:ro(e.duration))!=null?a:t?(s=ro(t.executionTime))!=null?s:ro(t.executionTimeMs):void 0}function qy(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Da=class{constructor(t=qy){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:ll(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(!$g(n)){_g.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Vy(t,n),r=this.now();if(Dy.has(o)){this.startRun(r);return}if(Oy.has(o)){this.run||this.startRun(r);return}if(Fy.has(o)){if(!Uy(o,n))return;let a=$y(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+Cc(i.visibleCharCount),l=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:ll(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Ny.has(o)){if(!this.run)return;let a=this.run,i=Vg(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Cc(a.visibleCharCount),u=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:ll(l,u),outputTokens:l,durationMs:u,source:d?"usage":"estimate"};return}if(_y.has(o)){if(!this.run)return;let a=this.run,i=Vg(n),d=i!=null?i:a.exactOutputTokens+Cc(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:ll(d,u),outputTokens:d,durationMs:u,source:l},this.run=null;return}if(_g.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=zy(n);return s!=null?s:o-t.startedAt}};function ks(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var jy={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)"}},Ky={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Gy=["flowName","stepName","reasoningText","text","name","tool","toolName"],Yy=100;function Qy(e,t){let n={...jy,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Ky}function Xy(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Jy(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 Zy(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 ev(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 tv(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function nv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function ov(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 rv(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 Sc(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");ks(l,(f=o.classNames)==null?void 0:f.eventRow);let u=a.find(m=>m.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let m=u.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>g(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(m)return l.appendChild(m),l}return l.appendChild(g()),l;function g(){var $,G;let m=b("div",""),x=b("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");x.setAttribute("data-event-id",e.id);let 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=($=o.timestampFormat)!=null?$:"relative";I.textContent=R==="relative"?Xy(e.timestamp,n):Jy(e.timestamp);let B=null;o.showSequenceNumbers!==!1&&(B=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),B.textContent=String(t+1));let D=Qy(e.type,o.badgeColors),P=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");P.style.backgroundColor=D.bg,P.style.color=D.text,P.style.borderColor=D.text+"50",P.textContent=e.type;let w=(G=o.descriptionFields)!=null?G:Gy,C=Zy(e.payload,w),E=null;C&&(E=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),E.textContent=C);let A=b("div","persona-flex-1 persona-min-w-0"),S=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&&S.appendChild(V),S.addEventListener("click",async he=>{he.stopPropagation(),await ev(tv(e)),S.innerHTML="";let me=Me("check","12px","currentColor",1.5);me&&S.appendChild(me),setTimeout(()=>{S.innerHTML="";let de=Me("clipboard","12px","currentColor",1.5);de&&S.appendChild(de)},1500)}),x.appendChild(v),x.appendChild(I),B&&x.appendChild(B),x.appendChild(P),E&&x.appendChild(E),x.appendChild(A),x.appendChild(S),m.appendChild(x),d&&m.appendChild(rv(e,a,i)),m}}function Ug(e){var x,v,M,I,R;let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,i=(x=r==null?void 0:r.features)==null?void 0:x.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(v=i==null?void 0:i.iconName)!=null?v:"arrow-down",u=(M=i==null?void 0:i.label)!=null?M:"",g=(R=(I=r==null?void 0:r.features)==null?void 0:I.eventStream)!=null?R:{},f=s.find(B=>B.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&r){let B=f.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>m().element,onClose:o});if(B)return{element:B,update:()=>{},destroy:()=>{}}}return m();function m(){let B=g.classNames,D=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ks(D,B==null?void 0:B.panel);let P=[],w="",C="",E=null,A=[],S={},V=0,$=zi(),G=0,he=0,me=!1,de=null,Ee=!1,xe=0,De=new Set,Ae=new Map,le="",X="",se=null,ye,be,K,ae,Pe,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");ks(ce,B==null?void 0:B.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 An=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");An.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 Tn=ee,yn=re,Io=()=>{if(!yn.textContent)return;let qn=Tn.getBoundingClientRect(),jn=Se.getBoundingClientRect();yn.style.left=`${qn.left-jn.left}px`,yn.style.top=`${qn.bottom-jn.top+4}px`,yn.style.display="block"},St=()=>{yn.style.display="none"};ee.addEventListener("mouseenter",Io),ee.addEventListener("mouseleave",St),ee.appendChild(An),ee.appendChild(oe)}let en=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 Kt=b("option","");Kt.value="",Kt.textContent="All events",be.appendChild(Kt),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 wn=Me("clipboard-copy","12px","currentColor",1.5);wn&&K.appendChild(wn);let mt=b("span","persona-text-xs");mt.textContent="Copy All",K.appendChild(mt),ce.appendChild(et),ce.appendChild(ye),ee&&ce.appendChild(ee),ce.appendChild(en),ce.appendChild(be),ce.appendChild(K);let Et=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ks(Et,B==null?void 0:B.searchBar);let Je=Me("search","14px","var(--persona-muted, #9ca3af)",1.5),zt=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Je&&zt.appendChild(Je),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"),ks(ae,B==null?void 0:B.searchInput),ae.type="text",ae.placeholder="Search event payloads...",Pe=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"),Pe.type="button",Pe.style.display="none";let cn=Me("x","12px","currentColor",2);return cn&&Pe.appendChild(cn),Et.appendChild(zt),Et.appendChild(ae),Et.appendChild(Pe),Se.appendChild(ce),Se.appendChild(Et),re&&Se.appendChild(re),Se}let lt,Ie=s.find(Se=>Se.renderEventStreamToolbar);if(Ie!=null&&Ie.renderEventStreamToolbar&&r){let Se=Ie.renderEventStreamToolbar({config:r,defaultRenderer:()=>it(),eventCount:t.getSize(),filteredCount:0,onFilterChange:ce=>{w=ce,ln(),O()},onSearchChange:ce=>{C=ce,ln(),O()}});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 Xe(){if(!a||!oe||!ee)return;let Se=a();oe.textContent=nv(Se);let ce=ov(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 ge=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");ks(ge,B==null?void 0:B.scrollIndicator),ge.style.display="none",ge.setAttribute("data-persona-scroll-to-bottom-has-label",u?"true":"false");let nt=Me(l,"14px","currentColor",2);nt&&ge.appendChild(nt);let kt=b("span","");kt.textContent=u,ge.appendChild(kt);let ne=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ne.style.display="none",Be.appendChild(j),Be.appendChild(ne),Be.appendChild(ge),D.setAttribute("tabindex","0"),D.appendChild(lt),D.appendChild(pe),D.appendChild(Be);function qe(){let Se=t.getAll(),ce={};for(let mt of Se)ce[mt.type]=(ce[mt.type]||0)+1;let et=Object.keys(ce).sort(),en=et.length!==A.length||!et.every((mt,Et)=>mt===A[Et]),Kt=!en&&et.some(mt=>ce[mt]!==S[mt]),Pn=Se.length!==Object.values(S).reduce((mt,Et)=>mt+Et,0);if(!en&&!Kt&&!Pn||(A=et,S=ce,!be))return;let wn=be.value;if(be.options[0].textContent="All events",en){for(;be.options.length>1;)be.remove(1);for(let mt of et){let Et=b("option","");Et.value=mt,Et.textContent=`${mt} (${ce[mt]||0})`,be.appendChild(Et)}wn&&et.includes(wn)?be.value=wn:wn&&(be.value="",w="")}else for(let mt=1;mt<be.options.length;mt++){let Et=be.options[mt];Et.textContent=`${Et.value} (${ce[Et.value]||0})`}}function _n(){let Se=t.getAll();if(w&&(Se=Se.filter(ce=>ce.type===w)),C){let ce=C.toLowerCase();Se=Se.filter(et=>et.type.toLowerCase().includes(ce)||et.payload.toLowerCase().includes(ce))}return Se}function Ht(){return w!==""||C!==""}function ln(){V=0,G=0,$.resume(),ge.style.display="none"}function so(Se){De.has(Se)?De.delete(Se):De.add(Se),se=Se;let ce=j.scrollTop,et=$.isFollowing();Ee=!0,$.pause(),O(),j.scrollTop=ce,et&&$.resume(),Ee=!1}function Lo(){return qr(j,50)}function O(){he=Date.now(),me=!1,Xe(),qe();let Se=t.getEvictedCount();Se>0?(pe.textContent=`${Se.toLocaleString()} older events truncated`,pe.style.display=""):pe.style.display="none",P=_n();let ce=P.length,et=t.getSize()>0;ye&&(ye.textContent=String(t.getSize())),ce===0&&et&&Ht()?(ne.textContent=C?`No events matching '${C}'`:"No events matching filter",ne.style.display="",j.style.display="none"):(ne.style.display="none",j.style.display=""),K&&(K.title=Ht()?`Copy Filtered (${ce})`:"Copy All"),d&&!$.isFollowing()&&ce>V&&(G+=ce-V,kt.textContent=u?`${u}${G>0?` (${G})`:""}`:"",ge.style.display=""),V=ce;let en=t.getAll(),Kt=en.length>0?en[0].timestamp:0,Pn=new Set(P.map(Et=>Et.id));for(let Et of De)Pn.has(Et)||De.delete(Et);let wn=w!==le||C!==X,mt=Ae.size===0&&P.length>0;if(wn||mt||P.length===0){j.innerHTML="",Ae.clear();let Et=document.createDocumentFragment();for(let Je=0;Je<P.length;Je++){let zt=Sc(P[Je],Je,Kt,g,De,so,s,r);Ae.set(P[Je].id,zt),Et.appendChild(zt)}j.appendChild(Et),le=w,X=C,se=null}else{if(se!==null){let Je=Ae.get(se);if(Je&&Je.parentNode===j){let zt=P.findIndex(cn=>cn.id===se);if(zt>=0){let cn=Sc(P[zt],zt,Kt,g,De,so,s,r);j.insertBefore(cn,Je),Je.remove(),Ae.set(se,cn)}}se=null}let Et=new Set(P.map(Je=>Je.id));for(let[Je,zt]of Ae)Et.has(Je)||(zt.remove(),Ae.delete(Je));for(let Je=0;Je<P.length;Je++){let zt=P[Je];if(!Ae.has(zt.id)){let cn=Sc(zt,Je,Kt,g,De,so,s,r);Ae.set(zt.id,cn),j.appendChild(cn)}}}$.isFollowing()&&(j.scrollTop=j.scrollHeight)}function ue(){if(Date.now()-he>=Yy){de!==null&&(cancelAnimationFrame(de),de=null),O();return}me||(me=!0,de=requestAnimationFrame(()=>{de=null,O()}))}let Oe=(Se,ce)=>{if(!K)return;K.innerHTML="";let et=Me(Se,"12px","currentColor",1.5);et&&K.appendChild(et);let en=b("span","persona-text-xs");en.textContent="Copy All",K.appendChild(en),setTimeout(()=>{K.innerHTML="";let Kt=Me("clipboard-copy","12px","currentColor",1.5);Kt&&K.appendChild(Kt);let Pn=b("span","persona-text-xs");Pn.textContent="Copy All",K.appendChild(Pn),K.disabled=!1},ce)},Ge=async()=>{if(K){K.disabled=!0;try{let Se;Ht()?Se=P: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)),Oe("check",1500)}catch{Oe("x",1500)}}},_e=()=>{be&&(w=be.value,ln(),O())},$e=()=>{!ae||!Pe||(Pe.style.display=ae.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{C=ae.value,ln(),O()},150))},rt=()=>{!ae||!Pe||(ae.value="",C="",Pe.style.display="none",E&&clearTimeout(E),ln(),O())},Rt=()=>{if(Ee)return;let Se=j.scrollTop,{action:ce,nextLastScrollTop:et}=qi({following:$.isFollowing(),currentScrollTop:Se,lastScrollTop:xe,nearBottom:Lo(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});xe=et,ce==="resume"?($.resume(),G=0,ge.style.display="none"):ce==="pause"&&($.pause(),d&&(kt.textContent=u,ge.style.display=""))},jt=Se=>{let ce=ji({following:$.isFollowing(),deltaY:Se.deltaY,nearBottom:Lo(),resumeWhenNearBottom:!0});ce==="pause"?($.pause(),d&&(kt.textContent=u,ge.style.display="")):ce==="resume"&&($.resume(),G=0,ge.style.display="none")},Jt=()=>{d&&(j.scrollTop=j.scrollHeight,$.resume(),G=0,ge.style.display="none")},Y=Se=>{let ce=Se.target;if(!ce||ce.closest("button"))return;let et=ce.closest("[data-event-id]");if(!et)return;let en=et.getAttribute("data-event-id");en&&so(en)},vt=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?(rt(),ae.blur(),D.focus()):o&&o())};K&&K.addEventListener("click",Ge),be&&be.addEventListener("change",_e),ae&&ae.addEventListener("input",$e),Pe&&Pe.addEventListener("click",rt),j.addEventListener("scroll",Rt),j.addEventListener("wheel",jt,{passive:!0}),j.addEventListener("click",Y),ge.addEventListener("click",Jt),D.addEventListener("keydown",vt);function at(){E&&clearTimeout(E),de!==null&&(cancelAnimationFrame(de),de=null),me=!1,Ae.clear(),K&&K.removeEventListener("click",Ge),be&&be.removeEventListener("change",_e),ae&&ae.removeEventListener("input",$e),Pe&&Pe.removeEventListener("click",rt),j.removeEventListener("scroll",Rt),j.removeEventListener("wheel",jt),j.removeEventListener("click",Y),ge.removeEventListener("click",Jt),D.removeEventListener("keydown",vt)}return{element:D,update:ue,destroy:at}}}function zg(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",o=typeof e.artifactId=="string"?e.artifactId:"",r=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),o&&i.setAttribute("data-open-artifact",o);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=n;let g=document.createElement("div");if(g.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",g.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",g.appendChild(f);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,g.appendChild(m)}else g.textContent=a;if(l.append(u,g),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 qg=(e,t)=>{var o,r,s;let n=(s=(r=(o=t==null?void 0:t.config)==null?void 0:o.features)==null?void 0:r.artifacts)==null?void 0:s.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",u=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>zg(e,t)});if(u)return u}return zg(e,t)};var Ac=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)})}},Gr=new Ac;Gr.register("PersonaArtifactCard",qg);function sv(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 jg(e,t){var be,K,ae,Pe;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=(Pe=n==null?void 0:n.panePadding)==null?void 0:Pe.trim(),a=e.markdown?Si(e.markdown):null,i=Ai(e.sanitize),d=oe=>{let ee=a?a(oe):ua(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,u=()=>{l==null||l.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open"),V==null||V.hide()};l&&l.addEventListener("click",()=>{var oe;u(),(oe=t.onDismiss)==null||oe.call(t)});let g=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");g.setAttribute("data-persona-theme-zone","artifact-pane"),r&&g.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 m=b("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let x=b("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");x.type="button",x.textContent="Close",x.setAttribute("aria-label","Close artifacts panel"),x.addEventListener("click",()=>{var oe;u(),(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?Rn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Rn({icon:"eye",label:"Rendered view"}),R=r?Rn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Rn({icon:"code-2",label:"Source"}),B=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),D=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,P=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,w=n==null?void 0:n.documentToolbarCopyMenuItems,C=!!(P&&w&&w.length>0),E=null,A,S=null,V=null;if(r&&(D||P)&&!C){if(A=D?hc({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Rn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P){let oe=Me("chevron-down",14,"currentColor",2);oe&&A.appendChild(oe)}}else r&&C?(E=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),A=D?hc({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Rn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),S=Rn({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(A,S)):r?A=Rn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):A=Rn({icon:"copy",label:"Copy"});let $=r?Rn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Rn({icon:"refresh-cw",label:"Refresh"}),G=r?Rn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Rn({icon:"x",label:"Close"}),he=()=>{var lt,Ie,pe;let oe=(lt=Ae.find(Xe=>Xe.id===le))!=null?lt:Ae[Ae.length-1],ee=(Ie=oe==null?void 0:oe.id)!=null?Ie: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(Ie=>Ie.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(A.addEventListener("click",async()=>{let oe=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(oe&&C){let{markdown:ee,jsonPayload:re,id:it}=he();try{await oe({actionId:"primary",artifactId:it,markdown:ee,jsonPayload:re})}catch{}return}await me()}),S&&(w!=null&&w.length)){let oe=()=>{var re;return(re=g.closest("[data-persona-root]"))!=null?re:document.body},ee=()=>{V=Ss({items:w.map(re=>({id:re.id,label:re.label})),onSelect:async re=>{let{markdown:it,jsonPayload:lt,id:Ie}=he(),pe=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{pe?await pe({actionId:re,artifactId:Ie,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:S,position:"bottom-right",portal:oe()})};g.isConnected?ee():requestAnimationFrame(ee),S.addEventListener("click",re=>{re.stopPropagation(),V==null||V.toggle()})}$.addEventListener("click",async()=>{var oe;try{await((oe=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:oe.call(n))}catch{}se()}),G.addEventListener("click",()=>{var oe;u(),(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?(f.replaceChildren(),M.append(I,R),E?B.append(E,$,G):B.append(A,$,G),f.append(M,Ee,B),de()):(f.appendChild(m),f.appendChild(x)),s&&(f.style.paddingLeft=s,f.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),g.appendChild(f),g.appendChild(xe),g.appendChild(De);let Ae=[],le=null,X=!1,se=()=>{var it,lt,Ie,pe;let oe=r&&Ae.length<=1;xe.classList.toggle("persona-hidden",oe),xe.replaceChildren();for(let Xe 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=Xe.title||Xe.id.slice(0,8),Xe.id===le&&Be.classList.add("persona-bg-persona-container","persona-border-persona-border"),Be.addEventListener("click",()=>t.onSelect(Xe.id)),xe.appendChild(Be)}De.replaceChildren();let ee=le&&Ae.find(Xe=>Xe.id===le)||Ae[Ae.length-1];if(!ee)return;if(r){let Xe=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 ${Xe}`}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 Xe=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Xe.innerHTML=d((Ie=ee.markdown)!=null?Ie:""),De.appendChild(Xe);return}let re=ee.component?Gr.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(sv(ee))},ye=()=>{var ee;let oe=Ae.length>0;if(g.classList.toggle("persona-hidden",!oe),l){let re=typeof g.closest=="function"?g.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&<&&X?(l.classList.remove("persona-hidden"),g.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open"))}};return{element:g,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&&(X=!0),se(),ye()},setMobileOpen(oe){X=oe,!oe&&l?(l.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open")):ye()}}}function ho(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function Kg(e,t){var s,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!ho(t))return;let n=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,o=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),r=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function av(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 cl(e,t){var d,l,u,g,f,m,x,v,M,I;if(!ho(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),av(e),Kg(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(u=n==null?void 0:n.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(g=n==null?void 0:n.paneWidth)!=null?g:"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=(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=(x=n==null?void 0:n.panePadding)==null?void 0:x.trim();r?e.style.setProperty("--persona-artifact-pane-padding",r):e.style.removeProperty("--persona-artifact-pane-padding");let s=(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"),Kg(e,t)}var Gg=["panel","seamless"];function dl(e,t){var i,d,l,u,g,f;for(let m of Gg)e.classList.remove(`persona-artifact-appearance-${m}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!ho(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,o=(l=n==null?void 0:n.paneAppearance)!=null?l:"panel",r=Gg.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${r}`);let s=(u=n==null?void 0:n.paneBorderRadius)==null?void 0:u.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(g=n==null?void 0:n.paneShadow)==null?void 0:g.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=((f=n.unifiedSplitOuterRadius)==null?void 0:f.trim())||s;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Yg(e,t){var n,o,r;return!t||!ho(e)?!1:((r=(o=(n=e.features)==null?void 0:n.artifacts)==null?void 0:o.layout)==null?void 0:r.expandLauncherPanelWhenOpen)!==!1}function iv(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 lv(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 cv(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function dv(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Qg(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 Xg(e,t,n,o,r,s){let a=iv(r,200),i=dv(t,n,o,200);i=Math.max(a,i);let d=lv(s);return d!==null&&(i=Math.min(i,d)),cv(e,a,i)}var Jg={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"}},Tc=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var x,v,M;if(s.dataset.enhanced==="true")return;let a=(x=s.dataset.tvForm)!=null?x:"init";s.dataset.enhanced="true";let i=(v=Jg[a])!=null?v:Jg.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 u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(I=>{var w,C;let R=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");R.htmlFor=`${t.id}-${a}-${I.name}`;let B=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");B.textContent=I.label,R.appendChild(B);let D=(w=I.type)!=null?w:"text",P;D==="textarea"?(P=document.createElement("textarea"),P.rows=3):(P=document.createElement("input"),P.type=D),P.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",P.id=`${t.id}-${a}-${I.name}`,P.name=I.name,P.placeholder=(C=I.placeholder)!=null?C:"",I.required&&(P.required=!0),R.appendChild(P),u.appendChild(R)});let g=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]"),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",g.appendChild(f),g.appendChild(m),u.appendChild(g),s.replaceChildren(d,u),u.addEventListener("submit",async I=>{var P,w;I.preventDefault();let R=(P=n.formEndpoint)!=null?P:"/form",B=new FormData(u),D={};B.forEach((C,E)=>{D[E]=C}),D.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let C=await fetch(R,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D)});if(!C.ok)throw new Error(`Form submission failed (${C.status})`);let E=await C.json();f.textContent=(w=E.message)!=null?w:"Thanks! We'll be in touch soon.",E.success&&E.nextPrompt&&await o.sendMessage(String(E.nextPrompt))}catch(C){f.textContent=C instanceof Error?C.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var kc=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()}},Ec=new kc;var Zg=()=>{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 pv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},uv=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},Lc=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=pv(e),n=uv(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}},Mc=e=>typeof e=="string"?e:e==null?"":String(e),Oa={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Mc(e.payload.text)},messageAndClick:(e,t)=>{var r;if(e.type!=="message_and_click")return;let n=e.payload,o=Mc(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:Mc(n.text)}}},ef=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ic=e=>{let t=new Set(ef(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(ef(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,u)=>l||(u==null?void 0:u({text:a,message:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),o();let d={action:i,message:s.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let u=()=>{e.emit("action:resubmit",d)},g=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!g)continue;if(g.handled){let f=g.persistMessage!==!1;return{text:g.displayText!==void 0?g.displayText:"",persist:f,resubmit:g.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:n}};var mv=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},gv=e=>e.map(t=>({...t,streaming:!1})),fv=e=>e.map(t=>({...t,status:"complete"})),tf=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?mv(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?gv(n.messages):void 0,artifacts:n.artifacts?fv(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 Rc=require("partial-json");function nf(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Gr.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 of(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 rf(e){let t=of(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 sf(e){let t=of(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 hv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function af(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=hv}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let g=null,f=document.createElement("div");f.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=o,m.appendChild(x);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=r,m.appendChild(v),f.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 C=document.createElement("button");C.type="button",C.className="persona-feedback-rating-btn persona-feedback-star-btn",C.setAttribute("role","radio"),C.setAttribute("aria-checked","false"),C.setAttribute("aria-label",`${w} star${w>1?"s":""}: ${l[w-1]}`),C.title=l[w-1],C.dataset.rating=String(w),C.innerHTML=`
|
|
27
|
-
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
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
|
-
</svg>
|
|
30
|
-
`,C.addEventListener("click",()=>{g=w,I.forEach((E,A)=>{let S=A<w;E.classList.toggle("selected",S),E.setAttribute("aria-checked",A===w-1?"true":"false")})}),I.push(C),M.appendChild(C)}f.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),f.appendChild(w)}let B=document.createElement("div");B.className="persona-feedback-actions";let D=document.createElement("button");D.type="button",D.className="persona-feedback-btn persona-feedback-btn-skip",D.textContent=i,D.addEventListener("click",()=>{n==null||n(),u.remove()});let P=document.createElement("button");return P.type="button",P.className="persona-feedback-btn persona-feedback-btn-submit",P.textContent=a,P.addEventListener("click",async()=>{if(g===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}P.disabled=!0,P.textContent="Submitting...";try{let w=(R==null?void 0:R.value.trim())||void 0;await t(g,w),u.remove()}catch(w){P.disabled=!1,P.textContent=a,console.error("[CSAT Feedback] Failed to submit:",w)}}),B.appendChild(D),B.appendChild(P),f.appendChild(B),u.appendChild(f),u}function lf(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:u="Very likely"}=e,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-nps",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Net Promoter Score feedback");let f=null,m=document.createElement("div");m.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=o,x.appendChild(v);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=r,x.appendChild(M),m.appendChild(x);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 B=document.createElement("span");B.className="persona-feedback-label-low",B.textContent=l;let D=document.createElement("span");D.className="persona-feedback-label-high",D.textContent=u,R.appendChild(B),R.appendChild(D);let P=document.createElement("div");P.className="persona-feedback-numbers";let w=[];for(let V=0;V<=10;V++){let $=document.createElement("button");$.type="button",$.className="persona-feedback-rating-btn persona-feedback-number-btn",$.setAttribute("role","radio"),$.setAttribute("aria-checked","false"),$.setAttribute("aria-label",`Rating ${V} out of 10`),$.textContent=String(V),$.dataset.rating=String(V),V<=6?$.classList.add("persona-feedback-detractor"):V<=8?$.classList.add("persona-feedback-passive"):$.classList.add("persona-feedback-promoter"),$.addEventListener("click",()=>{f=V,w.forEach((G,he)=>{G.classList.toggle("selected",he===V),G.setAttribute("aria-checked",he===V?"true":"false")})}),w.push($),P.appendChild($)}I.appendChild(R),I.appendChild(P),m.appendChild(I);let C=null;if(d){let V=document.createElement("div");V.className="persona-feedback-comment-container",C=document.createElement("textarea"),C.className="persona-feedback-comment",C.placeholder=s,C.rows=3,C.setAttribute("aria-label","Additional comments"),V.appendChild(C),m.appendChild(V)}let E=document.createElement("div");E.className="persona-feedback-actions";let A=document.createElement("button");A.type="button",A.className="persona-feedback-btn persona-feedback-btn-skip",A.textContent=i,A.addEventListener("click",()=>{n==null||n(),g.remove()});let S=document.createElement("button");return S.type="button",S.className="persona-feedback-btn persona-feedback-btn-submit",S.textContent=a,S.addEventListener("click",async()=>{if(f===null){P.classList.add("persona-feedback-shake"),setTimeout(()=>P.classList.remove("persona-feedback-shake"),500);return}S.disabled=!0,S.textContent="Submitting...";try{let V=(C==null?void 0:C.value.trim())||void 0;await t(f,V),g.remove()}catch(V){S.disabled=!1,S.textContent=a,console.error("[NPS Feedback] Failed to submit:",V)}}),E.appendChild(A),E.appendChild(S),m.appendChild(E),g.appendChild(m),g}var Es="persona-chat-history",bv=30*1e3,yv={"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 vv(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=yv[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 pl(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 xv(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 wv(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Pc=e=>!e||typeof e!="object"?{}:{...e},cf=e=>e.map(t=>({...t,streaming:!1})),df=(e,t,n)=>{let o=e!=null&&e.markdown?Si(e.markdown):null,r=Ai(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&r&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var l,u,g;let a=(l=s.text)!=null?l:"",i=(u=s.message.rawContent)!=null?u:null;if(t){let f=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});f!==null&&(a=f.text,f.persist||(s.message.__skipPersist=!0),f.resubmit&&!s.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...s,text:a,raw:(g=i!=null?i:s.text)!=null?g:""}):o?d=o(a):d=ua(a),r?r(d):d}};function pf(e){var i,d,l,u;let t=b("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",o=(d=e==null?void 0:e.iconSize)!=null?d:"48px",r=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(u=e==null?void 0:e.iconStrokeWidth)!=null?u:.5,a=Me(n,o,r,s);if(a&&t.appendChild(a),e!=null&&e.label){let g=b("span","persona-drop-overlay-label");g.textContent=e.label,t.appendChild(g)}return t}var uf=(e,t,n)=>{var cd,dd,pd,ud,md,gd,fd,hd,bd,yd,vd,xd,wd,Cd,Sd,Ad,Td,kd,Ed,Md,Ld,Id,Rd,Pd,Wd,Bd,Hd,Dd,Od,Fd,Nd,_d,Vd,$d,Ud,zd,qd,jd,Kd,Gd,Yd,Qd,Xd,Jd,Zd,ep,tp,np,op,rp;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=lm(t),r=Ec.getForInstance(o.plugins);o.components&&Gr.registerAll(o.components);let s=Zg(),i=o.persistState===!1?null:(cd=o.storageAdapter)!=null?cd:tf(),d={},l=null,u=!1,g=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&&(u=!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 g(h)});else{let p=c!=null?c:{messages:[],metadata:{}},h=g(p);h.metadata&&(d=Pc(h.metadata)),(dd=h.messages)!=null&&dd.length&&(o={...o,initialMessages:h.messages}),(pd=h.artifacts)!=null&&pd.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(ud=h.selectedArtifactId)!=null?ud:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(o.onStateLoaded)try{let c=g({messages:[],metadata:{}});(md=c.messages)!=null&&md.length&&(o={...o,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let f=()=>d,m=c=>{var h;d=(h=c({...d}))!=null?h:{},rs()},x=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Lc],v=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Oa.message,Oa.messageAndClick],M=Ic({parsers:x,handlers:v,getSessionMetadata:f,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let I=(fd=(gd=o.launcher)==null?void 0:gd.enabled)!=null?fd:!0,R=(bd=(hd=o.launcher)==null?void 0:hd.autoExpand)!=null?bd:!1,B=(yd=o.autoFocusInput)!=null?yd:!1,D=R,P=I,w=(xd=(vd=o.layout)==null?void 0:vd.header)==null?void 0:xd.layout,C=!1,E=()=>Ia(o),A=()=>I||E(),S=E()?!1:I?R:!0,V=!1,$=null,G=()=>{V=!0,$&&clearTimeout($),$=setTimeout(()=>{V&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),V=!1)},1e4)},he=df(o,M,G),me=(Cd=(wd=o.features)==null?void 0:wd.showReasoning)!=null?Cd:!0,de=(Ad=(Sd=o.features)==null?void 0:Sd.showToolCalls)!=null?Ad:!0,Ee=(kd=(Td=o.features)==null?void 0:Td.showEventStreamToggle)!=null?kd:!1,xe=(Md=(Ed=o.features)==null?void 0:Ed.scrollToBottom)!=null?Md:{},De=(Id=(Ld=o.features)==null?void 0:Ld.scrollBehavior)!=null?Id:{},le=`${(Pd=typeof o.persistState=="object"?(Rd=o.persistState)==null?void 0:Rd.keyPrefix:void 0)!=null?Pd:"persona-"}event-stream`,X=Ee?new Ha(le):null,se=(Hd=(Bd=(Wd=o.features)==null?void 0:Wd.eventStream)==null?void 0:Bd.maxEvents)!=null?Hd:2e3,ye=Ee?new Ba(se,X):null,be=Ee?new Da:null,K=null,ae=!1,Pe=null,oe=0;X==null||X.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),U!=null&&U.isClientTokenMode()&&U.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),U!=null&&U.isClientTokenMode()&&U.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=(Dd=o.statusIndicator)!=null?Dd:{},it=c=>{var p,h,y,L;return c==="idle"?(p=re.idleText)!=null?p:Ln.idle:c==="connecting"?(h=re.connectingText)!=null?h:Ln.connecting:c==="connected"?(y=re.connectedText)!=null?y:Ln.connected:c==="error"?(L=re.errorText)!=null?L:Ln.error:Ln[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:Ie,panel:pe,pillRoot:Xe}=Lg(o),Be=Ig(o,A()),{container:j,body:ge,messagesWrapper:nt,suggestions:kt,textarea:ne,sendButton:qe,sendButtonWrapper:_n,composerForm:Ht,statusText:ln,introTitle:so,introSubtitle:Lo,closeButton:O,iconHolder:ue,headerTitle:Oe,headerSubtitle:Ge,header:_e,footer:$e,actionsRow:rt,leftActions:Rt,rightActions:jt}=Be,Jt=Be.setSendButtonMode,Y=Be.micButton,vt=Be.micButtonWrapper,at=Be.attachmentButton,Se=Be.attachmentButtonWrapper,ce=Be.attachmentInput,et=Be.attachmentPreviewsContainer;j.classList.add("persona-relative"),ge.classList.add("persona-relative");let en=12,Kt=()=>{var c;return(c=xe.label)!=null?c:""},Pn=()=>{var c;return(c=xe.iconName)!=null?c:"arrow-down"},wn=()=>xe.enabled!==!1,mt=()=>{var c;return(c=De.mode)!=null?c:"follow"},Et=()=>{var c;return(c=De.anchorTopOffset)!=null?c:16},Je=b("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Je.type="button",Je.style.display="none",Je.setAttribute("data-persona-scroll-to-bottom","true");let zt=b("span","persona-flex persona-items-center"),cn=b("span",""),An=b("span","");An.setAttribute("data-persona-scroll-to-bottom-count",""),An.style.display="none",Je.append(zt,cn,An),j.appendChild(Je);let Tn=b("div","persona-stream-anchor-spacer");Tn.setAttribute("aria-hidden","true"),Tn.setAttribute("data-persona-anchor-spacer",""),Tn.style.flexShrink="0",Tn.style.pointerEvents="none",Tn.style.height="0px",ge.appendChild(Tn);let yn=()=>{let p=$e.style.display==="none"?0:$e.offsetHeight;Je.style.bottom=`${p+en}px`};yn();let Io=()=>{let c=!!Kt();Je.setAttribute("aria-label",Kt()||"Jump to latest"),Je.title=Kt(),Je.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),zt.innerHTML="";let p=Me(Pn(),"14px","currentColor",2);p?(zt.appendChild(p),zt.style.display=""):zt.style.display="none",cn.textContent=Kt(),cn.style.display=c?"":"none"};Io();let St=null,qn=null,jn=r.find(c=>c.renderHeader);if(jn!=null&&jn.renderHeader){let c=jn.renderHeader({config:o,defaultRenderer:()=>{let p=jr({config:o,showClose:A()});return Pa(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=Ug({buffer:ye,getFullHistory:()=>ye.getAllFromStore(),onClose:()=>bo(),config:o,plugins:r,getThroughput:()=>{var N;return(N=be==null?void 0:be.getMetric())!=null?N:{status:"idle"}}})),K&&(ge.style.display="none",(p=$e.parentNode)==null||p.insertBefore(K.element,$e),K.update()),xt){xt.style.boxShadow=`inset 0 0 0 1.5px ${Nn.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(_=>_&&xt.classList.add(_))}let c=()=>{if(!ae)return;let N=Date.now();N-oe>=200&&(K==null||K.update(),oe=N),Pe=requestAnimationFrame(c)};oe=0,Pe=requestAnimationFrame(c),Un(),s.emit("eventStream:opened",{timestamp:Date.now()})},bo=()=>{var c,p,h;if(ae){if(ae=!1,K&&K.element.remove(),ge.style.display="",xt){xt.style.boxShadow="";let y=(h=(p=(c=o.features)==null?void 0:c.eventStream)==null?void 0:p.classNames)==null?void 0:h.toggleButtonActive;y&&y.split(/\s+/).forEach(L=>L&&xt.classList.remove(L))}Pe!==null&&(cancelAnimationFrame(Pe),Pe=null),Un(),s.emit("eventStream:closed",{timestamp:Date.now()})}},xt=null;if(Ee){let c=(Fd=(Od=o.features)==null?void 0:Od.eventStream)==null?void 0:Fd.classNames,p="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");xt=b("button",p),xt.style.width="28px",xt.style.height="28px",xt.style.color=Nn.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let h=Me("activity","18px","currentColor",1.5);h&&xt.appendChild(h);let y=Be.clearChatButtonWrapper,L=Be.closeButtonWrapper,N=y||L;N&&N.parentNode===_e?_e.insertBefore(xt,N):_e.appendChild(xt),xt.addEventListener("click",()=>{ae?bo():Vo()})}let Sr=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(_)}},Ro=r.find(c=>c.renderComposer);if(Ro!=null&&Ro.renderComposer){let c=o.composer,p=Ro.renderComposer({config:o,defaultRenderer:()=>sl({config:o}).footer,onSubmit:h=>{var _;if(!U||U.isStreaming())return;let y=h.trim(),L=(_=St==null?void 0:St.hasAttachments())!=null?_:!1;if(!y&&!L)return;z();let N;L&&(N=[],N.push(...St.getContentParts()),y&&N.push(cc(y))),U.sendMessage(y,{contentParts:N}),L&&St.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:((Nd=o.voiceRecognition)==null?void 0:Nd.enabled)===!0?()=>{qn==null||qn()}:void 0});p&&($e.replaceWith(p),$e=p)}let Ar=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&&(Ht=p),h&&(ne=h),y&&(qe=y),L&&(Y=L,vt=L.parentElement),N&&(ln=N);let _=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");_&&(kt=_);let q=c.querySelector(".persona-attachment-button");q&&(at=q,Se=q.parentElement),ce=c.querySelector('input[type="file"]'),et=c.querySelector(".persona-attachment-previews");let F=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");F&&(rt=F)};Sr($e),Ar($e);let Vn=(zd=(_d=o.layout)==null?void 0:_d.contentMaxWidth)!=null?zd:E()?(Ud=($d=(Vd=o.launcher)==null?void 0:Vd.composerBar)==null?void 0:$d.contentMaxWidth)!=null?Ud:"720px":void 0;if(Vn&&(nt.style.maxWidth=Vn,nt.style.marginLeft="auto",nt.style.marginRight="auto",nt.style.width="100%"),Vn&&Ht&&!E()&&(Ht.style.maxWidth=Vn,Ht.style.marginLeft="auto",Ht.style.marginRight="auto"),Vn&&kt&&!E()&&(kt.style.maxWidth=Vn,kt.style.marginLeft="auto",kt.style.marginRight="auto"),Vn&&et&&!E()&&(et.style.maxWidth=Vn,et.style.marginLeft="auto",et.style.marginRight="auto"),(qd=o.attachments)!=null&&qd.enabled&&ce&&et){St=Sa.fromConfig(o.attachments),St.setPreviewsContainer(et),ce.addEventListener("change",h=>{let y=h.target;St==null||St.handleFileSelect(y.files),y.value=""});let c=o.attachments.dropOverlay,p=pf(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 nt;case"footer-top":return kt;case"composer":return Ht;case"footer-bottom":return ln;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 F=_e.querySelector(".persona-flex-col");F?(q=F.parentNode)==null||q.insertBefore(_,F.nextSibling):_e.appendChild(_)}break;case"body-top":{let F=ge.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");F?F.replaceWith(_):ge.insertBefore(_,ge.firstChild);break}case"body-bottom":ge.appendChild(_);break;case"footer-top":kt.replaceWith(_);break;case"footer-bottom":ln.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 er=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")As.has(L)?As.delete(L):As.add(L),Wg(L,y);else if(N==="tool")Ts.has(L)?Ts.delete(L):Ts.add(L),Bg(L,y,o);else if(N==="approval"){let F=o.approval!==!1?o.approval:void 0,Ce=((_=F==null?void 0:F.detailsDisplay)!=null?_:"collapsed")==="expanded",fe=(q=al.get(L))!=null?q:Ce;al.set(L,!fe),Fg(L,y,o)}qo.delete(L)};nt.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),er(c))}),nt.addEventListener("keydown",c=>{let p=c.target;(c.key==="Enter"||c.key===" ")&&p.closest('button[data-expand-header="true"]')&&(c.preventDefault(),er(c))});let $o=new Map;nt.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 F=U.getMessages().find(Ce=>Ce.id===L);if(F&&ee.onCopy){let Ce=F.content||"";navigator.clipboard.writeText(Ce).then(()=>{h.classList.add("persona-message-action-success");let fe=Me("check",14,"currentColor",2);fe&&(h.innerHTML="",h.appendChild(fe)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let te=Me("copy",14,"currentColor",2);te&&(h.innerHTML="",h.appendChild(te))},2e3)}).catch(fe=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",fe)}),ee.onCopy(F)}}else if(N==="upvote"||N==="downvote"){let F=((_=$o.get(L))!=null?_:null)===N,Ce=N==="upvote"?"thumbs-up":"thumbs-down";if(F){$o.delete(L),h.classList.remove("persona-message-action-active");let fe=Me(Ce,14,"currentColor",2);fe&&(h.innerHTML="",h.appendChild(fe))}else{let fe=N==="upvote"?"downvote":"upvote",te=y.querySelector(`[data-action="${fe}"]`);if(te){te.classList.remove("persona-message-action-active");let je=Me(fe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);je&&(te.innerHTML="",te.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=U.getMessages().find(ot=>ot.id===L);Te&&ee.onFeedback&&ee.onFeedback({type:N,messageId:Te.id,message:Te})}}}),nt.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",F=U.getMessages().find(fe=>fe.id===L);if(!(F!=null&&F.approval))return;let Ce=y.querySelector("[data-approval-buttons]");Ce&&Ce.querySelectorAll("button").forEach(te=>{te.disabled=!0,te.style.opacity="0.5",te.style.cursor="not-allowed"}),F.approval.toolType==="webmcp"?U.resolveWebMcpApproval(L,_):U.resolveApproval(F.approval,_)});let At=null,Kn=null,Gn={artifacts:[],selectedId:null},Wn=!1,It={current:null};nt.addEventListener("click",c=>{var te,ke,Ve,Te,ot;let h=c.target.closest("[data-download-artifact]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||((Ve=(ke=(te=o.features)==null?void 0:te.artifacts)==null?void 0:ke.onArtifactAction)==null?void 0:Ve.call(ke,{type:"download",artifactId:y}))===!0)return;let N=U.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 Re=U.getMessages().find(ze=>ze.id===pt);if(Re!=null&&Re.rawContent)try{let ze=JSON.parse(Re.rawContent);_=(Te=ze==null?void 0:ze.props)==null?void 0:Te.markdown,q=((ot=ze==null?void 0:ze.props)==null?void 0:ot.title)||q}catch{}}}if(!_)return;let F=new Blob([_],{type:"text/markdown"}),Ce=URL.createObjectURL(F),fe=document.createElement("a");fe.href=Ce,fe.download=`${q}.md`,fe.click(),URL.revokeObjectURL(Ce)}),nt.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(),Wn=!1,U.selectArtifact(y),Xn())}),nt.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let p=c.target;p.hasAttribute("data-open-artifact")&&(c.preventDefault(),p.click())});let ao=Be.composerOverlay,io=(c,p,h)=>{var q,F,Ce,fe;let y=p.trim();if(!y||!It.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:(F=h.values)!=null?F:h.source==="multi"?y.split(", "):[y],isFreeText:N,source:h.source},bubbles:!0,composed:!0})),xs(ao,L);let _=It.current.getMessages().find(te=>{var ke;return((ke=te.toolCall)==null?void 0:ke.id)===L});(Ce=_==null?void 0:_.agentMetadata)!=null&&Ce.awaitingLocalTool?It.current.resolveAskUserQuestion(_,(fe=h.structured)!=null?fe:y):It.current.sendMessage(y)},Yn=c=>{var L;let p=It.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:Ei(c,y),currentIndex:fo(c)})},tr=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=fo(c),h=vs(c);if(p>=h-1)return;let y=(_=It.current)==null?void 0:_.getMessages().find(q=>{var F;return((F=q.toolCall)==null?void 0:F.id)===c.getAttribute("data-tool-call-id")});y&&(Li(c,y,o,p+1),Yn(c))};ao.addEventListener("click",c=>{var N,_,q,F,Ce,fe,te,ke,Ve,Te,ot,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})),xs(ao,We);let Re=(_=It.current)==null?void 0:_.getMessages().find(ze=>{var Ye;return((Ye=ze.toolCall)==null?void 0:Ye.id)===We});(q=Re==null?void 0:Re.agentMetadata)!=null&&q.awaitingLocalTool&&((F=It.current)==null||F.markAskUserQuestionResolved(Re),(Ce=It.current)==null||Ce.resolveAskUserQuestion(Re,"(dismissed)"));return}if(L==="pick"){let We=h.getAttribute("data-option-label");if(!We)return;let Re=y.getAttribute("data-multi-select")==="true",ze=br(y);if(ze&&Re){let Ye=$r(y)[fo(y)],wt=new Set(Array.isArray(Ye)?Ye:[]);wt.has(We)?wt.delete(We):wt.add(We),yr(y,Array.from(wt)),Yn(y);return}if(ze){yr(y,We),Yn(y),Uo(y);return}if(Re){let Ye=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Ye?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Ye);let wt=y.querySelector('[data-ask-user-action="submit-multi"]');wt&&(wt.disabled=oc(y).length===0);return}io(y,We,{source:"pick",values:[We]});return}if(L==="submit-multi"){let We=oc(y);if(We.length===0)return;io(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 Re=We.querySelector('[data-ask-free-text-input="true"]');Re==null||Re.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"]'),Re=(fe=We==null?void 0:We.value)!=null?fe:"";if(!Re.trim())return;if(br(y)){yr(y,Re.trim()),Yn(y),Uo(y);return}io(y,Re,{source:"free-text"});return}if(L==="next"||L==="back"){if(!It.current)return;let We=(te=y.getAttribute("data-tool-call-id"))!=null?te:"",Re=It.current.getMessages().find(He=>{var Fe;return((Fe=He.toolCall)==null?void 0:Fe.id)===We});if(!Re)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=$r(y)[fo(y)];(typeof He!="string"||He!==Ye)&&yr(y,Ye)}let wt=L==="next"?1:-1,H=fo(y)+wt;Li(y,Re,o,H),Yn(y);return}if(L==="submit-all"){if(!It.current)return;let We=(Te=y.getAttribute("data-tool-call-id"))!=null?Te:"",Re=It.current.getMessages().find(He=>{var Fe;return((Fe=He.toolCall)==null?void 0:Fe.id)===We});if(!Re)return;let ze=y.querySelector('[data-ask-free-text-input="true"]'),Ye=(je=(ot=ze==null?void 0:ze.value)==null?void 0:ot.trim())!=null?je:"";Ye&&yr(y,Ye);let wt=Ei(y,Re);It.current.persistAskUserQuestionProgress(Re,{answers:wt,currentIndex:fo(y)});let H=tr(wt);io(y,H||"(submitted)",{source:"submit-all",structured:wt});return}if(L==="skip"){if(!It.current)return;let We=(dt=y.getAttribute("data-tool-call-id"))!=null?dt:"",Re=It.current.getMessages().find(Fe=>{var ve;return((ve=Fe.toolCall)==null?void 0:ve.id)===We});if(!Re)return;let ze=br(y),Ye=fo(y),wt=vs(y),H=Ye>=wt-1;if(!ze){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:We},bubbles:!0,composed:!0})),xs(ao,We),(pt=Re.agentMetadata)!=null&&pt.awaitingLocalTool&&(It.current.markAskUserQuestionResolved(Re),It.current.resolveAskUserQuestion(Re,"(dismissed)"));return}yr(y,"");let He=y.querySelector('[data-ask-free-text-input="true"]');if(He&&(He.value=""),H){let Fe=Ei(y,Re),ve=tr(Fe);io(y,ve||"(skipped)",{source:"submit-all",structured:Fe});return}Li(y,Re,o,Ye+1),Yn(y);return}}),ao.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(br(y)){yr(y,L.trim()),Yn(y),Uo(y);return}io(y,L,{source:"free-text"})}});let nr=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=ao.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",nr);let Qn=null,Dt=null,Bn=null,lo=null,or=()=>{};function zo(){lo==null||lo(),lo=null}let rr=()=>{var _;if(!Qn||!Dt)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){Dt.style.removeProperty("position"),Dt.style.removeProperty("left"),Dt.style.removeProperty("top"),Dt.style.removeProperty("bottom"),Dt.style.removeProperty("width"),Dt.style.removeProperty("z-index");return}let y=Qn.firstElementChild;if(!y||y===Dt)return;let L=10;Dt.style.position="absolute",Dt.style.top="0",Dt.style.bottom="0",Dt.style.width=`${L}px`,Dt.style.zIndex="5";let N=y.offsetWidth-L/2;Dt.style.left=`${Math.max(0,N)}px`},Po=()=>{},Xn=()=>{var h,y,L,N,_;if(!At||!ho(o))return;cl(e,o),dl(e,o),Po();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),At.update(Gn),Wn?(At.setMobileOpen(!1),At.element.classList.add("persona-hidden"),(_=At.backdrop)==null||_.classList.add("persona-hidden")):Gn.artifacts.length>0&&(At.element.classList.remove("persona-hidden"),At.setMobileOpen(!0)),or()};if(ho(o)){pe.style.position="relative";let c=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),p=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(j),At=jg(o,{onSelect:h=>{var y;return(y=It.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{Wn=!0,Xn()}}),At.element.classList.add("persona-hidden"),Qn=p,p.appendChild(c),p.appendChild(At.element),At.backdrop&&pe.appendChild(At.backdrop),pe.appendChild(p),or=()=>{var y,L,N,_;if(!Qn||!At)return;if(!(((N=(L=(y=o.features)==null?void 0:y.artifacts)==null?void 0:L.layout)==null?void 0:N.resizable)===!0)){Bn==null||Bn(),Bn=null,zo(),Dt&&(Dt.remove(),Dt=null),At.element.style.removeProperty("width"),At.element.style.removeProperty("maxWidth");return}if(!Dt){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,Ce=(_=F.defaultView)!=null?_:window,fe=te=>{var dt,pt;if(!At||te.button!==0||e.classList.contains("persona-artifact-narrow-host")||Ce.innerWidth<=640)return;te.preventDefault(),zo();let ke=te.clientX,Ve=At.element.getBoundingClientRect().width,Te=(pt=(dt=o.features)==null?void 0:dt.artifacts)==null?void 0:pt.layout,ot=We=>{let Re=Qn.getBoundingClientRect().width,ze=e.classList.contains("persona-artifact-appearance-seamless"),Ye=ze?0:Qg(Qn,Ce),wt=ze?0:q.getBoundingClientRect().width||6,H=Ve-(We.clientX-ke),He=Xg(H,Re,Ye,wt,Te==null?void 0:Te.resizableMinWidth,Te==null?void 0:Te.resizableMaxWidth);At.element.style.width=`${He}px`,At.element.style.maxWidth="none",rr()},je=()=>{F.removeEventListener("pointermove",ot),F.removeEventListener("pointerup",je),F.removeEventListener("pointercancel",je),lo=null;try{q.releasePointerCapture(te.pointerId)}catch{}};lo=je,F.addEventListener("pointermove",ot),F.addEventListener("pointerup",je),F.addEventListener("pointercancel",je);try{q.setPointerCapture(te.pointerId)}catch{}};q.addEventListener("pointerdown",fe),Dt=q,Qn.insertBefore(q,At.element),Bn=()=>{q.removeEventListener("pointerdown",fe)}}if(Dt){let q=Gn.artifacts.length>0&&!Wn;Dt.classList.toggle("persona-hidden",!q),rr()}},Po=()=>{var Ce,fe,te,ke,Ve,Te,ot,je,dt,pt,We,Re,ze,Ye;if(!I||!At||((fe=(Ce=o.launcher)==null?void 0:Ce.sidebarMode)!=null?fe:!1)||Sn(o)&&Eo(o).reveal==="emerge")return;let y=(te=e.ownerDocument.defaultView)!=null?te:window,L=(Ve=(ke=o.launcher)==null?void 0:ke.mobileFullscreen)!=null?Ve:!0,N=(ot=(Te=o.launcher)==null?void 0:Te.mobileBreakpoint)!=null?ot:640;if(L&&y.innerWidth<=N||!Yg(o,I))return;let _=(pt=(dt=(je=o.launcher)==null?void 0:je.width)!=null?dt:o.launcherWidth)!=null?pt:go,q=(Ye=(ze=(Re=(We=o.features)==null?void 0:We.artifacts)==null?void 0:Re.layout)==null?void 0:ze.expandedPanelWidth)!=null?Ye:"min(720px, calc(100vw - 24px))";Gn.artifacts.length>0&&!Wn?(pe.style.width=q,pe.style.maxWidth=q):(pe.style.width=_,pe.style.maxWidth=_)},typeof ResizeObserver!="undefined"&&(Kn=new ResizeObserver(()=>{Xn()}),Kn.observe(pe))}else pe.appendChild(j),E()&&Xe&&(Be.peekBanner&&Xe.appendChild(Be.peekBanner),Xe.appendChild($e));e.appendChild(Ie),Xe&&e.appendChild(Xe);let yo=()=>{var He,Fe,ve,Nt,Ft,Gt,Ct,qt,to,an,Qe,Pt,pn,mo,no,Ir,Rr,ds,ps,Qt,Pr,mr,gr,Qo,Wr,So,tt,gn;if(E()){pe.style.width="100%",pe.style.maxWidth="100%";let $t=(Fe=(He=o.launcher)==null?void 0:He.composerBar)!=null?Fe:{},_t=Ie.dataset.state==="expanded",bt=(ve=$t.expandedSize)!=null?ve:"anchored";if(!(_t&&bt!=="fullscreen")){j.style.background="",j.style.border="",j.style.borderRadius="",j.style.overflow="",j.style.boxShadow="";return}let Mt=(Ft=(Nt=o.theme)==null?void 0:Nt.components)==null?void 0:Ft.panel,En=ui(o),Hn=(On,Br)=>{var Gs;return On==null||On===""?Br:(Gs=us(En,On))!=null?Gs:On},Fo="1px solid var(--persona-border)",xn="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Dn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";j.style.background="var(--persona-surface, #ffffff)",j.style.border=Hn(Mt==null?void 0:Mt.border,Fo),j.style.borderRadius=Hn(Mt==null?void 0:Mt.borderRadius,Dn),j.style.boxShadow=Hn(Mt==null?void 0:Mt.shadow,xn),j.style.overflow="hidden";return}let c=Sn(o),p=(Ct=(Gt=o.launcher)==null?void 0:Gt.sidebarMode)!=null?Ct:!1,h=c||p||((to=(qt=o.launcher)==null?void 0:qt.fullHeight)!=null?to:!1),y=((an=o.launcher)==null?void 0:an.enabled)===!1,L=(Pt=(Qe=o.theme)==null?void 0:Qe.components)==null?void 0:Pt.panel,N=ui(o),_=($t,_t)=>{var bt;return $t==null||$t===""?_t:(bt=us(N,$t))!=null?bt:$t},q=(pn=e.ownerDocument.defaultView)!=null?pn:window,F=(no=(mo=o.launcher)==null?void 0:mo.mobileFullscreen)!=null?no:!0,Ce=(Rr=(Ir=o.launcher)==null?void 0:Ir.mobileBreakpoint)!=null?Rr:640,fe=q.innerWidth<=Ce,te=F&&fe&&I,ke=(ps=(ds=o.launcher)==null?void 0:ds.position)!=null?ps:"bottom-left",Ve=ke==="bottom-left"||ke==="top-left",Te=(Pr=(Qt=o.launcher)==null?void 0:Qt.zIndex)!=null?Pr:In,ot=p||te?"none":"1px solid var(--persona-border)",je=te?"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&&!te&&(je="none",ot="none");let dt=p||te?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",pt=_(L==null?void 0:L.border,ot),We=_(L==null?void 0:L.shadow,je),Re=_(L==null?void 0:L.borderRadius,dt),ze=ge.scrollTop;e.style.cssText="",Ie.style.cssText="",pe.style.cssText="",j.style.cssText="",ge.style.cssText="",$e.style.cssText="";let Ye=()=>{var _t;if(ze<=0)return;((_t=ge.ownerDocument.defaultView)!=null?_t:window).requestAnimationFrame(()=>{if(ge.scrollTop===ze)return;let bt=ge.scrollHeight-ge.clientHeight;bt<=0||(ge.scrollTop=Math.min(ze,bt))})};if(te){Ie.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"),Ie.style.cssText=`
|
|
31
|
-
position: fixed !important;
|
|
32
|
-
inset: 0 !important;
|
|
33
|
-
width: 100% !important;
|
|
34
|
-
height: 100% !important;
|
|
35
|
-
max-height: 100% !important;
|
|
36
|
-
margin: 0 !important;
|
|
37
|
-
padding: 0 !important;
|
|
38
|
-
display: flex !important;
|
|
39
|
-
flex-direction: column !important;
|
|
40
|
-
z-index: ${Te} !important;
|
|
41
|
-
background-color: var(--persona-surface, #ffffff) !important;
|
|
42
|
-
`,pe.style.cssText=`
|
|
43
|
-
position: relative !important;
|
|
44
|
-
display: flex !important;
|
|
45
|
-
flex-direction: column !important;
|
|
46
|
-
flex: 1 1 0% !important;
|
|
47
|
-
width: 100% !important;
|
|
48
|
-
max-width: 100% !important;
|
|
49
|
-
height: 100% !important;
|
|
50
|
-
min-height: 0 !important;
|
|
51
|
-
margin: 0 !important;
|
|
52
|
-
padding: 0 !important;
|
|
53
|
-
box-shadow: none !important;
|
|
54
|
-
border-radius: 0 !important;
|
|
55
|
-
`,j.style.cssText=`
|
|
56
|
-
display: flex !important;
|
|
57
|
-
flex-direction: column !important;
|
|
58
|
-
flex: 1 1 0% !important;
|
|
59
|
-
width: 100% !important;
|
|
60
|
-
height: 100% !important;
|
|
61
|
-
min-height: 0 !important;
|
|
62
|
-
max-height: 100% !important;
|
|
63
|
-
overflow: hidden !important;
|
|
64
|
-
border-radius: 0 !important;
|
|
65
|
-
border: none !important;
|
|
66
|
-
`,ge.style.flex="1 1 0%",ge.style.minHeight="0",ge.style.overflowY="auto",$e.style.flexShrink="0",C=!0,Ye();return}let wt=(gr=(mr=o==null?void 0:o.launcher)==null?void 0:mr.width)!=null?gr:o==null?void 0:o.launcherWidth,H=wt!=null?wt: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(Eo(o).reveal==="emerge"){let _t=Eo(o).width;pe.style.width=_t,pe.style.maxWidth=_t}else pe.style.width="100%",pe.style.maxWidth="100%";if(Po(),pe.style.boxShadow=We,pe.style.borderRadius=Re,j.style.border=pt,j.style.borderRadius=Re,c&&!te&&(L==null?void 0:L.border)===void 0&&(j.style.border="none",Eo(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%"),Ie.style.display="flex",Ie.style.flexDirection="column",Ie.style.flex="1 1 0%",Ie.style.minHeight="0",Ie.style.maxHeight="100%",Ie.style.height="100%",y&&(Ie.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",ge.style.flex="1 1 0%",ge.style.minHeight="0",ge.style.overflowY="auto",$e.style.flexShrink="0"),Ie.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&&((Qo=Mo[ke])!=null?Qo:Mo["bottom-right"]).split(" ").forEach(_t=>Ie.classList.add(_t)),p){let $t=(So=(Wr=o.launcher)==null?void 0:Wr.sidebarWidth)!=null?So:"420px";Ie.style.cssText=`
|
|
67
|
-
position: fixed !important;
|
|
68
|
-
top: 0 !important;
|
|
69
|
-
bottom: 0 !important;
|
|
70
|
-
width: ${$t} !important;
|
|
71
|
-
height: 100vh !important;
|
|
72
|
-
max-height: 100vh !important;
|
|
73
|
-
margin: 0 !important;
|
|
74
|
-
padding: 0 !important;
|
|
75
|
-
display: flex !important;
|
|
76
|
-
flex-direction: column !important;
|
|
77
|
-
z-index: ${Te} !important;
|
|
78
|
-
${Ve?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
79
|
-
`,pe.style.cssText=`
|
|
80
|
-
position: relative !important;
|
|
81
|
-
display: flex !important;
|
|
82
|
-
flex-direction: column !important;
|
|
83
|
-
flex: 1 1 0% !important;
|
|
84
|
-
width: 100% !important;
|
|
85
|
-
max-width: 100% !important;
|
|
86
|
-
height: 100% !important;
|
|
87
|
-
min-height: 0 !important;
|
|
88
|
-
margin: 0 !important;
|
|
89
|
-
padding: 0 !important;
|
|
90
|
-
box-shadow: ${We} !important;
|
|
91
|
-
border-radius: ${Re} !important;
|
|
92
|
-
`,pe.style.setProperty("width","100%","important"),pe.style.setProperty("max-width","100%","important"),j.style.cssText=`
|
|
93
|
-
display: flex !important;
|
|
94
|
-
flex-direction: column !important;
|
|
95
|
-
flex: 1 1 0% !important;
|
|
96
|
-
width: 100% !important;
|
|
97
|
-
height: 100% !important;
|
|
98
|
-
min-height: 0 !important;
|
|
99
|
-
max-height: 100% !important;
|
|
100
|
-
overflow: hidden !important;
|
|
101
|
-
border-radius: ${Re} !important;
|
|
102
|
-
border: ${pt} !important;
|
|
103
|
-
`,$e.style.cssText=`
|
|
104
|
-
flex-shrink: 0 !important;
|
|
105
|
-
border-top: none !important;
|
|
106
|
-
padding: 8px 16px 12px 16px !important;
|
|
107
|
-
`}if(!y&&!c){let $t="max-height: -moz-available !important; max-height: stretch !important;",_t=p?"":"padding-top: 1.25em !important;",bt=p?"":`z-index: ${(gn=(tt=o.launcher)==null?void 0:tt.zIndex)!=null?gn:In} !important;`;Ie.style.cssText+=$t+_t+bt}Ye()};yo(),ms(e,o),cl(e,o),dl(e,o);let ft=[];ft.push(()=>{document.removeEventListener("keydown",nr)});let tn=null,nn=null;ft.push(()=>{tn==null||tn(),tn=null,nn==null||nn(),nn=null}),Kn&&ft.push(()=>{Kn==null||Kn.disconnect(),Kn=null}),ft.push(()=>{Bn==null||Bn(),Bn=null,zo(),Dt&&(Dt.remove(),Dt=null),At==null||At.element.style.removeProperty("width"),At==null||At.element.style.removeProperty("maxWidth")}),Ee&&ft.push(()=>{Pe!==null&&(cancelAnimationFrame(Pe),Pe=null),K==null||K.destroy(),K=null,ye==null||ye.destroy(),ye=null,X=null});let Jn=null,sr=()=>{Jn&&(Jn(),Jn=null),o.colorScheme==="auto"&&(Jn=mm(()=>{ms(e,o)}))};sr(),ft.push(()=>{Jn&&(Jn(),Jn=null)});let we=(jd=o.features)==null?void 0:jd.streamAnimation;if(we!=null&&we.type&&we.type!=="none"){let c=Ta(we.type,we.plugins);c&&(mc(c,e),ft.push(()=>Ag(e)))}let vo=Ng(kt),co=null,U,Zr=c=>{var y,L;if(!U)return;let p=c!=null?c:U.getMessages(),h=((L=(y=o.features)==null?void 0:y.suggestReplies)==null?void 0:L.enabled)!==!1?Gm(p):null;h?vo.render(h,U,ne,p,o.suggestionChipsConfig,{agentPushed:!0}):p.some(N=>N.role==="user")?vo.render([],U,ne,p):vo.render(o.suggestionChips,U,ne,p,o.suggestionChipsConfig)},Wo=!1,qo=fg(),jo=new Map,Bo=new Map,xo=new Map,Ps=0,Zn=zi(),eo=0,wo=null,Co=!1,Tr=!1,Ko=0,kn=null,Ho=null,es=!1,kr=!1,ts=null,Ga=4,ns=24,Ya=80,os=new Map,yt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ws=(Gd=(Kd=o.voiceRecognition)==null?void 0:Kd.autoResume)!=null?Gd:!1,po=c=>{s.emit("voice:state",{active:yt.active,source:c,timestamp:Date.now()})},$n=()=>{m(c=>({...c,voiceState:{active:yt.active,timestamp:Date.now(),manuallyDeactivated:yt.manuallyDeactivated}}))},Qa=()=>{var y,L;if(((y=o.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=Pc(d.voiceState),p=!!c.active,h=Number((L=c.timestamp)!=null?L:0);yt.manuallyDeactivated=!!c.manuallyDeactivated,p&&Date.now()-h<bv&&setTimeout(()=>{var N,_;yt.active||(yt.manuallyDeactivated=!1,((_=(N=o.voiceRecognition)==null?void 0:N.provider)==null?void 0:_.type)==="runtype"?U.toggleVoice().then(()=>{yt.active=U.isVoiceActive(),po("restore"),U.isVoiceActive()&&qs()}):Yt("restore"))},1e3)},Xa=()=>U?cf(U.getMessages()).filter(c=>!c.__skipPersist):[];function rs(c){if(!(i!=null&&i.save))return;let h={messages:c?cf(c):U?Xa():[],metadata:d,artifacts:Gn.artifacts,selectedArtifactId:Gn.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,Bs=()=>Ie.querySelector("#persona-scroll-container")||ge,ar=()=>{Go!==null&&(cancelAnimationFrame(Go),Go=null),Co=!1},Hs=()=>{wo!==null&&(cancelAnimationFrame(wo),wo=null),Tr=!1,ar()},Ds=()=>{Ko>0?(An.textContent=String(Ko),An.style.display="",Je.setAttribute("aria-label",`${Kt()||"Jump to latest"} (${Ko} new)`)):(An.textContent="",An.style.display="none",Je.setAttribute("aria-label",Kt()||"Jump to latest"))},Os=()=>{Ko!==0&&(Ko=0,Ds())},Fs=()=>mt()==="follow"?!Zn.isFollowing():!qr(ge,ns),Un=()=>{if(!wn()||ae){Je.parentNode&&Je.remove(),Je.style.display="none";return}Je.parentNode!==j&&j.appendChild(Je),yn();let p=Zo(ge)>0&&Fs();p||Os(),Je.style.display=p?"":"none"},ss=()=>{Zn.pause()&&(Hs(),Un())},Do=()=>{Zn.resume(),Os(),Un()},Oo=(c=!1)=>{mt()==="follow"&&Zn.isFollowing()&&(!c&&!Wo||(wo!==null&&(cancelAnimationFrame(wo),wo=null),Tr=!0,wo=requestAnimationFrame(()=>{wo=null,Tr=!1,Zn.isFollowing()&&Ja(Bs(),c?220:140)})))},Ns=(c,p,h,y=()=>!0)=>{let L=c.scrollTop,N=p(),_=N-L;ar();let q=performance.now();Co=!0;let F=fe=>1-Math.pow(1-fe,3),Ce=fe=>{if(!y()){ar();return}let te=p();te!==N&&(N=te,_=N-L);let ke=fe-q,Ve=Math.min(ke/h,1),Te=F(Ve),ot=L+_*Te;c.scrollTop=ot,eo=c.scrollTop,Ve<1?Go=requestAnimationFrame(Ce):(c.scrollTop=N,eo=c.scrollTop,Go=null,Co=!1)};Go=requestAnimationFrame(Ce)},Ja=(c,p=500)=>{let h=Zo(c)-c.scrollTop;if(Math.abs(h)<1){eo=c.scrollTop;return}if(Math.abs(h)>=Ya){ar(),Co=!0,c.scrollTop=Zo(c),eo=c.scrollTop,Co=!1;return}Ns(c,()=>Zo(c),p,()=>Zn.isFollowing())},_s=()=>{let c=Bs();Co=!0,c.scrollTop=Zo(c),eo=c.scrollTop,Co=!1,Un()},Vs=c=>{Tn.style.height=`${Math.max(0,Math.round(c))}px`,kn&&(kn.spacerHeight=Math.max(0,c))},Er=()=>{Ho!==null&&(cancelAnimationFrame(Ho),Ho=null),ar(),kn=null,Tn.style.height="0px"},Za=c=>{Ho!==null&&cancelAnimationFrame(Ho),Ho=requestAnimationFrame(()=>{var Ce;Ho=null;let p=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(c):c.replace(/"/g,'\\"'),h=ge.querySelector(`[data-message-id="${p}"]`);if(!h)return;let y=0,L=h;for(;L&&L!==ge;)y+=L.offsetTop,L=L.offsetParent;let N=(Ce=kn==null?void 0:kn.spacerHeight)!=null?Ce:0,_=ge.scrollHeight-N,{targetScrollTop:q,spacerHeight:F}=xg({anchorOffsetTop:y,topOffset:Et(),viewportHeight:ge.clientHeight,contentHeight:_});kn={initialSpacerHeight:F,contentHeightAtAnchor:_,spacerHeight:F},Vs(F),Ns(ge,()=>q,220)})},ei=()=>{if(mt()==="follow"){if(!Zn.isFollowing()||qr(ge,1))return;Oo(!Wo);return}if(kn&&kn.initialSpacerHeight>0){let c=ge.scrollHeight-kn.spacerHeight,p=wg({initialSpacerHeight:kn.initialSpacerHeight,contentHeightAtAnchor:kn.contentHeightAtAnchor,currentContentHeight:c});p!==kn.spacerHeight&&Vs(p)}Un()},ti=c=>{let p=mt();p==="follow"?(Do(),Oo(!0)):p==="anchor-top"&&Za(c)},ni=c=>{let p=new Map;c.forEach(h=>{let y=os.get(h.id);p.set(h.id,{streaming:h.streaming,role:h.role}),!y&&h.role==="assistant"&&(s.emit("assistant:message",h),!kr&&mt()!=="anchor-top"&&Fs()&&(Ko+=1,Ds(),Un())),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}))}),os.clear(),p.forEach((h,y)=>{os.set(y,h)})},Mr=(c,p,h)=>{var pt,We,Re,ze,Ye,wt;let y=document.createElement("div"),N=(()=>{var He;let H=r.find(Fe=>Fe.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,F=new Set,Ce=r.some(H=>H.renderAskUserQuestion),fe=[],te=[],ke=o.enableComponentStreaming!==!1,Ve=r.some(H=>H.renderApproval)&&o.approval!==!1,Te=[];if(p.forEach(H=>{var Qe,Pt,pn,mo,no,Ir,Rr,ds,ps,Qt,Pr,mr,gr,Qo,Wr,So;q.add(H.id);let He=Ce&&Vr(H),Fe=Ve&&H.variant==="approval"&&!!H.approval,ve=!He&&H.role==="assistant"&&!H.variant&&ke&&rf(H);if(!Fe&&xo.has(H.id)){let tt=c.querySelector(`#wrapper-${H.id}`);tt==null||tt.removeAttribute("data-preserve-runtime"),xo.delete(H.id)}if(!ve&&Bo.has(H.id)){let tt=c.querySelector(`#wrapper-${H.id}`);tt==null||tt.removeAttribute("data-preserve-runtime"),Bo.delete(H.id)}let Nt=Vr(H)?`:${(Qe=H.agentMetadata)!=null&&Qe.askUserQuestionAnswered?"a":"u"}:${(Pt=H.agentMetadata)!=null&&Pt.askUserQuestionAnswers?Object.keys(H.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ft=gg(H,Ps)+Nt,Gt=He||Fe||ve?null:hg(qo,H.id,Ft);if(Gt){y.appendChild(Gt.cloneNode(!0)),Vr(H)&&((pn=H.toolCall)!=null&&pn.id)&&((mo=H.agentMetadata)==null?void 0:mo.awaitingLocalTool)===!0&&!((no=H.agentMetadata)!=null&&no.askUserQuestionAnswered)&&(F.add(H.toolCall.id),Mi(H,o,Be.composerOverlay));return}let Ct=null,qt=r.find(tt=>!!(H.variant==="reasoning"&&tt.renderReasoning||H.variant==="tool"&&tt.renderToolCall||!H.variant&&tt.renderMessage)),to=(Ir=o.layout)==null?void 0:Ir.messages;if(Vr(H)&&((Rr=H.agentMetadata)==null?void 0:Rr.askUserQuestionAnswered)===!0){jo.delete(H.id);let tt=c.querySelector(`#wrapper-${H.id}`);tt==null||tt.removeAttribute("data-preserve-runtime");return}if(sc(H)&&((ps=(ds=o.features)==null?void 0:ds.suggestReplies)==null?void 0:ps.enabled)!==!1)return;if(Vr(H)&&((Pr=(Qt=o.features)==null?void 0:Qt.askUserQuestion)==null?void 0:Pr.enabled)!==!1){let tt=r.find(gn=>typeof gn.renderAskUserQuestion=="function");if(tt&&It.current){let gn=jo.get(H.id),$t=gn!==Ft,_t=null;if($t){let{payload:Mt,complete:En}=ys(H),Hn=H.id,Fo=()=>{var xn;return(xn=It.current)==null?void 0:xn.getMessages().find(Dn=>Dn.id===Hn)};_t=tt.renderAskUserQuestion({message:H,payload:Mt,complete:En,resolve:xn=>{var On;let Dn=Fo();Dn&&((On=It.current)==null||On.resolveAskUserQuestion(Dn,xn))},dismiss:()=>{var Dn,On,Br;let xn=Fo();(Dn=xn==null?void 0:xn.agentMetadata)!=null&&Dn.awaitingLocalTool&&((On=It.current)==null||On.markAskUserQuestionResolved(xn),(Br=It.current)==null||Br.resolveAskUserQuestion(xn,"(dismissed)"))},config:o})}let bt=gn!=null;if($t&&_t===null&&!bt){((mr=H.agentMetadata)==null?void 0:mr.awaitingLocalTool)===!0&&!((gr=H.agentMetadata)!=null&&gr.askUserQuestionAnswered)&&(F.add(H.toolCall.id),Mi(H,o,Be.composerOverlay));return}let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id=`wrapper-${H.id}`,Xt.setAttribute("data-wrapper-id",H.id),Xt.setAttribute("data-ask-plugin-stub","true"),Xt.setAttribute("data-preserve-runtime","true"),y.appendChild(Xt),fe.push({messageId:H.id,fingerprint:Ft,bubble:_t});return}else{((Qo=H.agentMetadata)==null?void 0:Qo.awaitingLocalTool)===!0&&!((Wr=H.agentMetadata)!=null&&Wr.askUserQuestionAnswered)&&(F.add(H.toolCall.id),Mi(H,o,Be.composerOverlay));return}}else if(Fe){let tt=r.find(bt=>typeof bt.renderApproval=="function"),$t=xo.get(H.id)!==Ft,_t=null;if($t&&(tt!=null&&tt.renderApproval)){let bt=H.id,Xt=(Mt,En)=>{var Fo,xn,Dn;let Hn=(Fo=It.current)==null?void 0:Fo.getMessages().find(On=>On.id===bt);Hn!=null&&Hn.approval&&(Hn.approval.toolType==="webmcp"?(xn=It.current)==null||xn.resolveWebMcpApproval(Hn.id,Mt):(Dn=It.current)==null||Dn.resolveApproval(Hn.approval,Mt,En))};_t=tt.renderApproval({message:H,defaultRenderer:()=>il(H,o),config:o,approve:Mt=>Xt("approved",Mt),deny:Mt=>Xt("denied",Mt)})}if($t&&_t===null){let bt=c.querySelector(`#wrapper-${H.id}`);bt==null||bt.removeAttribute("data-preserve-runtime"),xo.delete(H.id),Ct=il(H,o)}else{let bt=document.createElement("div");bt.className="persona-flex",bt.id=`wrapper-${H.id}`,bt.setAttribute("data-wrapper-id",H.id),bt.setAttribute("data-approval-plugin-stub","true"),bt.setAttribute("data-preserve-runtime","true"),y.appendChild(bt),Te.push({messageId:H.id,fingerprint:Ft,bubble:_t});return}}else if(qt)if(H.variant==="reasoning"&&H.reasoning&&qt.renderReasoning){if(!me)return;Ct=qt.renderReasoning({message:H,defaultRenderer:()=>xc(H,o),config:o})}else if(H.variant==="tool"&&H.toolCall&&qt.renderToolCall){if(!de)return;Ct=qt.renderToolCall({message:H,defaultRenderer:()=>wc(H,o),config:o})}else qt.renderMessage&&(Ct=qt.renderMessage({message:H,defaultRenderer:()=>{let tt=vc(H,h,to,o.messageActions,ee,{loadingIndicatorRenderer:N,widgetConfig:o});return H.role!=="user"&&Tc(tt,H,o,U),tt},config:o}));if(!Ct&&ve){let tt=sf(H);if(tt){let gn=Bo.get(H.id),$t=gn!==Ft,_t=o.wrapComponentDirectiveInBubble!==!1,bt=null;if($t){let Xt=nf(tt,{config:o,message:H,transform:h});if(Xt)if(_t){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 En=document.createElement("div");En.className="persona-mb-3 persona-text-sm persona-leading-relaxed",En.innerHTML=h({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),Mt.appendChild(En)}Mt.appendChild(Xt),bt=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 En=document.createElement("div");En.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",En.innerHTML=h({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),Mt.appendChild(En)}Mt.appendChild(Xt),bt=Mt}}if(bt||gn!=null){let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id=`wrapper-${H.id}`,Xt.setAttribute("data-wrapper-id",H.id),Xt.setAttribute("data-component-directive-stub","true"),Xt.setAttribute("data-preserve-runtime","true"),_t||Xt.classList.add("persona-w-full"),y.appendChild(Xt),te.push({messageId:H.id,fingerprint:Ft,bubble:bt});return}}}if(!Ct)if(H.variant==="reasoning"&&H.reasoning){if(!me)return;Ct=xc(H,o)}else if(H.variant==="tool"&&H.toolCall){if(!de)return;Ct=wc(H,o)}else if(H.variant==="approval"&&H.approval){if(o.approval===!1)return;Ct=il(H,o)}else{let tt=(So=o.layout)==null?void 0:So.messages;tt!=null&&tt.renderUserMessage&&H.role==="user"?Ct=tt.renderUserMessage({message:H,config:o,streaming:!!H.streaming}):tt!=null&&tt.renderAssistantMessage&&H.role==="assistant"?Ct=tt.renderAssistantMessage({message:H,config:o,streaming:!!H.streaming}):Ct=vc(H,h,tt,o.messageActions,ee,{loadingIndicatorRenderer:N,widgetConfig:o}),H.role!=="user"&&Ct&&Tc(Ct,H,o,U)}let an=document.createElement("div");an.className="persona-flex",an.id=`wrapper-${H.id}`,an.setAttribute("data-wrapper-id",H.id),H.role==="user"&&an.classList.add("persona-justify-end"),(Ct==null?void 0:Ct.getAttribute("data-persona-component-directive"))==="true"&&an.classList.add("persona-w-full"),an.appendChild(Ct),bg(qo,H.id,Ft,an),y.appendChild(an)}),Be.composerOverlay&&Be.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(He=>{let Fe=He.getAttribute("data-persona-ask-sheet-for");Fe&&!F.has(Fe)&&xs(Be.composerOverlay,Fe)}),(We=(pt=o.features)==null?void 0:pt.toolCallDisplay)!=null&&We.grouped){let H=[],He=[];p.forEach(Fe=>{if(Fe.variant==="tool"&&Fe.toolCall&&de){He.push(Fe);return}He.length>1&&H.push(He),He=[]}),He.length>1&&H.push(He),H.forEach((Fe,ve)=>{var Qe,Pt;let Nt=Fe.map(pn=>Array.from(y.children).find(mo=>mo instanceof HTMLElement&&mo.getAttribute("data-wrapper-id")===pn.id)).filter(pn=>!!pn);if(Nt.length<2)return;let Ft=document.createElement("div");Ft.className="persona-flex",Ft.id=`wrapper-tool-group-${ve}-${Fe[0].id}`,Ft.setAttribute("data-wrapper-id",`tool-group-${ve}-${Fe[0].id}`);let Gt=document.createElement("div");Gt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Gt.setAttribute("data-persona-tool-group","true");let Ct=document.createElement("div");Ct.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let qt=`Called ${Fe.length} tools`,to=(Pt=(Qe=o.toolCall)==null?void 0:Qe.renderGroupedSummary)==null?void 0:Pt.call(Qe,{messages:Fe,toolCalls:Fe.map(pn=>pn.toolCall).filter(pn=>!!pn),defaultSummary:qt,config:o});_(Ct,to)||(Ct.textContent=qt);let an=document.createElement("div");an.className="persona-tool-group-stack persona-flex persona-flex-col",Gt.append(Ct,an),Ft.appendChild(Gt),Nt[0].before(Ft),Nt.forEach((pn,mo)=>{let no=document.createElement("div");no.className="persona-tool-group-item persona-relative",no.setAttribute("data-persona-tool-group-item","true"),mo<Nt.length-1&&no.setAttribute("data-persona-tool-group-connector","true"),no.appendChild(pn),an.appendChild(no)})})}yg(qo,q);let ot=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(Wo&&p.some(H=>H.role==="user")&&!ot&&!dt){let H={config:o,streaming:!0,location:"standalone",defaultRenderer:Wa},He=r.find(ve=>ve.renderLoadingIndicator),Fe=null;if(He!=null&&He.renderLoadingIndicator&&(Fe=He.renderLoadingIndicator(H)),Fe===null&&((Re=o.loadingIndicator)!=null&&Re.render)&&(Fe=o.loadingIndicator.render(H)),Fe===null&&(Fe=Wa()),Fe){let ve=document.createElement("div"),Nt=((ze=o.loadingIndicator)==null?void 0:ze.showBubble)!==!1;ve.className=Nt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),ve.setAttribute("data-typing-indicator","true"),ve.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",ve.appendChild(Fe);let Ft=document.createElement("div");Ft.className="persona-flex",Ft.id="wrapper-typing-indicator",Ft.setAttribute("data-wrapper-id","typing-indicator"),Ft.appendChild(ve),y.appendChild(Ft)}}if(!Wo&&p.length>0){let H=p[p.length-1],He={config:o,lastMessage:H,messageCount:p.length},Fe=r.find(Nt=>Nt.renderIdleIndicator),ve=null;if(Fe!=null&&Fe.renderIdleIndicator&&(ve=Fe.renderIdleIndicator(He)),ve===null&&((Ye=o.loadingIndicator)!=null&&Ye.renderIdle)&&(ve=o.loadingIndicator.renderIdle(He)),ve){let Nt=document.createElement("div"),Ft=((wt=o.loadingIndicator)==null?void 0:wt.showBubble)!==!1;Nt.className=Ft?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Nt.setAttribute("data-idle-indicator","true"),Nt.appendChild(ve);let Gt=document.createElement("div");Gt.className="persona-flex",Gt.id="wrapper-idle-indicator",Gt.setAttribute("data-wrapper-id","idle-indicator"),Gt.appendChild(Nt),y.appendChild(Gt)}}if($i(c,y),fe.length>0)for(let{messageId:H,fingerprint:He,bubble:Fe}of fe){let ve=c.querySelector(`#wrapper-${H}`);ve&&Fe!==null&&(ve.replaceChildren(Fe),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(te.length>0)for(let{messageId:H,fingerprint:He,bubble:Fe}of te){let ve=c.querySelector(`#wrapper-${H}`);ve&&Fe!==null&&(ve.replaceChildren(Fe),ve.setAttribute("data-bubble-fp",He),Bo.set(H,He))}if(Bo.size>0)for(let H of Bo.keys())q.has(H)||Bo.delete(H);if(Te.length>0)for(let{messageId:H,fingerprint:He,bubble:Fe}of Te){let ve=c.querySelector(`#wrapper-${H}`);ve&&Fe!==null&&(ve.replaceChildren(Fe),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)},ir=null,oi=()=>{var h;if(ir)return;let c=y=>{let L=y.composedPath();L.includes(Ie)||Xe&&L.includes(Xe)||Ot(!1,"user")};ir=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},$s=()=>{var p;if(!ir)return;((p=e.ownerDocument)!=null?p:document).removeEventListener("pointerdown",ir,!0),ir=null};ft.push(()=>$s());let lr=null,ri=()=>{var h;if(lr)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Ot(!1,"user"))};lr=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},Us=()=>{var p;if(!lr)return;((p=e.ownerDocument)!=null?p:document).removeEventListener("keydown",lr,!0),lr=null};ft.push(()=>Us());let cr=!1,zs=new Set,si=()=>{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,Re;if(!E())return;let c=Be.peekBanner,p=Be.peekTextNode;if(!c||!p)return;if(S){c.classList.remove("persona-pill-peek--visible");return}let h=(dt=U==null?void 0:U.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,_=si(),q=Ki(_),F=q.type!=="none"?Ta(q.type,_==null?void 0:_.plugins):null,Ce=((pt=F==null?void 0:F.isAnimating)==null?void 0:pt.call(F,y))===!0,fe=F!==null&&(N||Ce);fe&&F&&!zs.has(F.name)&&(mc(F,e),zs.add(F.name));let te=fe&&(F!=null&&F.containerClass)?F.containerClass:null,ke=(We=p.dataset.personaPeekStreamClass)!=null?We:null;ke&&ke!==te&&(p.classList.remove(ke),delete p.dataset.personaPeekStreamClass),te&&ke!==te&&(p.classList.add(te),p.dataset.personaPeekStreamClass=te),fe?(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=fe?Gi(L,q.buffer,F,y,N):L;if(fe&&q.placeholder==="skeleton"&&N&&(!Ve||!Ve.trim())){let ze=document.createElement("div"),Ye=Ea();Ye.classList.add("persona-pill-peek__skeleton"),ze.appendChild(Ye),$i(p,ze)}else{let ze=Math.max(0,Ve.length-100),Ye=Ve.length>100?Ve.slice(-100):Ve,wt=ua(Ye);if(!fe||!F){let H=Ve.length>100?`\u2026${Ye}`:Ye;p.textContent!==H&&(p.textContent=H)}else{let H=wt;(F.wrap==="char"||F.wrap==="word")&&(H=ka(wt,F.wrap,`peek-${y.id}`,{skipTags:F.skipTags,startIndex:ze}));let He=document.createElement("div");if(He.innerHTML=H,F.useCaret&&Ye.length>0){let Fe=Yi(),ve=He.querySelectorAll(".persona-stream-char, .persona-stream-word"),Nt=ve[ve.length-1];Nt!=null&&Nt.parentNode?Nt.parentNode.insertBefore(Fe,Nt.nextSibling):He.appendChild(Fe)}$i(p,He),(Re=F.onAfterRender)==null||Re.call(F,{container:p,bubble:c,messageId:y.id,message:y,speed:q.speed,duration:q.duration})}}let je=Wo||cr;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),ft.push(()=>{c.removeEventListener("pointerdown",y)})}let p=()=>{cr||(cr=!0,Yo())},h=()=>{cr&&(cr=!1,Yo())};pe.addEventListener("pointerenter",p),pe.addEventListener("pointerleave",h),ft.push(()=>{pe.removeEventListener("pointerenter",p),pe.removeEventListener("pointerleave",h)}),Xe&&(Xe.addEventListener("pointerenter",p),Xe.addEventListener("pointerleave",h),ft.push(()=>{Xe.removeEventListener("pointerenter",p),Xe.removeEventListener("pointerleave",h)}))}let ai=c=>{var ke,Ve,Te,ot,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=(ot=p.bottomOffset)!=null?ot:"16px",L=p.collapsedMaxWidth,N=(je=p.expandedMaxWidth)!=null?je:"880px",_=(dt=p.expandedTopOffset)!=null?dt:"5vh",q=(pt=p.modalMaxWidth)!=null?pt:"880px",F=(We=p.modalMaxHeight)!=null?We:"min(90vh, 800px)",Ce="calc(100vw - 32px)",fe="var(--persona-pill-area-height, 80px)",te=Ie.style;if(te.left="",te.right="",te.top="",te.bottom="",te.transform="",te.width="",te.maxWidth="",te.height="",te.maxHeight="",Xe){let Re=Xe.style;Re.bottom=y,Re.width=L!=null?L:""}if(c&&h!=="fullscreen"){if(h==="modal"){te.top="50%",te.left="50%",te.transform="translate(-50%, -50%)",te.bottom="auto",te.right="auto",te.width=q,te.maxWidth=Ce,te.maxHeight=F,te.height=F;return}te.left="50%",te.transform="translateX(-50%)",te.bottom=`calc(${y} + ${fe})`,te.top=_,te.width=N,te.maxWidth=Ce}},dr=()=>{var F,Ce,fe,te,ke,Ve,Te,ot;if(!A())return;if(E()){let dt=(fe=((Ce=(F=o.launcher)==null?void 0:F.composerBar)!=null?Ce:{}).expandedSize)!=null?fe:"anchored",pt=S?"expanded":"collapsed";Ie.dataset.state=pt,Ie.dataset.expandedSize=dt,Xe&&(Xe.dataset.state=pt,Xe.dataset.expandedSize=dt),Ie.style.removeProperty("display"),Ie.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ai(S),j.style.display=S?"flex":"none",yo(),S?(oi(),ri()):($s(),Us()),Yo();return}let c=Sn(o),p=(te=e.ownerDocument.defaultView)!=null?te:window,h=(Ve=(ke=o.launcher)==null?void 0:ke.mobileBreakpoint)!=null?Ve:640,y=(ot=(Te=o.launcher)==null?void 0:Te.mobileFullscreen)!=null?ot:!0,L=p.innerWidth<=h,N=y&&L&&I,_=Eo(o).reveal;S?(Ie.style.removeProperty("display"),Ie.style.display=c?"flex":"",Ie.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"),on?on.element.style.display="none":rn&&(rn.style.display="none")):(c?c&&(_==="overlay"||_==="push")&&!N?(Ie.style.removeProperty("display"),Ie.style.display="flex",Ie.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ie.style.setProperty("display","none","important"),Ie.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ie.style.display="",Ie.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")),on?on.element.style.display=c?"none":"":rn&&(rn.style.display=c?"none":""))},Ot=(c,p="user")=>{var N,_;if(!A()||S===c)return;let h=S;S=c,dr();let y=(()=>{var Te,ot,je,dt,pt,We,Re,ze,Ye,wt;let q=(ot=(Te=o.launcher)==null?void 0:Te.sidebarMode)!=null?ot:!1,F=(je=e.ownerDocument.defaultView)!=null?je:window,Ce=(pt=(dt=o.launcher)==null?void 0:dt.mobileFullscreen)!=null?pt:!0,fe=(Re=(We=o.launcher)==null?void 0:We.mobileBreakpoint)!=null?Re:640,te=F.innerWidth<=fe,ke=Sn(o)&&Ce&&te,Ve=E()&&((wt=(Ye=(ze=o.launcher)==null?void 0:ze.composerBar)==null?void 0:Ye.expandedSize)!=null?wt:"fullscreen")==="fullscreen";return q||Ce&&te&&I||ke||Ve})();if(S&&y){if(!tn){let q=e.getRootNode(),F=q instanceof ShadowRoot?q.host:e.closest(".persona-host");F&&(tn=gc(F,(_=(N=o.launcher)==null?void 0:N.zIndex)!=null?_:In))}nn||(nn=fc(e.ownerDocument))}else S||(tn==null||tn(),tn=null,nn==null||nn(),nn=null);S&&(js(),mt()==="follow"?Oo(!0):_s());let L={open:S,source:p,timestamp:Date.now()};S&&!h?s.emit("widget:opened",L):!S&&h&&s.emit("widget:closed",L),s.emit("widget:state",{open:S,launcherEnabled:I,voiceActive:yt.active,streaming:U.isStreaming()})},as=c=>{Jt(c?"stop":"send"),Y&&(Y.disabled=c),vo.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)})},is=()=>{yt.active||ne&&ne.focus()};s.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>is(),200)});let Lr=()=>{var h,y,L,N,_,q,F,Ce,fe,te,ke;so.textContent=(y=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",Lo.textContent=(N=(L=o.copy)==null?void 0:L.welcomeSubtitle)!=null?N:"Ask anything about your account or products.",ne.placeholder=(q=(_=o.copy)==null?void 0:_.inputPlaceholder)!=null?q:"How can I help...";let c=ge.querySelector("[data-persona-intro-card]");if(c){let Ve=((F=o.copy)==null?void 0:F.showWelcomeCard)!==!1;c.style.display=Ve?"":"none",Ve?(ge.classList.remove("persona-gap-3"),ge.classList.add("persona-gap-6")):(ge.classList.remove("persona-gap-6"),ge.classList.add("persona-gap-3"))}!((fe=(Ce=o.sendButton)==null?void 0:Ce.useIcon)!=null&&fe)&&!(U!=null&&U.isStreaming())&&(qe.textContent=(ke=(te=o.copy)==null?void 0:te.sendButtonLabel)!=null?ke:"Send"),ne.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ne.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 Ue=null,k=()=>{Ue==null&&(Ue=setInterval(()=>{let c=nt.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Ue),Ue=null;return}let p=Date.now();c.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=Ii(p-y))})},100))};if(U=new _i(o,{onMessagesChanged(c){var y;Mr(nt,c,he),k(),Zr(c),Oo(!Wo),ni(c);let p=[...c].reverse().find(L=>L.role==="user");c.length===0&&Er(),!es||kr?(es=!0,ts=(y=p==null?void 0:p.id)!=null?y:null):p&&p.id!==ts&&(ts=p.id,ti(p.id));let h=yt.lastUserMessageId;p&&p.id!==h&&(yt.lastUserMessageId=p.id,s.emit("user:message",p)),yt.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),rs(c),Yo()},onStatusChanged(c){var y;let p=(y=o.statusIndicator)!=null?y:{};lt(ln,(L=>{var N,_,q,F;return L==="idle"?(N=p.idleText)!=null?N:Ln.idle:L==="connecting"?(_=p.connectingText)!=null?_:Ln.connecting:L==="connected"?(q=p.connectedText)!=null?q:Ln.connected:L==="error"?(F=p.errorText)!=null?F:Ln.error:Ln[L]})(c),p,c)},onStreamingChanged(c){Wo=c,as(c),U&&Mr(nt,U.getMessages(),he),c||Oo(!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":pr(),Bf();break;case"speaking":pr(),Hf();break;default:c==="idle"&&U.isBargeInActive()?(pr(),qs(),Y==null||Y.setAttribute("aria-label","End voice session")):(yt.active=!1,pr(),po("system"),$n());break}},onArtifactsState(c){Gn=c,Xn(),rs()}}),It.current=U,es=!0,((Qd=(Yd=o.voiceRecognition)==null?void 0:Yd.provider)==null?void 0:Qd.type)==="runtype")try{U.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}o.clientToken&&U.initClientSession().catch(c=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(ye||o.onSSEEvent)&&U.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=Pc(c.metadata),M.syncFromMetadata()),(p=c.messages)!=null&&p.length){kr=!0;try{U.hydrateMessages(c.messages)}finally{kr=!1}}(h=c.artifacts)!=null&&h.length&&U.hydrateArtifacts(c.artifacts,(y=c.selectedArtifactId)!=null?y:null)}}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let z=()=>{var p,h,y;!E()||S||!((y=(h=(p=o.launcher)==null?void 0:p.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||Ot(!0,"auto")},W=c=>{var L;if(c.preventDefault(),U.isStreaming()){U.cancel(),be==null||be.reset(),K==null||K.update();return}let p=ne.value.trim(),h=(L=St==null?void 0:St.hasAttachments())!=null?L:!1;if(!p&&!h)return;z();let y;h&&(y=[],y.push(...St.getContentParts()),p&&y.push(cc(p))),ne.value="",ne.style.height="auto",Le(),U.sendMessage(p,{contentParts:y}),h&&St.clearAttachments()},Z=()=>{var c;return((c=o.features)==null?void 0:c.composerHistory)!==!1},ie={...Ui},Q=!1,Le=()=>{ie={...Ui}},Ne=()=>U.getMessages().filter(c=>c.role==="user").map(c=>{var p;return(p=c.content)!=null?p:""}).filter(c=>c.length>0),ct=c=>{if(!ne)return;Q=!0,ne.value=c,ne.dispatchEvent(new Event("input",{bubbles:!0})),Q=!1;let p=ne.value.length;ne.setSelectionRange(p,p)},Ze=()=>{Q||Le()},Bt=c=>{if(ne){if(Z()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let p=ne.selectionStart===0&&ne.selectionEnd===0,h=mg({direction:c.key==="ArrowUp"?"up":"down",history:Ne(),currentValue:ne.value,atStart:p,state:ie});if(ie=h.state,h.handled){c.preventDefault(),h.value!==void 0&&ct(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(U.isStreaming()){c.preventDefault();return}Le(),c.preventDefault(),qe.click()}}},Vt=c=>{c.key!=="Escape"||c.isComposing||U.isStreaming()&&c.composedPath().includes(j)&&(U.cancel(),be==null||be.reset(),K==null||K.update(),Le(),c.preventDefault(),c.stopImmediatePropagation())},mn=async c=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!St)return;let p=vv(c.clipboardData);p.length!==0&&(c.preventDefault(),await St.handleFiles(p))},st=null,ht=!1,Zt=null,Ke=null,Cn=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Yt=(c="user")=>{var N,_,q,F,Ce,fe,te;if(ht||U.isStreaming())return;let p=Cn();if(!p)return;st=new p;let y=(_=((N=o.voiceRecognition)!=null?N:{}).pauseDuration)!=null?_:2e3;st.continuous=!0,st.interimResults=!0,st.lang="en-US";let L=ne.value;st.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 ot=L+Ve+Te;ne.value=ot,Zt&&clearTimeout(Zt),(Ve||Te)&&(Zt=window.setTimeout(()=>{let je=ne.value.trim();je&&st&&ht&&(vn(),ne.value="",ne.style.height="auto",U.sendMessage(je,{viaVoice:!0}))},y))},st.onerror=ke=>{ke.error!=="no-speech"&&vn()},st.onend=()=>{if(ht){let ke=ne.value.trim();ke&&ke!==L.trim()&&(ne.value="",ne.style.height="auto",U.sendMessage(ke,{viaVoice:!0})),vn()}};try{if(st.start(),ht=!0,yt.active=!0,c!=="system"&&(yt.manuallyDeactivated=!1),po(c),$n(),Y){let ke=(q=o.voiceRecognition)!=null?q:{};Ke={backgroundColor:Y.style.backgroundColor,color:Y.style.color,borderColor:Y.style.borderColor,iconName:(F=ke.iconName)!=null?F:"mic",iconSize:parseFloat((te=(fe=ke.iconSize)!=null?fe:(Ce=o.sendButton)==null?void 0:Ce.size)!=null?te:"40")||24};let Ve=ke.recordingBackgroundColor,Te=ke.recordingIconColor,ot=ke.recordingBorderColor;if(Y.classList.add("persona-voice-recording"),Y.style.backgroundColor=Ve!=null?Ve:"var(--persona-voice-recording-bg, #ef4444)",Y.style.color=Te!=null?Te:"var(--persona-voice-recording-indicator, #ffffff)",Te){let je=Y.querySelector("svg");je&&je.setAttribute("stroke",Te)}ot&&(Y.style.borderColor=ot),Y.setAttribute("aria-label","Stop voice recognition")}}catch{vn("system")}},vn=(c="user")=>{if(ht){if(ht=!1,Zt&&(clearTimeout(Zt),Zt=null),st){try{st.stop()}catch{}st=null}if(yt.active=!1,po(c),$n(),Y){if(Y.classList.remove("persona-voice-recording"),Ke){Y.style.backgroundColor=Ke.backgroundColor,Y.style.color=Ke.color,Y.style.borderColor=Ke.borderColor;let p=Y.querySelector("svg");p&&p.setAttribute("stroke",Ke.color||"currentColor"),Ke=null}Y.setAttribute("aria-label","Start voice recognition")}}},Wf=(c,p)=>{var dt,pt,We,Re,ze,Ye,wt,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",F=(We=p==null?void 0:p.size)!=null?We:"40px",Ce=(Re=c==null?void 0:c.iconSize)!=null?Re:F,fe=parseFloat(Ce)||24,te=(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,fe,ke||"currentColor",1.5);Te?_.appendChild(Te):_.textContent="\u{1F3A4}",te?_.style.backgroundColor=te:_.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 ot=(wt=c==null?void 0:c.tooltipText)!=null?wt:"Start voice recognition";if(((H=c==null?void 0:c.showTooltip)!=null?H:!1)&&ot){let He=b("div","persona-send-button-tooltip");He.textContent=ot,N.appendChild(He)}return{micButton:_,micButtonWrapper:N}},kl=()=>{var p,h,y,L,N;if(!Y||Ke)return;let c=(p=o.voiceRecognition)!=null?p:{};Ke={backgroundColor:Y.style.backgroundColor,color:Y.style.color,borderColor:Y.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}},El=(c,p)=>{var N,_,q,F,Ce;if(!Y)return;let h=Y.querySelector("svg");h&&h.remove();let y=(Ce=Ke==null?void 0:Ke.iconSize)!=null?Ce:parseFloat((F=(q=(N=o.voiceRecognition)==null?void 0:N.iconSize)!=null?q:(_=o.sendButton)==null?void 0:_.size)!=null?F:"40")||24,L=Me(c,y,p,1.5);L&&Y.appendChild(L)},ii=()=>{Y&&Y.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},qs=()=>{var L;if(!Y)return;kl();let c=(L=o.voiceRecognition)!=null?L:{},p=c.recordingBackgroundColor,h=c.recordingIconColor,y=c.recordingBorderColor;if(ii(),Y.classList.add("persona-voice-recording"),Y.style.backgroundColor=p!=null?p:"var(--persona-voice-recording-bg, #ef4444)",Y.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let N=Y.querySelector("svg");N&&N.setAttribute("stroke",h)}y&&(Y.style.borderColor=y),Y.setAttribute("aria-label","Stop voice recognition")},Bf=()=>{var q,F,Ce,fe,te,ke,Ve,Te;if(!Y)return;kl();let c=(q=o.voiceRecognition)!=null?q:{},p=U.getVoiceInterruptionMode(),h=(F=c.processingIconName)!=null?F:"loader",y=(fe=(Ce=c.processingIconColor)!=null?Ce:Ke==null?void 0:Ke.color)!=null?fe:"",L=(ke=(te=c.processingBackgroundColor)!=null?te:Ke==null?void 0:Ke.backgroundColor)!=null?ke:"",N=(Te=(Ve=c.processingBorderColor)!=null?Ve:Ke==null?void 0:Ke.borderColor)!=null?Te:"";ii(),Y.classList.add("persona-voice-processing"),Y.style.backgroundColor=L,Y.style.borderColor=N;let _=y||"currentColor";Y.style.color=_,El(h,_),Y.setAttribute("aria-label","Processing voice input"),p==="none"&&(Y.style.cursor="default")},Hf=()=>{var Ce,fe,te,ke,Ve,Te,ot,je,dt,pt,We,Re;if(!Y)return;kl();let c=(Ce=o.voiceRecognition)!=null?Ce:{},p=U.getVoiceInterruptionMode(),h=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",y=(fe=c.speakingIconName)!=null?fe:h,L=(Te=c.speakingIconColor)!=null?Te:p==="barge-in"?(ke=(te=c.recordingIconColor)!=null?te:Ke==null?void 0:Ke.color)!=null?ke:"":(Ve=Ke==null?void 0:Ke.color)!=null?Ve:"",N=(dt=c.speakingBackgroundColor)!=null?dt:p==="barge-in"?(ot=c.recordingBackgroundColor)!=null?ot:"var(--persona-voice-recording-bg, #ef4444)":(je=Ke==null?void 0:Ke.backgroundColor)!=null?je:"",_=(Re=c.speakingBorderColor)!=null?Re:p==="barge-in"?(pt=c.recordingBorderColor)!=null?pt:"":(We=Ke==null?void 0:Ke.borderColor)!=null?We:"";ii(),Y.classList.add("persona-voice-speaking"),Y.style.backgroundColor=N,Y.style.borderColor=_;let q=L||"currentColor";Y.style.color=q,El(y,q);let F=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";Y.setAttribute("aria-label",F),p==="none"&&(Y.style.cursor="default"),p==="barge-in"&&Y.classList.add("persona-voice-recording")},pr=()=>{var c,p,h;Y&&(ii(),Ke&&(Y.style.backgroundColor=(c=Ke.backgroundColor)!=null?c:"",Y.style.color=(p=Ke.color)!=null?p:"",Y.style.borderColor=(h=Ke.borderColor)!=null?h:"",El(Ke.iconName,Ke.color||"currentColor"),Ke=null),Y.style.cursor="",Y.setAttribute("aria-label","Start voice recognition"))},li=()=>{var c,p;if(((p=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:p.type)==="runtype"){let h=U.getVoiceStatus(),y=U.getVoiceInterruptionMode();if(y==="none"&&(h==="processing"||h==="speaking"))return;if(y==="cancel"&&(h==="processing"||h==="speaking")){U.stopVoicePlayback();return}if(U.isBargeInActive()){U.stopVoicePlayback(),U.deactivateBargeIn().then(()=>{yt.active=!1,yt.manuallyDeactivated=!0,$n(),po("user"),pr()});return}U.toggleVoice().then(()=>{yt.active=U.isVoiceActive(),yt.manuallyDeactivated=!U.isVoiceActive(),$n(),po("user"),U.isVoiceActive()?qs():pr()});return}if(ht){let h=ne.value.trim();yt.manuallyDeactivated=!0,$n(),vn("user"),h&&(ne.value="",ne.style.height="auto",U.sendMessage(h))}else yt.manuallyDeactivated=!1,$n(),Yt("user")};qn=li,Y&&(Y.addEventListener("click",li),ft.push(()=>{var c,p;((p=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:p.type)==="runtype"?(U.isVoiceActive()&&U.toggleVoice(),pr()):vn("system"),Y&&Y.removeEventListener("click",li)}));let Df=s.on("assistant:complete",()=>{Ws&&(yt.active||yt.manuallyDeactivated||Ws==="assistant"&&!yt.lastUserMessageWasVoice||setTimeout(()=>{var c,p;!yt.active&&!yt.manuallyDeactivated&&(((p=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:p.type)==="runtype"?U.toggleVoice().then(()=>{yt.active=U.isVoiceActive(),po("auto"),U.isVoiceActive()&&qs()}):Yt("auto"))},600))});ft.push(Df);let Of=s.on("action:resubmit",()=>{setTimeout(()=>{U&&!U.isStreaming()&&U.continueConversation()},100)});ft.push(Of);let ls=()=>{Ot(!S,"user")},on=null,rn=null;if(I&&!E()){let c=r.find(p=>p.renderLauncher);if(c!=null&&c.renderLauncher){let p=c.renderLauncher({config:o,defaultRenderer:()=>Ra(o,ls).element,onToggle:ls});p&&(rn=p)}rn||(on=Ra(o,ls))}on?e.appendChild(on.element):rn&&e.appendChild(rn),dr(),Zr(),Lr(),as(U.isStreaming()),mt()==="follow"?Oo(!0):_s(),Qa(),B&&(!I||E()?setTimeout(()=>is(),0):S&&setTimeout(()=>is(),200));let js=()=>{var F,Ce,fe,te,ke,Ve,Te,ot,je,dt,pt,We,Re,ze,Ye,wt,H,He,Fe,ve,Nt,Ft;if(E()){yn(),dr();return}let c=Sn(o),p=(Ce=(F=o.launcher)==null?void 0:F.sidebarMode)!=null?Ce:!1,h=c||p||((te=(fe=o.launcher)==null?void 0:fe.fullHeight)!=null?te:!1),y=(ke=e.ownerDocument.defaultView)!=null?ke:window,L=(Te=(Ve=o.launcher)==null?void 0:Ve.mobileFullscreen)!=null?Te:!0,N=(je=(ot=o.launcher)==null?void 0:ot.mobileBreakpoint)!=null?je:640,_=y.innerWidth<=N,q=L&&_&&I;try{if(q){yo(),ms(e,o);return}if(C&&(C=!1,yo(),ms(e,o)),!I&&!c){pe.style.height="",pe.style.width="";return}if(!p&&!c){let Gt=(pt=(dt=o==null?void 0:o.launcher)==null?void 0:dt.width)!=null?pt:o==null?void 0:o.launcherWidth,Ct=Gt!=null?Gt:go;pe.style.width=Ct,pe.style.maxWidth=Ct}if(Po(),!h){let Gt=y.innerHeight,Ct=64,qt=(Re=(We=o.launcher)==null?void 0:We.heightOffset)!=null?Re:0,to=Math.max(200,Gt-Ct),an=Math.min(640,to),Qe=Math.max(200,an-qt);pe.style.height=`${Qe}px`}}finally{if(yn(),dr(),S&&I){let Ct=((ze=e.ownerDocument.defaultView)!=null?ze:window).innerWidth<=((wt=(Ye=o.launcher)==null?void 0:Ye.mobileBreakpoint)!=null?wt:640),qt=(He=(H=o.launcher)==null?void 0:H.sidebarMode)!=null?He:!1,to=(ve=(Fe=o.launcher)==null?void 0:Fe.mobileFullscreen)!=null?ve:!0,an=Sn(o)&&to&&Ct,Qe=qt||to&&Ct&&I||an;if(Qe&&!nn){let Pt=e.getRootNode(),pn=Pt instanceof ShadowRoot?Pt.host:e.closest(".persona-host");pn&&!tn&&(tn=gc(pn,(Ft=(Nt=o.launcher)==null?void 0:Nt.zIndex)!=null?Ft:In)),nn=fc(e.ownerDocument)}else Qe||(tn==null||tn(),tn=null,nn==null||nn(),nn=null)}}};js();let Gc=(Xd=e.ownerDocument.defaultView)!=null?Xd:window;if(Gc.addEventListener("resize",js),ft.push(()=>Gc.removeEventListener("resize",js)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{yn()});c.observe($e),ft.push(()=>c.disconnect())}eo=ge.scrollTop;let Yc=Zo(ge),Ff=()=>{let c=ge.getRootNode(),p=typeof c.getSelection=="function"?c.getSelection():null;return p!=null?p:ge.ownerDocument.getSelection()},Ml=()=>vg(Ff(),ge),Qc=()=>{let c=ge.scrollTop,p=Zo(ge),h=p<Yc;if(Yc=p,mt()!=="follow"){eo=c,Un();return}let{action:y,nextLastScrollTop:L}=qi({following:Zn.isFollowing(),currentScrollTop:c,lastScrollTop:eo,nearBottom:qr(ge,ns),userScrollThreshold:Ga,isAutoScrolling:Co||Tr||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(eo=L,y==="resume"){Ml()||Do();return}y==="pause"&&ss()};if(ge.addEventListener("scroll",Qc,{passive:!0}),ft.push(()=>ge.removeEventListener("scroll",Qc)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{ei()});c.observe(nt),c.observe(ge),ft.push(()=>c.disconnect())}let Xc=()=>{mt()==="follow"&&Zn.isFollowing()&&Ml()&&ss()},Jc=ge.ownerDocument;Jc.addEventListener("selectionchange",Xc),ft.push(()=>{Jc.removeEventListener("selectionchange",Xc)});let Zc=c=>{if(mt()!=="follow")return;let p=ji({following:Zn.isFollowing(),deltaY:c.deltaY,nearBottom:qr(ge,ns),resumeWhenNearBottom:!0});p==="pause"?ss():p==="resume"&&!Ml()&&Do()};ge.addEventListener("wheel",Zc,{passive:!0}),ft.push(()=>ge.removeEventListener("wheel",Zc)),Je.addEventListener("click",()=>{Er(),ge.scrollTop=ge.scrollHeight,eo=ge.scrollTop,Do(),Oo(!0),Un()}),ft.push(()=>Je.remove()),ft.push(()=>{Hs(),Er()});let ed=()=>{O&&(co&&(O.removeEventListener("click",co),co=null),A()?(O.style.display="",co=()=>{Ot(!1,"user")},O.addEventListener("click",co)):O.style.display="none")};ed(),(()=>{let{clearChatButton:c}=Be;c&&c.addEventListener("click",()=>{U.clearMessages(),qo.clear(),Do(),xs(Be.composerOverlay);try{localStorage.removeItem(Es),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Es}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Es)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let 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()})})(),Ht&&Ht.addEventListener("submit",W),ne==null||ne.addEventListener("keydown",Bt),ne==null||ne.addEventListener("input",Ze),ne==null||ne.addEventListener("paste",mn);let td=(Jd=e.ownerDocument)!=null?Jd:document;td.addEventListener("keydown",Vt,!0);let nd="persona-attachment-drop-active",Ks=0,Ll=()=>{Ks=0,j.classList.remove(nd)},cs=()=>{var c;return((c=o.attachments)==null?void 0:c.enabled)===!0&&St!==null},od=c=>{!pl(c.dataTransfer)||!cs()||(Ks++,Ks===1&&j.classList.add(nd))},rd=c=>{!pl(c.dataTransfer)||!cs()||(Ks--,Ks<=0&&Ll())},sd=c=>{!pl(c.dataTransfer)||!cs()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},ad=c=>{var h;if(!pl(c.dataTransfer)||!cs())return;c.preventDefault(),c.stopPropagation(),Ll();let p=Array.from((h=c.dataTransfer.files)!=null?h:[]);p.length!==0&&St.handleFiles(p)},ur=!0;j.addEventListener("dragenter",od,ur),j.addEventListener("dragleave",rd,ur),e.addEventListener("dragover",sd,ur),e.addEventListener("drop",ad,ur);let ci=e.ownerDocument,id=c=>{cs()&&c.preventDefault()},ld=c=>{cs()&&c.preventDefault()};ci.addEventListener("dragover",id),ci.addEventListener("drop",ld),ft.push(()=>{Ht&&Ht.removeEventListener("submit",W),ne==null||ne.removeEventListener("keydown",Bt),ne==null||ne.removeEventListener("input",Ze),ne==null||ne.removeEventListener("paste",mn),td.removeEventListener("keydown",Vt,!0)}),ft.push(()=>{j.removeEventListener("dragenter",od,ur),j.removeEventListener("dragleave",rd,ur),e.removeEventListener("dragover",sd,ur),e.removeEventListener("drop",ad,ur),ci.removeEventListener("dragover",id),ci.removeEventListener("drop",ld),Ll()}),ft.push(()=>{U.cancel()}),on?ft.push(()=>{on==null||on.destroy()}):rn&&ft.push(()=>{rn==null||rn.remove()});let dn={update(c){var En,Hn,Fo,xn,Dn,On,Br,Gs,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,Op,Fp,Np,_p,Vp,$p,Up,zp,qp,jp,Kp,Gp,Yp,Qp,Xp,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,Lu,Iu,Ru,Pu,Wu,Bu,Hu,Du,Ou,Fu,Nu,_u,Vu,$u,Uu,zu,qu,ju,Ku,Gu,Yu,Qu,Xu,Ju,Zu,em,tm,nm,om;let p=o.toolCall,h=o.messageActions,y=(En=o.layout)==null?void 0:En.messages,L=o.colorScheme,N=o.loadingIndicator,_=o.iterationDisplay,q=(Hn=o.features)==null?void 0:Hn.showReasoning,F=(Fo=o.features)==null?void 0:Fo.showToolCalls,Ce=(xn=o.features)==null?void 0:xn.toolCallDisplay,fe=(Dn=o.features)==null?void 0:Dn.reasoningDisplay;o={...o,...c},yo(),ms(e,o),cl(e,o),dl(e,o),Xn(),o.colorScheme!==L&&sr();let te=Ec.getForInstance(o.plugins);r.length=0,r.push(...te),I=(Br=(On=o.launcher)==null?void 0:On.enabled)!=null?Br:!0,R=(sp=(Gs=o.launcher)==null?void 0:Gs.autoExpand)!=null?sp:!1,me=(ip=(ap=o.features)==null?void 0:ap.showReasoning)!=null?ip:!0,de=(cp=(lp=o.features)==null?void 0:lp.showToolCalls)!=null?cp:!0,xe=(pp=(dp=o.features)==null?void 0:dp.scrollToBottom)!=null?pp:{};let ke=mt();De=(mp=(up=o.features)==null?void 0:up.scrollBehavior)!=null?mp:{},ke!==mt()&&(Er(),Do()),Io(),Un();let Ve=Ee;if(Ee=(fp=(gp=o.features)==null?void 0:gp.showEventStreamToggle)!=null?fp:!1,Ee&&!Ve){if(ye||(X=new Ha(le),ye=new Ba(se,X),be=be!=null?be:new Da,X.open().then(()=>ye==null?void 0:ye.restore()).catch(()=>{}),U.setSSEEventCallback((J,Tt)=>{var Ut;(Ut=o.onSSEEvent)==null||Ut.call(o,J,Tt),be==null||be.processEvent(J,Tt),ye.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:J,timestamp:Date.now(),payload:JSON.stringify(Tt)})})),!xt&&_e){let J=(bp=(hp=o.features)==null?void 0:hp.eventStream)==null?void 0:bp.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:"");xt=b("button",Tt),xt.style.width="28px",xt.style.height="28px",xt.style.color=Nn.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let Ut=Me("activity","18px","currentColor",1.5);Ut&&xt.appendChild(Ut);let ut=Be.clearChatButtonWrapper,Wt=Be.closeButtonWrapper,fn=ut||Wt;fn&&fn.parentNode===_e?_e.insertBefore(xt,fn):_e.appendChild(xt),xt.addEventListener("click",()=>{ae?bo():Vo()})}}else!Ee&&Ve&&(bo(),xt&&(xt.remove(),xt=null),ye==null||ye.clear(),X==null||X.destroy(),ye=null,X=null,be==null||be.reset(),be=null);if(((yp=o.launcher)==null?void 0:yp.enabled)===!1&&on&&(on.destroy(),on=null),((vp=o.launcher)==null?void 0:vp.enabled)===!1&&rn&&(rn.remove(),rn=null),((xp=o.launcher)==null?void 0:xp.enabled)!==!1&&!on&&!rn){let J=r.find(Tt=>Tt.renderLauncher);if(J!=null&&J.renderLauncher){let Tt=J.renderLauncher({config:o,defaultRenderer:()=>Ra(o,ls).element,onToggle:ls});Tt&&(rn=Tt,e.appendChild(rn))}rn||(on=Ra(o,ls),e.appendChild(on.element))}on&&on.update(o),Oe&&((wp=o.launcher)==null?void 0:wp.title)!==void 0&&(Oe.textContent=o.launcher.title),Ge&&((Cp=o.launcher)==null?void 0:Cp.subtitle)!==void 0&&(Ge.textContent=o.launcher.subtitle);let Te=(Sp=o.layout)==null?void 0:Sp.header;if((Te==null?void 0:Te.layout)!==w&&_e){let J=Te?Ji(o,Te,{showClose:A(),onClose:()=>Ot(!1,"user")}):jr({config:o,showClose:A(),onClose:()=>Ot(!1,"user")});_e.replaceWith(J.header),_e=J.header,ue=J.iconHolder,Oe=J.headerTitle,Ge=J.headerSubtitle,O=J.closeButton,w=Te==null?void 0:Te.layout}else if(Te&&(ue&&(ue.style.display=Te.showIcon===!1?"none":""),Oe&&(Oe.style.display=Te.showTitle===!1?"none":""),Ge&&(Ge.style.display=Te.showSubtitle===!1?"none":""),O&&(O.style.display=Te.showCloseButton===!1?"none":""),Be.clearChatButtonWrapper)){let J=Te.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 je=((Ap=o.layout)==null?void 0:Ap.showHeader)!==!1;_e&&(_e.style.display=je?"":"none");let dt=((Tp=o.layout)==null?void 0:Tp.showFooter)!==!1;$e&&($e.style.display=dt?"":"none"),yn(),Un(),I!==P?I?Ot(R,"auto"):(S=!0,dr()):R!==D&&Ot(R,"auto"),D=R,P=I,js(),ed();let Re=JSON.stringify(c.toolCall)!==JSON.stringify(p),ze=JSON.stringify(o.messageActions)!==JSON.stringify(h),Ye=JSON.stringify((kp=o.layout)==null?void 0:kp.messages)!==JSON.stringify(y),wt=((Ep=o.loadingIndicator)==null?void 0:Ep.render)!==(N==null?void 0:N.render)||((Mp=o.loadingIndicator)==null?void 0:Mp.renderIdle)!==(N==null?void 0:N.renderIdle)||((Lp=o.loadingIndicator)==null?void 0:Lp.showBubble)!==(N==null?void 0:N.showBubble),H=o.iterationDisplay!==_,He=((Rp=(Ip=o.features)==null?void 0:Ip.showReasoning)!=null?Rp:!0)!==(q!=null?q:!0)||((Wp=(Pp=o.features)==null?void 0:Pp.showToolCalls)!=null?Wp:!0)!==(F!=null?F:!0)||JSON.stringify((Bp=o.features)==null?void 0:Bp.toolCallDisplay)!==JSON.stringify(Ce)||JSON.stringify((Hp=o.features)==null?void 0:Hp.reasoningDisplay)!==JSON.stringify(fe);(Re||ze||Ye||wt||H||He)&&U&&(Ps++,Mr(nt,U.getMessages(),he));let ve=(Dp=o.launcher)!=null?Dp:{},Nt=(Op=ve.headerIconHidden)!=null?Op:!1,Ft=(Np=(Fp=o.layout)==null?void 0:Fp.header)==null?void 0:Np.showIcon,Gt=Nt||Ft===!1,Ct=ve.headerIconName,qt=(_p=ve.headerIconSize)!=null?_p:"48px";if(ue){let J=j.querySelector(".persona-border-b-persona-divider"),Tt=J==null?void 0:J.querySelector(".persona-flex-col");if(Gt)ue.style.display="none",J&&Tt&&!J.contains(Tt)&&J.insertBefore(Tt,J.firstChild);else{if(ue.style.display="",ue.style.height=qt,ue.style.width=qt,J&&Tt&&(J.contains(ue)?ue.nextSibling!==Tt&&(ue.remove(),J.insertBefore(ue,Tt)):J.insertBefore(ue,Tt)),Ct){let ut=parseFloat(qt)||24,Wt=Me(Ct,ut*.6,"#ffffff",2);Wt?ue.replaceChildren(Wt):ue.textContent=(Vp=ve.agentIconText)!=null?Vp:"\u{1F4AC}"}else if(ve.iconUrl){let ut=ue.querySelector("img");if(ut)ut.src=ve.iconUrl,ut.style.height=qt,ut.style.width=qt;else{let Wt=document.createElement("img");Wt.src=ve.iconUrl,Wt.alt="",Wt.className="persona-rounded-xl persona-object-cover",Wt.style.height=qt,Wt.style.width=qt,ue.replaceChildren(Wt)}}else{let ut=ue.querySelector("svg"),Wt=ue.querySelector("img");(ut||Wt)&&ue.replaceChildren(),ue.textContent=($p=ve.agentIconText)!=null?$p:"\u{1F4AC}"}let Ut=ue.querySelector("img");Ut&&(Ut.style.height=qt,Ut.style.width=qt)}}let to=(zp=(Up=o.layout)==null?void 0:Up.header)==null?void 0:zp.showTitle,an=(jp=(qp=o.layout)==null?void 0:qp.header)==null?void 0:jp.showSubtitle;if(Oe&&(Oe.style.display=to===!1?"none":""),Ge&&(Ge.style.display=an===!1?"none":""),O){((Gp=(Kp=o.layout)==null?void 0:Kp.header)==null?void 0:Gp.showCloseButton)===!1?O.style.display="none":O.style.display="";let Tt=(Yp=ve.closeButtonSize)!=null?Yp:"32px",Ut=(Qp=ve.closeButtonPlacement)!=null?Qp:"inline";O.style.height=Tt,O.style.width=Tt;let{closeButtonWrapper:ut}=Be,Wt=Ut==="top-right",fn=ut==null?void 0:ut.classList.contains("persona-absolute");if(ut&&Wt!==fn)if(ut.remove(),Wt)ut.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",j.style.position="relative",j.appendChild(ut);else{let gt=(Jp=(Xp=ve.clearChat)==null?void 0:Xp.placement)!=null?Jp:"inline",hn=(eu=(Zp=ve.clearChat)==null?void 0:Zp.enabled)!=null?eu:!0;ut.className=hn&>==="inline"?"":"persona-ml-auto";let zn=j.querySelector(".persona-border-b-persona-divider");zn&&zn.appendChild(ut)}if(O.style.color=ve.closeButtonColor||Nn.actionIconColor,ve.closeButtonBackgroundColor?(O.style.backgroundColor=ve.closeButtonBackgroundColor,O.classList.remove("hover:persona-bg-gray-100")):(O.style.backgroundColor="",O.classList.add("hover:persona-bg-gray-100")),ve.closeButtonBorderWidth||ve.closeButtonBorderColor){let gt=ve.closeButtonBorderWidth||"0px",hn=ve.closeButtonBorderColor||"transparent";O.style.border=`${gt} solid ${hn}`,O.classList.remove("persona-border-none")}else O.style.border="",O.classList.add("persona-border-none");ve.closeButtonBorderRadius?(O.style.borderRadius=ve.closeButtonBorderRadius,O.classList.remove("persona-rounded-full")):(O.style.borderRadius="",O.classList.add("persona-rounded-full")),ve.closeButtonPaddingX?(O.style.paddingLeft=ve.closeButtonPaddingX,O.style.paddingRight=ve.closeButtonPaddingX):(O.style.paddingLeft="",O.style.paddingRight=""),ve.closeButtonPaddingY?(O.style.paddingTop=ve.closeButtonPaddingY,O.style.paddingBottom=ve.closeButtonPaddingY):(O.style.paddingTop="",O.style.paddingBottom="");let Mn=(tu=ve.closeButtonIconName)!=null?tu:"x",Ao=(nu=ve.closeButtonIconText)!=null?nu:"\xD7";O.innerHTML="";let Fn=Me(Mn,"28px","currentColor",1);Fn?O.appendChild(Fn):O.textContent=Ao;let sn=(ou=ve.closeButtonTooltipText)!=null?ou:"Close chat",oo=(ru=ve.closeButtonShowTooltip)!=null?ru:!0;if(O.setAttribute("aria-label",sn),ut&&(ut._cleanupTooltip&&(ut._cleanupTooltip(),delete ut._cleanupTooltip),oo&&sn)){let gt=null,hn=()=>{if(gt||!O)return;let Hr=O.ownerDocument,Ys=Hr.body;if(!Ys)return;gt=No(Hr,"div","persona-clear-chat-tooltip"),gt.textContent=sn;let Qs=No(Hr,"div");Qs.className="persona-clear-chat-tooltip-arrow",gt.appendChild(Qs);let Dr=O.getBoundingClientRect();gt.style.position="fixed",gt.style.zIndex=String(vr),gt.style.left=`${Dr.left+Dr.width/2}px`,gt.style.top=`${Dr.top-8}px`,gt.style.transform="translate(-50%, -100%)",Ys.appendChild(gt)},zn=()=>{gt&>.parentNode&&(gt.parentNode.removeChild(gt),gt=null)};ut.addEventListener("mouseenter",hn),ut.addEventListener("mouseleave",zn),O.addEventListener("focus",hn),O.addEventListener("blur",zn),ut._cleanupTooltip=()=>{zn(),ut&&(ut.removeEventListener("mouseenter",hn),ut.removeEventListener("mouseleave",zn)),O&&(O.removeEventListener("focus",hn),O.removeEventListener("blur",zn))}}}let{clearChatButton:Qe,clearChatButtonWrapper:Pt}=Be;if(Qe){let J=(su=ve.clearChat)!=null?su:{},Tt=(au=J.enabled)!=null?au:!0,Ut=(lu=(iu=o.layout)==null?void 0:iu.header)==null?void 0:lu.showClearChat,ut=Ut!==void 0?Ut:Tt,Wt=(cu=J.placement)!=null?cu:"inline";if(Pt){Pt.style.display=ut?"":"none";let{closeButtonWrapper:fn}=Be;!E()&&fn&&!fn.classList.contains("persona-absolute")&&(ut?fn.classList.remove("persona-ml-auto"):fn.classList.add("persona-ml-auto"));let Mn=Wt==="top-right",Ao=Pt.classList.contains("persona-absolute");if(!E()&&Mn!==Ao&&ut){if(Pt.remove(),Mn)Pt.className="persona-absolute persona-top-4 persona-z-50",Pt.style.right="48px",j.style.position="relative",j.appendChild(Pt);else{Pt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Pt.style.right="";let sn=j.querySelector(".persona-border-b-persona-divider"),oo=Be.closeButtonWrapper;sn&&oo&&oo.parentElement===sn?sn.insertBefore(Pt,oo):sn&&sn.appendChild(Pt)}let Fn=Be.closeButtonWrapper;Fn&&!Fn.classList.contains("persona-absolute")&&(Mn?Fn.classList.add("persona-ml-auto"):Fn.classList.remove("persona-ml-auto"))}}if(ut){if(!E()){let gt=(du=J.size)!=null?du:"32px";Qe.style.height=gt,Qe.style.width=gt}let fn=(pu=J.iconName)!=null?pu:"refresh-cw",Mn=(uu=J.iconColor)!=null?uu:"";Qe.style.color=Mn||Nn.actionIconColor,Qe.innerHTML="";let Ao=E()?"14px":"20px",Fn=Me(fn,Ao,"currentColor",2);if(Fn&&Qe.appendChild(Fn),J.backgroundColor?(Qe.style.backgroundColor=J.backgroundColor,Qe.classList.remove("hover:persona-bg-gray-100")):(Qe.style.backgroundColor="",Qe.classList.add("hover:persona-bg-gray-100")),J.borderWidth||J.borderColor){let gt=J.borderWidth||"0px",hn=J.borderColor||"transparent";Qe.style.border=`${gt} solid ${hn}`,Qe.classList.remove("persona-border-none")}else Qe.style.border="",Qe.classList.add("persona-border-none");J.borderRadius?(Qe.style.borderRadius=J.borderRadius,Qe.classList.remove("persona-rounded-full")):(Qe.style.borderRadius="",Qe.classList.add("persona-rounded-full")),J.paddingX?(Qe.style.paddingLeft=J.paddingX,Qe.style.paddingRight=J.paddingX):(Qe.style.paddingLeft="",Qe.style.paddingRight=""),J.paddingY?(Qe.style.paddingTop=J.paddingY,Qe.style.paddingBottom=J.paddingY):(Qe.style.paddingTop="",Qe.style.paddingBottom="");let sn=(mu=J.tooltipText)!=null?mu:"Clear chat",oo=(gu=J.showTooltip)!=null?gu:!0;if(Qe.setAttribute("aria-label",sn),Pt&&(Pt._cleanupTooltip&&(Pt._cleanupTooltip(),delete Pt._cleanupTooltip),oo&&sn)){let gt=null,hn=()=>{if(gt||!Qe)return;let Hr=Qe.ownerDocument,Ys=Hr.body;if(!Ys)return;gt=No(Hr,"div","persona-clear-chat-tooltip"),gt.textContent=sn;let Qs=No(Hr,"div");Qs.className="persona-clear-chat-tooltip-arrow",gt.appendChild(Qs);let Dr=Qe.getBoundingClientRect();gt.style.position="fixed",gt.style.zIndex=String(vr),gt.style.left=`${Dr.left+Dr.width/2}px`,gt.style.top=`${Dr.top-8}px`,gt.style.transform="translate(-50%, -100%)",Ys.appendChild(gt)},zn=()=>{gt&>.parentNode&&(gt.parentNode.removeChild(gt),gt=null)};Pt.addEventListener("mouseenter",hn),Pt.addEventListener("mouseleave",zn),Qe.addEventListener("focus",hn),Qe.addEventListener("blur",zn),Pt._cleanupTooltip=()=>{zn(),Pt&&(Pt.removeEventListener("mouseenter",hn),Pt.removeEventListener("mouseleave",zn)),Qe&&(Qe.removeEventListener("focus",hn),Qe.removeEventListener("blur",zn))}}}}let pn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Lc],mo=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Oa.message,Oa.messageAndClick];M=Ic({parsers:pn,handlers:mo,getSessionMetadata:f,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),he=df(o,M,G),U.updateConfig(o),Mr(nt,U.getMessages(),he),Zr(),Lr(),as(U.isStreaming());let no=((fu=o.voiceRecognition)==null?void 0:fu.enabled)===!0,Ir=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Rr=((bu=(hu=o.voiceRecognition)==null?void 0:hu.provider)==null?void 0:bu.type)==="runtype";if(no&&(Ir||Rr))if(!Y||!vt){let J=Wf(o.voiceRecognition,o.sendButton);J&&(Y=J.micButton,vt=J.micButtonWrapper,jt.insertBefore(vt,_n),Y.addEventListener("click",li),Y.disabled=U.isStreaming())}else{let J=(yu=o.voiceRecognition)!=null?yu:{},Tt=(vu=o.sendButton)!=null?vu:{},Ut=(xu=J.iconName)!=null?xu:"mic",ut=(wu=Tt.size)!=null?wu:"40px",Wt=(Cu=J.iconSize)!=null?Cu:ut,fn=parseFloat(Wt)||24;Y.style.width=Wt,Y.style.height=Wt,Y.style.minWidth=Wt,Y.style.minHeight=Wt;let Mn=(Au=(Su=J.iconColor)!=null?Su:Tt.textColor)!=null?Au:"currentColor";Y.innerHTML="";let Ao=Me(Ut,fn,Mn,2);Ao?Y.appendChild(Ao):Y.textContent="\u{1F3A4}";let Fn=(Tu=J.backgroundColor)!=null?Tu:Tt.backgroundColor;Fn?Y.style.backgroundColor=Fn:Y.style.backgroundColor="",Mn?Y.style.color=Mn:Y.style.color="var(--persona-text, #111827)",J.borderWidth?(Y.style.borderWidth=J.borderWidth,Y.style.borderStyle="solid"):(Y.style.borderWidth="",Y.style.borderStyle=""),J.borderColor?Y.style.borderColor=J.borderColor:Y.style.borderColor="",J.paddingX?(Y.style.paddingLeft=J.paddingX,Y.style.paddingRight=J.paddingX):(Y.style.paddingLeft="",Y.style.paddingRight=""),J.paddingY?(Y.style.paddingTop=J.paddingY,Y.style.paddingBottom=J.paddingY):(Y.style.paddingTop="",Y.style.paddingBottom="");let sn=vt==null?void 0:vt.querySelector(".persona-send-button-tooltip"),oo=(ku=J.tooltipText)!=null?ku:"Start voice recognition";if(((Eu=J.showTooltip)!=null?Eu:!1)&&oo)if(sn)sn.textContent=oo,sn.style.display="";else{let hn=document.createElement("div");hn.className="persona-send-button-tooltip",hn.textContent=oo,vt==null||vt.insertBefore(hn,Y)}else sn&&(sn.style.display="none");vt.style.display="",Y.disabled=U.isStreaming()}else Y&&vt&&(vt.style.display="none",((Lu=(Mu=o.voiceRecognition)==null?void 0:Mu.provider)==null?void 0:Lu.type)==="runtype"?U.isVoiceActive()&&U.toggleVoice():ht&&vn());if(((Iu=o.attachments)==null?void 0:Iu.enabled)===!0)if(!Se||!at){let J=(Ru=o.attachments)!=null?Ru:{},Ut=(Wu=((Pu=o.sendButton)!=null?Pu:{}).size)!=null?Wu:"40px";et||(et=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),et.style.display="none",Ht.insertBefore(et,ne)),ce||(ce=document.createElement("input"),ce.type="file",ce.accept=((Bu=J.allowedTypes)!=null?Bu:Jo).join(","),ce.multiple=((Hu=J.maxFiles)!=null?Hu:4)>1,ce.style.display="none",ce.setAttribute("aria-label","Attach files"),Ht.insertBefore(ce,ne)),Se=b("div","persona-send-button-wrapper"),at=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),at.type="button",at.setAttribute("aria-label",(Du=J.buttonTooltipText)!=null?Du:"Attach file");let ut=(Ou=J.buttonIconName)!=null?Ou:"paperclip",Wt=Ut,fn=parseFloat(Wt)||40,Mn=Math.round(fn*.6);at.style.width=Wt,at.style.height=Wt,at.style.minWidth=Wt,at.style.minHeight=Wt,at.style.fontSize="18px",at.style.lineHeight="1",at.style.backgroundColor="transparent",at.style.color="var(--persona-primary, #111827)",at.style.border="none",at.style.borderRadius="6px",at.style.transition="background-color 0.15s ease",at.addEventListener("mouseenter",()=>{at.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),at.addEventListener("mouseleave",()=>{at.style.backgroundColor="transparent"});let Ao=Me(ut,Mn,"currentColor",1.5);Ao?at.appendChild(Ao):at.textContent="\u{1F4CE}",at.addEventListener("click",oo=>{oo.preventDefault(),ce==null||ce.click()}),Se.appendChild(at);let Fn=(Fu=J.buttonTooltipText)!=null?Fu:"Attach file",sn=b("div","persona-send-button-tooltip");sn.textContent=Fn,Se.appendChild(sn),Rt.append(Se),!St&&ce&&et&&(St=Sa.fromConfig(J),St.setPreviewsContainer(et),ce.addEventListener("change",async()=>{St&&(ce!=null&&ce.files)&&(await St.handleFileSelect(ce.files),ce.value="")})),j.querySelector(".persona-attachment-drop-overlay")||j.appendChild(pf(J.dropOverlay))}else{Se.style.display="";let J=(Nu=o.attachments)!=null?Nu:{};ce&&(ce.accept=((_u=J.allowedTypes)!=null?_u:Jo).join(","),ce.multiple=((Vu=J.maxFiles)!=null?Vu:4)>1),St&&St.updateConfig({allowedTypes:J.allowedTypes,maxFileSize:J.maxFileSize,maxFiles:J.maxFiles})}else Se&&(Se.style.display="none"),St&&St.clearAttachments(),($u=j.querySelector(".persona-attachment-drop-overlay"))==null||$u.remove();let Qt=(Uu=o.sendButton)!=null?Uu:{},Pr=(zu=Qt.useIcon)!=null?zu:!1,mr=(qu=Qt.iconText)!=null?qu:"\u2191",gr=Qt.iconName,Qo=(ju=Qt.tooltipText)!=null?ju:"Send message",Wr=(Ku=Qt.showTooltip)!=null?Ku:!1,So=(Gu=Qt.size)!=null?Gu:"40px",tt=Qt.backgroundColor,gn=Qt.textColor;if(Pr){if(qe.style.width=So,qe.style.height=So,qe.style.minWidth=So,qe.style.minHeight=So,qe.style.fontSize="18px",qe.style.lineHeight="1",qe.innerHTML="",gn?qe.style.color=gn:qe.style.color="var(--persona-button-primary-fg, #ffffff)",gr){let J=parseFloat(So)||24,Tt=(gn==null?void 0:gn.trim())||"currentColor",Ut=Me(gr,J,Tt,2);Ut?qe.appendChild(Ut):qe.textContent=mr}else qe.textContent=mr;qe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",tt?(qe.style.backgroundColor=tt,qe.classList.remove("persona-bg-persona-primary")):(qe.style.backgroundColor="",qe.classList.add("persona-bg-persona-primary"))}else qe.textContent=(Qu=(Yu=o.copy)==null?void 0:Yu.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",tt?(qe.style.backgroundColor=tt,qe.classList.remove("persona-bg-persona-accent")):qe.classList.add("persona-bg-persona-accent"),gn?qe.style.color=gn:qe.classList.add("persona-text-white");Qt.borderWidth?(qe.style.borderWidth=Qt.borderWidth,qe.style.borderStyle="solid"):(qe.style.borderWidth="",qe.style.borderStyle=""),Qt.borderColor?qe.style.borderColor=Qt.borderColor:qe.style.borderColor="",Qt.paddingX?(qe.style.paddingLeft=Qt.paddingX,qe.style.paddingRight=Qt.paddingX):(qe.style.paddingLeft="",qe.style.paddingRight=""),Qt.paddingY?(qe.style.paddingTop=Qt.paddingY,qe.style.paddingBottom=Qt.paddingY):(qe.style.paddingTop="",qe.style.paddingBottom="");let $t=_n==null?void 0:_n.querySelector(".persona-send-button-tooltip");if(Wr&&Qo)if($t)$t.textContent=Qo,$t.style.display="";else{let J=document.createElement("div");J.className="persona-send-button-tooltip",J.textContent=Qo,_n==null||_n.insertBefore(J,qe)}else $t&&($t.style.display="none");let _t=(tm=(Xu=o.layout)==null?void 0:Xu.contentMaxWidth)!=null?tm:E()?(em=(Zu=(Ju=o.launcher)==null?void 0:Ju.composerBar)==null?void 0:Zu.contentMaxWidth)!=null?em:"720px":void 0;_t?(nt.style.maxWidth=_t,nt.style.marginLeft="auto",nt.style.marginRight="auto",nt.style.width="100%",Ht&&(Ht.style.maxWidth=_t,Ht.style.marginLeft="auto",Ht.style.marginRight="auto"),kt&&(kt.style.maxWidth=_t,kt.style.marginLeft="auto",kt.style.marginRight="auto")):(nt.style.maxWidth="",nt.style.marginLeft="",nt.style.marginRight="",nt.style.width="",Ht&&(Ht.style.maxWidth="",Ht.style.marginLeft="",Ht.style.marginRight=""),kt&&(kt.style.maxWidth="",kt.style.marginLeft="",kt.style.marginRight=""));let bt=(nm=o.statusIndicator)!=null?nm:{},Xt=(om=bt.visible)!=null?om:!0;if(ln.style.display=Xt?"":"none",U){let J=U.getStatus();lt(ln,(Ut=>{var ut,Wt,fn,Mn;return Ut==="idle"?(ut=bt.idleText)!=null?ut:Ln.idle:Ut==="connecting"?(Wt=bt.connectingText)!=null?Wt:Ln.connecting:Ut==="connected"?(fn=bt.connectedText)!=null?fn:Ln.connected:Ut==="error"?(Mn=bt.errorText)!=null?Mn:Ln.error:Ln[Ut]})(J),bt,J)}ln.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Mt=bt.align==="left"?"persona-text-left":bt.align==="center"?"persona-text-center":"persona-text-right";ln.classList.add(Mt)},open(){A()&&Ot(!0,"api")},close(){A()&&Ot(!1,"api")},toggle(){A()&&Ot(!S,"api")},clearChat(){Wn=!1,U.clearMessages(),qo.clear(),Do();try{localStorage.removeItem(Es),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Es}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Es)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!ne||U.isStreaming()?!1:(!S&&A()&&Ot(!0,"system"),ne.value=c,ne.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(U.isStreaming())return!1;let p=(c==null?void 0:c.trim())||ne.value.trim();return p?(!S&&A()&&Ot(!0,"system"),ne.value="",ne.style.height="auto",U.sendMessage(p),!0):!1},startVoiceRecognition(){var p,h;return U.isStreaming()?!1:((h=(p=o.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype"?(U.isVoiceActive()||(!S&&A()&&Ot(!0,"system"),yt.manuallyDeactivated=!1,$n(),U.toggleVoice().then(()=>{yt.active=U.isVoiceActive(),po("user"),U.isVoiceActive()&&qs()})),!0):ht?!0:Cn()?(!S&&A()&&Ot(!0,"system"),yt.manuallyDeactivated=!1,$n(),Yt("user"),!0):!1},stopVoiceRecognition(){var c,p;return((p=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:p.type)==="runtype"?U.isVoiceActive()?(U.toggleVoice().then(()=>{yt.active=!1,yt.manuallyDeactivated=!0,$n(),po("user"),pr()}),!0):!1:ht?(yt.manuallyDeactivated=!0,$n(),vn("user"),!0):!1},injectMessage(c){return!S&&A()&&Ot(!0,"system"),U.injectMessage(c)},injectAssistantMessage(c){!S&&A()&&Ot(!0,"system");let p=U.injectAssistantMessage(c);return V&&(V=!1,$&&(clearTimeout($),$=null),setTimeout(()=>{U&&!U.isStreaming()&&U.continueConversation()},100)),p},injectUserMessage(c){return!S&&A()&&Ot(!0,"system"),U.injectUserMessage(c)},injectSystemMessage(c){return!S&&A()&&Ot(!0,"system"),U.injectSystemMessage(c)},injectMessageBatch(c){return!S&&A()&&Ot(!0,"system"),U.injectMessageBatch(c)},injectComponentDirective(c){return!S&&A()&&Ot(!0,"system"),U.injectComponentDirective(c)},injectTestMessage(c){!S&&A()&&Ot(!0,"system"),U.injectTestEvent(c)},async connectStream(c,p){return U.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&&bo()},isEventStreamVisible(){return ae},showArtifacts(){ho(o)&&(Wn=!1,Xn(),At==null||At.setMobileOpen(!0))},hideArtifacts(){ho(o)&&(Wn=!0,Xn())},upsertArtifact(c){return ho(o)?(Wn=!1,U.upsertArtifact(c)):null},selectArtifact(c){ho(o)&&U.selectArtifact(c)},clearArtifacts(){ho(o)&&U.clearArtifacts()},getArtifacts(){var c;return(c=U==null?void 0:U.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=U==null?void 0:U.getSelectedArtifactId())!=null?c:null},focusInput(){return I&&!S&&!E()||!ne?!1:(ne.focus(),!0)},async resolveApproval(c,p,h){let L=U.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"){U.resolveWebMcpApproval(L.id,p);return}return U.resolveApproval(L.approval,p,h)},getMessages(){return U.getMessages()},getStatus(){return U.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 A()&&S},isVoiceActive(){return yt.active},getState(){return{open:A()&&S,launcherEnabled:I,voiceActive:yt.active,streaming:U.isStreaming()}},showCSATFeedback(c){!S&&A()&&Ot(!0,"system");let p=nt.querySelector(".persona-feedback-container");p&&p.remove();let h=af({onSubmit:async(y,L)=>{var N;U.isClientTokenMode()&&await U.submitCSATFeedback(y,L),(N=c==null?void 0:c.onSubmit)==null||N.call(c,y,L)},onDismiss:c==null?void 0:c.onDismiss,...c});nt.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!S&&A()&&Ot(!0,"system");let p=nt.querySelector(".persona-feedback-container");p&&p.remove();let h=lf({onSubmit:async(y,L)=>{var N;U.isClientTokenMode()&&await U.submitNPSFeedback(y,L),(N=c==null?void 0:c.onSubmit)==null||N.call(c,y,L)},onDismiss:c==null?void 0:c.onDismiss,...c});nt.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,p){return U.submitCSATFeedback(c,p)},async submitNPSFeedback(c,p){return U.submitNPSFeedback(c,p)},destroy(){Ue!=null&&(clearInterval(Ue),Ue=null),ft.forEach(c=>c()),Ie.remove(),Xe==null||Xe.remove(),on==null||on.destroy(),rn==null||rn.remove(),co&&O.removeEventListener("click",co)}};if((((Zd=n==null?void 0:n.debugTools)!=null?Zd:!1)||!!o.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,p={controller:dn,getMessages:dn.getMessages,getStatus:dn.getStatus,getMetadata:dn.getPersistentMetadata,updateMetadata:dn.updatePersistentMetadata,clearHistory:()=>dn.clearChat(),setVoiceActive:h=>h?dn.startVoiceRecognition():dn.stopVoiceRecognition()};window.AgentWidgetBrowser=p,ft.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 F=q.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&dn.focusInput()};if(window.addEventListener("persona:focusInput",p),ft.push(()=>{window.removeEventListener("persona:focusInput",p)}),Ee){let q=Ce=>{let fe=Ce.detail;(!(fe!=null&&fe.instanceId)||fe.instanceId===c)&&dn.showEventStream()},F=Ce=>{let fe=Ce.detail;(!(fe!=null&&fe.instanceId)||fe.instanceId===c)&&dn.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",F),ft.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)&&dn.showArtifacts()},y=q=>{let F=q.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&dn.hideArtifacts()},L=q=>{let F=q.detail;F!=null&&F.instanceId&&F.instanceId!==c||F!=null&&F.artifact&&dn.upsertArtifact(F.artifact)},N=q=>{let F=q.detail;F!=null&&F.instanceId&&F.instanceId!==c||typeof(F==null?void 0:F.id)=="string"&&dn.selectArtifact(F.id)},_=q=>{let F=q.detail;(!(F!=null&&F.instanceId)||F.instanceId===c)&&dn.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",_),ft.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=xv(o.persistState);if(uo&&A()){let c=wv(uo.storage),p=`${uo.keyPrefix}widget-open`,h=`${uo.keyPrefix}widget-voice`,y=`${uo.keyPrefix}widget-voice-mode`;if(c){let L=((ep=uo.persist)==null?void 0:ep.openState)&&c.getItem(p)==="true",N=((tp=uo.persist)==null?void 0:tp.voiceState)&&c.getItem(h)==="true",_=((np=uo.persist)==null?void 0:np.voiceState)&&c.getItem(y)==="true";if(L&&setTimeout(()=>{dn.open(),setTimeout(()=>{var q;if(N||_)dn.startVoiceRecognition();else if((q=uo.persist)!=null&&q.focusInput){let F=e.querySelector("textarea");F&&F.focus()}},100)},0),(op=uo.persist)!=null&&op.openState&&(s.on("widget:opened",()=>{c.setItem(p,"true")}),s.on("widget:closed",()=>{c.setItem(p,"false")})),(rp=uo.persist)!=null&&rp.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)},F=()=>q();window.addEventListener("persona:clear-chat",F),ft.push(()=>{window.removeEventListener("persona:clear-chat",F)})}}}return u&&A()&&setTimeout(()=>{dn.open()},0),Yo(),dn};var Cv=(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},Sv=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Av=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Tv=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},mf=(e,t)=>{var o,r;let n=(r=(o=t==null?void 0:t.launcher)==null?void 0:o.enabled)!=null?r:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},Dc=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=""},gf=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Dc(e)},Wc=e=>{e.style.transition=""},Bc=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="",e.style.marginLeft=""},Hc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ul=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},kv=(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))},Ev=(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)},ff=(e,t,n,o,r,s,a)=>{var x,v,M,I,R,B;let i=Eo(s),d=i.reveal==="push";kv(e,t,n,o,d),Ev(e,t,n,o,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,u=(v=(x=s==null?void 0:s.launcher)==null?void 0:x.mobileFullscreen)!=null?v:!0,g=(I=(M=s==null?void 0:s.launcher)==null?void 0:M.mobileBreakpoint)!=null?I:640,f=l!=null?l.innerWidth<=g:!1;if(u&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Bc(t),Wc(o),gf(o),Hc(n),ul(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((B=(R=s==null?void 0:s.launcher)==null?void 0:R.zIndex)!=null?B:In),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.marginLeft="0",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"),gf(o),Sv(o,i.maxHeight),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Bc(t),Wc(o),Hc(n),ul(r,o);let D=i.animate?"transform 180ms ease":"none",P=i.side==="right"?"translateX(100%)":"translateX(-100%)",w=a?"translateX(0)":P;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=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",Wc(o),Dc(o),ul(r,o);let D=Cv(i.width,e.clientWidth),P=Math.max(0,e.clientWidth),w=i.animate?"margin-left 180ms ease":"none",C=i.side==="right"?a?-D:0:a?0:-D;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${P+D}px`,t.style.transition=w,t.style.marginLeft=`${C}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${P}px`,n.style.maxWidth=`${P}px`,n.style.minWidth=`${P}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.position="relative",o.style.top="",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="",Bc(t),Dc(o),Hc(n),ul(r,o);let D=i.reveal==="emerge";D?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let P=a?i.width:"0px",w=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",C=!a;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${P}`,o.style.width=P,o.style.maxWidth=P,o.style.minWidth=P,o.style.minHeight="0",Av(o,i.maxHeight),o.style.overflow=D||C?"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")}},Mv=(e,t)=>{let n=e.ownerDocument.createElement("div");return mf(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){mf(n,o)},destroy(){n.remove()}}},Lv=(e,t)=>{var B,D,P,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"),u=n.createElement("div"),g=(D=(B=t==null?void 0:t.launcher)==null?void 0:B.enabled)==null||D?(w=(P=t==null?void 0:t.launcher)==null?void 0:P.autoExpand)!=null?w:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",l.appendChild(u),o.insertBefore(a,e),d.appendChild(e);let f=null,m=()=>{f==null||f.disconnect(),f=null},x=()=>{m(),Eo(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{ff(a,i,d,l,u,t,g)}),f.observe(a))},v=!1,M=()=>{ff(a,i,d,l,u,t,g),x(),g&&!v&&a.dataset.personaDockMobileFullscreen!=="true"&&(v=!0,Tv(a,Eo(t)))},I=a.ownerDocument.defaultView,R=()=>{M()};return I==null||I.addEventListener("resize",R),Eo(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),M(),{mode:"docked",host:u,shell:a,syncWidgetState(C){let E=C.launcherEnabled?C.open:!0;g!==E&&(g=E,M())},updateConfig(C){var E,A;t=C,((A=(E=t==null?void 0:t.launcher)==null?void 0:E.enabled)!=null?A:!0)===!1&&(g=!0),M()},destroy(){I==null||I.removeEventListener("resize",R),m(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},hf=(e,t)=>Sn(t)?Lv(e,t):Mv(e,t);var Yr={desktop:{w:1280,h:800},mobile:{w:390,h:844}},ml=.15,gl=1.5,Fa="persona-preview-shell-theme",Oc={load:()=>null,save:()=>{},clear:()=>{}},Fc=["How do I get started?","Pricing & plans","Talk to support"];function Na(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Nc(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 fl(e){let t=Nc(e);return`* { box-sizing: border-box; }
|
|
1
|
+
"use strict";var We=Object.defineProperty;var eo=Object.getOwnPropertyDescriptor;var to=Object.getOwnPropertyNames;var oo=Object.prototype.hasOwnProperty;var ao=(e,t)=>{for(var o in t)We(e,o,{get:t[o],enumerable:!0})},ro=(e,t,o,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of to(t))!oo.call(e,r)&&r!==o&&We(e,r,{get:()=>t[r],enumerable:!(a=eo(t,r))||a.enumerable});return e};var no=e=>ro(We({},"__esModule",{value:!0}),e);var Ca={};ao(Ca,{ADVANCED_TOKENS_SECTION:()=>et,ALL_ROLES:()=>P,ALL_TABS:()=>Ee,BRAND_PALETTE_SECTION:()=>Ze,BUILT_IN_PRESETS:()=>tt,COLORS_SECTIONS:()=>Et,COLOR_FAMILIES:()=>Ce,COMPONENTS_SECTIONS:()=>Ge,COMPONENT_COLOR_SECTIONS:()=>je,COMPONENT_SHAPE_SECTIONS:()=>Ue,CONFIGURE_SECTIONS:()=>Ye,CONFIGURE_SUB_GROUPS:()=>ce,CONTRAST_PAIRS:()=>j,CSS_NAMED_COLORS:()=>me,DEVICE_DIMENSIONS:()=>Lt,HOME_SUGGESTION_CHIPS:()=>at,INTERFACE_ROLES_SECTION:()=>Je,MOCK_BROWSER_CONTENT:()=>st,MOCK_WORKSPACE_CONTENT:()=>lt,PALETTE_SECTION:()=>Ct,PREVIEW_STORAGE_ADAPTER:()=>ot,RADIUS_PRESETS:()=>G,ROLE_ASSISTANT_MESSAGES:()=>te,ROLE_BORDERS:()=>se,ROLE_FAMILIES:()=>X,ROLE_FAMILY_LABELS:()=>vt,ROLE_HEADER:()=>Q,ROLE_INPUT:()=>re,ROLE_INTENSITIES:()=>E,ROLE_LINKS_FOCUS:()=>ne,ROLE_PRIMARY_ACTIONS:()=>oe,ROLE_SCROLL_TO_BOTTOM:()=>ae,ROLE_SURFACES:()=>J,ROLE_USER_MESSAGES:()=>ee,SEMANTIC_COLORS_SECTION:()=>At,SHADE_KEYS:()=>B,SHELL_STYLE_ID:()=>de,STATUS_COLORS_SECTION:()=>Qe,STATUS_PALETTE_SECTION:()=>Xe,STYLE_SECTIONS:()=>D,STYLE_SECTIONS_V2:()=>It,THEME_EDITOR_PRESETS:()=>U,THEME_SECTION:()=>Ke,ThemeEditorState:()=>ke,ZOOM_MAX:()=>Dt,ZOOM_MIN:()=>Bt,appendPreviewTranscriptEntry:()=>Ft,applySceneConfig:()=>Oe,applyShellTheme:()=>_t,buildPreviewConfig:()=>$t,buildPreviewConfigWithMessages:()=>zt,buildShellCss:()=>Pe,buildSrcdoc:()=>Mt,buildSummary:()=>V,buildTranscriptStreamFrames:()=>Nt,coerceColor:()=>_,coerceFamily:()=>he,coerceIntensity:()=>ge,coerceRadius:()=>ye,coerceRoundnessStyle:()=>be,coerceScheme:()=>fe,convertFromPx:()=>wt,convertToPx:()=>yt,createPreviewMessages:()=>ct,createPreviewTranscriptEntry:()=>Ve,createThemeEditorTools:()=>mt,detectRoleAssignment:()=>Ae,escapeHtml:()=>rt,findSection:()=>Vt,formatCssValue:()=>ve,generateColorScale:()=>Re,getPreviewTranscriptPresetLabel:()=>Wt,getShellPalette:()=>nt,getThemeEditorPreset:()=>Ie,hexToHsl:()=>Ne,hslToHex:()=>He,isValidHex:()=>Se,normalizeColorValue:()=>$,paletteColorPath:()=>kt,parseCssValue:()=>xe,presetStreamsText:()=>it,quickContrastWarnings:()=>M,resolveRoleAssignment:()=>le,resolveThemeColorPath:()=>$e,rgbToHex:()=>Te,runContrastChecks:()=>Y,scopeSection:()=>Ot,tokenRefDisplayName:()=>xt,toolResult:()=>I,wcagContrastRatio:()=>Z});module.exports=no(Ca);var N="min(440px, calc(100vw - 24px))",we="440px",lo={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:N,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)"},H={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:lo,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};var io={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"}},co={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"}},po={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:N,maxWidth:we,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 uo(e){let t=[],o=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||o.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||o.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:o}}function bt(e,t){let o={...e};for(let[a,r]of Object.entries(t)){let n=o[a];n&&typeof n=="object"&&!Array.isArray(n)&&r&&typeof r=="object"&&!Array.isArray(r)?o[a]=bt(n,r):o[a]=r}return o}function mo(e,t){return t?bt(e,t):e}function S(e,t={}){var r,n,l,i,c,m,g,w,k,C,A,W,F;let o={palette:io,semantic:co,components:po},a={palette:{...o.palette,...e==null?void 0:e.palette,colors:{...o.palette.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors},spacing:{...o.palette.spacing,...(n=e==null?void 0:e.palette)==null?void 0:n.spacing},typography:{...o.palette.typography,...(l=e==null?void 0:e.palette)==null?void 0:l.typography},shadows:{...o.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...o.palette.borders,...(c=e==null?void 0:e.palette)==null?void 0:c.borders},radius:{...o.palette.radius,...(m=e==null?void 0:e.palette)==null?void 0:m.radius}},semantic:{...o.semantic,...e==null?void 0:e.semantic,colors:{...o.semantic.colors,...(g=e==null?void 0:e.semantic)==null?void 0:g.colors,interactive:{...o.semantic.colors.interactive,...(k=(w=e==null?void 0:e.semantic)==null?void 0:w.colors)==null?void 0:k.interactive},feedback:{...o.semantic.colors.feedback,...(A=(C=e==null?void 0:e.semantic)==null?void 0:C.colors)==null?void 0:A.feedback}},spacing:{...o.semantic.spacing,...(W=e==null?void 0:e.semantic)==null?void 0:W.spacing},typography:{...o.semantic.typography,...(F=e==null?void 0:e.semantic)==null?void 0:F.typography}},components:mo(o.components,e==null?void 0:e.components)};if(t.validate!==!1){let K=uo(a);if(!K.valid)throw new Error(`Theme validation failed: ${K.errors.map(ht=>ht.message).join(", ")}`)}if(t.plugins)for(let K of t.plugins)a=K.transform(a);return a}function Fe(e,t){let o=t.split("."),a=e;for(let r of o){if(a==null)return;a=a[r]}return a}function L(e,t,o){var i;let a=t.split(".");if(a.length===1)return{...e,[a[0]]:o};let[r,...n]=a,l=e;return{...l,[r]:L((i=l==null?void 0:l[r])!=null?i:{},n.join("."),o)}}var ke=class{constructor(t,o,a){this.listeners=[];this.history=[];this.historyIndex=-1;this.suppressHistory=!1;var n;let r=(n=a==null?void 0:a.mergeDefaults)!=null?n:!0;this.config=r?{...H,...o}:o!=null?o:H,this.theme=S(t,{validate:!1}),this.syncThemeIntoConfig(),this.pushHistorySnapshot(this.exportSnapshot(),!0)}get(t){var o;return t.startsWith("theme.")?Fe(this.theme,t.replace("theme.","")):t.startsWith("darkTheme.")?Fe((o=this.config.darkTheme)!=null?o:{},t.replace("darkTheme.","")):Fe(this.config,t)}getTheme(){return this.theme}getConfig(){return this.config}set(t,o){var a;if(t.startsWith("theme.")){let r=t.replace("theme.","");this.theme=L(this.theme,r,o),this.syncThemeIntoConfig()}else if(t.startsWith("darkTheme.")){let r=t.replace("darkTheme.",""),n=(a=this.config.darkTheme)!=null?a:S();this.config={...this.config,darkTheme:L(n,r,o)}}else this.config=L(this.config,t,o);this.recordHistory(),this.notifyListeners()}setBatch(t){var n;let o=!1,a=!1,r=!1;for(let[l,i]of Object.entries(t))if(l.startsWith("theme.")){let c=l.replace("theme.","");this.theme=L(this.theme,c,i),o=!0}else if(l.startsWith("darkTheme.")){let c=l.replace("darkTheme.",""),m=(n=this.config.darkTheme)!=null?n:S();this.config={...this.config,darkTheme:L(m,c,i)},a=!0}else this.config=L(this.config,l,i),r=!0;o&&this.syncThemeIntoConfig(),(o||a||r)&&(this.recordHistory(),this.notifyListeners())}setTheme(t){this.theme=t,this.syncThemeIntoConfig(),this.recordHistory(),this.notifyListeners()}setFullConfig(t,o){this.config={...t},o&&(this.theme=o),this.syncThemeIntoConfig(),this.recordHistory(),this.notifyListeners()}importSnapshot(t){var r,n;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Snapshot must be a JSON object");let o=t;if("config"in o||"theme"in o||o.version===2){let l=(r=o.config)!=null?r:this.config,i=S((n=o.theme)!=null?n:this.theme,{validate:!1});this.setFullConfig(l,i);return}let a=S(o,{validate:!1});this.setTheme(a)}resetToDefaults(){this.config={...H},this.theme=S(),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 o=this.listeners.indexOf(t);o>=0&&this.listeners.splice(o,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,o=!1){if(this.suppressHistory)return;let a=JSON.stringify(t),r=this.historyIndex>=0&&this.history[this.historyIndex]?JSON.stringify(this.history[this.historyIndex]):null;if(o&&this.historyIndex>=0){this.history[this.historyIndex]=t;return}a!==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=S(t.theme,{validate:!1}),this.syncThemeIntoConfig(),this.suppressHistory=!1,this.notifyListeners()}};function xe(e){let t=e.trim();if(t==="9999px")return{value:100,unit:"px"};let o=t.match(/^([\d.]+)(px|rem)$/);if(!o){let a=parseFloat(t);return{value:isNaN(a)?0:a,unit:"px"}}return{value:parseFloat(o[1]),unit:o[2]}}function ve(e,t){return t==="rem"?`${e}rem`:`${e}px`}function yt(e,t){return t==="rem"?e*16:e}function wt(e,t){return t==="rem"?e/16:e}function $(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 Se(e){return/^#[0-9A-Fa-f]{6}$/.test(e)}function Te(e){let t=e.trim().toLowerCase().match(/^rgba?\(([^)]+)\)$/);if(!t)return null;let o=t[1].split(",").map(c=>c.trim());if(o.length<3)return null;let a=c=>{let m=c.endsWith("%"),g=parseFloat(m?c.slice(0,-1):c);return Number.isFinite(g)?Math.max(0,Math.min(255,Math.round(m?g/100*255:g))):NaN},r=a(o[0]),n=a(o[1]),l=a(o[2]);if(!Number.isFinite(r)||!Number.isFinite(n)||!Number.isFinite(l))return null;let i=c=>c.toString(16).padStart(2,"0");return`#${i(r)}${i(n)}${i(l)}`}function Z(e,t){let o=n=>{var m;let l=$(n),i=l.startsWith("rgb")?(m=Te(l))!=null?m:"#000000":l,c=[1,3,5].map(g=>{let w=parseInt(i.slice(g,g+2),16)/255;return w<=.03928?w/12.92:Math.pow((w+.055)/1.055,2.4)});return .2126*c[0]+.7152*c[1]+.0722*c[2]},a=o(e),r=o(t);return(Math.max(a,r)+.05)/(Math.min(a,r)+.05)}function Ne(e){var k;let t=$(e),o=t.startsWith("rgb")?(k=Te(t))!=null?k:"#000000":t,a=parseInt(o.slice(1,3),16)/255,r=parseInt(o.slice(3,5),16)/255,n=parseInt(o.slice(5,7),16)/255,l=Math.max(a,r,n),i=Math.min(a,r,n),c=(l+i)/2;if(l===i)return{h:0,s:0,l:c};let m=l-i,g=c>.5?m/(2-l-i):m/(l+i),w;switch(l){case a:w=((r-n)/m+(r<n?6:0))/6;break;case r:w=((n-a)/m+2)/6;break;default:w=((a-r)/m+4)/6;break}return{h:w*360,s:g,l:c}}function He(e,t,o){let a=(e%360+360)%360,r=(1-Math.abs(2*o-1))*t,n=r*(1-Math.abs(a/60%2-1)),l=o-r/2,i,c,m;a<60?[i,c,m]=[r,n,0]:a<120?[i,c,m]=[n,r,0]:a<180?[i,c,m]=[0,r,n]:a<240?[i,c,m]=[0,n,r]:a<300?[i,c,m]=[n,0,r]:[i,c,m]=[r,0,n];let g=w=>{let k=Math.round((w+l)*255).toString(16);return k.length===1?"0"+k:k};return`#${g(i)}${g(c)}${g(m)}`}function Re(e){let{h:t,s:o,l:a}=Ne(e),r={50:.97,100:.94,200:.87,300:.77,400:.64,500:a,600:Math.max(.05,a-.1),700:Math.max(.05,a-.2),800:Math.max(.05,a-.28),900:Math.max(.05,a-.35),950:Math.max(.03,a-.42)},n={50:Math.min(1,o*.85),100:Math.min(1,o*.9),200:Math.min(1,o*.95),300:o,400:o,500:o,600:Math.min(1,o*1.05),700:Math.min(1,o*1.05),800:Math.min(1,o*1),900:Math.min(1,o*.95),950:Math.min(1,o*.9)},l={};for(let[i,c]of Object.entries(r)){let m=n[i];l[i]=He(t,m,c)}return l}var B=["50","100","200","300","400","500","600","700","800","900","950"],Ce=["primary","secondary","accent","gray","success","warning","error","info"];function kt(e,t){return`palette.colors.${e}.${t}`}function $e(e,t,o=0){if(o>5)return"#cbd5e1";let a=e(t);return typeof a!="string"?"#cbd5e1":a.startsWith("#")||a.startsWith("rgb")||a==="transparent"?a:a.startsWith("palette.")||a.startsWith("semantic.")||a.startsWith("components.")?$e(e,`theme.${a}`,o+1):"#cbd5e1"}function xt(e){if(!e.startsWith("palette.")&&!e.startsWith("semantic."))return e;let t=e.split(".");if(t[0]==="palette"&&t[1]==="colors"){let o=t[2],a=t[3];return`${o.charAt(0).toUpperCase()+o.slice(1)} ${a}`}return t[0]==="semantic"?t.slice(1).map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join(" "):t[t.length-1]}var E=[{id:"solid",label:"Solid"},{id:"soft",label:"Soft"}],X=["primary","secondary","accent","gray"],vt={primary:"Primary",secondary:"Secondary",accent:"Accent",gray:"Neutral"},J={roleId:"role-surfaces",helper:"Page and panel backgrounds",previewZone:"container",intensities:E,targets:[{path:"semantic.colors.background",kind:"background"},{path:"semantic.colors.surface",kind:"background"},{path:"semantic.colors.container",kind:"background"}]},Q={roleId:"role-header",helper:"Widget header bar",previewZone:"header",intensities:E,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"}]},ee={roleId:"role-user-messages",helper:"User chat bubbles",previewZone:"user-message",intensities:E,targets:[{path:"components.message.user.background",kind:"background"},{path:"components.message.user.text",kind:"foreground"}]},te={roleId:"role-assistant-messages",helper:"Assistant chat bubbles",previewZone:"assistant-message",intensities:E,targets:[{path:"components.message.assistant.background",kind:"background"},{path:"components.message.assistant.text",kind:"foreground"}]},oe={roleId:"role-primary-actions",helper:"Send button and primary buttons",intensities:E,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"}]},ae={roleId:"role-scroll-to-bottom",helper:"Scroll-to-bottom affordances in transcript and event stream",intensities:E,targets:[{path:"components.scrollToBottom.background",kind:"background"},{path:"components.scrollToBottom.foreground",kind:"foreground"},{path:"components.scrollToBottom.border",kind:"border"}]},re={roleId:"role-input",helper:"Message input field",previewZone:"composer",intensities:E,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"}]},ne={roleId:"role-links-focus",helper:"Links, focus rings, and interactive highlights",intensities:E,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"}]},se={roleId:"role-borders",helper:"Borders, dividers, and separators",intensities:E,targets:[{path:"semantic.colors.border",kind:"border"},{path:"semantic.colors.divider",kind:"border"}]},P=[J,Q,ee,te,oe,ae,re,ne,se];function le(e,t,o){let a={},r=e==="neutral"?"gray":e;for(let n of o.targets){let l=ho(r,t,n,o.roleId);a[`theme.${n.path}`]=l,a[`darkTheme.${n.path}`]=l}if(o.roleId==="role-primary-actions"){let n=t==="solid"?`palette.colors.${r}.700`:`palette.colors.${r}.200`;a["theme.semantic.colors.interactive.hover"]=n,a["darkTheme.semantic.colors.interactive.hover"]=n}return a}function ho(e,t,o,a){let r=t==="solid";if(a==="role-header")return go(e,r,o);if(a==="role-input")return fo(e,r,o);switch(o.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 go(e,t,o){let a=o.path;return a.endsWith(".background")?t?`palette.colors.${e}.500`:`palette.colors.${e}.${e==="gray"?"50":"100"}`:a.endsWith(".border")?t?`palette.colors.${e}.600`:`palette.colors.${e}.200`:a.endsWith(".iconBackground")?t?`palette.colors.${e}.${e==="gray"?"700":"600"}`:`palette.colors.${e}.500`:a.endsWith(".iconForeground")?t?`palette.colors.${e}.50`:`palette.colors.${e}.50`:a.endsWith(".titleForeground")?t?`palette.colors.${e}.50`:`palette.colors.${e}.${e==="gray"?"900":"700"}`:a.endsWith(".subtitleForeground")?t?`palette.colors.${e}.200`:`palette.colors.${e}.500`:a.endsWith(".actionIconForeground")?t?`palette.colors.${e}.200`:`palette.colors.${e}.500`:`palette.colors.${e}.500`}function fo(e,t,o){let a=o.path;return a.endsWith(".background")?t?`palette.colors.${e}.${e==="gray"?"100":"50"}`:`palette.colors.${e}.50`:a.endsWith(".placeholder")?`palette.colors.${e}.400`:a.endsWith(".border")||a.endsWith(".ring")?t?`palette.colors.${e}.500`:`palette.colors.${e}.400`:`palette.colors.${e}.500`}var bo=/^palette\.colors\.(\w+)\.(\d+)$/;function Ae(e,t){var i,c;let o=(i=t.targets.find(m=>m.kind==="background"))!=null?i:t.targets[0];if(!o)return null;let r=String((c=e(o.path))!=null?c:"").match(bo);if(!r)return null;let n=r[1],l=X.includes(n)?n:null;if(!l)return null;for(let m of["solid","soft"]){let g=le(l,m,t);if(t.targets.every(k=>{var A;return String((A=e(k.path))!=null?A:"")===g[`theme.${k.path}`]}))return{family:l,intensity:m}}return null}var yo={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"}]}]},wo={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"}]},ko={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"}}]},xo={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)"}]}]},vo={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"}]}]},So={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"}}]},To={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)"}]},Ro={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"}]}]},D=[wo,ko,vo,xo,yo,So,To,Ro];function Tt(){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:Ce.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 Rt={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"}}]},Ct=Tt(),At=Rt,Et=[Tt(),Rt],Co={id:"comp-panel",title:"Panel",collapsed:!1,fields:[{id:"panel-width",label:"Width",type:"text",path:"theme.components.panel.width",defaultValue:N},{id:"panel-max-width",label:"Max Width",type:"text",path:"theme.components.panel.maxWidth",defaultValue:we},{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"}]}]},Ao={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"}]}]},Eo={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"}]}]},Io={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"}]}]},Po={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"}]}]},Vo={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"}}]},Oo={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"}}]},Lo={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"}}]},Bo={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"}}]},Do={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"}]},z=[{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"}],ze="0 5px 15px rgba(15, 23, 42, 0.08)",St=[{value:ze,label:"Default"},...z],_o={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:z},{id:"shadow-msg-assistant",label:"Assistant Message",type:"select",path:"theme.components.message.assistant.shadow",defaultValue:"palette.shadows.sm",options:z},{id:"shadow-tool-bubble",label:"Tool Call Bubble",type:"select",path:"theme.components.toolBubble.shadow",defaultValue:"palette.shadows.sm",options:z},{id:"shadow-reasoning-bubble",label:"Reasoning Bubble",type:"select",path:"theme.components.reasoningBubble.shadow",defaultValue:"palette.shadows.sm",options:z},{id:"shadow-approval",label:"Approval Bubble",type:"select",path:"theme.components.approval.requested.shadow",defaultValue:ze,options:St},{id:"shadow-intro-card",label:"Intro Card",type:"select",path:"theme.components.introCard.shadow",defaultValue:ze,options:St},{id:"shadow-composer",label:"Composer",type:"select",path:"theme.components.composer.shadow",defaultValue:"palette.shadows.none",options:z}]},Ue=[Co,Ao,Eo,Io,Po,_o],je=[Vo,Oo,Lo,Bo,Do],Ge=[...Ue,...je],qe=1024*1024,Mo=["What can you help me with?","Tell me about your features","How does this work?"],ie={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 Wo(e){return Number(e)*qe}function Fo(e){let t=Number(e);return Number.isFinite(t)?t>1024?String(Math.round(t/qe)):String(t):"10"}function No(e){var t;return(t=ie[String(e)])!=null?t:ie.images}function Ho(e){let t=Array.isArray(e)?e:ie.images,o=[...new Set(t)].sort();for(let[a,r]of Object.entries(ie)){let n=[...r].sort();if(o.length===n.length&&o.every((l,i)=>l===n[i]))return a}return o.some(a=>a.startsWith("application/vnd")||a==="application/msword")?"all":o.some(a=>a==="text/plain"||a==="text/markdown"||a==="text/csv")?"images-text-pdf":o.includes("application/pdf")?"images-pdf":"images"}var $o={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"}]},zo={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:Mo}]},Uo={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:""}]},jo={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}]},Go={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"}]}]},qo={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-read-aloud",label:"Show Read Aloud",type:"toggle",path:"messageActions.showReadAloud",defaultValue:!1},{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"}]}]},Yo={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:N},{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"}]},Ko={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:""}]},Zo={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"}]},Xo={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"}]},Jo={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"}]},Qo={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"}]},ea={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:""}]},ta={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: stream every character"},{value:"word",label:"Word: hold until whitespace"},{value:"line",label:"Line: 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: snappy"},{value:"80",label:"80ms"},{value:"120",label:"120ms (default)"},{value:"200",label:"200ms"},{value:"320",label:"320ms"},{value:"480",label:"480ms: 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: slow"}],formatValue:e=>String(e!=null?e:1800),parseValue:e=>Number(e)}]},oa={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*qe,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:Fo,parseValue:Wo},{id:"attach-types",label:"Allowed File Types",type:"select",path:"attachments.allowedTypes",defaultValue:ie.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:Ho,parseValue:No}]},aa={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"}]}]},ra={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}]},na={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"}]}]},sa={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}]},la={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}]},ce=[{label:"Content",sections:[$o,zo]},{label:"Layout",sections:[Uo,jo,Go,qo]},{label:"Widget",sections:[Yo,Ko,Zo,Xo,Jo,Qo]},{label:"Features",sections:[ea,ta,oa,aa,ra]},{label:"Developer",collapsedByDefault:!0,sections:[na,sa,la]}],Ye=ce.flatMap(e=>e.sections),Ke={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"}]}]},Ze={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"}]},Xe={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"}]},Je={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:J},{id:"role-header",label:"Header",type:"role-assignment",path:"theme.components.header.background",roleAssignment:Q},{id:"role-user-messages",label:"User Messages",type:"role-assignment",path:"theme.components.message.user.background",roleAssignment:ee},{id:"role-assistant-messages",label:"Assistant Messages",type:"role-assignment",path:"theme.components.message.assistant.background",roleAssignment:te},{id:"role-primary-actions",label:"Primary Actions",type:"role-assignment",path:"theme.components.button.primary.background",roleAssignment:oe},{id:"role-scroll-to-bottom",label:"Scroll To Bottom",type:"role-assignment",path:"theme.components.scrollToBottom.background",roleAssignment:ae},{id:"role-input",label:"Input Field",type:"role-assignment",path:"theme.components.input.background",roleAssignment:re},{id:"role-links-focus",label:"Links & Focus",type:"role-assignment",path:"theme.semantic.colors.accent",roleAssignment:ne},{id:"role-borders",label:"Borders & Dividers",type:"role-assignment",path:"theme.semantic.colors.border",roleAssignment:se}]},Qe={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"}}]},et={id:"advanced-tokens",title:"Advanced Tokens",description:"Override individual semantic and component values when you need precise control.",collapsed:!0,fields:[]},It=[Ke,Ze,Xe,Je,Qe,et],Ee=[{id:"style",label:"Style",sections:D},{id:"design-system",label:"Design System",sections:Ge},{id:"configure",label:"Configure",sections:Ye}];function Pt(e,t){return e.startsWith("theme.")?e.replace(/^theme\./,`${t}.`):e}function ia(e,t,o){return{...e,id:`${o}-${e.id}`,path:Pt(e.path,t)}}function Vt(e,t){let o=e.find(a=>a.id===t);if(!o)throw new Error(`Section "${t}" not found in definitions`);return o}function Ot(e,t,o,a=e.collapsed){var l;let r=o==="light"?"Light":"Dark",n=o==="light"?"Applies when the widget is in light mode.":"Applies when the widget is in dark mode.";return{...e,id:`${o}-${e.id}`,title:`${r} ${e.title}`,description:e.description?`${n} ${e.description}`:n,collapsed:a,fields:e.fields.map(i=>ia(i,t,o)),presets:(l=e.presets)==null?void 0:l.map(i=>({...i,id:`${o}-${i.id}`,values:Object.fromEntries(Object.entries(i.values).map(([c,m])=>[Pt(c,t),m]))}))}}var tt=[{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"]}],U=[...tt];function Ie(e){return U.find(t=>t.id===e)}var Lt={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Bt=.15,Dt=1.5,de="persona-preview-shell-theme",ot={load:()=>null,save:()=>{},clear:()=>{}},at=["How do I get started?","Pricing & plans","Talk to support"];function rt(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function nt(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 Pe(e){let t=nt(e);return`* { box-sizing: border-box; }
|
|
108
2
|
html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
|
|
109
3
|
html { color-scheme: ${e}; }
|
|
110
4
|
body { font-family: system-ui, sans-serif; background: ${t.pageBg}; }
|
|
@@ -128,7 +22,7 @@ _Details: ${n.message}_`:o}var Ca=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
128
22
|
.preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
|
|
129
23
|
.preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
|
|
130
24
|
.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
|
|
25
|
+
.preview-workspace-card.short { height: 96px; }`}function _t(e,t){let o=e.contentDocument;if(!(o!=null&&o.documentElement))return;let a=o.getElementById(de);a||(a=o.createElement("style"),a.id=de,o.head.appendChild(a)),a.textContent=Pe(t)}var st=`
|
|
132
26
|
<div class="preview-iframe-mock" aria-hidden="true">
|
|
133
27
|
<div class="preview-iframe-chrome">
|
|
134
28
|
<span class="preview-iframe-dot"></span>
|
|
@@ -147,7 +41,7 @@ _Details: ${n.message}_`:o}var Ca=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
147
41
|
<div class="preview-iframe-line body"></div>
|
|
148
42
|
<div class="preview-iframe-line body"></div>
|
|
149
43
|
</div>
|
|
150
|
-
</div>`,
|
|
44
|
+
</div>`,lt=`
|
|
151
45
|
<div class="preview-workspace-content-shell" aria-hidden="true">
|
|
152
46
|
<div class="preview-iframe-line hero"></div>
|
|
153
47
|
<div class="preview-iframe-line body"></div>
|
|
@@ -160,9 +54,9 @@ _Details: ${n.message}_`:o}var Ca=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
160
54
|
<div class="preview-workspace-card short"></div>
|
|
161
55
|
<div class="preview-workspace-card short"></div>
|
|
162
56
|
</div>
|
|
163
|
-
</div>`;function
|
|
164
|
-
${
|
|
165
|
-
<div style="position:fixed;inset:0;z-index:9999;"><div id="${e}" data-mount-id="${e}"></div></div>`,
|
|
57
|
+
</div>`;function Mt(e,t,o,a){let r=`
|
|
58
|
+
${st}
|
|
59
|
+
<div style="position:fixed;inset:0;z-index:9999;"><div id="${e}" data-mount-id="${e}"></div></div>`,n=`
|
|
166
60
|
<div class="preview-workspace-shell">
|
|
167
61
|
<div class="preview-workspace-topbar">
|
|
168
62
|
<div class="preview-workspace-topbar-left">
|
|
@@ -173,7 +67,7 @@ _Details: ${n.message}_`:o}var Ca=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
173
67
|
</div>
|
|
174
68
|
<div class="preview-workspace-body">
|
|
175
69
|
<div id="preview-content-${e}" class="preview-workspace-content" data-mount-id="${e}">
|
|
176
|
-
${
|
|
70
|
+
${lt}
|
|
177
71
|
</div>
|
|
178
72
|
</div>
|
|
179
73
|
</div>`;return`<!DOCTYPE html>
|
|
@@ -181,24 +75,13 @@ _Details: ${n.message}_`:o}var Ca=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
181
75
|
<head>
|
|
182
76
|
<meta charset="UTF-8">
|
|
183
77
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
184
|
-
<link rel="stylesheet" href="${
|
|
185
|
-
<style id="${
|
|
78
|
+
<link rel="stylesheet" href="${rt(a)}">
|
|
79
|
+
<style id="${de}">${Pe(t)}</style>
|
|
186
80
|
</head>
|
|
187
81
|
<body>
|
|
188
|
-
${n
|
|
82
|
+
${o?n:r}
|
|
189
83
|
</body>
|
|
190
|
-
</html>`}var
|
|
191
|
-
`),createdAt:
|
|
192
|
-
`),createdAt:
|
|
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 yf(e,t){return[...e,yl(t,e.length)]}function $c(e){return e==="assistant-message"||e==="assistant-code-block"||e==="assistant-markdown-table"||e==="assistant-image"}function vf(e,t,n){var d,l;let o=yl(e,t);if(!$c(e)||typeof o.content!="string")return[{message:o,delayMs:0,done:!0}];let r=Math.max(1,(d=n==null?void 0:n.chunkSize)!=null?d:24),s=Math.max(0,(l=n==null?void 0:n.delayMs)!=null?l:42),a=o.content,i=[];i.push({message:{...o,content:"",streaming:!0},delayMs:0,done:!1});for(let u=r;u<a.length;u+=r)i.push({message:{...o,content:a.slice(0,u),streaming:!0},delayMs:s,done:!1});return i.push({message:{...o,content:a,streaming:!1},delayMs:s,done:!0}),i}var Rv=()=>[{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()}],Pv=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 Uc(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"&&Pv(t)?[...Rv(),...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 vl(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:Fc:e.suggestionChips,initialMessages:Uc(t,e,n),storageAdapter:Oc};return t==="artifact"&&(r.features={...r.features,artifacts:{...(a=r.features)==null?void 0:a.artifacts,enabled:!0}}),r}function wr(e,t){var s,a,i,d;let n=e.theme?un(e.theme,{validate:!1}):un(),o=(s=e.scene)!=null?s:"conversation",r={...Lt,...e.config,theme:n,darkTheme:e.darkTheme,colorScheme:(i=t!=null?t:(a=e.config)==null?void 0:a.colorScheme)!=null?i:"light"};return vl(r,o,(d=e.appendedMessages)!=null?d:[])}function xf(e,t,n){var a,i,d;let o=e.theme?un(e.theme,{validate:!1}):un(),r=(a=e.scene)!=null?a:"conversation",s={...Lt,...e.config,theme:o,darkTheme:e.darkTheme,colorScheme:(d=n!=null?n:(i=e.config)==null?void 0:i.colorScheme)!=null?d:"light"};return vl(s,r,t)}function wf(e){var o,r,s,a,i;let t=(o=e.compareMode)!=null?o:"off",n=(r=e.shellMode)!=null?r:"light";if(t==="themes")return[{mountId:"preview-light",label:"Light",config:wr(e,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:wr(e,"dark"),shellMode:"dark"}];if(t==="baseline"&&(e.baselineConfig||e.baselineTheme)){let d={...e,config:(s=e.baselineConfig)!=null?s:e.config,theme:(a=e.baselineTheme)!=null?a:e.theme,darkTheme:(i=e.baselineDarkTheme)!=null?i:e.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:wr(d,n),shellMode:n},{mountId:"preview-current",label:"Current",config:wr(e,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:wr(e,n),shellMode:n}]}function Cf(e,t){let n={...t},o=[],r=[],s=null,a=!1,i=1,d=1,l=0;function u(){var R;return(R=n.device)!=null?R:"desktop"}function g(){var R;return(R=n.zoom)!=null?R:i}function f(){var S,V;let R=getComputedStyle(e),B=parseFloat(R.paddingLeft)+parseFloat(R.paddingRight),D=parseFloat(R.paddingTop)+parseFloat(R.paddingBottom),P=40,w=((S=n.compareMode)!=null?S:"off")!=="off",C=(e.clientWidth-B-P)/(w?2:1),E=e.clientHeight-D-P;if(C<=0||E<=0)return 1;let A=(V=Yr[u()])!=null?V:Yr.desktop;return Math.min(C/A.w,E/A.h,1)}function m(){var D,P,w;i=f();let R=Math.max(ml,Math.min(gl,g()));d=R;let B=Array.from(e.querySelectorAll(".preview-iframe-wrapper"));for(let C of B){let E=(D=C.dataset.device)!=null?D:"desktop",A=(P=Yr[E])!=null?P:Yr.desktop;C.style.width=`${A.w*R}px`,C.style.height=`${A.h*R}px`,E==="mobile"&&(C.style.borderRadius=`${32*R}px`);let S=C.querySelector("iframe");S&&(S.style.width=`${A.w}px`,S.style.height=`${A.h}px`,S.style.transformOrigin="top left",S.style.transition="none",S.style.transform=`scale(${R})`)}(w=n.onScaleChange)==null||w.call(n,R)}function x(){var R;(R=n.onBeforeDestroy)==null||R.call(n);for(let B of o)B.destroy();for(let B of r)B();o=[],r=[]}function v(){return Array.from(e.querySelectorAll("iframe[data-mount-id]"))}function M(){var de,Ee,xe,De;if(a)return;x();let R=++l,B=wf(n),D=u(),P=((de=n.compareMode)!=null?de:"off")!=="off",w=((Ee=n.scene)!=null?Ee:"conversation")==="minimized",C=(xe=n.widgetCssPath)!=null?xe:"/widget-dist/widget.css",E=(De=n.buildSrcdoc)!=null?De:bl,A=D==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",S=Ae=>`<div class="${A}" data-mount-id="${Ae.mountId}" data-device="${D}" data-shell-mode="${Ae.shellMode}">
|
|
194
|
-
${P?`<div class="preview-frame-meta"><span class="preview-frame-label">${Na(Ae.label)}</span></div>`:""}
|
|
195
|
-
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${Ae.mountId}"></iframe>
|
|
196
|
-
</div>`,V=P?`<div class="preview-compare-grid">${B.map(Ae=>`<div class="preview-compare-cell">${S(Ae)}</div>`).join("")}</div>`:`<div class="preview-single">${S(B[0])}</div>`;n.morphContainer?n.morphContainer(e,V):e.innerHTML=V,m();let $=v(),G=0,he=$.length,me=()=>{var le,X,se,ye,be;if(a||R!==l)return;for(let K of $){let ae=K.dataset.mountId;if(!ae||!K.contentDocument)continue;let Pe=B.find(lt=>lt.mountId===ae);if(!Pe)continue;let oe=()=>{},ee=Sn(Pe.config),re=ee?(()=>{var j;let lt=(j=K.contentDocument)==null?void 0:j.getElementById(`preview-content-${ae}`);if(!lt)return null;let Ie=hf(lt,Pe.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",Ie.host.appendChild(pe);let Xe=()=>Ie.syncWidgetState(it.getState()),Be=oe;return oe=()=>{Ie.destroy(),Be()},pe.__syncDock=Xe,pe.__hostLayout=Ie,pe})():K.contentDocument.getElementById(ae);if(!re)continue;let it=uf(re,Pe.config);if(o.push(it),ee&&re.__syncDock){let lt=re.__syncDock,Ie=it.on("widget:opened",lt),pe=it.on("widget:closed",lt),Xe=oe;oe=()=>{Ie(),pe(),Xe()},lt()}r.push(oe),w&&it.close()}if(((le=n.scene)!=null?le:"conversation")==="artifact"||(ye=(se=(X=n.config)==null?void 0:X.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
|
-
|
|
198
|
-
This is a preview of the artifact sidebar.
|
|
199
|
-
|
|
200
|
-
## Features
|
|
201
|
-
|
|
202
|
-
- Markdown rendering
|
|
203
|
-
- Document toolbar
|
|
204
|
-
- Resizable panes`});(be=n.onAfterMount)==null||be.call(n,{iframes:$,controllers:[...o]})};for(let Ae of $){let le=Ae.dataset.mountId;if(!le)continue;let X=B.find(se=>se.mountId===le);X&&(Ae.addEventListener("load",()=>{G++,G>=he&&me()},{once:!0}),Ae.srcdoc=E(le,X.shellMode,Sn(X.config),C))}he===0&&me()}function I(){var D;if(a)return;let R=wf(n);if(o.length!==R.length){M();return}if(R.some(P=>{let w=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${P.mountId}"]`);return!w||w.dataset.shellMode!==P.shellMode})){M();return}o.forEach((P,w)=>{var C;P.update(R[w].config),((C=n.scene)!=null?C:"conversation")==="minimized"&&P.close()});for(let P of R){let w=e.querySelector(`iframe[data-mount-id="${P.mountId}"]`);w&&hl(w,P.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 B=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},B?M():I()},destroy(){a||(a=!0,x(),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)}],structuredContent:e}}var $a={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"},Wv=/^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 Bv(e){return Wv.test(e)}function Qr(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=$a[t];if(n)return n;let o=gs(t);if(hi(o)||o==="transparent"||Bv(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($a).slice(0,6).join(", ")}).`)}var wl=Zs.map(e=>e==="gray"?"neutral":e),Hv={...Object.fromEntries(wl.map(e=>[e,e])),gray:"neutral",grey:"neutral"};function Ua(e,t=!0){let n=String(e!=null?e:"").trim().toLowerCase(),o=Hv[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 za(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 qa(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 Dv={sharp:"sharp",square:"sharp",none:"sharp",default:"default",normal:"default",rounded:"rounded",round:"rounded",soft:"rounded",pill:"pill",circle:"pill",full:"pill"};function ja(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=Dv[t];if(!n)throw new Error(`Unknown roundness "${e}". Valid: sharp, default, rounded, pill.`);return n}function Ka(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=gi(t);return fi(n.value,n.unit)}throw new Error('Radius must be a number (px) or a CSS length string like "0.5rem".')}function Cl(e){for(let t of Nr){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 Sf=Cl("typo-font-family"),_a=Cl("typo-font-size"),Va=Cl("typo-font-weight"),xl=Cl("typo-line-height"),Af={...Sf,monospace:Sf.mono},Tf={..._a,small:_a.sm,md:_a.base,medium:_a.base,large:_a.lg},kf={...Va,400:Va.normal,500:Va.medium,600:Va.semibold,700:Va.bold},Ef={...xl,"1.25":xl.tight,"1.5":xl.normal,"1.625":xl.relaxed};function Mf(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 Lf="theme.palette.radius.";function Ov(){var t;let e={pill:{sm:"9999px",md:"9999px",lg:"9999px",xl:"9999px",full:"9999px"}};for(let n of Nr)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(Lf)&&typeof i=="string"&&(s[a.slice(Lf.length)]=i);e[r[1]]=s}return e}var Ls=Ov(),If=["sm","md","lg","xl","full"];function Al(e,t,n="theme",o=0){if(o>6)return null;let r=e.get(`${n}.${t}`);return typeof r!="string"||r===""?n==="darkTheme"?Al(e,t,"theme",o):null:r.startsWith("#")||r.startsWith("rgb")||r==="transparent"?r:r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components.")?Al(e,r,n,o+1):null}function Sl(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 Is(e){return e.replace(/^role-/,"")}function Fv(e){for(let[t,n]of Object.entries(Ls))if(If.every(o=>e[o]===n[o]))return t;return"custom"}function Cr(e){var o,r;let t={};for(let s of If)t[s]=String((o=e.get(`theme.palette.radius.${s}`))!=null?o:"");let n={};for(let s of fr)n[Is(s.roleId)]=xi(a=>e.get(`theme.${a}`),s);return{brand:{primary:zc(e.get("theme.palette.colors.primary.500")),secondary:zc(e.get("theme.palette.colors.secondary.500")),accent:zc(e.get("theme.palette.colors.accent.500"))},roles:n,typography:{fontFamily:Sl(e,"theme.semantic.typography.fontFamily"),fontSize:Sl(e,"theme.semantic.typography.fontSize"),fontWeight:Sl(e,"theme.semantic.typography.fontWeight"),lineHeight:Sl(e,"theme.semantic.typography.lineHeight")},roundness:{style:Fv(t),radius:t},colorScheme:String((r=e.get("colorScheme"))!=null?r:"light"),history:{index:e.getHistoryIndex(),canUndo:e.canUndo(),canRedo:e.canRedo()}}}function zc(e){return typeof e=="string"&&e!==""?e:null}var Ms=[{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 Rf(e){let t=new Set(e.targets.map(n=>n.path));return Ms.filter(n=>t.has(n.fg)||t.has(n.bg)).map(n=>n.key)}var Nv={AA:4.5,AAA:7};function _v(e){return Math.round(e*100)/100}function Vv(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=Fr.indexOf(a[2]),l=null,u=1/0;return Fr.forEach((g,f)=>{let m=e.get(`${r}.palette.colors.${i}.${g}`);if(!(typeof m!="string"||!(m.startsWith("#")||m.startsWith("rgb")))&&Js(m,n)>=o){let x=d>=0?Math.abs(f-d):f;x<u&&(u=x,l=`palette.colors.${i}.${g}`)}}),l}function Rs(e,t="AA",n="both",o){let r=Nv[t],s=n==="both"?["light","dark"]:[n],a=o?Ms.filter(d=>o.includes(d.key)):Ms,i=[];for(let d of s){let l=d==="light"?"theme":"darkTheme";for(let u of a){let g=Al(e,u.fg,l),f=Al(e,u.bg,l);if(!g||!f)continue;let m=_v(Js(g,f)),x=m>=r,v={pair:u.key,label:u.label,variant:d,fg:g,bg:f,ratio:m,threshold:r,passes:x};if(!x){let M=Vv(e,u.fg,f,r,l);M&&(v.suggestion=M)}i.push(v)}}return{level:t,checks:i,failures:i.filter(d=>!d.passes)}}function Xr(e,t,n="light",o="AA"){return t.length===0?[]:Rs(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=Is(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 $v(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=bn[t];if(!n){let o=fr.map(r=>Is(r.roleId)).join(", ");throw new Error(`Unknown role "${e}". Valid roles: ${o}.`)}return n}function Pf(){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 wi)t(n.sections);for(let n of pa)t(n.sections);return e}var Uv={voice:"voiceRecognition.enabled",artifacts:"features.artifacts.enabled",attachments:"attachments.enabled",toolCalls:"features.showToolCalls",reasoning:"features.showReasoning",feedback:"messageActions.enabled"},zv={avatars:"layout.messages.avatar.show",timestamps:"layout.messages.timestamp.show",showHeader:"layout.showHeader",messageStyle:"layout.messages.layout"},qc=["bottom-right","bottom-left","top-right","top-left"],jc=["bubble","flat","minimal"],qv={title:"copy.welcomeTitle",subtitle:"copy.welcomeSubtitle",placeholder:"copy.inputPlaceholder",sendLabel:"copy.sendButtonLabel"};function Kc(e,t){var P;let n=(P=t==null?void 0:t.editTarget)!=null?P:"both",o=null,r=w=>w&&typeof w=="object"?w:{},s=(w,C,E=n)=>{let A={};return(E==="light"||E==="both")&&(A[`theme.${w}`]=C),(E==="dark"||E==="both")&&(A[`darkTheme.${w}`]=C),A},a=w=>{if(n==="both")return w;let C={};for(let[E,A]of Object.entries(w))(n==="light"&&E.startsWith("theme.")||n==="dark"&&E.startsWith("darkTheme."))&&(C[E]=A);return C},i=()=>n==="dark"?"dark":"light",d=(w,C=[])=>_o({ok:!0,summary:Cr(e),warnings:C,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:C}=r(w),E={summary:Cr(e),availableRoles:fr.map(A=>({role:Is(A.roleId),helper:A.helper})),availableFamilies:wl,presets:hs.map(A=>{var S;return{id:A.id,name:A.name,description:A.description,tags:(S=A.tags)!=null?S:[]}}),tools:[{tool:"set_brand_colors",hint:"Recolor the palette (primary/secondary/accent) \u2014 auto-generates shade scales."},{tool:"assign_color_role",hint:"Recolor a region (header, user/assistant messages, actions, input, links, borders, surfaces, scroll) with a family + intensity."},{tool:"set_typography",hint:"Set font family, size, weight, line height."},{tool:"set_roundness",hint:"Set corner roundness (sharp/default/rounded/pill) or granular radii."},{tool:"set_color_scheme",hint:"Set light/dark/auto and which variant edits target."},{tool:"apply_preset",hint:"Apply a complete built-in preset."},{tool:"configure_widget",hint:"Toggle launcher position, features, and layout."},{tool:"set_copy_and_suggestions",hint:"Set welcome copy, placeholder, and suggestion chips."},{tool:"set_theme_fields",hint:"Advanced escape hatch: set any field by id or dot-path."},{tool:"check_contrast",hint:"Audit WCAG contrast across key text/background pairs."},{tool:"manage_session",hint:"Undo, redo, reset, or export the theme."}]};return C==="full"&&(o!=null||(o=Pf()),E.fieldIndex=Array.from(o.values()).map(A=>{var S;return{id:A.id,path:A.path,type:A.type,label:A.label,options:(S=A.options)==null?void 0:S.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 C=r(w),E=["primary","secondary","accent"],A={},S={};for(let $ of E){if(C[$]===void 0)continue;let G=Qr(C[$]);S[$]=G;let he=yi(G);for(let me of Fr){let de=he[me];de!==void 0&&Object.assign(A,s(`palette.colors.${$}.${me}`,de))}}if(Object.keys(S).length===0)throw new Error("Provide at least one of: primary, secondary, accent.");e.setBatch(A);let V=Xr(e,["primary-button","user-message"],i());return d(S,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:wl},intensity:{type:"string",enum:["solid","soft"],description:"Defaults to 'solid'."}},required:["role","family"],additionalProperties:!1},execute(w){let C=r(w),E=$v(C.role),A=Ua(C.family,!0),S=za(C.intensity),V=a(ca(A,S,E)),$=Object.keys(V).length;e.setBatch(V);let G=Xr(e,Rf(E),i());return d({role:Is(E.roleId),family:A,intensity:S,tokensWritten:$},G)}},{name:"set_typography",title:"Set typography",description:"Set font family, base size, weight, and line height in one call. fontFamily: sans|serif|mono. fontSize: xs|sm|base|lg|xl. fontWeight: normal|medium|semibold|bold (or 400\u2013700). lineHeight: tight|normal|relaxed (or 1.25/1.5/1.625).",inputSchema:{type:"object",properties:{fontFamily:{type:"string"},fontSize:{type:"string"},fontWeight:{type:["string","number"]},lineHeight:{type:["string","number"]}},additionalProperties:!1},execute(w){let C=r(w),E={},A={},S=(V,$)=>{var he;if(C[V]===void 0)return;let G=Mf(C[V],$,V);A[V]=(he=G.split(".").pop())!=null?he:G,Object.assign(E,s(`semantic.typography.${V}`,G))};if(S("fontFamily",Af),S("fontSize",Tf),S("fontWeight",kf),S("lineHeight",Ef),Object.keys(A).length===0)throw new Error("Provide at least one of: fontFamily, fontSize, fontWeight, lineHeight.");return e.setBatch(E),d(A)}},{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 C=r(w),E={},A={};if(C.style!==void 0){let S=ja(C.style);A.style=S;for(let[V,$]of Object.entries(Ls[S]))Object.assign(E,s(`palette.radius.${V}`,$))}if(C.radius!==void 0){let S=r(C.radius),V={};for(let $ of["sm","md","lg","xl","full"]){if(S[$]===void 0)continue;let G=Ka(S[$]);V[$]=G,Object.assign(E,s(`palette.radius.${$}`,G))}A.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(A)}},{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 C=r(w),E={};if(C.scheme!==void 0){let A=qa(C.scheme);e.set("colorScheme",A),E.scheme=A}if(C.editTarget!==void 0){let A=String(C.editTarget).trim().toLowerCase();if(A!=="light"&&A!=="dark"&&A!=="both")throw new Error(`Unknown editTarget "${C.editTarget}". Valid: light, dark, both.`);n=A,E.editTarget=A}if(Object.keys(E).length===0)throw new Error("Provide `scheme` and/or `editTarget`.");return _o({ok:!0,summary:Cr(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:C}=r(w),E=Ci(String(C!=null?C:""));if(!E){let $=hs.map(G=>G.id).join(", ");throw new Error(`Unknown preset "${C}". Valid presets: ${$}.`)}let A=un(E.theme,{validate:!1}),S={...e.getConfig()};E.darkTheme&&(S.darkTheme=un(E.darkTheme,{validate:!1})),E.toolCall&&(S.toolCall=E.toolCall),e.setFullConfig(S,A);let V=Xr(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:qc},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:jc}},additionalProperties:!1}},additionalProperties:!1},execute(w){var $,G,he;let C=r(w),E={},A={};if(C.launcherPosition!==void 0){let me=String(C.launcherPosition);if(!qc.includes(me))throw new Error(`Unknown launcherPosition "${me}". Valid: ${qc.join(", ")}.`);E["launcher.position"]=me,A.launcherPosition=me}let S=r(C.features);for(let[me,de]of Object.entries(Uv))S[me]!==void 0&&(E[de]=!!S[me],($=A.features)!=null||(A.features={}),A.features[me]=!!S[me]);let V=r(C.layout);for(let[me,de]of Object.entries(zv))if(V[me]!==void 0)if(me==="messageStyle"){let Ee=String(V[me]);if(!jc.includes(Ee))throw new Error(`Unknown messageStyle "${Ee}". Valid: ${jc.join(", ")}.`);E[de]=Ee,(G=A.layout)!=null||(A.layout={}),A.layout[me]=Ee}else E[de]=!!V[me],(he=A.layout)!=null||(A.layout={}),A.layout[me]=!!V[me];if(Object.keys(E).length===0)throw new Error("Provide launcherPosition, features, and/or layout.");return e.setBatch(E),d(A)}},{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 C=r(w),E={},A={};for(let[S,V]of Object.entries(qv))C[S]!==void 0&&(E[V]=String(C[S]),A[S]=String(C[S]));if(C.suggestions!==void 0){if(!Array.isArray(C.suggestions))throw new Error("`suggestions` must be an array of strings.");let S=C.suggestions.filter(V=>typeof V=="string");E.suggestionChips=S,A.suggestions=S}if(Object.keys(E).length===0)throw new Error("Provide at least one of: title, subtitle, placeholder, sendLabel, suggestions.");return e.setBatch(E),d(A)}},{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:C}=r(w);if(!Array.isArray(C)||C.length===0)throw new Error("`updates` must be a non-empty array of { field, value }.");o!=null||(o=Pf());let E={},A=[];for(let $ of C){let G=r($),he=String((V=G.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=jv(me,G.value);if(me&&de.startsWith("theme.")){let xe=s(de.slice(6),Ee);Object.assign(E,xe),A.push({field:he,resolvedPath:Object.keys(xe),ok:!0})}else E[de]=Ee,A.push({field:he,resolvedPath:de,ok:!0})}catch(me){A.push({field:he,ok:!1,error:me.message})}}let S=A.filter($=>$.ok);return Object.keys(E).length>0&&e.setBatch(E),_o({ok:S.length>0,summary:Cr(e),warnings:[],applied:{updates:A}})}},{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 C=r(w),E=C.level==="AAA"?"AAA":"AA",A=C.variant==="light"||C.variant==="dark"?C.variant:"both",S=Rs(e,E,A);return _o({level:S.level,passing:S.checks.length-S.failures.length,total:S.checks.length,checks:S.checks,failures:S.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:C}=r(w);switch(C){case"undo":return e.undo(),d({action:"undo"});case"redo":return e.redo(),d({action:"redo"});case"reset":return e.resetToDefaults(),d({action:"reset"});case"export":return _o({ok:!0,snapshot:e.exportSnapshot()});default:throw new Error(`Unknown action "${C}". Valid: undo, redo, reset, export.`)}}}]}function jv(e,t){if(!e)return t;switch(e.type){case"color":return e.parseValue?e.parseValue(Qr(t)):Qr(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});
|
|
84
|
+
</html>`}var ca={"user-message":"User message","assistant-message":"Assistant message","assistant-code-block":"Assistant: code block","assistant-markdown-table":"Assistant: markdown table","assistant-image":"Assistant: image","reasoning-streaming":"Reasoning (streaming)","reasoning-complete":"Reasoning (complete)","tool-running":"Tool call (running)","tool-complete":"Tool call (complete)","approval-request":"Approval request"};function Wt(e){return ca[e]}function Ve(e,t=0){let o=new Date(Date.now()-Math.max(0,60-t)*1e3).toISOString(),a=`${e}-${t}`;switch(e){case"user-message":return{id:`preview-seq-user-${a}`,role:"user",content:"Can you continue with the next step?",createdAt:o};case"assistant-message":return{id:`preview-seq-assistant-${a}`,role:"assistant",content:"Absolutely. I can keep going and explain what happens next.",createdAt:o};case"assistant-code-block":return{id:`preview-seq-assistant-code-${a}`,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(`
|
|
85
|
+
`),createdAt:o};case"assistant-markdown-table":return{id:`preview-seq-assistant-table-${a}`,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(`
|
|
86
|
+
`),createdAt:o};case"assistant-image":return{id:`preview-seq-assistant-image-${a}`,role:"assistant",content:["Here's the reference diagram you asked for: let me know if you'd like a different view:","","","","The gradient shows how per-unit delays stagger across the reply."].join(`
|
|
87
|
+
`),createdAt:o};case"reasoning-streaming":return{id:`preview-seq-reasoning-stream-${a}`,role:"assistant",content:"",createdAt:o,streaming:!0,variant:"reasoning",reasoning:{id:`preview-reasoning-stream-${a}`,status:"streaming",chunks:["Thinking through the next step in the workflow..."]}};case"reasoning-complete":return{id:`preview-seq-reasoning-complete-${a}`,role:"assistant",content:"",createdAt:o,streaming:!1,variant:"reasoning",reasoning:{id:`preview-reasoning-complete-${a}`,status:"complete",chunks:["Reviewed the requirements and finalized the reasoning output."],durationMs:1200}};case"approval-request":{let r=`preview-approval-${a}`;return{id:`approval-${r}`,role:"assistant",content:"",createdAt:o,streaming:!1,variant:"approval",approval:{id:r,status:"pending",agentId:"preview-agent",executionId:`preview-exec-${a}`,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-${a}`,role:"assistant",content:"",createdAt:o,streaming:!1,variant:"tool",toolCall:{id:`preview-tool-complete-${a}`,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-${a}`,role:"assistant",content:"",createdAt:o,streaming:!0,variant:"tool",toolCall:{id:`preview-tool-running-${a}`,name:"Get platform documentation",status:"running",chunks:["Fetching the relevant platform documentation..."]}}}}function Ft(e,t){return[...e,Ve(t,e.length)]}function it(e){return e==="assistant-message"||e==="assistant-code-block"||e==="assistant-markdown-table"||e==="assistant-image"}function Nt(e,t,o){var c,m;let a=Ve(e,t);if(!it(e)||typeof a.content!="string")return[{message:a,delayMs:0,done:!0}];let r=Math.max(1,(c=o==null?void 0:o.chunkSize)!=null?c:24),n=Math.max(0,(m=o==null?void 0:o.delayMs)!=null?m:42),l=a.content,i=[];i.push({message:{...a,content:"",streaming:!0},delayMs:0,done:!1});for(let g=r;g<l.length;g+=r)i.push({message:{...a,content:l.slice(0,g),streaming:!0},delayMs:n,done:!1});return i.push({message:{...a,content:l,streaming:!1},delayMs:n,done:!0}),i}var da=()=>[{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()}],pa=e=>{var t,o,a,r,n,l,i,c;return!!((o=(t=e==null?void 0:e.features)==null?void 0:t.toolCallDisplay)!=null&&o.activePreview||(r=(a=e==null?void 0:e.features)==null?void 0:a.toolCallDisplay)!=null&&r.grouped||(l=(n=e==null?void 0:e.features)==null?void 0:n.toolCallDisplay)!=null&&l.collapsedMode&&e.features.toolCallDisplay.collapsedMode!=="tool-call"||(c=(i=e==null?void 0:e.features)==null?void 0:i.reasoningDisplay)!=null&&c.activePreview)};function ct(e,t,o=[]){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"&&pa(t)?[...da(),...o]:[{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()},...o]}function Oe(e,t,o=[]){var n,l;let a={...e.launcher,enabled:!0,autoExpand:t!=="minimized"},r={...e,launcher:a,suggestionChips:t==="home"?(n=e.suggestionChips)!=null&&n.length?e.suggestionChips:at:e.suggestionChips,initialMessages:ct(t,e,o),storageAdapter:ot};return t==="artifact"&&(r.features={...r.features,artifacts:{...(l=r.features)==null?void 0:l.artifacts,enabled:!0}}),r}function Ht(e,t){var a,r;let o=e.theme?S(e.theme,{validate:!1}):S();return{...H,...e.config,theme:o,darkTheme:e.darkTheme,colorScheme:(r=t!=null?t:(a=e.config)==null?void 0:a.colorScheme)!=null?r:"light"}}function $t(e,t){var a,r;let o=(a=e.scene)!=null?a:"conversation";return Oe(Ht(e,t),o,(r=e.appendedMessages)!=null?r:[])}function zt(e,t,o){var r;let a=(r=e.scene)!=null?r:"conversation";return Oe(Ht(e,o),a,t)}function I(e){return{content:[{type:"text",text:JSON.stringify(e)}],structuredContent:e}}var me={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"},ua=/^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 ma(e){return ua.test(e)}function _(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(),o=me[t];if(o)return o;let a=$(t);if(Se(a)||a==="transparent"||ma(a))return a;throw new Error(`"${e}" is not a recognized color. Pass a hex value like "#ef4444" or a CSS color name (e.g. ${Object.keys(me).slice(0,6).join(", ")}).`)}var Be=X.map(e=>e==="gray"?"neutral":e),ha={...Object.fromEntries(Be.map(e=>[e,e])),gray:"neutral",grey:"neutral"};function he(e,t=!0){let o=String(e!=null?e:"").trim().toLowerCase(),a=ha[o];if(!a||!t&&a==="neutral"){let r=t?"primary, secondary, accent, neutral":"primary, secondary, accent";throw new Error(`Unknown color family "${e}". Valid families: ${r}.`)}return a}function ge(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 fe(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 ga={sharp:"sharp",square:"sharp",none:"sharp",default:"default",normal:"default",rounded:"rounded",round:"rounded",soft:"rounded",pill:"pill",circle:"pill",full:"pill"};function be(e){let t=String(e!=null?e:"").trim().toLowerCase(),o=ga[t];if(!o)throw new Error(`Unknown roundness "${e}". Valid: sharp, default, rounded, pill.`);return o}function ye(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 o=xe(t);return ve(o.value,o.unit)}throw new Error('Radius must be a number (px) or a CSS length string like "0.5rem".')}function De(e){for(let t of D){let o=t.fields.find(a=>a.id===e);if(o!=null&&o.options){let a={};for(let r of o.options){let n=r.value.split(".").pop();n&&(a[n]=r.value)}return a}}return{}}var Ut=De("typo-font-family"),pe=De("typo-font-size"),ue=De("typo-font-weight"),Le=De("typo-line-height"),jt={...Ut,monospace:Ut.mono},Gt={...pe,small:pe.sm,md:pe.base,medium:pe.base,large:pe.lg},qt={...ue,400:ue.normal,500:ue.medium,600:ue.semibold,700:ue.bold},Yt={...Le,"1.25":Le.tight,"1.5":Le.normal,"1.625":Le.relaxed};function Kt(e,t,o){let a=String(e!=null?e:"").trim().toLowerCase(),r=t[a];if(!r){let n=[...new Set(Object.values(t).map(l=>l.split(".").pop()))].join(", ");throw new Error(`Unknown ${o} "${e}". Valid: ${n}.`)}return r}var Zt="theme.palette.radius.";function fa(){var t;let e={pill:{sm:"9999px",md:"9999px",lg:"9999px",xl:"9999px",full:"9999px"}};for(let o of D)for(let a of(t=o.presets)!=null?t:[]){let r=a.id.match(/^radius-(\w+)$/);if(!r)continue;let n={};for(let[l,i]of Object.entries(a.values))l.startsWith(Zt)&&typeof i=="string"&&(n[l.slice(Zt.length)]=i);e[r[1]]=n}return e}var G=fa(),Xt=["sm","md","lg","xl","full"];function Me(e,t,o="theme",a=0){if(a>6)return null;let r=e.get(`${o}.${t}`);return typeof r!="string"||r===""?o==="darkTheme"?Me(e,t,"theme",a):null:r.startsWith("#")||r.startsWith("rgb")||r==="transparent"?r:r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components.")?Me(e,r,o,a+1):null}function _e(e,t){let o=e.get(t);if(typeof o!="string")return"unknown";let a=o.split(".");return a[a.length-1]||String(o)}function q(e){return e.replace(/^role-/,"")}function ba(e){for(let[t,o]of Object.entries(G))if(Xt.every(a=>e[a]===o[a]))return t;return"custom"}function V(e){var a,r;let t={};for(let n of Xt)t[n]=String((a=e.get(`theme.palette.radius.${n}`))!=null?a:"");let o={};for(let n of P)o[q(n.roleId)]=Ae(l=>e.get(`theme.${l}`),n);return{brand:{primary:dt(e.get("theme.palette.colors.primary.500")),secondary:dt(e.get("theme.palette.colors.secondary.500")),accent:dt(e.get("theme.palette.colors.accent.500"))},roles:o,typography:{fontFamily:_e(e,"theme.semantic.typography.fontFamily"),fontSize:_e(e,"theme.semantic.typography.fontSize"),fontWeight:_e(e,"theme.semantic.typography.fontWeight"),lineHeight:_e(e,"theme.semantic.typography.lineHeight")},roundness:{style:ba(t),radius:t},colorScheme:String((r=e.get("colorScheme"))!=null?r:"light"),history:{index:e.getHistoryIndex(),canUndo:e.canUndo(),canRedo:e.canRedo()}}}function dt(e){return typeof e=="string"&&e!==""?e:null}var j=[{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 Jt(e){let t=new Set(e.targets.map(o=>o.path));return j.filter(o=>t.has(o.fg)||t.has(o.bg)).map(o=>o.key)}var ya={AA:4.5,AAA:7};function wa(e){return Math.round(e*100)/100}function ka(e,t,o,a,r){let n=e.get(`${r}.${t}`);if(typeof n!="string")return null;let l=n.match(/^palette\.colors\.(\w+)\.(\d+)$/);if(!l)return null;let i=l[1],c=B.indexOf(l[2]),m=null,g=1/0;return B.forEach((w,k)=>{let C=e.get(`${r}.palette.colors.${i}.${w}`);if(!(typeof C!="string"||!(C.startsWith("#")||C.startsWith("rgb")))&&Z(C,o)>=a){let A=c>=0?Math.abs(k-c):k;A<g&&(g=A,m=`palette.colors.${i}.${w}`)}}),m}function Y(e,t="AA",o="both",a){let r=ya[t],n=o==="both"?["light","dark"]:[o],l=a?j.filter(c=>a.includes(c.key)):j,i=[];for(let c of n){let m=c==="light"?"theme":"darkTheme";for(let g of l){let w=Me(e,g.fg,m),k=Me(e,g.bg,m);if(!w||!k)continue;let C=wa(Z(w,k)),A=C>=r,W={pair:g.key,label:g.label,variant:c,fg:w,bg:k,ratio:C,threshold:r,passes:A};if(!A){let F=ka(e,g.fg,k,r,m);F&&(W.suggestion=F)}i.push(W)}}return{level:t,checks:i,failures:i.filter(c=>!c.passes)}}function M(e,t,o="light",a="AA"){return t.length===0?[]:Y(e,a,o,t).failures.map(n=>({code:"contrast",pair:n.pair,variant:n.variant,ratio:n.ratio,threshold:n.threshold,message:`${n.label} (${n.variant}) has a contrast ratio of ${n.ratio}:1, below the ${a} threshold of ${n.threshold}:1${n.suggestion?`. Try ${n.suggestion} for the foreground.`:"."}`}))}var v={};for(let e of P){let t=q(e.roleId);v[t]=e,v[e.roleId]=e}Object.assign(v,{surface:v.surfaces,background:v.surfaces,backgrounds:v.surfaces,user:v["user-messages"],"user-message":v["user-messages"],assistant:v["assistant-messages"],"assistant-message":v["assistant-messages"],actions:v["primary-actions"],buttons:v["primary-actions"],composer:v.input,links:v["links-focus"],focus:v["links-focus"],border:v.borders,dividers:v.borders,scroll:v["scroll-to-bottom"]});function xa(e){let t=String(e!=null?e:"").trim().toLowerCase(),o=v[t];if(!o){let a=P.map(r=>q(r.roleId)).join(", ");throw new Error(`Unknown role "${e}". Valid roles: ${a}.`)}return o}function Qt(){let e=new Map,t=o=>{for(let a of o)for(let r of a.fields)e.has(r.id)||e.set(r.id,r)};for(let o of Ee)t(o.sections);for(let o of ce)t(o.sections);return e}var va={voice:"voiceRecognition.enabled",artifacts:"features.artifacts.enabled",attachments:"attachments.enabled",toolCalls:"features.showToolCalls",reasoning:"features.showReasoning",feedback:"messageActions.enabled"},Sa={avatars:"layout.messages.avatar.show",timestamps:"layout.messages.timestamp.show",showHeader:"layout.showHeader",messageStyle:"layout.messages.layout"},pt=["bottom-right","bottom-left","top-right","top-left"],ut=["bubble","flat","minimal"],Ta={title:"copy.welcomeTitle",subtitle:"copy.welcomeSubtitle",placeholder:"copy.inputPlaceholder",sendLabel:"copy.sendButtonLabel"};function mt(e,t){var gt;let o=(gt=t==null?void 0:t.editTarget)!=null?gt:"both",a=null,r=h=>h&&typeof h=="object"?h:{},n=(h,d,p=o)=>{let s={};return(p==="light"||p==="both")&&(s[`theme.${h}`]=d),(p==="dark"||p==="both")&&(s[`darkTheme.${h}`]=d),s},l=h=>{if(o==="both")return h;let d={};for(let[p,s]of Object.entries(h))(o==="light"&&p.startsWith("theme.")||o==="dark"&&p.startsWith("darkTheme."))&&(d[p]=s);return d},i=()=>o==="dark"?"dark":"light",c=(h,d=[])=>I({ok:!0,summary:V(e),warnings:d,applied:h});return[{name:"get_theme_overview",title:"Get current theme & what is editable",description:"Read theme summary, presets, and editable levers. Call before editing.",annotations:{readOnlyHint:!0},inputSchema:{type:"object",properties:{verbosity:{type:"string",enum:["summary","full"],description:"'full' includes the field-id index."}},additionalProperties:!1},execute(h){let{verbosity:d}=r(h),p={summary:V(e),availableRoles:P.map(s=>({role:q(s.roleId),helper:s.helper})),availableFamilies:Be,presets:U.map(s=>{var u;return{id:s.id,name:s.name,description:s.description,tags:(u=s.tags)!=null?u:[]}}),tools:[{tool:"set_brand_colors",hint:"Recolor primary/secondary/accent and generate shade scales."},{tool:"assign_color_role",hint:"Recolor a widget region with family + intensity."},{tool:"set_typography",hint:"Set font family, size, weight, line height."},{tool:"set_roundness",hint:"Set corner roundness or granular radii."},{tool:"set_color_scheme",hint:"Set light/dark/auto and edit target."},{tool:"apply_preset",hint:"Apply a 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:"Set any field by id or dot-path."},{tool:"check_contrast",hint:"Audit WCAG contrast."},{tool:"manage_session",hint:"Undo, redo, reset, or export the theme."}]};return d==="full"&&(a!=null||(a=Qt()),p.fieldIndex=Array.from(a.values()).map(s=>{var u;return{id:s.id,path:s.path,type:s.type,label:s.label,options:(u=s.options)==null?void 0:u.map(f=>f.value)}})),I(p)}},{name:"set_brand_colors",title:"Set brand colors",description:"Set primary, secondary, and/or accent colors. Generates shade scales and accepts hex, rgb/rgba, or CSS names.",inputSchema:{type:"object",properties:{primary:{type:"string",description:"Hex, rgb/rgba, or CSS name."},secondary:{type:"string",description:"Hex, rgb/rgba, or CSS name."},accent:{type:"string",description:"Hex, rgb/rgba, or CSS name."}},additionalProperties:!1},execute(h){let d=r(h),p=["primary","secondary","accent"],s={},u={};for(let y of p){if(d[y]===void 0)continue;let x=_(d[y]);u[y]=x;let T=Re(x);for(let b of B){let R=T[b];R!==void 0&&Object.assign(s,n(`palette.colors.${y}.${b}`,R))}}if(Object.keys(u).length===0)throw new Error("Provide at least one of: primary, secondary, accent.");e.setBatch(s);let f=M(e,["primary-button","user-message"],i());return c(u,f)}},{name:"assign_color_role",title:"Assign a color family to an interface role",description:"Recolor a widget region by role, palette family, and intensity.",inputSchema:{type:"object",properties:{role:{type:"string",description:"Role, e.g. header or user-messages."},family:{type:"string",enum:Be},intensity:{type:"string",enum:["solid","soft"],description:"Default: solid."}},required:["role","family"],additionalProperties:!1},execute(h){let d=r(h),p=xa(d.role),s=he(d.family,!0),u=ge(d.intensity),f=l(le(s,u,p)),y=Object.keys(f).length;e.setBatch(f);let x=M(e,Jt(p),i());return c({role:q(p.roleId),family:s,intensity:u,tokensWritten:y},x)}},{name:"set_typography",title:"Set typography",description:"Set font family, size, weight, and line height.",inputSchema:{type:"object",properties:{fontFamily:{type:"string"},fontSize:{type:"string"},fontWeight:{type:["string","number"]},lineHeight:{type:["string","number"]}},additionalProperties:!1},execute(h){let d=r(h),p={},s={},u=(f,y)=>{var T;if(d[f]===void 0)return;let x=Kt(d[f],y,f);s[f]=(T=x.split(".").pop())!=null?T:x,Object.assign(p,n(`semantic.typography.${f}`,x))};if(u("fontFamily",jt),u("fontSize",Gt),u("fontWeight",qt),u("lineHeight",Yt),Object.keys(s).length===0)throw new Error("Provide at least one of: fontFamily, fontSize, fontWeight, lineHeight.");return e.setBatch(p),c(s)}},{name:"set_roundness",title:"Set corner roundness",description:"Set roundness by style or granular radius values.",inputSchema:{type:"object",properties:{style:{type:"string",enum:["sharp","default","rounded","pill"]},radius:{type:"object",description:"Granular px or CSS length overrides.",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(h){let d=r(h),p={},s={};if(d.style!==void 0){let u=be(d.style);s.style=u;for(let[f,y]of Object.entries(G[u]))Object.assign(p,n(`palette.radius.${f}`,y))}if(d.radius!==void 0){let u=r(d.radius),f={};for(let y of["sm","md","lg","xl","full"]){if(u[y]===void 0)continue;let x=ye(u[y]);f[y]=x,Object.assign(p,n(`palette.radius.${y}`,x))}s.radius=f}if(Object.keys(p).length===0)throw new Error("Provide `style` (sharp|default|rounded|pill) or a `radius` object.");return e.setBatch(p),c(s)}},{name:"set_color_scheme",title:"Set color scheme",description:"Set light/dark/auto color scheme and optional edit target.",inputSchema:{type:"object",properties:{scheme:{type:"string",enum:["light","dark","auto"]},editTarget:{type:"string",enum:["light","dark","both"]}},additionalProperties:!1},execute(h){let d=r(h),p={};if(d.scheme!==void 0){let s=fe(d.scheme);e.set("colorScheme",s),p.scheme=s}if(d.editTarget!==void 0){let s=String(d.editTarget).trim().toLowerCase();if(s!=="light"&&s!=="dark"&&s!=="both")throw new Error(`Unknown editTarget "${d.editTarget}". Valid: light, dark, both.`);o=s,p.editTarget=s}if(Object.keys(p).length===0)throw new Error("Provide `scheme` and/or `editTarget`.");return I({ok:!0,summary:V(e),warnings:[],applied:p,editTarget:o})}},{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(h){let{presetId:d}=r(h),p=Ie(String(d!=null?d:""));if(!p){let y=U.map(x=>x.id).join(", ");throw new Error(`Unknown preset "${d}". Valid presets: ${y}.`)}let s=S(p.theme,{validate:!1}),u={...e.getConfig()};p.darkTheme&&(u.darkTheme=S(p.darkTheme,{validate:!1})),p.toolCall&&(u.toolCall=p.toolCall),e.setFullConfig(u,s);let f=M(e,["body","assistant-message"],"light");return c({appliedPreset:{id:p.id,name:p.name}},f)}},{name:"configure_widget",title:"Configure launcher, features, and layout",description:"Toggle launcher position, feature flags, and message layout.",inputSchema:{type:"object",properties:{launcherPosition:{type:"string",enum:pt},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:ut}},additionalProperties:!1}},additionalProperties:!1},execute(h){var y,x,T;let d=r(h),p={},s={};if(d.launcherPosition!==void 0){let b=String(d.launcherPosition);if(!pt.includes(b))throw new Error(`Unknown launcherPosition "${b}". Valid: ${pt.join(", ")}.`);p["launcher.position"]=b,s.launcherPosition=b}let u=r(d.features);for(let[b,R]of Object.entries(va))u[b]!==void 0&&(p[R]=!!u[b],(y=s.features)!=null||(s.features={}),s.features[b]=!!u[b]);let f=r(d.layout);for(let[b,R]of Object.entries(Sa))if(f[b]!==void 0)if(b==="messageStyle"){let O=String(f[b]);if(!ut.includes(O))throw new Error(`Unknown messageStyle "${O}". Valid: ${ut.join(", ")}.`);p[R]=O,(x=s.layout)!=null||(s.layout={}),s.layout[b]=O}else p[R]=!!f[b],(T=s.layout)!=null||(s.layout={}),s.layout[b]=!!f[b];if(Object.keys(p).length===0)throw new Error("Provide launcherPosition, features, and/or layout.");return e.setBatch(p),c(s)}},{name:"set_copy_and_suggestions",title:"Set welcome copy and suggestion chips",description:"Set welcome copy, input placeholder, send label, and suggestion chips.",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(h){let d=r(h),p={},s={};for(let[u,f]of Object.entries(Ta))d[u]!==void 0&&(p[f]=String(d[u]),s[u]=String(d[u]));if(d.suggestions!==void 0){if(!Array.isArray(d.suggestions))throw new Error("`suggestions` must be an array of strings.");let u=d.suggestions.filter(f=>typeof f=="string");p.suggestionChips=u,s.suggestions=u}if(Object.keys(p).length===0)throw new Error("Provide at least one of: title, subtitle, placeholder, sendLabel, suggestions.");return e.setBatch(p),c(s)}},{name:"set_theme_fields",title:"Set theme fields by id or path (advanced)",description:"Advanced escape hatch: set fields by id or raw dot-path. Values are validated when metadata exists.",inputSchema:{type:"object",properties:{updates:{type:"array",items:{type:"object",properties:{field:{type:"string",description:"Field id or path."},value:{type:["string","number","boolean"]}},required:["field","value"],additionalProperties:!1}}},required:["updates"],additionalProperties:!1},execute(h){var f;let{updates:d}=r(h);if(!Array.isArray(d)||d.length===0)throw new Error("`updates` must be a non-empty array of { field, value }.");a!=null||(a=Qt());let p={},s=[];for(let y of d){let x=r(y),T=String((f=x.field)!=null?f:"");try{let b=a.get(T),R=b?b.path:T;if(!b&&!/^(theme|darkTheme)\.|\./.test(R))throw new Error(`Unknown field "${T}". Pass a known field id or a dot-path (e.g. theme.palette.radius.md).`);let O=Ra(b,x.value);if(b&&R.startsWith("theme.")){let ft=n(R.slice(6),O);Object.assign(p,ft),s.push({field:T,resolvedPath:Object.keys(ft),ok:!0})}else p[R]=O,s.push({field:T,resolvedPath:R,ok:!0})}catch(b){s.push({field:T,ok:!1,error:b.message})}}let u=s.filter(y=>y.ok);return Object.keys(p).length>0&&e.setBatch(p),I({ok:u.length>0,summary:V(e),warnings:[],applied:{updates:s}})}},{name:"check_contrast",title:"Check accessibility contrast",description:"Run WCAG checks over key text/background pairs.",annotations:{readOnlyHint:!0},inputSchema:{type:"object",properties:{level:{type:"string",enum:["AA","AAA"],description:"Default: AA."},variant:{type:"string",enum:["light","dark","both"],description:"Default: both."}},additionalProperties:!1},execute(h){let d=r(h),p=d.level==="AAA"?"AAA":"AA",s=d.variant==="light"||d.variant==="dark"?d.variant:"both",u=Y(e,p,s);return I({level:u.level,passing:u.checks.length-u.failures.length,total:u.checks.length,checks:u.checks,failures:u.failures})}},{name:"manage_session",title:"Undo, redo, reset, or export the theme",description:"Undo, redo, reset defaults, or export the theme snapshot.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["undo","redo","reset","export"]}},required:["action"],additionalProperties:!1},execute(h){let{action:d}=r(h);switch(d){case"undo":return e.undo(),c({action:"undo"});case"redo":return e.redo(),c({action:"redo"});case"reset":return e.resetToDefaults(),c({action:"reset"});case"export":return I({ok:!0,snapshot:e.exportSnapshot()});default:throw new Error(`Unknown action "${d}". Valid: undo, redo, reset, export.`)}}}]}function Ra(e,t){if(!e)return t;switch(e.type){case"color":return e.parseValue?e.parseValue(_(t)):_(t);case"toggle":return typeof t=="boolean"?t:t==="true"||t===1;case"slider":{let o=Number(t);if(!Number.isFinite(o))throw new Error(`"${e.id}" expects a number.`);if(e.slider){let{min:a,max:r}=e.slider;if(o<a||o>r)throw new Error(`"${e.id}" must be between ${a} and ${r}.`)}return e.parseValue?e.parseValue(o):o}case"select":{let o=String(t);if(e.options&&!e.options.some(a=>a.value===o))throw new Error(`"${e.id}" must be one of: ${e.options.map(a=>a.value).join(", ")}.`);return e.parseValue?e.parseValue(o):o}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,detectRoleAssignment,escapeHtml,findSection,formatCssValue,generateColorScale,getPreviewTranscriptPresetLabel,getShellPalette,getThemeEditorPreset,hexToHsl,hslToHex,isValidHex,normalizeColorValue,paletteColorPath,parseCssValue,presetStreamsText,quickContrastWarnings,resolveRoleAssignment,resolveThemeColorPath,rgbToHex,runContrastChecks,scopeSection,tokenRefDisplayName,toolResult,wcagContrastRatio});
|