@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.
Files changed (186) hide show
  1. package/README.md +11 -11
  2. package/dist/animations/glyph-cycle.d.cts +1 -1
  3. package/dist/animations/glyph-cycle.d.ts +1 -1
  4. package/dist/animations/{types-CthJFfNx.d.cts → types-DgYsuwXL.d.cts} +15 -14
  5. package/dist/animations/{types-CthJFfNx.d.ts → types-DgYsuwXL.d.ts} +15 -14
  6. package/dist/animations/wipe.d.cts +1 -1
  7. package/dist/animations/wipe.d.ts +1 -1
  8. package/dist/codegen.cjs +11 -11
  9. package/dist/codegen.js +10 -10
  10. package/dist/index.cjs +46 -44
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +514 -158
  13. package/dist/index.d.ts +514 -158
  14. package/dist/index.global.js +41 -89
  15. package/dist/index.global.js.map +1 -1
  16. package/dist/index.js +46 -44
  17. package/dist/index.js.map +1 -1
  18. package/dist/install.global.js +1 -1
  19. package/dist/install.global.js.map +1 -1
  20. package/dist/launcher.global.js +2 -2
  21. package/dist/launcher.global.js.map +1 -1
  22. package/dist/markdown-parsers.js +53 -0
  23. package/dist/plugin-kit.d.cts +4 -4
  24. package/dist/plugin-kit.d.ts +4 -4
  25. package/dist/runtype-tts.js +1 -0
  26. package/dist/smart-dom-reader.cjs +1 -1
  27. package/dist/smart-dom-reader.d.cts +352 -103
  28. package/dist/smart-dom-reader.d.ts +352 -103
  29. package/dist/smart-dom-reader.js +1 -1
  30. package/dist/theme-editor-preview.cjs +203 -0
  31. package/dist/theme-editor-preview.d.cts +5748 -0
  32. package/dist/theme-editor-preview.d.ts +5748 -0
  33. package/dist/theme-editor-preview.js +203 -0
  34. package/dist/theme-editor.cjs +14 -131
  35. package/dist/theme-editor.d.cts +362 -574
  36. package/dist/theme-editor.d.ts +362 -574
  37. package/dist/theme-editor.js +14 -131
  38. package/dist/theme-reference.cjs +1 -1
  39. package/dist/theme-reference.d.cts +1 -1
  40. package/dist/theme-reference.d.ts +1 -1
  41. package/dist/theme-reference.js +1 -1
  42. package/dist/voice-worklet-player.cjs +80 -0
  43. package/dist/voice-worklet-player.d.cts +215 -0
  44. package/dist/voice-worklet-player.d.ts +215 -0
  45. package/dist/voice-worklet-player.js +80 -0
  46. package/dist/widget.css +54 -36
  47. package/package.json +16 -2
  48. package/src/animations/glyph-cycle.ts +11 -14
  49. package/src/animations/wipe.ts +1 -1
  50. package/src/ask-user-question-tool.test.ts +1 -1
  51. package/src/ask-user-question-tool.ts +6 -8
  52. package/src/client.test.ts +67 -12
  53. package/src/client.ts +40 -32
  54. package/src/codegen.test.ts +1 -1
  55. package/src/codegen.ts +1 -1
  56. package/src/components/approval-bubble.test.ts +1 -1
  57. package/src/components/approval-bubble.ts +3 -3
  58. package/src/components/artifact-pane.ts +3 -3
  59. package/src/components/ask-user-question-bubble.test.ts +14 -14
  60. package/src/components/ask-user-question-bubble.ts +10 -10
  61. package/src/components/composer-builder.ts +17 -16
  62. package/src/components/composer-parts.test.ts +54 -0
  63. package/src/components/composer-parts.ts +95 -126
  64. package/src/components/demo-carousel.ts +1 -1
  65. package/src/components/event-stream-view.test.ts +7 -7
  66. package/src/components/event-stream-view.ts +5 -5
  67. package/src/components/header-builder.ts +33 -27
  68. package/src/components/header-layouts.ts +1 -1
  69. package/src/components/header-parts.test.ts +90 -0
  70. package/src/components/header-parts.ts +62 -93
  71. package/src/components/launcher.test.ts +11 -0
  72. package/src/components/launcher.ts +1 -1
  73. package/src/components/message-bubble.test.ts +74 -2
  74. package/src/components/message-bubble.ts +25 -11
  75. package/src/components/messages.ts +2 -2
  76. package/src/components/panel.test.ts +1 -1
  77. package/src/components/panel.ts +92 -97
  78. package/src/components/pill-composer-builder.ts +28 -24
  79. package/src/components/reasoning-bubble.ts +2 -2
  80. package/src/components/suggestions.ts +1 -1
  81. package/src/components/tool-bubble.ts +1 -1
  82. package/src/components/widget-view.test.ts +181 -0
  83. package/src/components/widget-view.ts +234 -0
  84. package/src/defaults.ts +54 -51
  85. package/src/generated/runtype-openapi-contract.ts +5 -0
  86. package/src/index-core.ts +30 -4
  87. package/src/index-global.ts +73 -6
  88. package/src/index.ts +7 -1
  89. package/src/install.test.ts +11 -11
  90. package/src/install.ts +28 -18
  91. package/src/launcher-global.ts +25 -14
  92. package/src/markdown-parsers-eager.ts +20 -0
  93. package/src/markdown-parsers-entry.ts +4 -0
  94. package/src/markdown-parsers-loader.ts +49 -0
  95. package/src/plugin-kit.test.ts +1 -1
  96. package/src/plugin-kit.ts +7 -7
  97. package/src/plugins/types.ts +5 -5
  98. package/src/postprocessors.ts +27 -14
  99. package/src/runtime/host-layout.test.ts +1 -1
  100. package/src/runtime/host-layout.ts +4 -5
  101. package/src/runtime/init.ts +2 -2
  102. package/src/session.test.ts +5 -6
  103. package/src/session.ts +333 -227
  104. package/src/session.voice.test.ts +146 -0
  105. package/src/session.webmcp.test.ts +24 -25
  106. package/src/smart-dom-reader.ts +3 -4
  107. package/src/styles/widget.css +54 -36
  108. package/src/suggest-replies-tool.test.ts +3 -3
  109. package/src/suggest-replies-tool.ts +5 -5
  110. package/src/testing/index.ts +1 -1
  111. package/src/theme-editor/color-utils.ts +2 -2
  112. package/src/theme-editor/index.ts +4 -13
  113. package/src/theme-editor/presets.ts +1 -1
  114. package/src/theme-editor/preview-utils.ts +22 -20
  115. package/src/theme-editor/preview.ts +4 -1
  116. package/src/theme-editor/role-mappings.ts +3 -3
  117. package/src/theme-editor/sections.ts +21 -20
  118. package/src/theme-editor/types.ts +1 -1
  119. package/src/theme-editor/webmcp/index.ts +1 -1
  120. package/src/theme-editor/webmcp/summary.ts +1 -2
  121. package/src/theme-editor/webmcp/tools.ts +30 -30
  122. package/src/theme-editor/webmcp/types.ts +2 -2
  123. package/src/theme-editor-preview.ts +10 -0
  124. package/src/theme-reference.ts +26 -26
  125. package/src/types.ts +368 -99
  126. package/src/ui.approval-plugin.test.ts +3 -3
  127. package/src/ui.ask-user-question-plugin.test.ts +9 -9
  128. package/src/ui.component-directive.test.ts +4 -4
  129. package/src/ui.composer-bar.test.ts +10 -11
  130. package/src/ui.composer-keyboard.test.ts +5 -5
  131. package/src/ui.header-icon-color.test.ts +59 -0
  132. package/src/ui.scroll.test.ts +5 -6
  133. package/src/ui.stop-button.test.ts +3 -4
  134. package/src/ui.suggest-replies.test.ts +2 -2
  135. package/src/ui.ts +292 -131
  136. package/src/utils/buttons.ts +1 -1
  137. package/src/utils/code-generators.ts +1 -1
  138. package/src/utils/composer-history.ts +3 -3
  139. package/src/utils/dom-context.test.ts +2 -2
  140. package/src/utils/dom-context.ts +7 -7
  141. package/src/utils/dom.test.ts +67 -0
  142. package/src/utils/dom.ts +75 -0
  143. package/src/utils/dropdown.ts +2 -2
  144. package/src/utils/event-stream-buffer.test.ts +2 -2
  145. package/src/utils/message-fingerprint.test.ts +9 -0
  146. package/src/utils/message-fingerprint.ts +5 -0
  147. package/src/utils/morph.ts +1 -1
  148. package/src/utils/sanitize.ts +32 -16
  149. package/src/utils/sequence-buffer.test.ts +8 -8
  150. package/src/utils/sequence-buffer.ts +4 -4
  151. package/src/utils/smart-dom-adapter.test.ts +1 -1
  152. package/src/utils/smart-dom-adapter.ts +4 -5
  153. package/src/utils/speech-text.test.ts +122 -0
  154. package/src/utils/speech-text.ts +101 -0
  155. package/src/utils/stream-animation.test.ts +3 -3
  156. package/src/utils/stream-animation.ts +6 -6
  157. package/src/utils/theme.test.ts +1 -1
  158. package/src/utils/throughput-tracker.test.ts +11 -11
  159. package/src/utils/throughput-tracker.ts +9 -9
  160. package/src/utils/tokens.ts +13 -13
  161. package/src/utils/virtual-scroller.ts +1 -1
  162. package/src/vendor/smart-dom-reader/README.md +4 -4
  163. package/src/vendor/smart-dom-reader/index.d.ts +1 -1
  164. package/src/vendor/smart-dom-reader/index.js +2 -2
  165. package/src/version.ts +1 -1
  166. package/src/voice/audio-playback-manager.test.ts +159 -0
  167. package/src/voice/audio-playback-manager.ts +145 -30
  168. package/src/voice/browser-speech-engine.ts +130 -0
  169. package/src/voice/fallback-speech-engine.ts +89 -0
  170. package/src/voice/index.ts +21 -0
  171. package/src/voice/read-aloud-controller.test.ts +143 -0
  172. package/src/voice/read-aloud-controller.ts +136 -0
  173. package/src/voice/runtype-speech-engine.test.ts +280 -0
  174. package/src/voice/runtype-speech-engine.ts +211 -0
  175. package/src/voice/runtype-tts-entry.ts +10 -0
  176. package/src/voice/runtype-tts-loader.test.ts +47 -0
  177. package/src/voice/runtype-tts-loader.ts +42 -0
  178. package/src/voice/runtype-voice-provider.ts +332 -537
  179. package/src/voice/voice-factory.ts +26 -4
  180. package/src/voice/voice.test.ts +321 -7
  181. package/src/voice/worklet-playback-engine.ts +272 -0
  182. package/src/voice-worklet-player.ts +39 -0
  183. package/src/webmcp-bridge.test.ts +6 -6
  184. package/src/webmcp-bridge.ts +24 -25
  185. package/src/webmcp-polyfill.ts +1 -1
  186. package/src/voice/voice-activity-detector.ts +0 -90
@@ -1,110 +1,4 @@
1
- var Ru=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Us(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];Ru(s)&&Ru(r)?n[o]=Us(s,r):n[o]=r}return n}var mo="min(440px, calc(100vw - 24px))",_a="440px",Mt={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:mo,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 Pu(e,t){if(!(!e&&!t))return e?t?Us(e,t):e:t}function Wu(e){var t,n,o,r,s,a,i,d,l,u,g,f,m,x,v,E,L,I,W,H,R;return e?{...Mt,...e,theme:Pu(Mt.theme,e.theme),darkTheme:Pu(Mt.darkTheme,e.darkTheme),launcher:{...Mt.launcher,...e.launcher,dock:{...(t=Mt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(o=Mt.launcher)==null?void 0:o.clearChat,...(r=e.launcher)==null?void 0:r.clearChat}},copy:{...Mt.copy,...e.copy},sendButton:{...Mt.sendButton,...e.sendButton},statusIndicator:{...Mt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Mt.voiceRecognition,...e.voiceRecognition},features:(()=>{var ie,Q,re,be,he,j,se,Re,ne,Z;let w=(ie=Mt.features)==null?void 0:ie.artifacts,C=(Q=e.features)==null?void 0:Q.artifacts,k=(re=Mt.features)==null?void 0:re.scrollToBottom,A=(be=e.features)==null?void 0:be.scrollToBottom,S=(he=Mt.features)==null?void 0:he.scrollBehavior,_=(j=e.features)==null?void 0:j.scrollBehavior,V=(se=Mt.features)==null?void 0:se.streamAnimation,K=(Re=e.features)==null?void 0:Re.streamAnimation,fe=(ne=Mt.features)==null?void 0:ne.askUserQuestion,ue=(Z=e.features)==null?void 0:Z.askUserQuestion,ce=w===void 0&&C===void 0?void 0:{...w,...C,layout:{...w==null?void 0:w.layout,...C==null?void 0:C.layout}},ke=k===void 0&&A===void 0?void 0:{...k,...A},ve=S===void 0&&_===void 0?void 0:{...S,..._},He=V===void 0&&K===void 0?void 0:{...V,...K},Se=fe===void 0&&ue===void 0?void 0:{...fe,...ue,styles:{...fe==null?void 0:fe.styles,...ue==null?void 0:ue.styles}};return{...Mt.features,...e.features,...ke!==void 0?{scrollToBottom:ke}:{},...ve!==void 0?{scrollBehavior:ve}:{},...ce!==void 0?{artifacts:ce}:{},...He!==void 0?{streamAnimation:He}:{},...Se!==void 0?{askUserQuestion:Se}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Mt.suggestionChips,suggestionChipsConfig:{...Mt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Mt.layout,...e.layout,header:{...(a=Mt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Mt.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(g=(u=Mt.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=Mt.layout)==null?void 0:x.messages)==null?void 0:v.timestamp,...(L=(E=e.layout)==null?void 0:E.messages)==null?void 0:L.timestamp}},slots:{...(I=Mt.layout)==null?void 0:I.slots,...(W=e.layout)==null?void 0:W.slots}},markdown:{...Mt.markdown,...e.markdown,options:{...(H=Mt.markdown)==null?void 0:H.options,...(R=e.markdown)==null?void 0:R.options}},messageActions:{...Mt.messageActions,...e.messageActions}}:Mt}var mf={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"}},gf={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"}},ff={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:mo,maxWidth:_a,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 ss(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."))?ss(e,o):o}function Bu(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let i=`${r}.${s}`;if(typeof a=="string"){let d=ss(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 hf(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function Hu(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=Hu(s,r):n[o]=r}return n}function bf(e,t){return t?Hu(e,t):e}function pn(e,t={}){var r,s,a,i,d,l,u,g,f,m,x,v,E;let n={palette:mf,semantic:gf,components:ff},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,...(E=e==null?void 0:e.semantic)==null?void 0:E.typography}},components:bf(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let L=hf(o);if(!L.valid)throw new Error(`Theme validation failed: ${L.errors.map(I=>I.message).join(", ")}`)}if(t.plugins)for(let L of t.plugins)o=L.transform(o);return o}function Du(e){var v,E,L,I,W,H,R,w,C,k,A,S,_,V,K,fe,ue,ce,ke,ve,He,Se,ie,Q,re,be,he,j,se,Re,ne,Z,oe,at,it,Le,de,Qe,We,q,me,tt,Tt,te,ze,Nn,Bt,an,ro,Eo,D,pe,De,Ke,Ne,Ve,ot,It,qt,Xt,G,yt,st,Ce,le,Ze,Zt,jt,Rn,xn,ut,kt,Xe,Ut,ln,Sn,An,bn,Mo,Ct,zn,qn,No,ho,vt,yr,Lo,vr,_n,qr,Zo,_o,St,jn,Kn,Pn,Lt,so,ao,Gn,er,Vo,tr,Yn,Ht,Wn,io,nr,$o,or,Io,Qn,bo,gt,en,tn,Xn,rr;let t=Bu(e),n={};for(let[xe,yo]of Object.entries(t)){let lo=xe.replace(/\./g,"-");n[`--persona-${lo}`]=yo.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(E=n["--persona-semantic-colors-secondary"])!=null?E:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(L=n["--persona-semantic-colors-accent"])!=null?L:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(I=n["--persona-semantic-colors-surface"])!=null?I:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(W=n["--persona-semantic-colors-background"])!=null?W:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(H=n["--persona-semantic-colors-container"])!=null?H:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(R=n["--persona-semantic-colors-text"])!=null?R: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"]=(k=n["--persona-semantic-colors-border"])!=null?k: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"]=(_=n["--persona-components-voice-recording-background"])!=null?_:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(V=n["--persona-components-voice-processing-icon"])!=null?V:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(K=n["--persona-components-voice-speaking-icon"])!=null?K:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(fe=n["--persona-components-approval-requested-background"])!=null?fe:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(ue=n["--persona-components-approval-requested-border"])!=null?ue:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(ce=n["--persona-components-approval-requested-text"])!=null?ce:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(ke=n["--persona-components-approval-requested-shadow"])!=null?ke:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-approval-approve-bg"]=(ve=n["--persona-components-approval-approve-background"])!=null?ve:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(He=n["--persona-components-approval-deny-background"])!=null?He:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Se=n["--persona-components-attachment-image-background"])!=null?Se:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(ie=n["--persona-components-attachment-image-border"])!=null?ie:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(Q=n["--persona-semantic-typography-fontFamily"])!=null?Q:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(re=n["--persona-semantic-typography-fontSize"])!=null?re:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(be=n["--persona-semantic-typography-fontWeight"])!=null?be:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(he=n["--persona-semantic-typography-lineHeight"])!=null?he:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(j=n["--persona-palette-radius-sm"])!=null?j:"0.125rem",n["--persona-radius-md"]=(se=n["--persona-palette-radius-md"])!=null?se:"0.375rem",n["--persona-radius-lg"]=(Re=n["--persona-palette-radius-lg"])!=null?Re:"0.5rem",n["--persona-radius-xl"]=(ne=n["--persona-palette-radius-xl"])!=null?ne:"0.75rem",n["--persona-radius-full"]=(Z=n["--persona-palette-radius-full"])!=null?Z:"9999px",n["--persona-launcher-radius"]=(at=(oe=n["--persona-components-launcher-borderRadius"])!=null?oe:n["--persona-palette-radius-full"])!=null?at:"9999px",n["--persona-launcher-bg"]=(it=n["--persona-components-launcher-background"])!=null?it:n["--persona-primary"],n["--persona-launcher-fg"]=(Le=n["--persona-components-launcher-foreground"])!=null?Le:n["--persona-text-inverse"],n["--persona-launcher-border"]=(de=n["--persona-components-launcher-border"])!=null?de:n["--persona-border"],n["--persona-button-primary-bg"]=(Qe=n["--persona-components-button-primary-background"])!=null?Qe:n["--persona-primary"],n["--persona-button-primary-fg"]=(We=n["--persona-components-button-primary-foreground"])!=null?We:n["--persona-text-inverse"],n["--persona-button-radius"]=(me=(q=n["--persona-components-button-primary-borderRadius"])!=null?q:n["--persona-palette-radius-full"])!=null?me:"9999px",n["--persona-panel-radius"]=(Tt=(tt=n["--persona-components-panel-borderRadius"])!=null?tt:n["--persona-radius-xl"])!=null?Tt:"0.75rem",n["--persona-panel-border"]=(te=n["--persona-components-panel-border"])!=null?te:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Nn=(ze=n["--persona-components-panel-shadow"])!=null?ze:n["--persona-palette-shadows-xl"])!=null?Nn:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(Bt=n["--persona-components-launcher-shadow"])!=null?Bt:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(ro=(an=n["--persona-components-input-borderRadius"])!=null?an:n["--persona-radius-lg"])!=null?ro:"0.5rem",n["--persona-message-user-radius"]=(D=(Eo=n["--persona-components-message-user-borderRadius"])!=null?Eo:n["--persona-radius-lg"])!=null?D:"0.5rem",n["--persona-message-assistant-radius"]=(De=(pe=n["--persona-components-message-assistant-borderRadius"])!=null?pe:n["--persona-radius-lg"])!=null?De:"0.5rem",n["--persona-header-bg"]=(Ke=n["--persona-components-header-background"])!=null?Ke:n["--persona-surface"],n["--persona-header-border"]=(Ne=n["--persona-components-header-border"])!=null?Ne:n["--persona-divider"],n["--persona-header-icon-bg"]=(Ve=n["--persona-components-header-iconBackground"])!=null?Ve:n["--persona-primary"],n["--persona-header-icon-fg"]=(ot=n["--persona-components-header-iconForeground"])!=null?ot:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(It=n["--persona-components-header-titleForeground"])!=null?It:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(qt=n["--persona-components-header-subtitleForeground"])!=null?qt:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Xt=n["--persona-components-header-actionIconForeground"])!=null?Xt:n["--persona-muted"];let o=(G=e.components)==null?void 0:G.header;o!=null&&o.shadow&&(n["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom);let r=(yt=e.components)==null?void 0:yt.introCard;n["--persona-intro-card-bg"]=(st=n["--persona-components-introCard-background"])!=null?st:n["--persona-surface"],n["--persona-intro-card-radius"]=(Ce=n["--persona-components-introCard-borderRadius"])!=null?Ce:"1rem",n["--persona-intro-card-padding"]=(le=n["--persona-components-introCard-padding"])!=null?le:"1.5rem",n["--persona-intro-card-shadow"]=(Zt=(Ze=r==null?void 0:r.shadow)!=null?Ze:n["--persona-components-introCard-shadow"])!=null?Zt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(jt=n["--persona-components-input-background"])!=null?jt:n["--persona-surface"],n["--persona-input-placeholder"]=(Rn=n["--persona-components-input-placeholder"])!=null?Rn:n["--persona-text-muted"],n["--persona-message-user-bg"]=(xn=n["--persona-components-message-user-background"])!=null?xn:n["--persona-accent"],n["--persona-message-user-text"]=(ut=n["--persona-components-message-user-text"])!=null?ut:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(kt=n["--persona-components-message-user-shadow"])!=null?kt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Xe=n["--persona-components-message-assistant-background"])!=null?Xe:n["--persona-surface"],n["--persona-message-assistant-text"]=(Ut=n["--persona-components-message-assistant-text"])!=null?Ut:n["--persona-text"],n["--persona-message-assistant-border"]=(ln=n["--persona-components-message-assistant-border"])!=null?ln:n["--persona-border"],n["--persona-message-assistant-shadow"]=(Sn=n["--persona-components-message-assistant-shadow"])!=null?Sn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(bn=(An=n["--persona-components-scrollToBottom-background"])!=null?An:n["--persona-button-primary-bg"])!=null?bn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(Ct=(Mo=n["--persona-components-scrollToBottom-foreground"])!=null?Mo:n["--persona-button-primary-fg"])!=null?Ct:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(zn=n["--persona-components-scrollToBottom-border"])!=null?zn:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(qn=n["--persona-components-scrollToBottom-size"])!=null?qn:"40px",n["--persona-scroll-to-bottom-radius"]=(vt=(ho=(No=n["--persona-components-scrollToBottom-borderRadius"])!=null?No:n["--persona-button-radius"])!=null?ho:n["--persona-radius-full"])!=null?vt:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Lo=(yr=n["--persona-components-scrollToBottom-shadow"])!=null?yr:n["--persona-palette-shadows-sm"])!=null?Lo:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(vr=n["--persona-components-scrollToBottom-padding"])!=null?vr:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(_n=n["--persona-components-scrollToBottom-gap"])!=null?_n:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Zo=(qr=n["--persona-components-scrollToBottom-fontSize"])!=null?qr:n["--persona-palette-typography-fontSize-sm"])!=null?Zo:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(_o=n["--persona-components-scrollToBottom-iconSize"])!=null?_o:"14px",n["--persona-tool-bubble-shadow"]=(St=n["--persona-components-toolBubble-shadow"])!=null?St:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(jn=n["--persona-components-reasoningBubble-shadow"])!=null?jn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Kn=n["--persona-components-composer-shadow"])!=null?Kn:"none",n["--persona-md-inline-code-bg"]=(Pn=n["--persona-components-markdown-inlineCode-background"])!=null?Pn:n["--persona-container"],n["--persona-md-inline-code-color"]=(Lt=n["--persona-components-markdown-inlineCode-foreground"])!=null?Lt:n["--persona-text"],n["--persona-md-link-color"]=(ao=(so=n["--persona-components-markdown-link-foreground"])!=null?so:n["--persona-accent"])!=null?ao:"#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"]=(Gn=n["--persona-components-markdown-codeBlock-background"])!=null?Gn:n["--persona-container"],n["--persona-md-code-block-border-color"]=(er=n["--persona-components-markdown-codeBlock-borderColor"])!=null?er:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Vo=n["--persona-components-markdown-codeBlock-textColor"])!=null?Vo:"inherit",n["--persona-md-table-header-bg"]=(tr=n["--persona-components-markdown-table-headerBackground"])!=null?tr:n["--persona-container"],n["--persona-md-table-border-color"]=(Yn=n["--persona-components-markdown-table-borderColor"])!=null?Yn:n["--persona-border"],n["--persona-md-hr-color"]=(Ht=n["--persona-components-markdown-hr-color"])!=null?Ht:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Wn=n["--persona-components-markdown-blockquote-borderColor"])!=null?Wn:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(io=n["--persona-components-markdown-blockquote-background"])!=null?io:"transparent",n["--persona-md-blockquote-text-color"]=(nr=n["--persona-components-markdown-blockquote-textColor"])!=null?nr:n["--persona-palette-colors-gray-500"],n["--cw-container"]=($o=n["--persona-components-collapsibleWidget-container"])!=null?$o:n["--persona-surface"],n["--cw-surface"]=(or=n["--persona-components-collapsibleWidget-surface"])!=null?or:n["--persona-surface"],n["--cw-border"]=(Io=n["--persona-components-collapsibleWidget-border"])!=null?Io:n["--persona-border"],n["--persona-message-border"]=(Qn=n["--persona-components-message-border"])!=null?Qn: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 xe=x.toolbar;xe.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=xe.iconHoverColor),xe.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=xe.iconHoverBackground),xe.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=xe.iconPadding),xe.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=xe.iconBorderRadius),xe.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=xe.iconBorder),xe.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=xe.toggleGroupGap),xe.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=xe.toggleBorderRadius),xe.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=xe.copyBackground),xe.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=xe.copyBorder),xe.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=xe.copyColor),xe.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=xe.copyBorderRadius),xe.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=xe.copyPadding),xe.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=xe.copyMenuBackground,n["--persona-dropdown-bg"]=(bo=n["--persona-dropdown-bg"])!=null?bo:xe.copyMenuBackground),xe.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=xe.copyMenuBorder,n["--persona-dropdown-border"]=(gt=n["--persona-dropdown-border"])!=null?gt:xe.copyMenuBorder),xe.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=xe.copyMenuShadow,n["--persona-dropdown-shadow"]=(en=n["--persona-dropdown-shadow"])!=null?en:xe.copyMenuShadow),xe.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=xe.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(tn=n["--persona-dropdown-radius"])!=null?tn:xe.copyMenuBorderRadius),xe.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=xe.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(Xn=n["--persona-dropdown-item-hover-bg"])!=null?Xn:xe.copyMenuItemHoverBackground),xe.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=xe.iconBackground),xe.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=xe.toolbarBorder)}if(x!=null&&x.tab){let xe=x.tab;xe.background&&(n["--persona-artifact-tab-bg"]=xe.background),xe.activeBackground&&(n["--persona-artifact-tab-active-bg"]=xe.activeBackground),xe.activeBorder&&(n["--persona-artifact-tab-active-border"]=xe.activeBorder),xe.borderRadius&&(n["--persona-artifact-tab-radius"]=xe.borderRadius),xe.textColor&&(n["--persona-artifact-tab-color"]=xe.textColor),xe.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=xe.hoverBackground),xe.listBackground&&(n["--persona-artifact-tab-list-bg"]=xe.listBackground),xe.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=xe.listBorderColor),xe.listPadding&&(n["--persona-artifact-tab-list-padding"]=xe.listPadding)}if(x!=null&&x.pane){let xe=x.pane;if(xe.toolbarBackground){let yo=(rr=ss(e,xe.toolbarBackground))!=null?rr:xe.toolbarBackground;n["--persona-artifact-toolbar-bg"]=yo}}return n}var yf={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"}}},Ou=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},cl=()=>{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"},vf=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":cl()},xf=e=>vf(e),wf=e=>pn(e),Cf=e=>{var n;let t=pn(void 0,{validate:!1});return pn({...e,palette:{...t.palette,colors:{...yf.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Va=e=>{let t=xf(e),n=Ou(e==null?void 0:e.theme),o=Ou(e==null?void 0:e.darkTheme);return t==="dark"?Cf(Us(n!=null?n:{},o!=null?o:{})):wf(n)},Sf=e=>Du(e),as=(e,t)=>{let n=Va(t),o=Sf(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s)},Fu=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(cl())});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(cl());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 dl(e,t){let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return o}function Pr(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]:Pr((i=a==null?void 0:a[r])!=null?i:{},s.join("."),n)}}var pl=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?{...Mt,...n}:n!=null?n:Mt,this.theme=pn(t,{validate:!1}),this.syncThemeIntoConfig(),this.pushHistorySnapshot(this.exportSnapshot(),!0)}get(t){var n;return t.startsWith("theme.")?dl(this.theme,t.replace("theme.","")):t.startsWith("darkTheme.")?dl((n=this.config.darkTheme)!=null?n:{},t.replace("darkTheme.","")):dl(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=Pr(this.theme,r,n),this.syncThemeIntoConfig()}else if(t.startsWith("darkTheme.")){let r=t.replace("darkTheme.",""),s=(o=this.config.darkTheme)!=null?o:pn();this.config={...this.config,darkTheme:Pr(s,r,n)}}else this.config=Pr(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=Pr(this.theme,d,i),n=!0}else if(a.startsWith("darkTheme.")){let d=a.replace("darkTheme.",""),l=(s=this.config.darkTheme)!=null?s:pn();this.config={...this.config,darkTheme:Pr(l,d,i)},o=!0}else this.config=Pr(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=pn((s=n.theme)!=null?s:this.theme,{validate:!1});this.setFullConfig(a,i);return}let o=pn(n,{validate:!1});this.setTheme(o)}resetToDefaults(){this.config={...Mt},this.theme=pn(),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=pn(t.theme,{validate:!1}),this.syncThemeIntoConfig(),this.suppressHistory=!1,this.notifyListeners()}};function ul(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 ml(e,t){return t==="rem"?`${e}rem`:`${e}px`}function Af(e,t){return t==="rem"?e*16:e}function Tf(e,t){return t==="rem"?e/16:e}function zs(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 gl(e){return/^#[0-9A-Fa-f]{6}$/.test(e)}function fl(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 $a(e,t){let n=s=>{var l;let a=zs(s),i=a.startsWith("rgb")?(l=fl(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 Nu(e){var f;let t=zs(e),n=t.startsWith("rgb")?(f=fl(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 _u(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 hl(e){let{h:t,s:n,l:o}=Nu(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]=_u(t,l,d)}return a}var is=["50","100","200","300","400","500","600","700","800","900","950"],bl=["primary","secondary","accent","gray","success","warning","error","info"];function kf(e,t){return`palette.colors.${e}.${t}`}function Vu(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.")?Vu(e,`theme.${o}`,n+1):"#cbd5e1"}function Ef(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 Oo=[{id:"solid",label:"Solid"},{id:"soft",label:"Soft"}],Ua=["primary","secondary","accent","gray"],Mf={primary:"Primary",secondary:"Secondary",accent:"Accent",gray:"Neutral"},za={roleId:"role-surfaces",helper:"Page and panel backgrounds",previewZone:"container",intensities:Oo,targets:[{path:"semantic.colors.background",kind:"background"},{path:"semantic.colors.surface",kind:"background"},{path:"semantic.colors.container",kind:"background"}]},qa={roleId:"role-header",helper:"Widget header bar",previewZone:"header",intensities:Oo,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"}]},ja={roleId:"role-user-messages",helper:"User chat bubbles",previewZone:"user-message",intensities:Oo,targets:[{path:"components.message.user.background",kind:"background"},{path:"components.message.user.text",kind:"foreground"}]},Ka={roleId:"role-assistant-messages",helper:"Assistant chat bubbles",previewZone:"assistant-message",intensities:Oo,targets:[{path:"components.message.assistant.background",kind:"background"},{path:"components.message.assistant.text",kind:"foreground"}]},Ga={roleId:"role-primary-actions",helper:"Send button and primary buttons",intensities:Oo,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"}]},Ya={roleId:"role-scroll-to-bottom",helper:"Scroll-to-bottom affordances in transcript and event stream",intensities:Oo,targets:[{path:"components.scrollToBottom.background",kind:"background"},{path:"components.scrollToBottom.foreground",kind:"foreground"},{path:"components.scrollToBottom.border",kind:"border"}]},Qa={roleId:"role-input",helper:"Message input field",previewZone:"composer",intensities:Oo,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"}]},Xa={roleId:"role-links-focus",helper:"Links, focus rings, and interactive highlights",intensities:Oo,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"}]},Ja={roleId:"role-borders",helper:"Borders, dividers, and separators",intensities:Oo,targets:[{path:"semantic.colors.border",kind:"border"},{path:"semantic.colors.divider",kind:"border"}]},Wr=[za,qa,ja,Ka,Ga,Ya,Qa,Xa,Ja];function Za(e,t,n){let o={},r=e==="neutral"?"gray":e;for(let s of n.targets){let a=Lf(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 Lf(e,t,n,o){let r=t==="solid";if(o==="role-header")return If(e,r,n);if(o==="role-input")return Rf(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 If(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 Rf(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 Pf=/^palette\.colors\.(\w+)\.(\d+)$/;function yl(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(Pf);if(!r)return null;let s=r[1],a=Ua.includes(s)?s:null;if(!a)return null;for(let l of["solid","soft"]){let u=Za(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 Wf={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"}]}]},Bf={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"}]},Hf={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"}}]},Df={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)"}]}]},Of={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"}]}]},Ff={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"}}]},Nf={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)"}]},_f={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"}]}]},cs=[Bf,Hf,Of,Df,Wf,Ff,Nf,_f];function Uu(){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:bl.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 zu={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"}}]},Vf=Uu(),$f=zu,Uf=[Uu(),zu],zf={id:"comp-panel",title:"Panel",collapsed:!1,fields:[{id:"panel-width",label:"Width",type:"text",path:"theme.components.panel.width",defaultValue:mo},{id:"panel-max-width",label:"Max Width",type:"text",path:"theme.components.panel.maxWidth",defaultValue:_a},{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"}]}]},qf={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"}]}]},jf={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"}]}]},Kf={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"}]}]},Gf={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"}]}]},Yf={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"}}]},Qf={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"}}]},Xf={id:"comp-input-colors",title:"Input Colors",collapsed:!0,fields:[{id:"input-bg",label:"Background",type:"token-ref",path:"theme.components.input.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"input-placeholder",label:"Placeholder Color",type:"token-ref",path:"theme.components.input.placeholder",defaultValue:"semantic.colors.textMuted",tokenRef:{tokenType:"color"}},{id:"input-focus-border",label:"Focus Border",type:"token-ref",path:"theme.components.input.focus.border",defaultValue:"semantic.colors.interactive.focus",tokenRef:{tokenType:"color"}},{id:"input-focus-ring",label:"Focus Ring",type:"token-ref",path:"theme.components.input.focus.ring",defaultValue:"semantic.colors.interactive.focus",tokenRef:{tokenType:"color"}}]},Jf={id:"comp-button-colors",title:"Button Colors",collapsed:!0,fields:[{id:"btn-primary-bg",label:"Primary Background",type:"token-ref",path:"theme.components.button.primary.background",defaultValue:"semantic.colors.primary",tokenRef:{tokenType:"color"}},{id:"btn-primary-fg",label:"Primary Foreground",type:"token-ref",path:"theme.components.button.primary.foreground",defaultValue:"semantic.colors.textInverse",tokenRef:{tokenType:"color"}},{id:"btn-secondary-bg",label:"Secondary Background",type:"token-ref",path:"theme.components.button.secondary.background",defaultValue:"semantic.colors.surface",tokenRef:{tokenType:"color"}},{id:"btn-secondary-fg",label:"Secondary Foreground",type:"token-ref",path:"theme.components.button.secondary.foreground",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}},{id:"btn-ghost-bg",label:"Ghost Background",type:"color",path:"theme.components.button.ghost.background",defaultValue:"transparent"},{id:"btn-ghost-fg",label:"Ghost Foreground",type:"token-ref",path:"theme.components.button.ghost.foreground",defaultValue:"semantic.colors.text",tokenRef:{tokenType:"color"}}]},Zf={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"}]},ls=[{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"}],vl="0 5px 15px rgba(15, 23, 42, 0.08)",$u=[{value:vl,label:"Default"},...ls],eh={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:ls},{id:"shadow-msg-assistant",label:"Assistant Message",type:"select",path:"theme.components.message.assistant.shadow",defaultValue:"palette.shadows.sm",options:ls},{id:"shadow-tool-bubble",label:"Tool Call Bubble",type:"select",path:"theme.components.toolBubble.shadow",defaultValue:"palette.shadows.sm",options:ls},{id:"shadow-reasoning-bubble",label:"Reasoning Bubble",type:"select",path:"theme.components.reasoningBubble.shadow",defaultValue:"palette.shadows.sm",options:ls},{id:"shadow-approval",label:"Approval Bubble",type:"select",path:"theme.components.approval.requested.shadow",defaultValue:vl,options:$u},{id:"shadow-intro-card",label:"Intro Card",type:"select",path:"theme.components.introCard.shadow",defaultValue:vl,options:$u},{id:"shadow-composer",label:"Composer",type:"select",path:"theme.components.composer.shadow",defaultValue:"palette.shadows.none",options:ls}]},qu=[zf,qf,jf,Kf,Gf,eh],ju=[Yf,Qf,Xf,Jf,Zf],Ku=[...qu,...ju],xl=1024*1024,th=["What can you help me with?","Tell me about your features","How does this work?"],qs={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 nh(e){return Number(e)*xl}function oh(e){let t=Number(e);return Number.isFinite(t)?t>1024?String(Math.round(t/xl)):String(t):"10"}function rh(e){var t;return(t=qs[String(e)])!=null?t:qs.images}function sh(e){let t=Array.isArray(e)?e:qs.images,n=[...new Set(t)].sort();for(let[o,r]of Object.entries(qs)){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 ah={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"}]},ih={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:th}]},lh={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:""}]},ch={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}]},dh={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"}]}]},ph={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"}]}]},uh={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:mo},{id:"launch-auto-expand",label:"Auto Expand",type:"toggle",path:"launcher.autoExpand",defaultValue:!1},{id:"launch-title",label:"Title",type:"text",path:"launcher.title",defaultValue:"Chat Assistant"},{id:"launch-subtitle",label:"Subtitle",type:"text",path:"launcher.subtitle",defaultValue:"Here to help you get answers fast"}]},mh={id:"launcher-advanced",title:"Launcher Advanced",collapsed:!0,fields:[{id:"launch-dock-side",label:"Dock Side",type:"select",path:"launcher.dock.side",defaultValue:"right",options:[{value:"right",label:"Right"},{value:"left",label:"Left"}]},{id:"launch-dock-width",label:"Dock Width",type:"text",path:"launcher.dock.width",defaultValue:"420px"},{id:"launch-dock-animate",label:"Dock Animate",type:"toggle",path:"launcher.dock.animate",defaultValue:!0},{id:"launch-dock-reveal",label:"Dock Reveal",type:"select",path:"launcher.dock.reveal",defaultValue:"resize",options:[{value:"resize",label:"Resize"},{value:"overlay",label:"Overlay"},{value:"push",label:"Push"},{value:"emerge",label:"Emerge"}]},{id:"launch-text-hidden",label:"Hide Text",type:"toggle",path:"launcher.textHidden",defaultValue:!1},{id:"launch-icon-text",label:"Agent Icon Text",type:"text",path:"launcher.agentIconText",defaultValue:"\u{1F4AC}"},{id:"launch-icon-name",label:"Agent Icon Name (Lucide)",type:"text",path:"launcher.agentIconName",defaultValue:"bot"},{id:"launch-icon-hidden",label:"Hide Agent Icon",type:"toggle",path:"launcher.agentIconHidden",defaultValue:!1},{id:"launch-icon-size",label:"Agent Icon Size",type:"slider",path:"launcher.agentIconSize",defaultValue:"40px",slider:{min:16,max:72,step:2}},{id:"launch-icon-url",label:"Icon Image URL",description:"Custom image URL (overrides emoji/lucide)",type:"text",path:"launcher.iconUrl",defaultValue:""},{id:"launch-header-icon-name",label:"Header Icon Name (Lucide)",type:"text",path:"launcher.headerIconName",defaultValue:"bot"},{id:"launch-header-icon-size",label:"Header Icon Size",type:"slider",path:"launcher.headerIconSize",defaultValue:"48px",slider:{min:24,max:80,step:2}},{id:"launch-header-icon-hidden",label:"Hide Header Icon",type:"toggle",path:"launcher.headerIconHidden",defaultValue:!1},{id:"launch-full-height",label:"Full Height",type:"toggle",path:"launcher.fullHeight",defaultValue:!1},{id:"launch-sidebar",label:"Sidebar Mode",type:"toggle",path:"launcher.sidebarMode",defaultValue:!1},{id:"launch-sidebar-width",label:"Sidebar Width",type:"text",path:"launcher.sidebarWidth",defaultValue:"420px"},{id:"launch-mobile-fullscreen",label:"Mobile Fullscreen",description:"Fullscreen on mobile devices",type:"toggle",path:"launcher.mobileFullscreen",defaultValue:!0},{id:"launch-mobile-breakpoint",label:"Mobile Breakpoint (px)",type:"text",path:"launcher.mobileBreakpoint",defaultValue:640,formatValue:e=>String(e!=null?e:640),parseValue:e=>Number(e)},{id:"launch-height-offset",label:"Height Offset (px)",type:"text",path:"launcher.heightOffset",defaultValue:0,formatValue:e=>String(e!=null?e:0),parseValue:e=>Number(e)},{id:"launch-collapsed-max-width",label:"Collapsed Max Width",description:"Max width of launcher pill when closed",type:"text",path:"launcher.collapsedMaxWidth",defaultValue:""},{id:"launch-cta-text",label:"CTA Icon Text",type:"text",path:"launcher.callToActionIconText",defaultValue:"\u2197"},{id:"launch-cta-name",label:"CTA Icon Name",type:"text",path:"launcher.callToActionIconName",defaultValue:""},{id:"launch-cta-hidden",label:"Hide CTA Icon",type:"toggle",path:"launcher.callToActionIconHidden",defaultValue:!1},{id:"launch-cta-size",label:"CTA Icon Size",type:"slider",path:"launcher.callToActionIconSize",defaultValue:"32px",slider:{min:16,max:64,step:2}},{id:"launch-cta-padding",label:"CTA Icon Padding",type:"slider",path:"launcher.callToActionIconPadding",defaultValue:"5px",slider:{min:0,max:24,step:1}},{id:"launch-cta-bg",label:"CTA Icon Background",type:"color",path:"launcher.callToActionIconBackgroundColor",defaultValue:""}]},gh={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"}]},fh={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"}]},hh={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"}]},bh={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"}]},yh={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:""}]},vh={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)}]},xh={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*xl,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:oh,parseValue:nh},{id:"attach-types",label:"Allowed File Types",type:"select",path:"attachments.allowedTypes",defaultValue:qs.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:sh,parseValue:rh}]},wh={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"}]}]},Ch={id:"artifacts-customization",title:"Artifact Customization",collapsed:!0,fields:[{id:"art-toolbar",label:"Toolbar Preset",type:"select",path:"features.artifacts.layout.toolbarPreset",defaultValue:"default",options:[{value:"default",label:"Default"},{value:"document",label:"Document"}]},{id:"art-pane-width",label:"Pane Width",description:"CSS width (e.g. 40%, 28rem)",type:"text",path:"features.artifacts.layout.paneWidth",defaultValue:"40%"},{id:"art-pane-max-width",label:"Pane Max Width",type:"text",path:"features.artifacts.layout.paneMaxWidth",defaultValue:"28rem"},{id:"art-split-gap",label:"Split Gap",type:"text",path:"features.artifacts.layout.splitGap",defaultValue:"0.5rem"},{id:"art-pane-bg",label:"Pane Background",type:"color",path:"features.artifacts.layout.paneBackground",defaultValue:""},{id:"art-unified",label:"Unified Split Chrome",description:"Wrap chat and artifact in a single container",type:"toggle",path:"features.artifacts.layout.unifiedSplitChrome",defaultValue:!1},{id:"art-resizable",label:"Resizable",description:"Allow dragging the pane divider",type:"toggle",path:"features.artifacts.layout.resizable",defaultValue:!1},{id:"art-expand-panel",label:"Expand Panel When Open",description:"Widen the launcher panel to fit artifacts",type:"toggle",path:"features.artifacts.layout.expandLauncherPanelWhenOpen",defaultValue:!0}]},Sh={id:"api-integration",title:"API & Integration",description:"Runtime and integration options.",collapsed:!0,fields:[{id:"dev-api-url",label:"API URL",type:"text",path:"apiUrl",defaultValue:""},{id:"dev-flow",label:"Flow ID",type:"text",path:"flowId",defaultValue:""},{id:"dev-parser",label:"Stream Parser",type:"select",path:"parserType",defaultValue:"plain",options:[{value:"plain",label:"Plain Text"},{value:"json",label:"JSON"},{value:"regex-json",label:"Regex JSON"},{value:"xml",label:"XML"}]}]},Ah={id:"debug-inspection",title:"Debug & Inspection",collapsed:!0,fields:[{id:"dev-reasoning",label:"Show Reasoning",description:"Display AI reasoning steps",type:"toggle",path:"features.showReasoning",defaultValue:!1},{id:"dev-tool-calls",label:"Show Tool Calls",description:"Display tool call details",type:"toggle",path:"features.showToolCalls",defaultValue:!1},{id:"dev-tool-collapsed-mode",label:"Tool Call Summary",description:"Choose what collapsed tool rows show by default",type:"select",path:"features.toolCallDisplay.collapsedMode",defaultValue:"tool-call",options:[{value:"tool-call",label:"Tool Call"},{value:"tool-name",label:"Tool Name"},{value:"tool-preview",label:"Tool Preview"}]},{id:"dev-tool-active-preview",label:"Tool Preview While Active",description:"Show a lightweight preview in collapsed active tool rows",type:"toggle",path:"features.toolCallDisplay.activePreview",defaultValue:!1},{id:"dev-tool-preview-lines",label:"Tool Preview Lines",type:"select",path:"features.toolCallDisplay.previewMaxLines",defaultValue:3,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"3",label:"3"},{value:"4",label:"4"},{value:"5",label:"5"}],formatValue:e=>String(e!=null?e:3),parseValue:e=>Number(e)},{id:"dev-tool-active-min-height",label:"Tool Active Min Height",description:"CSS min-height for collapsed active tool rows (e.g. 5rem)",type:"text",path:"features.toolCallDisplay.activeMinHeight",defaultValue:""},{id:"dev-tool-expandable",label:"Tool Calls Expandable",description:"Allow expanding tool call rows to see full details",type:"toggle",path:"features.toolCallDisplay.expandable",defaultValue:!0},{id:"dev-tool-grouped",label:"Group Sequential Tool Calls",description:"Render consecutive tool rows inside a grouped container",type:"toggle",path:"features.toolCallDisplay.grouped",defaultValue:!1},{id:"dev-reasoning-expandable",label:"Reasoning Expandable",description:"Allow expanding reasoning rows to see full details",type:"toggle",path:"features.reasoningDisplay.expandable",defaultValue:!0},{id:"dev-reasoning-active-preview",label:"Reasoning Preview While Active",description:"Show a lightweight preview in collapsed active reasoning rows",type:"toggle",path:"features.reasoningDisplay.activePreview",defaultValue:!1},{id:"dev-reasoning-preview-lines",label:"Reasoning Preview Lines",type:"select",path:"features.reasoningDisplay.previewMaxLines",defaultValue:3,options:[{value:"1",label:"1"},{value:"2",label:"2"},{value:"3",label:"3"},{value:"4",label:"4"},{value:"5",label:"5"}],formatValue:e=>String(e!=null?e:3),parseValue:e=>Number(e)},{id:"dev-reasoning-active-min-height",label:"Reasoning Active Min Height",description:"CSS min-height for collapsed active reasoning rows (e.g. 5rem)",type:"text",path:"features.reasoningDisplay.activeMinHeight",defaultValue:""},{id:"dev-debug",label:"Debug Mode",description:"Show debug information",type:"toggle",path:"debug",defaultValue:!1}]},Th={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}]},ei=[{label:"Content",sections:[ah,ih]},{label:"Layout",sections:[lh,ch,dh,ph]},{label:"Widget",sections:[uh,mh,gh,fh,hh,bh]},{label:"Features",sections:[yh,vh,xh,wh,Ch]},{label:"Developer",collapsedByDefault:!0,sections:[Sh,Ah,Th]}],Gu=ei.flatMap(e=>e.sections),Yu={id:"theme-mode-v2",title:"Theme",description:"Choose how the interface adapts across light and dark mode.",collapsed:!1,fields:[{id:"color-mode",label:"Color Mode",type:"select",path:"colorScheme",defaultValue:"auto",options:[{value:"auto",label:"Auto"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}]}]},Qu={id:"brand-palette-v2",title:"Brand Palette",description:"Set your brand, accent, and neutral colors. These are used to generate the interface theme.",collapsed:!1,fields:[{id:"bp-primary",label:"Primary",description:"Main brand color",type:"color",path:"theme.palette.colors.primary.500",defaultValue:"#171717"},{id:"bp-secondary",label:"Secondary",description:"Supporting brand color",type:"color",path:"theme.palette.colors.secondary.500",defaultValue:"#8b5cf6"},{id:"bp-accent",label:"Accent",description:"Highlight and decorative color",type:"color",path:"theme.palette.colors.accent.500",defaultValue:"#06b6d4"},{id:"bp-neutral",label:"Neutral",description:"Backgrounds, text, and borders",type:"color",path:"theme.palette.colors.gray.500",defaultValue:"#6b7280"}]},Xu={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"}]},Ju={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:za},{id:"role-header",label:"Header",type:"role-assignment",path:"theme.components.header.background",roleAssignment:qa},{id:"role-user-messages",label:"User Messages",type:"role-assignment",path:"theme.components.message.user.background",roleAssignment:ja},{id:"role-assistant-messages",label:"Assistant Messages",type:"role-assignment",path:"theme.components.message.assistant.background",roleAssignment:Ka},{id:"role-primary-actions",label:"Primary Actions",type:"role-assignment",path:"theme.components.button.primary.background",roleAssignment:Ga},{id:"role-scroll-to-bottom",label:"Scroll To Bottom",type:"role-assignment",path:"theme.components.scrollToBottom.background",roleAssignment:Ya},{id:"role-input",label:"Input Field",type:"role-assignment",path:"theme.components.input.background",roleAssignment:Qa},{id:"role-links-focus",label:"Links & Focus",type:"role-assignment",path:"theme.semantic.colors.accent",roleAssignment:Xa},{id:"role-borders",label:"Borders & Dividers",type:"role-assignment",path:"theme.semantic.colors.border",roleAssignment:Ja}]},Zu={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"}}]},em={id:"advanced-tokens",title:"Advanced Tokens",description:"Override individual semantic and component values when you need precise control.",collapsed:!0,fields:[]},kh=[Yu,Qu,Xu,Ju,Zu,em],wl=[{id:"style",label:"Style",sections:cs},{id:"design-system",label:"Design System",sections:Ku},{id:"configure",label:"Configure",sections:Gu}];function tm(e,t){return e.startsWith("theme.")?e.replace(/^theme\./,`${t}.`):e}function Eh(e,t,n){return{...e,id:`${n}-${e.id}`,path:tm(e.path,t)}}function Mh(e,t){let n=e.find(o=>o.id===t);if(!n)throw new Error(`Section "${t}" not found in definitions`);return n}function Lh(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=>Eh(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])=>[tm(d,t),l]))}))}}var nm=[{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"]}],js=[...nm];function Cl(e){return js.find(t=>t.id===e)}import{Marked as Ih}from"marked";var Rh=e=>{if(e)return e},Sl=e=>{var r,s;let t=e==null?void 0:e.markedOptions,n=new Ih({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=Rh(e==null?void 0:e.renderer);return o&&n.use({renderer:o}),a=>n.parse(a)},ti=e=>e?Sl({markedOptions:e.options,renderer:e.renderer}):Sl(),uC=Sl();var Ks=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");import Ph from"dompurify";var Wh={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"]},Bh=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Hh=()=>{let e=Ph(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:")&&!Bh.test(o)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,Wh)},ni=e=>e===!1?null:typeof e=="function"?e:Hh();var Br="webmcp:",Al=new Map,om=e=>{var t;Al.clear();for(let n of e){let o=(t=n.title)==null?void 0:t.trim();o&&Al.set(n.name,o)}},Tl=e=>Al.get(im(e)),oi={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},rm=null;function am(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}:${Dh(t.join(""))}`}function sm(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 Dh(e){let t=sm(e,0).toString(36),n=sm(e,2654435761).toString(36);return`${t}.${n}`}var ri=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 oi.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",r),[]}om(n);let o=typeof location!="undefined"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=Fh(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Ao("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let x=typeof document!="undefined"&&!!document.modelContext;return Ao(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=im(t),a;try{a=await r.getTools()}catch(x){let v=x instanceof Error?x.message:String(x);return Ao(`Failed to read WebMCP registry: ${v}`)}om(a);let i=a.find(x=>x.name===s);if(!i)return Ao(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Ao(`WebMCP tool not allowed by client allowlist: ${s}`);if(o!=null&&o.aborted)return Ao("Aborted by cancel()");let d=Tl(s),l={toolName:s,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(l))return Ao("User declined the tool call.");if(o!=null&&o.aborted)return Ao("Aborted by cancel()");let 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,$h(n),{signal:u.signal});return Nh(x)}catch(x){if(g)return Ao(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o!=null&&o.aborted)return Ao("Aborted by cancel()");let v=x instanceof Error?x.message:String(x);return Ao(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}(rm?await rm():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){oi.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,oi.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:_h;try{return await n(t)}catch(r){return oi.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=>Oh(t,o))}},im=e=>e.startsWith(Br)?e.slice(Br.length):e,Gs=e=>e.startsWith(Br),Oh=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Fh=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Nh=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:Uh(t)}]}},Ao=e=>({isError:!0,content:[{type:"text",text:e}]}),_h=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Vh(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)},Vh=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)}},$h=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Uh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};import{parse as zh,ARR as qh,OBJ as jh,STR as Kh}from"partial-json";var b=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Fo=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o};var kl="ask_user_question",Ys=8,ds="data-persona-ask-sheet-for",Gh="Other",Yh="Other\u2026",cm="Type your own answer here",dm="Send",Qh="Next",Xh="Back",Jh="Submit all",Zh="Skip",eb=3,El="data-ask-current-index",Ml="data-ask-question-count",pm="data-ask-answers",Ll="data-ask-grouped",um="data-ask-layout",tb=e=>e.layout==="pills"?"pills":"rows",nb=e=>e.getAttribute(um)==="pills"?"pills":"rows",lm=!1,mm=e=>e.replace(/["\\]/g,"\\$&"),Hr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===kl,Il=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},ps=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=zh(r,Kh|jh|qh);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Qs=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>Ys&&!lm&&(lm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Ys}.`)),t.slice(0,Ys)},ob=e=>{var t;return(t=Qs(e)[0])!=null?t:null},rb=(e,t)=>{var n;return(n=Qs(e)[t])!=null?n:null},sb=(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))},gm=(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},ab=(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=gm(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},ib=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},lb=(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<eb;m++)s.appendChild(ib(o));return s}if(d.forEach((m,x)=>{s.appendChild(ab(m,x,o,a))}),(e==null?void 0:e.allowFreeText)!==!1){let m=o==="rows"?Gh:Yh;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"),E=document.createElement("input");E.type="text",E.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",E.placeholder=(u=t.freeTextPlaceholder)!=null?u:cm,E.setAttribute("data-ask-free-text-input","true"),E.setAttribute("aria-label",(g=t.freeTextLabel)!=null?g:m),v.appendChild(E),x.appendChild(v);let L=gm(o,a,d.length);L&&x.appendChild(L),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},fm=(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:cm,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:dm,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},cb=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:dm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},db=(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:Xh,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:Zh,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:Jh:(f=n.nextLabel)!=null?f:Qh,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},Dr=e=>{let t=e.getAttribute(pm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},hm=(e,t)=>{e.setAttribute(pm,JSON.stringify(t))},go=e=>{var n;let t=Number((n=e.getAttribute(El))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},pb=(e,t)=>{e.setAttribute(El,String(Math.max(0,Math.floor(t))))},us=e=>{var n;let t=Number((n=e.getAttribute(Ml))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},gr=e=>e.getAttribute(Ll)==="true",ub=(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},mb=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},si=(e,t)=>{let{payload:n}=ps(t),o=Qs(n),r=Dr(e),s={},a=new Set;return o.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(r,d)&&(s[l]=r[d]))}),s},bm=e=>{let t=Dr(e),n=go(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(d=>r.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var 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=""},ym=e=>{if(!gr(e))return;let t=Dr(e),n=go(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Rl=(e,t,n)=>{let o=Il(n),r=nb(e),{payload:s,complete:a}=ps(t),i=gr(e),d=go(e),l=us(e),u=i?rb(s,d):ob(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 I=typeof(u==null?void 0:u.question)=="string"?u.question:"";x.textContent=I,x.classList.toggle("persona-ask-question-skeleton",!I&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let I=lb(u,o,a,r);v.replaceWith(I)}if(r!=="rows"){let I=e.querySelector('[data-ask-free-text-row="true"]');I&&I.replaceWith(fm(o,r))}let E=e.querySelector('[data-ask-multi-actions="true"]');!i&&g&&!E?e.appendChild(cb(o)):(!g||i)&&E&&E.remove(),e.setAttribute("data-multi-select",g?"true":"false");let L=e.querySelector('[data-ask-nav-row="true"]');if(i){let I=db(d,l,o);L?L.replaceWith(I):e.appendChild(I)}else L&&L.remove();bm(e),ym(e)},gb=(e,t,n)=>{let o=Il(t),r=tb(o),s=e.toolCall.id,a=Qs(n),i=Math.max(1,a.length),d=i>1,l=ub(e,a),u=d?mb(e,i):0,g=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(ds,s),g.setAttribute("data-tool-call-id",s),g.setAttribute("data-message-id",e.id),g.setAttribute(Ml,String(i)),g.setAttribute(El,String(u)),g.setAttribute(Ll,d?"true":"false"),g.setAttribute(um,r),hm(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`),sb(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 E=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),g.appendChild(E),r!=="rows"&&g.appendChild(fm(o,r)),Rl(g,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},fb=(e,t,n)=>{let{payload:o}=ps(t),r=Math.max(1,Qs(o).length);r>us(e)&&(e.setAttribute(Ml,String(r)),r>1&&!gr(e)&&e.setAttribute(Ll,"true")),Rl(e,t,n)};var ai=(e,t,n)=>{if(!n||!Hr(e)||Il(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${ds}]`).forEach(l=>{l.getAttribute(ds)!==r&&l.remove()});let a=n.querySelector(`[${ds}="${mm(r)}"]`);if(a){fb(a,e,t);return}let{payload:i}=ps(e),d=gb(e,t,i);n.appendChild(d)},ms=(e,t)=>{if(!e)return;let n=t?`[${ds}="${mm(t)}"]`:`[${ds}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},Pl=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),fr=(e,t)=>{let n=Dr(e),o=go(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,hm(e,n),bm(e),ym(e)},ii=(e,t,n,o)=>{let r=us(e),s=Math.max(0,Math.min(r-1,o));pb(e,s),Rl(e,t,n)};var Yo="suggest_replies";var hb={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},vm={name:Yo,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:hb,origin:"sdk",annotations:{readOnlyHint:!0}},Wl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Bl=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Yo},bb=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},xm=e=>{var t;for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return null;if(!Bl(o))continue;let r=bb((t=o.toolCall)==null?void 0:t.args);return r.length>0?r:null}return null},wm=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 yb={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ys,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},vb={name:kl,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:yb,origin:"sdk",annotations:{readOnlyHint:!0}},Hl=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(vb),wm(e)&&t.push(vm),t};import{parse as xb,STR as wb,OBJ as Cb}from"partial-json";var Cm=e=>e.replace(/\\n/g,`
7
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),gs=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)}},Sb=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`},Sm=e=>e.status==="complete"?Sb(e):e.status==="pending"?"Waiting":"",Ab=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 Am=e=>e.status==="complete"?Ab(e):"Using tool...",li=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Js=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 li(t)},ci=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 li(t)},Dl=(e,t,n)=>{var s;if(!t)return n;let o=((s=e.name)==null?void 0:s.trim())||"tool",r=Js(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},di=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Xs(o,n.slice(s,a.index),[]),a[1]!==void 0?Xs(o,a[1],["bold"]):a[2]!==void 0?Xs(o,a[2],["italic"]):a[3]!==void 0&&Xs(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Xs(o,n.slice(s),[]),o},Xs=(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})},Tb=()=>{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()=>{}}},Or=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Tm=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},km=()=>{var t;let e=Tb();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)}},Em=()=>{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=xb(n,wb|Cb);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Cm(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Cm(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var Mm=()=>{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 pi=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 kb="https://api.runtype.com/v1/dispatch",ui="https://api.runtype.com";function Eb(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 Ol=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 Mb(e){switch(e){case"json":return Em;case"regex-json":return km;case"xml":return Mm;default:return Tm}}var Lm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Lb(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=Lm(n);if(!Lm(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Or(e);return Or(t)!==null&&a===null?t:e}var Zs=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:kb,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:Mb(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 ri(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$/,""))||ui}/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$/,""))||ui}/v1/client/feedback`}async sendFeedback(t){var s,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var r,s,a,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(r=this.config).onSessionExpired)==null||s.call(r);let H=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:H}),H}let l=await this.buildPayload(t.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([H])=>H!=="sessionId"&&H!=="session_id")):void 0,g={sessionId:d.sessionId,messages:t.messages.filter(Ol).map(H=>{var R,w,C;return{id:H.id,role:H.role,content:(C=(w=(R=H.contentParts)!=null?R:H.llmContent)!=null?w:H.rawContent)!=null?C:H.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?am(f):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,E=m&&v&&this.lastSentClientToolsFingerprint===x,L=!1,I=null,W;for(let H=0;;H++){let w={...g,...m&&(L||!E)&&f?{clientTools:f}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",w),W=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w),signal:o.signal}),W.status===409&&H===0&&m){let C=await W.json().catch(()=>null);if((C==null?void 0:C.error)==="client_tools_resend_required"){L=!0,this.lastSentClientToolsFingerprint=null;continue}I=C!=null?C:{error:"Chat request failed"}}break}if(!W.ok){let H=I!=null?I:await W.json().catch(()=>({error:"Chat request failed"}));if(W.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(W.status===429){let w=new Error(H.hint||"Message limit reached for this session.");throw n({type:"error",error:w}),w}let R=new Error(H.error||"Failed to send message");throw n({type:"error",error:R}),R}if(!W.body){let H=new Error("No response body received");throw n({type:"error",error:H}),H}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(W.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let r=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ui}/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(/\/+$/,""))||ui}/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(Ol).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=[...Hl(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(Ol).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=[...Hl(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 Bt,an,ro,Eo;let r=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,u=D=>{let pe=D.reasoning?{...D.reasoning,chunks:[...D.reasoning.chunks]}:void 0,De=D.toolCall?{...D.toolCall,chunks:D.toolCall.chunks?[...D.toolCall.chunks]:void 0}:void 0,Ke=D.tools?D.tools.map(Ne=>({...Ne,chunks:Ne.chunks?[...Ne.chunks]:void 0})):void 0;return{...D,reasoning:pe,toolCall:De,tools:Ke}},g=D=>{if(D.role!=="assistant"||D.variant)return!0;let pe=Array.isArray(D.contentParts)&&D.contentParts.length>0,De=typeof D.rawContent=="string"&&D.rawContent.trim()!=="";return typeof D.content=="string"&&D.content.trim()!==""||pe||De||!!D.stopReason},f=D=>{g(D)&&n({type:"message",message:u(D)})},m=null,x=null,v={current:null},E={current:null},L=!1,I=new Map,W=new Map,H=new Map,R=new Map,w={lastId:null,byStep:new Map},C={lastId:null,byCall:new Map},k=(D,pe,De="")=>`${D}::${pe}::${De}`,A=(D,pe)=>`${D}::${pe}::`,S=(D,pe,De,Ke)=>{let Ne=k(D,pe,De),Ve=H.get(Ne);if(Ve)return Ve;let ot=De?`-${De}`:"",It={id:`nested-${D}-${pe}${ot}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...De?{partId:De}:{},agentMetadata:{executionId:Ke,parentToolId:D,parentStepId:pe}};return H.set(Ne,It),f(It),It},_=D=>{if(D==null)return null;try{return String(D)}catch{return null}},V=D=>{var pe,De,Ke,Ne,Ve;return _((Ve=(Ne=(Ke=(De=(pe=D.stepId)!=null?pe:D.step_id)!=null?De:D.step)!=null?Ke:D.parentId)!=null?Ne:D.flowStepId)!=null?Ve:D.flow_step_id)},K=D=>{var pe,De,Ke,Ne,Ve,ot,It;return _((It=(ot=(Ve=(Ne=(Ke=(De=(pe=D.callId)!=null?pe:D.call_id)!=null?De:D.requestId)!=null?Ke:D.request_id)!=null?Ne:D.toolCallId)!=null?Ve:D.tool_call_id)!=null?ot:D.stepId)!=null?It:D.step_id)},fe=o,ue=!1,ce=()=>{if(m)return m;let D;return!ue&&fe?(D=fe,ue=!0):fe&&E.current?D=`${fe}_${E.current}`:D=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:D,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(m),m},ke=(D,pe)=>{w.lastId=pe,D&&w.byStep.set(D,pe)},ve=(D,pe)=>{var Ve;let De=(Ve=D.reasoningId)!=null?Ve:D.id,Ke=V(D);if(De){let ot=String(De);return ke(Ke,ot),ot}if(Ke){let ot=w.byStep.get(Ke);if(ot)return w.lastId=ot,ot}if(w.lastId&&!pe)return w.lastId;if(!pe)return null;let Ne=`reason-${l()}`;return ke(Ke,Ne),Ne},He=D=>{let pe=I.get(D);if(pe)return pe;let De={id:`reason-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:D,status:"streaming",chunks:[]}};return I.set(D,De),f(De),De},Se=(D,pe)=>{C.lastId=pe,D&&C.byCall.set(D,pe)},ie=new Set,Q=new Map,re=new Set,be=new Map,he=D=>{if(!D)return!1;let pe=D.replace(/_+/g,"_").replace(/^_|_$/g,"");return pe==="emit_artifact_markdown"||pe==="emit_artifact_component"},j=(D,pe)=>{var Ve;let De=(Ve=D.toolId)!=null?Ve:D.id,Ke=K(D);if(De){let ot=String(De);return Se(Ke,ot),ot}if(Ke){let ot=C.byCall.get(Ke);if(ot)return C.lastId=ot,ot}if(C.lastId&&!pe)return C.lastId;if(!pe)return null;let Ne=`tool-${l()}`;return Se(Ke,Ne),Ne},se=D=>{let pe=W.get(D);if(pe)return pe;let De={id:`tool-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:D,status:"pending"}};return W.set(D,De),f(De),De},Re=D=>{if(typeof D=="number"&&Number.isFinite(D))return D;if(typeof D=="string"){let pe=Number(D);if(!Number.isNaN(pe)&&Number.isFinite(pe))return pe;let De=Date.parse(D);if(!Number.isNaN(De))return De}return Date.now()},ne=D=>{if(typeof D=="string")return D;if(D==null)return"";try{return JSON.stringify(D)}catch{return String(D)}},Z=new Map,oe=new Map,at=new Map,it=new Map,Le=null,de=(D,pe,De)=>{var It;let Ke=at.get(D);Ke||(Ke=[],at.set(D,Ke));let Ne=0,Ve=Ke.length;for(;Ne<Ve;){let qt=Ne+Ve>>>1;Ke[qt].seq<pe?Ne=qt+1:Ve=qt}((It=Ke[Ne])==null?void 0:It.seq)===pe?Ke[Ne]={seq:pe,text:De}:Ke.splice(Ne,0,{seq:pe,text:De});let ot="";for(let qt=0;qt<Ke.length;qt++)ot+=Ke[qt].text;return ot},Qe=(D,pe)=>{let De=ne(pe),Ke=oe.get(D.id),Ne=Lb(Ke,De);D.rawContent=Ne;let Ve=Z.get(D.id),ot=yt=>{var Ce;let st=(Ce=D.content)!=null?Ce:"";yt.trim()!==""&&(st.trim().length===0||yt.startsWith(st)||yt.trimStart().startsWith(st.trim()))&&(D.content=yt)},It=()=>{var yt;if(Ve){let st=(yt=Ve.close)==null?void 0:yt.call(Ve);st instanceof Promise&&st.catch(()=>{})}Z.delete(D.id),oe.delete(D.id),D.streaming=!1,f(D)};if(!Ve){ot(De),It();return}let qt=Or(Ne);if(qt!==null&&qt.trim()!==""){ot(qt),It();return}let Xt=yt=>{var le;let st=typeof yt=="string"?yt:(le=yt==null?void 0:yt.text)!=null?le:null;if(st!==null&&st.trim()!=="")return st;let Ce=Ve.getExtractedText();return Ce!==null&&Ce.trim()!==""?Ce:De},G;try{G=Ve.processChunk(Ne)}catch{ot(De),It();return}if(G instanceof Promise){G.then(yt=>{ot(Xt(yt)),It()}).catch(()=>{ot(De),It()});return}ot(Xt(G)),It()},We=[],q=!1,me,tt=()=>{q||(q=!0,queueMicrotask(()=>{q=!1,me()}))},Tt=new pi((D,pe)=>{We.push({payloadType:D,payload:pe}),tt()}),te=null,ze=new Map,Nn=(Bt=this.config.iterationDisplay)!=null?Bt:"separate";for(me=()=>{var D,pe,De,Ke,Ne,Ve,ot,It,qt,Xt,G,yt,st,Ce,le,Ze,Zt,jt,Rn,xn,ut,kt,Xe,Ut,ln,Sn,An,bn,Mo,Ct,zn,qn,No,ho,vt,yr,Lo,vr,_n,qr,Zo,_o,St,jn,Kn,Pn,Lt,so,ao,Gn,er,Vo,tr,Yn,Ht,Wn,io,nr,$o,or,Io,Qn,bo,gt,en,tn,Xn,rr,xe,yo,lo,$,jr,Ro,Uo,zo,Po,vo,As,Jn,Zn,xo,wo,xr,qo,Tn,Wo,Kr,wr,Gr,Aa,Yr,Ta,Qr,bt,Ts,co,Vn,ka,Ea,Xr,jo,ks,sr,Es,Ms,Ls,Is,$n,Jr,Bo,Ho,Rs,Ma,Ps,Ws,Cr,La,Ia,Ra,Pa,rl,Sr,ar,Wa,Bs,ir,Ba,Hs,lr,Ds,Ha,Ko,Da,cr,Dt,Zr,es;for(let Ar=0;Ar<We.length;Ar++){let $e=We[Ar].payloadType,T=We[Ar].payload;if($e==="reason_start"){let U=(D=ve(T,!0))!=null?D:`reason-${l()}`,P=He(U);P.reasoning=(pe=P.reasoning)!=null?pe:{id:U,status:"streaming",chunks:[]},P.reasoning.startedAt=(Ke=P.reasoning.startedAt)!=null?Ke:Re((De=T.startedAt)!=null?De:T.timestamp),P.reasoning.completedAt=void 0,P.reasoning.durationMs=void 0,P.streaming=!0,P.reasoning.status="streaming",f(P)}else if($e==="reason_delta"||$e==="reason_chunk"){let U=(Ve=(Ne=ve(T,!1))!=null?Ne:ve(T,!0))!=null?Ve:`reason-${l()}`,P=He(U);P.reasoning=(ot=P.reasoning)!=null?ot:{id:U,status:"streaming",chunks:[]},P.reasoning.startedAt=(qt=P.reasoning.startedAt)!=null?qt:Re((It=T.startedAt)!=null?It:T.timestamp);let J=(yt=(G=(Xt=T.reasoningText)!=null?Xt:T.text)!=null?G:T.delta)!=null?yt:"";if(J&&T.hidden!==!0){let ae=typeof T.sequenceIndex=="number"?T.sequenceIndex:void 0;if(ae!==void 0){let Y=de(U,ae,String(J));P.reasoning.chunks=[Y]}else P.reasoning.chunks.push(String(J))}if(P.reasoning.status=T.done?"complete":"streaming",T.done){P.reasoning.completedAt=Re((st=T.completedAt)!=null?st:T.timestamp);let ae=(Ce=P.reasoning.startedAt)!=null?Ce:Date.now();P.reasoning.durationMs=Math.max(0,((le=P.reasoning.completedAt)!=null?le:Date.now())-ae)}P.streaming=P.reasoning.status!=="complete",f(P)}else if($e==="reason_complete"){let U=(Zt=(Ze=ve(T,!1))!=null?Ze:ve(T,!0))!=null?Zt:`reason-${l()}`,P=I.get(U);if(P!=null&&P.reasoning){P.reasoning.status="complete",P.reasoning.completedAt=Re((jt=T.completedAt)!=null?jt:T.timestamp);let ae=(Rn=P.reasoning.startedAt)!=null?Rn:Date.now();P.reasoning.durationMs=Math.max(0,((xn=P.reasoning.completedAt)!=null?xn:Date.now())-ae),P.streaming=!1,f(P)}let J=V(T);J&&w.byStep.delete(J)}else if($e==="tool_start"){let U=(ut=j(T,!0))!=null?ut:`tool-${l()}`,P=(kt=T.toolName)!=null?kt:T.name;if(he(P)){ie.add(U);continue}let J=se(U),ae=(Xe=J.toolCall)!=null?Xe:{id:U,status:"pending"};ae.name=P!=null?P:ae.name,ae.status="running",T.args!==void 0?ae.args=T.args:T.parameters!==void 0&&(ae.args=T.parameters),ae.startedAt=(ln=ae.startedAt)!=null?ln:Re((Ut=T.startedAt)!=null?Ut:T.timestamp),ae.completedAt=void 0,ae.durationMs=void 0,J.toolCall=ae,J.streaming=!0;let Y=T.agentContext;(Y||T.executionId)&&(J.agentMetadata={executionId:(Sn=Y==null?void 0:Y.executionId)!=null?Sn:T.executionId,iteration:(An=Y==null?void 0:Y.iteration)!=null?An:T.iteration}),f(J)}else if($e==="tool_chunk"||$e==="tool_delta"){let U=(Mo=(bn=j(T,!1))!=null?bn:j(T,!0))!=null?Mo:`tool-${l()}`;if(ie.has(U))continue;let P=se(U),J=(Ct=P.toolCall)!=null?Ct:{id:U,status:"running"};J.startedAt=(qn=J.startedAt)!=null?qn:Re((zn=T.startedAt)!=null?zn:T.timestamp);let ae=(vt=(ho=(No=T.text)!=null?No:T.delta)!=null?ho:T.message)!=null?vt:"";ae&&(J.chunks=(yr=J.chunks)!=null?yr:[],J.chunks.push(String(ae))),J.status="running",P.toolCall=J,P.streaming=!0;let Y=T.agentContext;(Y||T.executionId)&&(P.agentMetadata=(_n=P.agentMetadata)!=null?_n:{executionId:(Lo=Y==null?void 0:Y.executionId)!=null?Lo:T.executionId,iteration:(vr=Y==null?void 0:Y.iteration)!=null?vr:T.iteration}),f(P)}else if($e==="tool_complete"){let U=(Zo=(qr=j(T,!1))!=null?qr:j(T,!0))!=null?Zo:`tool-${l()}`;if(ie.has(U)){ie.delete(U);continue}let P=se(U),J=(_o=P.toolCall)!=null?_o:{id:U,status:"running"};J.status="complete",T.result!==void 0&&(J.result=T.result),typeof T.duration=="number"&&(J.duration=T.duration),J.completedAt=Re((St=T.completedAt)!=null?St:T.timestamp);let ae=(jn=T.duration)!=null?jn:T.executionTime;if(typeof ae=="number")J.durationMs=ae;else{let Fe=(Kn=J.startedAt)!=null?Kn:Date.now();J.durationMs=Math.max(0,((Pn=J.completedAt)!=null?Pn:Date.now())-Fe)}P.toolCall=J,P.streaming=!1;let Y=T.agentContext;(Y||T.executionId)&&(P.agentMetadata=(ao=P.agentMetadata)!=null?ao:{executionId:(Lt=Y==null?void 0:Y.executionId)!=null?Lt:T.executionId,iteration:(so=Y==null?void 0:Y.iteration)!=null?so:T.iteration}),f(P);let Me=K(T);Me&&C.byCall.delete(Me)}else if($e==="step_await"&&T.awaitReason==="local_tool_required"&&T.toolName){let U=typeof T.toolCallId=="string"&&T.toolCallId.length>0?T.toolCallId:void 0,P=(Gn=U!=null?U:T.toolId)!=null?Gn:`local-${l()}`,J=se(P),ae=T.toolName,Y=Gs(ae),Me=(er=J.toolCall)!=null?er:{id:P,status:"pending"};Me.name=ae,Me.args=T.parameters,Me.status=Y?"running":"complete",Me.chunks=(Vo=Me.chunks)!=null?Vo:[],Me.startedAt=(Yn=Me.startedAt)!=null?Yn:Re((tr=T.startedAt)!=null?tr:T.timestamp),Y?(Me.completedAt=void 0,Me.duration=void 0,Me.durationMs=void 0):Me.completedAt=(Ht=Me.completedAt)!=null?Ht:Me.startedAt,J.toolCall=Me,J.streaming=!1,J.agentMetadata={...J.agentMetadata,executionId:(io=T.executionId)!=null?io:(Wn=J.agentMetadata)==null?void 0:Wn.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},f(J)}else if($e==="text_start"){if((nr=T.toolContext)!=null&&nr.toolId)continue;let U=T.partId;if(U!==void 0&&E.current!==null&&U!==E.current){let P=m;P&&(P.streaming=!1,f(P),Le=P,m=null,L=!0)}U!==void 0&&(E.current=U)}else if($e==="text_end"){if(($o=T.toolContext)!=null&&$o.toolId)continue;let U=m;U&&(U.streaming=!1,f(U),Le=U,m=null,L=!0)}else if($e==="step_chunk"||$e==="step_delta"){let U=T.stepType,P=T.executionType;if(U==="tool"||P==="context")continue;let J=T.toolContext;if(J!=null&&J.toolId){let Fe=String((Io=(or=T.id)!=null?or:J.stepId)!=null?Io:`step-${l()}`),lt=T.partId!==void 0&&T.partId!==null?String(T.partId):"",Je=`${J.toolId}::${Fe}`,Wt=R.get(Je);if(lt!==""&&Wt!==void 0&&Wt!==""&&Wt!==lt){let rt=H.get(k(J.toolId,Fe,Wt));rt&&rt.streaming!==!1&&(rt.streaming=!1,f(rt))}lt!==""&&R.set(Je,lt);let _t=S(J.toolId,Fe,lt,J.executionId),un=(en=(gt=(bo=(Qn=T.text)!=null?Qn:T.delta)!=null?bo:T.content)!=null?gt:T.chunk)!=null?en:"";un&&(_t.content+=String(un),_t.streaming=!0,f(_t)),T.isComplete&&(_t.streaming=!1,f(_t));continue}let ae=T.partId;if(ae!==void 0&&E.current!==null&&ae!==E.current){let Fe=m;Fe&&(Fe.streaming=!1,f(Fe),Le=Fe,m=null,L=!0)}ae!==void 0&&(E.current=ae);let Y=ae!==void 0&&(tn=it.get(ae))!=null?tn:ce();ae!==void 0&&(Y.partId||(Y.partId=ae),it.set(ae,Y));let Me=(yo=(xe=(rr=(Xn=T.text)!=null?Xn:T.delta)!=null?rr:T.content)!=null?xe:T.chunk)!=null?yo:"";if(Me){let Fe=typeof T.seq=="number"?T.seq:void 0,lt=ae!=null?ae:Y.id,Je=Fe!==void 0?de(lt,Fe,String(Me)):((lo=oe.get(Y.id))!=null?lo:"")+Me;Y.rawContent=Je,Z.has(Y.id)||Z.set(Y.id,this.createStreamParser());let Wt=Z.get(Y.id),_t=Je.trim().startsWith("{")||Je.trim().startsWith("[");if(_t&&oe.set(Y.id,Je),Wt.__isPlainTextParser===!0){Y.content=Fe!==void 0?Je:Y.content+Me,oe.delete(Y.id),Z.delete(Y.id),Y.rawContent=void 0,f(Y);continue}let rt=Wt.processChunk(Je);if(rt instanceof Promise)rt.then(ft=>{var je;let Jt=typeof ft=="string"?ft:(je=ft==null?void 0:ft.text)!=null?je:null;if(Jt!==null&&Jt.trim()!=="")Y.content=Jt,f(Y);else if(!_t&&!Je.trim().startsWith("<")){let wn=m,Gt=wn&&wn.id===Y.id?wn:Y;Gt.id===Y.id&&(Gt.content=Fe!==void 0?Je:Gt.content+Me,oe.delete(Gt.id),Z.delete(Gt.id),Gt.rawContent=void 0,f(Gt))}}).catch(()=>{Y.content=Fe!==void 0?Je:Y.content+Me,oe.delete(Y.id),Z.delete(Y.id),Y.rawContent=void 0,f(Y)});else{let ft=typeof rt=="string"?rt:($=rt==null?void 0:rt.text)!=null?$:null;ft!==null&&ft.trim()!==""?(Y.content=ft,f(Y)):!_t&&!Je.trim().startsWith("<")&&(Y.content=Fe!==void 0?Je:Y.content+Me,oe.delete(Y.id),Z.delete(Y.id),Y.rawContent=void 0,f(Y))}}if(T.isComplete){let Fe=(Ro=(jr=T.result)==null?void 0:jr.response)!=null?Ro:Y.content;if(Fe){let lt=oe.get(Y.id),Je=lt!=null?lt:ne(Fe);Y.rawContent=Je;let Wt=Z.get(Y.id),_t=null,un=!1;if(Wt&&(_t=Wt.getExtractedText(),_t===null&&(_t=Or(Je)),_t===null)){let rt=Wt.processChunk(Je);rt instanceof Promise?(un=!0,rt.then(ft=>{var je;let Jt=typeof ft=="string"?ft:(je=ft==null?void 0:ft.text)!=null?je:null;if(Jt!==null){let wn=m;wn&&wn.id===Y.id&&(wn.content=Jt,wn.streaming=!1,Z.delete(wn.id),oe.delete(wn.id),f(wn))}})):_t=typeof rt=="string"?rt:(Uo=rt==null?void 0:rt.text)!=null?Uo:null}if(!un){_t!==null&&_t.trim()!==""?Y.content=_t:oe.has(Y.id)||(Y.content=ne(Fe));let rt=Z.get(Y.id);if(rt){let ft=(zo=rt.close)==null?void 0:zo.call(rt);ft instanceof Promise&&ft.catch(()=>{}),Z.delete(Y.id)}oe.delete(Y.id),Y.streaming=!1,f(Y)}}}}else if($e==="step_complete"){let U=T.stepType,P=T.executionType;if(U==="tool"||P==="context")continue;let J=T.toolContext;if(J!=null&&J.toolId){let Fe=String((vo=(Po=T.id)!=null?Po:J.stepId)!=null?vo:"");if(Fe){let lt=A(J.toolId,Fe);for(let[Je,Wt]of H)Je.startsWith(lt)&&Wt.streaming!==!1&&(Wt.streaming=!1,f(Wt));R.delete(`${J.toolId}::${Fe}`)}continue}let ae=T.stopReason;if(L){if(m!==null){let Je=m;ae&&(Je.stopReason=ae),Z.delete(Je.id),oe.delete(Je.id),Je.streaming!==!1&&(Je.streaming=!1,f(Je))}let Fe=(As=T.result)==null?void 0:As.response,lt=Le;lt&&(ae&&(lt.stopReason=ae),Fe!=null?Qe(lt,Fe):(Z.delete(lt.id),oe.delete(lt.id))),Le=null;continue}let Y=(Jn=T.result)==null?void 0:Jn.response,Me=ce();if(ae&&(Me.stopReason=ae),Y!=null){let Fe=Z.get(Me.id),lt=!1,Je=!1;if(Fe){let Wt=Fe.getExtractedText(),_t=oe.get(Me.id),un=_t!=null?_t:ne(Y);if(Me.rawContent=un,Wt!==null&&Wt.trim()!=="")Me.content=Wt,lt=!0;else{let rt=Or(un);if(rt!==null)Me.content=rt,lt=!0;else{let ft=Fe.processChunk(un);if(ft instanceof Promise)Je=!0,ft.then(Jt=>{var wn;let je=typeof Jt=="string"?Jt:(wn=Jt==null?void 0:Jt.text)!=null?wn:null;if(je!==null&&je.trim()!==""){let Gt=m;Gt&&Gt.id===Me.id&&(Gt.content=je,Gt.streaming=!1,Z.delete(Gt.id),oe.delete(Gt.id),f(Gt))}else{let Gt=Fe.getExtractedText(),yn=m;yn&&yn.id===Me.id&&(Gt!==null&&Gt.trim()!==""?yn.content=Gt:oe.has(yn.id)||(yn.content=ne(Y)),yn.streaming=!1,Z.delete(yn.id),oe.delete(yn.id),f(yn))}});else{let Jt=typeof ft=="string"?ft:(Zn=ft==null?void 0:ft.text)!=null?Zn:null;if(Jt!==null&&Jt.trim()!=="")Me.content=Jt,lt=!0;else{let je=Fe.getExtractedText();je!==null&&je.trim()!==""&&(Me.content=je,lt=!0)}}}}}if(!Je){if(!Me.rawContent){let Wt=oe.get(Me.id);Me.rawContent=Wt!=null?Wt:ne(Y)}if(!lt&&!oe.has(Me.id)&&(Me.content=ne(Y)),Fe){let Wt=(xo=Fe.close)==null?void 0:xo.call(Fe);Wt instanceof Promise&&Wt.catch(()=>{})}Z.delete(Me.id),oe.delete(Me.id),Me.streaming=!1,f(Me)}}else Z.delete(Me.id),oe.delete(Me.id),Me.streaming=!1,f(Me)}else if($e==="flow_complete"){let U=(wo=T.result)==null?void 0:wo.response;if(L){if(m!==null){let P=m;Z.delete(P.id),oe.delete(P.id),P.streaming!==!1&&(P.streaming=!1,f(P))}}else if(U!=null){let P=ce(),J=oe.get(P.id),ae=J!=null?J:ne(U);P.rawContent=ae;let Y=ne(U),Me=Z.get(P.id);if(Me){let Je=Or(ae);if(Je!==null)Y=Je;else{let Wt=Me.processChunk(ae);Wt instanceof Promise&&Wt.then(un=>{var ft;let rt=typeof un=="string"?un:(ft=un==null?void 0:un.text)!=null?ft:null;rt!==null&&(P.content=rt,P.streaming=!1,f(P))});let _t=Me.getExtractedText();_t!==null&&(Y=_t)}}Z.delete(P.id),oe.delete(P.id);let Fe=Y!==P.content,lt=P.streaming!==!1;Fe&&(P.content=Y),P.streaming=!1,(Fe||lt)&&f(P)}else if(m!==null){let P=m;Z.delete(P.id),oe.delete(P.id),P.streaming!==!1&&(P.streaming=!1,f(P))}n({type:"status",status:"idle"})}else if($e==="agent_start")te={executionId:T.executionId,agentId:(xr=T.agentId)!=null?xr:"virtual",agentName:(qo=T.agentName)!=null?qo:"",status:"running",currentIteration:0,maxTurns:(Tn=T.maxTurns)!=null?Tn:1,startedAt:Re(T.startedAt)};else if($e==="agent_iteration_start"){if(te&&(te.currentIteration=T.iteration),Nn==="separate"&&T.iteration>1){let U=m;U&&(U.streaming=!1,f(U),ze.set(T.iteration-1,U),m=null)}}else if($e==="agent_turn_start")x=null;else if($e==="agent_turn_delta"){if(T.contentType==="text"){let U=ce();U.content+=(Wo=T.delta)!=null?Wo:"",U.agentMetadata={executionId:T.executionId,iteration:T.iteration,turnId:T.turnId,agentName:te==null?void 0:te.agentName},x=U,f(U)}else if(T.contentType==="thinking"){let U=(Kr=T.turnId)!=null?Kr:`agent-think-${T.iteration}`,P=He(U);P.reasoning=(wr=P.reasoning)!=null?wr:{id:U,status:"streaming",chunks:[]},P.reasoning.chunks.push((Gr=T.delta)!=null?Gr:""),P.agentMetadata={executionId:T.executionId,iteration:T.iteration,turnId:T.turnId},f(P)}else if(T.contentType==="tool_input"){let U=(Aa=T.toolCallId)!=null?Aa:C.lastId;if(U){let P=W.get(U);P!=null&&P.toolCall&&(P.toolCall.chunks=(Yr=P.toolCall.chunks)!=null?Yr:[],P.toolCall.chunks.push((Ta=T.delta)!=null?Ta:""),f(P))}}}else if($e==="agent_turn_complete"){let U=T.turnId;if(U){let ae=I.get(U);if(ae!=null&&ae.reasoning){ae.reasoning.status="complete",ae.reasoning.completedAt=Re(T.completedAt);let Y=(Qr=ae.reasoning.startedAt)!=null?Qr:Date.now();ae.reasoning.durationMs=Math.max(0,((bt=ae.reasoning.completedAt)!=null?bt:Date.now())-Y),ae.streaming=!1,f(ae)}}let P=T.stopReason,J=m!=null?m:x;if(P&&J!==null){let ae=T.turnId;(!ae||((Ts=J.agentMetadata)==null?void 0:Ts.turnId)===ae)&&(J.stopReason=P,f(J))}}else if($e==="agent_tool_start"){m&&(m.streaming=!1,f(m),m=null);let U=(co=T.toolCallId)!=null?co:`agent-tool-${l()}`;Se(K(T),U);let P=se(U),J=(Vn=P.toolCall)!=null?Vn:{id:U,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};J.name=(Ea=(ka=T.toolName)!=null?ka:T.name)!=null?Ea:J.name,J.status="running",T.parameters!==void 0&&(J.args=T.parameters),J.startedAt=Re((Xr=T.startedAt)!=null?Xr:T.timestamp),P.toolCall=J,P.streaming=!0,P.agentMetadata={executionId:T.executionId,iteration:T.iteration},f(P)}else if($e==="agent_tool_delta"){let U=(jo=T.toolCallId)!=null?jo:C.lastId;if(U){let P=(ks=W.get(U))!=null?ks:se(U);P.toolCall&&(P.toolCall.chunks=(sr=P.toolCall.chunks)!=null?sr:[],P.toolCall.chunks.push((Es=T.delta)!=null?Es:""),P.toolCall.status="running",P.streaming=!0,f(P))}}else if($e==="agent_tool_complete"){let U=(Ms=T.toolCallId)!=null?Ms:C.lastId;if(U){let P=(Ls=W.get(U))!=null?Ls:se(U);if(P.toolCall){P.toolCall.status="complete",T.result!==void 0&&(P.toolCall.result=T.result),typeof T.executionTime=="number"&&(P.toolCall.durationMs=T.executionTime),P.toolCall.completedAt=Re((Is=T.completedAt)!=null?Is:T.timestamp),P.streaming=!1,f(P);let J=K(T);J&&C.byCall.delete(J)}}}else if($e==="agent_media"){let U=Array.isArray(T.media)?T.media:[],P=[];for(let J of U){if(!J||typeof J!="object")continue;let ae=J,Y=typeof ae.type=="string"?ae.type:void 0,Me=typeof ae.mediaType=="string"?ae.mediaType.toLowerCase():"",Fe=null,lt="";if(Y==="media"){let Je=typeof ae.data=="string"?ae.data:void 0;if(!Je)continue;lt=Me.length>0?Me:"application/octet-stream",Fe=`data:${lt};base64,${Je}`}else if(Y==="image-url"){let Je=typeof ae.url=="string"?ae.url:void 0;if(!Je)continue;lt=Me,Fe=Je}else if(Y==="file-url"){let Je=typeof ae.url=="string"?ae.url:void 0;if(!Je)continue;lt=Me,Fe=Je}else continue;if(Fe)if(Y==="image-url"||lt.startsWith("image/"))P.push({type:"image",image:Fe,...lt?{mimeType:lt}:{}});else if(lt.startsWith("audio/"))P.push({type:"audio",audio:Fe,mimeType:lt});else if(lt.startsWith("video/"))P.push({type:"video",video:Fe,mimeType:lt});else{let Je=lt||"application/octet-stream";P.push({type:"file",data:Fe,mimeType:Je,filename:Eb(Je)})}}if(P.length>0){let J=l(),ae=T.toolCallId,Me={id:`agent-media-${typeof ae=="string"&&ae.length>0?`${ae}-${J}`:String(J)}`,role:"assistant",content:"",contentParts:P,createdAt:new Date().toISOString(),streaming:!1,sequence:J,agentMetadata:{executionId:T.executionId,iteration:T.iteration}};f(Me);let Fe=m;Fe&&(Fe.streaming=!1,f(Fe)),m=null,v.current=null}}else if($e!=="agent_iteration_complete"){if($e==="agent_reflection"||$e==="agent_reflect"){let U=`agent-reflection-${T.executionId}-${T.iteration}`,P={id:U,role:"assistant",content:($n=T.reflection)!=null?$n:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:U,status:"complete",chunks:[(Jr=T.reflection)!=null?Jr:""]},agentMetadata:{executionId:T.executionId,iteration:T.iteration}};f(P)}else if($e==="agent_complete"){te&&(te.status=T.success?"complete":"error",te.completedAt=Re(T.completedAt),te.stopReason=T.stopReason);let U=m;U&&(U.streaming=!1,f(U)),n({type:"status",status:"idle"})}else if($e==="agent_error"){let U=typeof T.error=="string"?T.error:(Ho=(Bo=T.error)==null?void 0:Bo.message)!=null?Ho:"Agent execution error";T.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",U):n({type:"error",error:new Error(U)})}else if($e!=="agent_ping"){if($e==="agent_approval_start"){let U=(Rs=T.approvalId)!=null?Rs:`approval-${l()}`,P={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(Ma=te==null?void 0:te.agentId)!=null?Ma:"virtual",executionId:(Ws=(Ps=T.executionId)!=null?Ps:te==null?void 0:te.executionId)!=null?Ws:"",toolName:(Cr=T.toolName)!=null?Cr:"",toolType:T.toolType,description:(Ia=T.description)!=null?Ia:`Execute ${(La=T.toolName)!=null?La:"tool"}`,...typeof T.reason=="string"&&T.reason?{reason:T.reason}:{},parameters:T.parameters}};f(P)}else if($e==="step_await"&&T.awaitReason==="approval_required"){let U=(Ra=T.approvalId)!=null?Ra:`approval-${l()}`,P={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(Pa=te==null?void 0:te.agentId)!=null?Pa:"virtual",executionId:(Sr=(rl=T.executionId)!=null?rl:te==null?void 0:te.executionId)!=null?Sr:"",toolName:(ar=T.toolName)!=null?ar:"",toolType:T.toolType,description:(Bs=T.description)!=null?Bs:`Execute ${(Wa=T.toolName)!=null?Wa:"tool"}`,...typeof T.reason=="string"&&T.reason?{reason:T.reason}:{},parameters:T.parameters}};f(P)}else if($e==="agent_approval_complete"){let U=T.approvalId;if(U){let J={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:(ir=T.decision)!=null?ir:"approved",agentId:(Ba=te==null?void 0:te.agentId)!=null?Ba:"virtual",executionId:(lr=(Hs=T.executionId)!=null?Hs:te==null?void 0:te.executionId)!=null?lr:"",toolName:(Ds=T.toolName)!=null?Ds:"",description:(Ha=T.description)!=null?Ha:"",resolvedAt:Date.now()}};f(J)}}else if($e==="artifact_start"||$e==="artifact_delta"||$e==="artifact_update"||$e==="artifact_complete"){if($e==="artifact_start"){let U=T.artifactType,P=String(T.id),J=typeof T.title=="string"?T.title:void 0;if(n({type:"artifact_start",id:P,artifactType:U,title:J,component:typeof T.component=="string"?T.component:void 0}),be.set(P,{markdown:"",title:J}),!re.has(P)){re.add(P);let ae={id:`artifact-ref-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:P,title:J,artifactType:U,status:"streaming"}})};Q.set(P,ae),f(ae)}}else if($e==="artifact_delta"){let U=String(T.id),P=typeof T.delta=="string"?T.delta:String((Ko=T.delta)!=null?Ko:"");n({type:"artifact_delta",id:U,artDelta:P});let J=be.get(U);J&&(J.markdown+=P)}else if($e==="artifact_update"){let U=T.props&&typeof T.props=="object"&&!Array.isArray(T.props)?T.props:{};n({type:"artifact_update",id:String(T.id),props:U,component:typeof T.component=="string"?T.component:void 0})}else if($e==="artifact_complete"){let U=String(T.id);n({type:"artifact_complete",id:U});let P=Q.get(U);if(P){P.streaming=!1;try{let J=JSON.parse((Da=P.rawContent)!=null?Da:"{}");if(J.props){J.props.status="complete";let ae=be.get(U);ae!=null&&ae.markdown&&(J.props.markdown=ae.markdown)}P.rawContent=JSON.stringify(J)}catch{}be.delete(U),f(P),Q.delete(U)}}}else if($e==="transcript_insert"){let U=T.message;if(!U||typeof U!="object")continue;let P=String((cr=U.id)!=null?cr:`msg-${l()}`),J=U.role,Y={id:P,role:J==="user"?"user":J==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:l()};if(f(Y),Y.rawContent)try{let Me=JSON.parse(Y.rawContent),Fe=(Dt=Me==null?void 0:Me.props)==null?void 0:Dt.artifactId;typeof Fe=="string"&&re.add(Fe)}catch{}m=null,v.current=null,Z.delete(P),oe.delete(P)}else if($e==="error"||$e==="step_error"||$e==="dispatch_error"||$e==="flow_error"){let U=null;if(T.error instanceof Error)U=T.error;else if($e==="dispatch_error"){let P=(Zr=T.message)!=null?Zr:T.error;P!=null&&P!==""&&(U=new Error(String(P)))}else if($e==="step_error"||$e==="flow_error"){let P=T.error;typeof P=="string"&&P!==""?U=new Error(P):P!=null&&typeof P=="object"&&"message"in P&&(U=new Error(String((es=P.message)!=null?es:P)))}else $e==="error"&&T.error!=null&&T.error!==""&&(U=new Error(String(T.error)));if(U){n({type:"error",error:U});let P=m;P&&P.streaming&&(P.streaming=!1,f(P)),n({type:"status",status:"idle"})}}}}}We.length=0};;){let{done:D,value:pe}=await r.read();if(D)break;a+=s.decode(pe,{stream:!0});let De=a.split(`
10
-
11
- `);a=(an=De.pop())!=null?an:"";for(let Ke of De){let Ne=Ke.split(`
12
- `),Ve="message",ot="";for(let Xt of Ne)Xt.startsWith("event:")?Ve=Xt.replace("event:","").trim():Xt.startsWith("data:")&&(ot+=Xt.replace("data:","").trim());if(!ot)continue;let It;try{It=JSON.parse(ot)}catch(Xt){n({type:"error",error:Xt instanceof Error?Xt:new Error("Failed to parse chat stream payload")});continue}let qt=Ve!=="message"?Ve:(ro=It.type)!=null?ro:"message";if((Eo=this.onSSEEvent)==null||Eo.call(this,qt,It),this.parseSSEEvent){v.current=m;let Xt=await this.handleCustomSSEEvent(It,n,v,f,l,E);if(v.current&&v.current!==m&&(m=v.current),Xt)continue}Tt.push(qt,It),me()}}Tt.flushPending(),me(),Tt.destroy()}};function mi(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function ea(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var gi="[Image]";function Fl(e){return{type:"text",text:e}}var Im=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Ib=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Qo=[...Im,...Ib];function Rb(e){return Im.includes(e)||e.startsWith("image/")}function fi(e){return Rb(e.type)}async function Rm(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;fi(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 Pm(e,t=Qo,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Pb(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Wm(e,t){let n=Pb(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 hi=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 bi=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 ta=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 bi;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=L=>{x||(x=!0,clearTimeout(E),m(new Error(L)))},E=setTimeout(()=>v("WebSocket connection timed out."+g),1e4);this.ws.addEventListener("open",()=>{x||(x=!0,clearTimeout(E),f())},{once:!0}),this.ws.addEventListener("error",()=>{v("WebSocket connection failed to "+u+"."+g)},{once:!0}),this.ws.addEventListener("close",L=>{if(!L.wasClean&&!x){let I=L.code!==1006?` (code ${L.code})`:"";v("WebSocket connection failed"+I+"."+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 hi(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 Fr=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 na(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ta(e.runtype);case"browser":if(!Fr.isSupported())throw new Error("Browser speech recognition not supported");return new Fr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Bm(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return na({type:"runtype",runtype:e.runtype});if(Fr.isSupported())return na({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Nl(e){try{return Bm(e),!0}catch{return!1}}var Wb=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Bb(e,t){return Wb.some(n=>e[n]!==t[n])}function Hm(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 oa=e=>({isError:!0,content:[{type:"text",text:e}]}),Dm=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Om=e=>Gs(e)||e===Yo,yi=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)&&(Gs(f.name)||f.name===Yo&&((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 Zs(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 Nl((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=na(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 E=(v=this.pendingVoiceAssistantMessageId)!=null?v:(x=[...this.messages].reverse().find(L=>L.role==="assistant"))==null?void 0:x.id;E&&this.ttsSpokenMessageIds.add(E)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var 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(!Bb(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 Zs(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"?mi():n==="assistant"?ea():`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"?mi():r==="assistant"?ea():`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=mi(),s=ea(),a={id:r,role:"user",content:o||gi,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 E=Hm(x,this.config.errorMessage);if(E){let L={id:s,role:"assistant",createdAt:new Date().toISOString(),content:E,sequence:this.nextSequence()};this.appendMessage(L)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(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=ea();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=Hm(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 E=null;if(v instanceof Response){if(!v.ok){let L=await v.json().catch(()=>null);throw new Error((f=L==null?void 0:L.error)!=null?f:`Approval request failed: ${v.status}`)}E=v.body}else v instanceof ReadableStream&&(E=v);E?await this.connectStream(E,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(v){let E=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,E||(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,E,L,I,W,H,R;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 k=typeof((E=C[0])==null?void 0:E.question)=="string"?C[0].question:"";k&&(a={[k]:n})}}this.markAskUserQuestionResolved(t,a),(L=this.abortController)==null||L.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(I=t.toolCall)==null?void 0:I.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let w=typeof n=="string"?n:Object.entries(n).map(([C,k])=>`${C}: ${Array.isArray(k)?k.join(", "):k}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:w,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let w=a!=null?a:{};l.forEach((C,k)=>{let A=typeof(C==null?void 0:C.question)=="string"?C.question:"";if(!A)return;let S=w[A],_=Array.isArray(S)?S.join(", "):typeof S=="string"?S:"";this.appendMessage({id:`ask-user-q-${i}-${k}`,role:"assistant",content:A,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${k}`,role:"user",content:_||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let w=await this.client.resumeFlow(r,{[s]:n});if(!w.ok){let C=await w.json().catch(()=>null);throw new Error((W=C==null?void 0:C.error)!=null?W:`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||(R=(H=this.callbacks).onError)==null||R.call(H,w instanceof Error?w:new Error(String(w)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,o=(a=t.toolCall)==null?void 0:a.id;if(!n||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){var r,s;let n=this.messages.find(a=>a.id===t.id),o=[(r=n==null?void 0:n.toolCall)==null?void 0:r.startedAt,(s=t.toolCall)==null?void 0:s.startedAt];for(let a of o)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(t){var o,r;if(((o=t.toolCall)==null?void 0:o.name)!==Yo)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 R,w,C,k,A,S,_;let m=(R=f.toolCall)==null?void 0:R.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 E=this.markWebMcpToolRunning(f),L=(k=(C=f.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?k:m;if(m===Yo)return{dedupeKey:v,resumeKey:L,output:Wl(),toolMessage:f,startedAt:E,completedAt:Date.now()};let I=new AbortController;this.webMcpResolveControllers.add(I),r.push(I);let W=this.client.executeWebMcpToolCall(m,(A=f.toolCall)==null?void 0:A.args,I.signal),H;if(!W)H={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{H=await W}catch(V){let K=V instanceof Error&&(V.name==="AbortError"||V.message.includes("aborted")||V.message.includes("abort"));return K||(_=(S=this.callbacks).onError)==null||_.call(S,V instanceof Error?V:new Error(String(V))),this.markWebMcpToolComplete(f,oa(K?"Aborted by cancel()":Dm(V)),E),this.webMcpInflightKeys.delete(v),null}return I.signal.aborted?(this.markWebMcpToolComplete(f,oa("Aborted by cancel()"),E),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:L,output:H,toolMessage:f,startedAt:E,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)===Yo?{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,oa("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,E,L,I,W,H,R,w,C,k,A;let n=(x=t.agentMetadata)==null?void 0:x.executionId,o=(v=t.toolCall)==null?void 0:v.name,r=(E=t.toolCall)==null?void 0:E.id;if(!n){(I=(L=this.callbacks).onError)==null||I.call(L,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(_){(H=(W=this.callbacks).onError)==null||H.call(W,_ instanceof Error?_:new Error(String(_)))}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===Yo,u=(R=t.toolCall)==null?void 0:R.args,g=l?null:this.client.executeWebMcpToolCall(o,u,d),f="execute",m=a;try{let S;if(l?S=Wl():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,oa("Aborted by cancel()"),a);return}let _=(C=(w=t.agentMetadata)==null?void 0:w.webMcpToolCallId)!=null?C:o;f="resume",await this.resumeWithToolOutput(n,_,S,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,S,a,m,l?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(S){let _=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));(f==="execute"||_||d.aborted)&&this.markWebMcpToolComplete(t,oa(_||d.aborted?"Aborted by cancel()":Dm(S)),a),_||(A=(k=this.callbacks).onError)==null||A.call(k,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,E,L,I,W,H,R,w,C,k;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=(E=n.toolCall)==null?void 0:E.name,d=(L=n.agentMetadata)==null?void 0:L.executionId,l=(I=n.toolCall)==null?void 0:I.id;if(i&&Om(i)&&d&&l&&((W=n.agentMetadata)==null?void 0:W.awaitingLocalTool)===!0){let A=`${d}:${l}`,S=this.webMcpInflightKeys.has(A),_=this.webMcpResolvedKeys.has(A),V=(H=r.toolCall)==null?void 0:H.name,K=((R=r.agentMetadata)==null?void 0:R.executionId)===d&&((w=r.toolCall)==null?void 0:w.id)===l&&V!==void 0&&Om(V)&&((C=r.toolCall)==null?void 0:C.status)==="complete";(S||_||K)&&(a.agentMetadata={...(k=a.agentMetadata)!=null?k:{},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)})}};import{Activity as Hb,ArrowDown as Db,ArrowUp as Ob,ArrowUpRight as Fb,Bot as Nb,ChevronDown as _b,ChevronUp as Vb,ChevronRight as $b,ChevronLeft as Ub,Check as zb,Clipboard as qb,ClipboardCopy as jb,Copy as Kb,File as Gb,FileCode as Yb,FileSpreadsheet as Qb,FileText as Xb,ImagePlus as Jb,Loader as Zb,LoaderCircle as ey,Mic as ty,Paperclip as ny,RefreshCw as oy,Search as ry,Send as sy,ShieldAlert as ay,ShieldCheck as iy,ShieldX as ly,Square as cy,ThumbsDown as dy,ThumbsUp as py,Upload as uy,Volume2 as my,X as gy,User as fy,Mail as hy,Phone as by,Calendar as yy,Clock as vy,Building as xy,MapPin as wy,Lock as Cy,Key as Sy,CreditCard as Ay,AtSign as Ty,Hash as ky,Globe as Ey,Link as My,CircleCheck as Ly,CircleX as Iy,TriangleAlert as Ry,Info as Py,Ban as Wy,Shield as By,ArrowLeft as Hy,ArrowRight as Dy,ExternalLink as Oy,Ellipsis as Fy,EllipsisVertical as Ny,Menu as _y,House as Vy,Plus as $y,Minus as Uy,Pencil as zy,Trash as qy,Trash2 as jy,Save as Ky,Download as Gy,Share as Yy,Funnel as Qy,Settings as Xy,RotateCw as Jy,Maximize as Zy,Minimize as ev,ShoppingCart as tv,ShoppingBag as nv,Package as ov,Truck as rv,Tag as sv,Gift as av,Receipt as iv,Wallet as lv,Store as cv,DollarSign as dv,Percent as pv,Play as uv,Pause as mv,VolumeX as gv,Camera as fv,Image as hv,Film as bv,Headphones as yv,MessageCircle as vv,MessageSquare as xv,Bell as wv,Heart as Cv,Star as Sv,Eye as Av,EyeOff as Tv,Bookmark as kv,CalendarDays as Ev,History as Mv,Timer as Lv,Folder as Iv,FolderOpen as Rv,Files as Pv,Sparkles as Wv,Zap as Bv,Sun as Hv,Moon as Dv,Flag as Ov,Monitor as Fv,Smartphone as Nv}from"lucide";var _v={activity:Hb,"arrow-down":Db,"arrow-up":Ob,"arrow-up-right":Fb,bot:Nb,"chevron-down":_b,"chevron-up":Vb,"chevron-right":$b,"chevron-left":Ub,check:zb,clipboard:qb,"clipboard-copy":jb,copy:Kb,file:Gb,"file-code":Yb,"file-spreadsheet":Qb,"file-text":Xb,"image-plus":Jb,loader:Zb,"loader-circle":ey,mic:ty,paperclip:ny,"refresh-cw":oy,search:ry,send:sy,"shield-alert":ay,"shield-check":iy,"shield-x":ly,square:cy,"thumbs-down":dy,"thumbs-up":py,upload:uy,"volume-2":my,x:gy,user:fy,mail:hy,phone:by,calendar:yy,clock:vy,building:xy,"map-pin":wy,lock:Cy,key:Sy,"credit-card":Ay,"at-sign":Ty,hash:ky,globe:Ey,link:My,"circle-check":Ly,"circle-x":Iy,"triangle-alert":Ry,info:Py,ban:Wy,shield:By,"arrow-left":Hy,"arrow-right":Dy,"external-link":Oy,ellipsis:Fy,"ellipsis-vertical":Ny,menu:_y,house:Vy,plus:$y,minus:Uy,pencil:zy,trash:qy,"trash-2":jy,save:Ky,download:Gy,share:Yy,funnel:Qy,settings:Xy,"rotate-cw":Jy,maximize:Zy,minimize:ev,"shopping-cart":tv,"shopping-bag":nv,package:ov,truck:rv,tag:sv,gift:av,receipt:iv,wallet:lv,store:cv,"dollar-sign":dv,percent:pv,play:uv,pause:mv,"volume-x":gv,camera:fv,image:hv,film:bv,headphones:yv,"message-circle":vv,"message-square":xv,bell:wv,heart:Cv,star:Sv,eye:Av,"eye-off":Tv,bookmark:kv,"calendar-days":Ev,history:Mv,timer:Lv,folder:Iv,"folder-open":Rv,files:Pv,sparkles:Wv,zap:Bv,sun:Hv,moon:Dv,flag:Ov,monitor:Fv,smartphone:Nv},Ee=(e,t=24,n="currentColor",o=2)=>{let r=_v[e];return r?Vv(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 Vv(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:Qo,maxFileSize:10*1024*1024,maxFiles:4};function $v(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Uv(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 ra=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=Pm(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 Rm(l),f=fi(l)?URL.createObjectURL(l):null,m={id:$v(),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=fi(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=Uv(t.file.type),d=Ee(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=b("span");l.textContent=Wm(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),o.appendChild(a)}let r=b("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=Ee("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};import{Idiomorph as zv}from"idiomorph";var xi=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;zv.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 wi={index:-1,draft:""};function Fm(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:{...wi}}}function Nm(e,t){var n,o,r,s,a,i,d,l,u,g,f,m,x,v,E,L,I,W,H,R,w,C,k,A,S,_,V,K,fe,ue,ce,ke,ve,He,Se,ie,Q,re;return[e.id,e.role,(o=(n=e.content)==null?void 0:n.length)!=null?o:0,(s=(r=e.content)==null?void 0:r.slice(-32))!=null?s:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(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:"",(E=(v=e.toolCall)==null?void 0:v.name)!=null?E:"",(W=(I=(L=e.toolCall)==null?void 0:L.chunks)==null?void 0:I.length)!=null?W:0,(C=(w=(R=(H=e.toolCall)==null?void 0:H.chunks)==null?void 0:R[e.toolCall.chunks.length-1])==null?void 0:w.slice(-32))!=null?C:"",typeof((k=e.toolCall)==null?void 0:k.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:_.length)!=null?V:0,(ce=(ue=(fe=(K=e.reasoning)==null?void 0:K.chunks)==null?void 0:fe[e.reasoning.chunks.length-1])==null?void 0:ue.length)!=null?ce:0,(Se=(He=(ve=(ke=e.reasoning)==null?void 0:ke.chunks)==null?void 0:ve[e.reasoning.chunks.length-1])==null?void 0:He.slice(-32))!=null?Se:"",(Q=(ie=e.contentParts)==null?void 0:ie.length)!=null?Q:0,(re=e.stopReason)!=null?re:"",t].join("\0")}function _m(){return new Map}function Vm(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function $m(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Um(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Ci(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Xo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Nr(e,t){return Xo(e)-e.scrollTop<=t}function Si(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,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 Ai(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function zm(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function qm(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 jm(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Mn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Ln=1e5,hr=Ln+1;var sa={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},qv=["pre","code","a","script","style"],Ti=e=>{var t,n,o,r,s;return{type:(t=e==null?void 0:e.type)!=null?t:sa.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:sa.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:sa.speed,duration:(r=e==null?void 0:e.duration)!=null?r:sa.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:sa.buffer}},jv=[{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"}],Gm=new Map;for(let e of jv)Gm.set(e.name,e);var aa=(e,t)=>{var n,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(o=Gm.get(e))!=null?o:null},ki=(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},Kv=(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},Gv=(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},_l=/\s/,Yv=(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},Qv=(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(_l.test(s[i])){let l=i;for(;l<s.length&&_l.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&&!_l.test(s[u]);)l.appendChild(Kv(o,s[u],t,n.value)),n.value+=1,u+=1;a.appendChild(l),i=u}r.replaceChild(a,e)},Xv=(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(Gv(o,l,t,n.value)),n.value+=1));r.replaceChild(a,e)},ia=(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:qv).map(m=>m.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Yv(d,s)||i.push(d),d=a.nextNode();let l={value:(f=o==null?void 0:o.startIndex)!=null?f:0},u=t==="char"?Qv:Xv;for(let m of i)u(m,n,l);return r.innerHTML},Ei=(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},la=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},Km=new WeakMap,Jv=(e,t)=>{var s;if(!e.styles)return;let n=Km.get(t);if(n||(n=new Set,Km.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},Vl=new WeakMap,Zv=(e,t)=>{if(!e.onAttach)return;let n=Vl.get(t);if(n||(n=new Map,Vl.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},Ym=e=>{let t=Vl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},$l=(e,t)=>{Jv(e,t),Zv(e,t)};function Ul(e,t=Ln){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 ca=0,br=null;function zl(e=document){var n;if(ca++,ca===1){let o=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;br={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,ca=Math.max(0,ca-1),ca===0&&br)){let r=e.body,s=(o=e.defaultView)!=null?o:window;r.style.overflow=br.originalOverflow,r.style.position=br.originalPosition,r.style.top=br.originalTop,r.style.width=br.originalWidth,s.scrollTo(0,br.scrollY),br=null}}}var da={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Cn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},pa=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},To=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:da.side,width:(r=t==null?void 0:t.width)!=null?r:da.width,animate:(s=t==null?void 0:t.animate)!=null?s:da.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:da.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:da.maxHeight}};var ko={"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 ua=(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 W,H,R,w,C,k,A,S,_,V,K,fe,ue;let a=(W=s.launcher)!=null?W:{},i=Cn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let ce=(H=a.title)!=null?H:"Chat Assistant";d.textContent=ce,d.setAttribute("title",ce)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let ce=(R=a.subtitle)!=null?R:"Get answers fast";l.textContent=ce,l.setAttribute("title",ce)}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 ce=(w=a.agentIconSize)!=null?w:"40px";if(g.style.height=ce,g.style.width=ce,g.innerHTML="",a.agentIconName){let ke=parseFloat(ce)||24,ve=Ee(a.agentIconName,ke*.6,"var(--persona-text-inverse, #ffffff)",2);ve?(g.appendChild(ve),g.style.display=""):(g.textContent=(C=a.agentIconText)!=null?C:"\u{1F4AC}",g.style.display="")}else a.iconUrl?g.style.display="none":(g.textContent=(k=a.agentIconText)!=null?k:"\u{1F4AC}",g.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let ce=(A=a.agentIconSize)!=null?A:"40px";f.style.height=ce,f.style.width=ce,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 ce=(S=a.callToActionIconSize)!=null?S:"32px";m.style.height=ce,m.style.width=ce,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let ke=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,ke=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let ve=parseFloat(ce)||24,He=Math.max(ve-ke,8),Se=Ee(a.callToActionIconName,He,"currentColor",2);Se?m.appendChild(Se):m.textContent=(_=a.callToActionIconText)!=null?_:"\u2197"}else m.textContent=(V=a.callToActionIconText)!=null?V:"\u2197"}let x=a.position&&ko[a.position]?ko[a.position]:ko["bottom-right"],v="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?E:`${v} ${x}`,i||(n.style.zIndex=String((K=a.zIndex)!=null?K:Ln));let L="1px solid var(--persona-border, #e5e7eb)",I="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(fe=a.border)!=null?fe:L,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:I,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(ue=a.collapsedMaxWidth)!=null?ue:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}};var ex="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Mi=(e,t={})=>{var v,E,L,I,W,H;let{showClose:n=!0,wrapperClassName:o=ex,buttonSize:r,iconSize:s="28px"}=t,a=(v=e==null?void 0:e.launcher)!=null?v:{},i=(E=r!=null?r:a.closeButtonSize)!=null?E:"32px",d=b("div",o),l=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let u=(L=a.closeButtonTooltipText)!=null?L:"Close chat",g=(I=a.closeButtonShowTooltip)!=null?I:!0;l.setAttribute("aria-label",u),l.style.display=n?"":"none";let f=(W=a.closeButtonIconName)!=null?W:"x",m=(H=a.closeButtonIconText)!=null?H:"\xD7";l.style.color=a.closeButtonColor||Fn.actionIconColor;let x=Ee(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 R=a.closeButtonBorderWidth||"0px",w=a.closeButtonBorderColor||"transparent";l.style.border=`${R} 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 R=null,w=()=>{if(R)return;let k=l.ownerDocument,A=k.body;if(!A)return;R=Fo(k,"div","persona-clear-chat-tooltip"),R.textContent=u;let S=Fo(k,"div");S.className="persona-clear-chat-tooltip-arrow",R.appendChild(S);let _=l.getBoundingClientRect();R.style.position="fixed",R.style.zIndex=String(hr),R.style.left=`${_.left+_.width/2}px`,R.style.top=`${_.top-8}px`,R.style.transform="translate(-50%, -100%)",A.appendChild(R)},C=()=>{R&&R.parentNode&&(R.parentNode.removeChild(R),R=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}},tx="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Li=(e,t={})=>{var R,w,C,k,A,S,_,V,K,fe,ue,ce,ke;let{wrapperClassName:n=tx,buttonSize:o,iconSize:r="20px"}=t,a=(w=((R=e==null?void 0:e.launcher)!=null?R:{}).clearChat)!=null?w:{},i=(C=o!=null?o:a.size)!=null?C:"32px",d=(k=a.iconName)!=null?k:"refresh-cw",l=(A=a.iconColor)!=null?A:"",u=(S=a.backgroundColor)!=null?S:"",g=(_=a.borderWidth)!=null?_:"",f=(V=a.borderColor)!=null?V:"",m=(K=a.borderRadius)!=null?K:"",x=(fe=a.paddingX)!=null?fe:"",v=(ue=a.paddingY)!=null?ue:"",E=(ce=a.tooltipText)!=null?ce:"Clear chat",L=(ke=a.showTooltip)!=null?ke:!0,I=b("div",n),W=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");W.style.height=i,W.style.width=i,W.type="button",W.setAttribute("aria-label",E),W.style.color=l||Fn.actionIconColor;let H=Ee(d,r,"currentColor",1);if(H&&(H.style.display="block",W.appendChild(H)),u&&(W.style.backgroundColor=u,W.classList.remove("hover:persona-bg-gray-100")),g||f){let ve=g||"0px",He=f||"transparent";W.style.border=`${ve} solid ${He}`,W.classList.remove("persona-border-none")}if(m&&(W.style.borderRadius=m,W.classList.remove("persona-rounded-full")),x&&(W.style.paddingLeft=x,W.style.paddingRight=x),v&&(W.style.paddingTop=v,W.style.paddingBottom=v),I.appendChild(W),L&&E){let ve=null,He=()=>{if(ve)return;let ie=W.ownerDocument,Q=ie.body;if(!Q)return;ve=Fo(ie,"div","persona-clear-chat-tooltip"),ve.textContent=E;let re=Fo(ie,"div");re.className="persona-clear-chat-tooltip-arrow",ve.appendChild(re);let be=W.getBoundingClientRect();ve.style.position="fixed",ve.style.zIndex=String(hr),ve.style.left=`${be.left+be.width/2}px`,ve.style.top=`${be.top-8}px`,ve.style.transform="translate(-50%, -100%)",Q.appendChild(ve)},Se=()=>{ve&&ve.parentNode&&(ve.parentNode.removeChild(ve),ve=null)};I.addEventListener("mouseenter",He),I.addEventListener("mouseleave",Se),W.addEventListener("focus",He),W.addEventListener("blur",Se),I._cleanupTooltip=()=>{Se(),I.removeEventListener("mouseenter",He),I.removeEventListener("mouseleave",Se),W.removeEventListener("focus",He),W.removeEventListener("blur",Se)}}return{button:W,wrapper:I}};var Fn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},_r=e=>{var R,w,C,k,A,S,_,V,K,fe,ue,ce,ke,ve,He,Se;let{config:t,showClose:n=!0}=e,o=b("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");o.setAttribute("data-persona-theme-zone","header"),o.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",o.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",o.style.boxShadow="var(--persona-header-shadow, none)",o.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let r=(R=t==null?void 0:t.launcher)!=null?R:{},s=(w=r.headerIconSize)!=null?w:"48px",a=(C=r.closeButtonPlacement)!=null?C:"inline",i=(k=r.headerIconHidden)!=null?k:!1,d=r.headerIconName,l=b("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let ie=parseFloat(s)||24,Q=Ee(d,ie*.6,"currentColor",1);Q?l.replaceChildren(Q):l.textContent=(S=(A=t==null?void 0:t.launcher)==null?void 0:A.agentIconText)!=null?S:"\u{1F4AC}"}else if((_=t==null?void 0:t.launcher)!=null&&_.iconUrl){let ie=b("img");ie.src=t.launcher.iconUrl,ie.alt="",ie.className="persona-rounded-xl persona-object-cover",ie.style.height=s,ie.style.width=s,l.replaceChildren(ie)}else l.textContent=(K=(V=t==null?void 0:t.launcher)==null?void 0:V.agentIconText)!=null?K:"\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=Fn.titleColor,g.textContent=(ue=(fe=t==null?void 0:t.launcher)==null?void 0:fe.title)!=null?ue:"Chat Assistant";let f=b("span","persona-text-xs");f.style.color=Fn.subtitleColor,f.textContent=(ke=(ce=t==null?void 0:t.launcher)==null?void 0:ce.subtitle)!=null?ke:"Here to help you get answers fast",u.append(g,f),i?o.append(u):o.append(l,u);let m=(ve=r.clearChat)!=null?ve:{},x=(He=m.enabled)!=null?He:!0,v=(Se=m.placement)!=null?Se:"inline",E=null,L=null;if(x){let Q=Li(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=Q.button,L=Q.wrapper,v==="top-right"&&(L.style.right="48px"),v==="inline"&&o.appendChild(L)}let I=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":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:W,wrapper:H}=Mi(t,{showClose:n,wrapperClassName:I});return a!=="top-right"&&o.appendChild(H),{header:o,iconHolder:l,headerTitle:g,headerSubtitle:f,closeButton:W,closeButtonWrapper:H,clearChatButton:E,clearChatButtonWrapper:L}},ma=(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 fs(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(hr)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of t){if(m.dividerBefore){let E=document.createElement("hr");a.appendChild(E)}let 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 E=Ee(m.icon,16,"currentColor",1.5);E&&x.appendChild(E)}let v=document.createElement("span");v.textContent=m.label,x.appendChild(v),x.addEventListener("click",E=>{E.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 In(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:i}=e,d=b("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=Ee(t,o!=null?o:16,"currentColor",r!=null?r:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[u,g]of Object.entries(i))d.setAttribute(u,g);return d}function ql(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=Ee(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 Qm(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=Ee(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,E;l.style.backgroundColor=(v=d.background)!=null?v:"",l.style.borderColor=(E=d.border)!=null?E:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=fs({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 E=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",E?"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 nx=e=>{var o;let t=_r({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(o=e.layoutHeaderConfig)==null?void 0:o.onTitleClick;if(n){let r=t.headerTitle.parentElement;r&&(r.style.cursor="pointer",r.setAttribute("role","button"),r.setAttribute("tabindex","0"),r.addEventListener("click",()=>n()),r.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function ox(e,t,n){var o,r,s;if(t!=null&&t.length)for(let a of t){let i=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(r=(o=a.ariaLabel)!=null?o:a.label)!=null?r:a.id),a.icon){let d=Ee(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=b("div","persona-relative");d.appendChild(i);let l=fs({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 rx=e=>{var I,W,H,R,w,C,k,A,S;let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=(I=t==null?void 0:t.launcher)!=null?I:{},i=b("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=r==null?void 0:r.titleMenu,l,u;if(d)l=Qm({label:(W=a.title)!=null?W:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Fn.titleColor,u=(H=l.querySelector(".persona-combo-btn-label"))!=null?H:l;else{if(l=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=b("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=Fn.titleColor,u.textContent=(R=a.title)!=null?R:"Chat Assistant",l.appendChild(u),ox(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 V=r.onTitleClick;l.addEventListener("click",K=>{K.target.closest("button")||V()}),l.addEventListener("keydown",K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),V())})}let _=r==null?void 0:r.titleRowHover;_&&(l.style.borderRadius=(C=_.borderRadius)!=null?C:"10px",l.style.padding=(k=_.padding)!=null?k:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var V,K;l.style.backgroundColor=(V=_.background)!=null?V:"",l.style.borderColor=(K=_.border)!=null?K:""}),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||Fn.actionIconColor;let x=(S=a.closeButtonIconName)!=null?S:"x",v=Ee(x,"28px","currentColor",1);v?m.appendChild(v):m.textContent="\xD7",o&&m.addEventListener("click",o),f.appendChild(m),i.appendChild(f);let E=b("div");E.style.display="none";let L=b("span");return L.style.display="none",{header:i,iconHolder:E,headerTitle:u,headerSubtitle:L,closeButton:m,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Xm={default:nx,minimal:rx},sx=e=>{var t;return(t=Xm[e])!=null?t:Xm.default},Ii=(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=sx(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 Ri=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}},Pi=e=>{var R,w,C,k,A,S,_,V,K,fe,ue,ce;let t=(R=e==null?void 0:e.sendButton)!=null?R:{},n=(w=t.useIcon)!=null?w:!1,o=(C=t.iconText)!=null?C:"\u2191",r=t.iconName,s=(k=t.stopIconName)!=null?k:"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:_.sendButtonLabel)!=null?V:"Send",l=(fe=(K=e==null?void 0:e.copy)==null?void 0:K.stopButtonLabel)!=null?fe:"Stop",u=(ue=t.showTooltip)!=null?ue:!1,g=(ce=t.size)!=null?ce:"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 E=null,L=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 ke=parseFloat(g)||24,ve=(m==null?void 0:m.trim())||"currentColor";r?(E=Ee(r,ke,ve,2),E?v.appendChild(E):v.textContent=o):v.textContent=o,L=Ee(s,ke,ve,2),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 I=null;u&&a&&(I=b("div","persona-send-button-tooltip"),I.textContent=a,x.appendChild(I)),v.setAttribute("aria-label",a),x.appendChild(v);let W="send";return{button:v,wrapper:x,setMode:ke=>{if(ke===W)return;W=ke;let ve=ke==="stop"?i:a;if(v.setAttribute("aria-label",ve),I&&(I.textContent=ve),n){if(E&&L){let He=ke==="stop"?L:E;v.replaceChildren(He)}}else v.textContent=ke==="stop"?l:d}}},Wi=e=>{var I,W,H,R,w,C,k,A,S,_,V,K;let t=(I=e==null?void 0:e.voiceRecognition)!=null?I:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),r=((W=t.provider)==null?void 0:W.type)==="runtype";if(!(o||r))return null;let a=(R=(H=e==null?void 0:e.sendButton)==null?void 0:H.size)!=null?R:"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:(k=e==null?void 0:e.sendButton)==null?void 0:k.backgroundColor,m=(_=t.iconColor)!=null?_:(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=Ee(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 E=(V=t.tooltipText)!=null?V:"Start voice recognition";if(((K=t.showTooltip)!=null?K:!1)&&E){let fe=b("div","persona-send-button-tooltip");fe.textContent=E,i.appendChild(fe)}return{button:d,wrapper:i}},Bi=e=>{var x,v,E,L,I,W,H,R;let t=(x=e==null?void 0:e.attachments)!=null?x:{};if(t.enabled!==!0)return null;let n=(E=(v=e==null?void 0:e.sendButton)==null?void 0:v.size)!=null?E:"40px",o=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.style.display="none";let r=b("input");r.type="file",r.accept=((L=t.allowedTypes)!=null?L:Qo).join(","),r.multiple=((I=t.maxFiles)!=null?I:4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=b("div","persona-send-button-wrapper"),a=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(W=t.buttonTooltipText)!=null?W:"Attach file");let i=(H=t.buttonIconName)!=null?H:"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=Ee(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=(R=t.buttonTooltipText)!=null?R:"Attach file",m=b("div","persona-send-button-tooltip");return m.textContent=f,s.appendChild(m),{button:a,wrapper:s,input:r,previewsContainer:o}},Hi=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},Di=()=>b("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var Oi=e=>{var x,v,E,L,I,W;let{config:t}=e,n=b("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");n.setAttribute("data-persona-theme-zone","composer");let o=Di(),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}=Ri(t);a();let i=Pi(t),d=Wi(t),l=Bi(t),u=Hi(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",H=>{H.target!==i.button&&H.target!==i.wrapper&&H.target!==(d==null?void 0:d.button)&&H.target!==(d==null?void 0:d.wrapper)&&H.target!==(l==null?void 0:l.button)&&H.target!==(l==null?void 0:l.wrapper)&&s.focus()}),n.append(o,r,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:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(L=l==null?void 0:l.wrapper)!=null?L:null,attachmentInput:(I=l==null?void 0:l.input)!=null?I:null,attachmentPreviewsContainer:(W=l==null?void 0:l.previewsContainer)!=null?W:null,actionsRow:g,leftActions:f,rightActions:m,setSendButtonMode:i.setMode}};var Jm=()=>{let e=b("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let t=b("span","persona-pill-peek__icon"),n=Ee("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=b("span","persona-pill-peek__text"),r=b("span","persona-pill-peek__caret"),s=Ee("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},Zm=e=>{var x,v,E,L,I,W;let{config:t}=e,n=b("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let o=Di();o.style.display="none";let r=Hi(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=Ri(t);s.style.maxHeight="100px",a();let i=Pi(t),d=Wi(t),l=Bi(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",H=>{H.target!==i.button&&H.target!==i.wrapper&&H.target!==(d==null?void 0:d.button)&&H.target!==(d==null?void 0:d.wrapper)&&H.target!==(l==null?void 0:l.button)&&H.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&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:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(L=l==null?void 0:l.wrapper)!=null?L:null,attachmentInput:(I=l==null?void 0:l.input)!=null?I:null,attachmentPreviewsContainer:(W=l==null?void 0:l.previewsContainer)!=null?W:null,actionsRow:m,leftActions:g,rightActions:f,setSendButtonMode:i.setMode}};var eg=e=>{var u,g,f,m,x,v,E,L,I,W,H,R,w,C,k,A,S;let t=(g=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?g:!0,n=Cn(e);if(pa(e)){let _=(m=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?m:{},V=b("div","persona-widget-wrapper persona-fixed persona-transition");V.setAttribute("data-persona-composer-bar",""),V.dataset.state="collapsed",V.dataset.expandedSize=(x=_.expandedSize)!=null?x:"anchored",V.style.zIndex=String((E=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?E:Ln);let K=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");K.style.width="100%",V.appendChild(K);let fe=b("div","persona-widget-pill-root");return fe.setAttribute("data-persona-composer-bar",""),fe.dataset.state="collapsed",fe.dataset.expandedSize=(L=_.expandedSize)!=null?L:"anchored",fe.style.zIndex=String((W=(I=e==null?void 0:e.launcher)==null?void 0:I.zIndex)!=null?W:Ln),{wrapper:V,panel:K,pillRoot:fe}}if(n){let _=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),V=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return _.appendChild(V),{wrapper:_,panel:V}}if(!t){let _=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),V=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),K=(R=(H=e==null?void 0:e.launcher)==null?void 0:H.width)!=null?R:"100%";return _.style.width=K,V.style.width="100%",_.appendChild(V),{wrapper:_,panel:V}}let r=(w=e==null?void 0:e.launcher)!=null?w:{},s=r.position&&ko[r.position]?ko[r.position]:ko["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((k=(C=e==null?void 0:e.launcher)==null?void 0:C.zIndex)!=null?k:Ln);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:mo;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},ax=(e,t)=>{var H,R,w,C,k,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}=Mi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=(w=(R=(H=e==null?void 0:e.launcher)==null?void 0:H.clearChat)==null?void 0:R.enabled)!=null?w:!0,a=null,i=null;if(s){let K=Li(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=K.button,i=K.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=(k=(C=e==null?void 0:e.copy)==null?void 0:C.welcomeTitle)!=null?k:"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=(_=e==null?void 0:e.layout)==null?void 0:_.contentMaxWidth;x&&(m.style.maxWidth=x,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((V=e==null?void 0:e.copy)==null?void 0:V.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,m);let E=b("div","persona-composer-overlay persona-pointer-events-none");E.setAttribute("data-persona-composer-overlay",""),E.style.position="absolute",E.style.left="0",E.style.right="0",E.style.bottom="0",E.style.zIndex="20";let L=Zm({config:e}),{root:I,textNode:W}=Jm();return n.append(d,r,l,E),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:m,composerOverlay:E,suggestions:L.suggestions,textarea:L.textarea,sendButton:L.sendButton,sendButtonWrapper:L.sendButtonWrapper,micButton:L.micButton,micButtonWrapper:L.micButtonWrapper,composerForm:L.composerForm,statusText:L.statusText,introTitle:g,introSubtitle:f,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:d,footer:L.footer,attachmentButton:L.attachmentButton,attachmentButtonWrapper:L.attachmentButtonWrapper,attachmentInput:L.attachmentInput,attachmentPreviewsContainer:L.attachmentPreviewsContainer,actionsRow:L.actionsRow,leftActions:L.leftActions,rightActions:L.rightActions,setSendButtonMode:L.setSendButtonMode,peekBanner:I,peekTextNode:W}},tg=(e,t=!0)=>{var E,L,I,W,H,R,w,C,k;if(pa(e))return ax(e,t);let n=b("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");n.setAttribute("data-persona-theme-zone","container");let o=(E=e==null?void 0:e.layout)==null?void 0:E.header,r=((L=e==null?void 0:e.layout)==null?void 0:L.showHeader)!==!1,s=o?Ii(e,o,{showClose:t}):_r({config:e,showClose:t}),a=b("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages"),a.style.setProperty("scrollbar-gutter","stable");let i=b("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=Cn(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=b("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(W=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeTitle)!=null?W:"Hello \u{1F44B}";let l=b("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(R=(H=e==null?void 0:e.copy)==null?void 0:H.welcomeSubtitle)!=null?R:"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=Oi({config:e}),x=((k=e==null?void 0:e.layout)==null?void 0:k.showFooter)!==!1;r?ma(n,s,e):(s.header.style.display="none",ma(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 ix=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}},lx=(e,t)=>{if(!e)return null;let n=ix(e);if(n===null)return null;let o=t==null?void 0:t[e],r=o!==void 0?o:n;return r||null},cx=(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},dx=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},jl=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(":"))},Kl=320,og=320,px=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),ux=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),mx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),gx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),fx=(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=`${Kl}px`,l.style.maxHeight=`${og}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}),dx(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}},hx=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(!jl(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=`${Kl}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},bx=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(!jl(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=`${Kl}px`,r.style.maxHeight=`${og}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}},yx=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(!jl(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}},ga=()=>{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},vx=(e,t,n)=>{let o={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:ga};if(t){let r=t(o);if(r!==null)return r}return ga()},xx=(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},ng=(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},wx=(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},Cx=(e,t,n)=>{var m,x,v,E,L,I;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 W=b("div");return W.style.display="none",W.id=`actions-${e.id}`,W.setAttribute("data-actions-for",e.id),W}let a=(E=t.visibility)!=null?E:"hover",i=(L=t.align)!=null?L:"right",d=(I=t.layout)!=null?I:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],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=(W,H,R)=>{let w=In({icon:W,label:H,size:14,className:"persona-message-action-btn"});return w.setAttribute("data-action",R),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},Gl=(e,t,n,o,r,s)=>{var ie,Q,re,be,he,j,se,Re,ne,Z,oe,at,it,Le,de,Qe,We;let a=n!=null?n:{},i=(ie=a.layout)!=null?ie:"bubble",d=a.avatar,l=a.timestamp,u=(Q=d==null?void 0:d.show)!=null?Q:!1,g=(re=l==null?void 0:l.show)!=null?re:!1,f=(be=d==null?void 0:d.position)!=null?be:"left",m=(he=l==null?void 0:l.position)!=null?he:"below",x=wx(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 E=px(e),L=(se=(j=e.content)==null?void 0:j.trim())!=null?se:"",W=E.length>0&&L===gi,H=Ti((ne=(Re=s==null?void 0:s.widgetConfig)==null?void 0:Re.features)==null?void 0:ne.streamAnimation),R=(at=(oe=(Z=s==null?void 0:s.widgetConfig)==null?void 0:Z.features)==null?void 0:oe.streamAnimation)==null?void 0:at.plugins,w=e.role==="assistant"&&H.type!=="none"?aa(H.type,R):null,C=e.role==="assistant"&&((it=w==null?void 0:w.isAnimating)==null?void 0:it.call(w,e))===!0,k=e.role==="assistant"&&w!==null&&(!!e.streaming||C);k&&(w!=null&&w.bubbleClass)&&v.classList.add(w.bubbleClass);let A=document.createElement("div");A.classList.add("persona-message-content"),k&&w&&(w.containerClass&&A.classList.add(w.containerClass),A.style.setProperty("--persona-stream-step",`${H.speed}ms`),A.style.setProperty("--persona-stream-duration",`${H.duration}ms`));let S=k?ki((Le=e.content)!=null?Le:"",H.buffer,w,e,!!e.streaming):(de=e.content)!=null?de:"",_=t({text:S,message:e,streaming:!!e.streaming,raw:e.rawContent}),V=_;k&&(w==null?void 0:w.wrap)==="char"?V=ia(_,"char",e.id,{skipTags:w.skipTags}):k&&(w==null?void 0:w.wrap)==="word"&&(V=ia(_,"word",e.id,{skipTags:w.skipTags}));let K=null;if(W?(K=document.createElement("div"),K.innerHTML=V,K.style.display="none",A.appendChild(K)):A.innerHTML=V,k&&(w!=null&&w.useCaret)&&!W&&L){let q=Ei(),me=A.querySelectorAll(".persona-stream-char, .persona-stream-word"),tt=me[me.length-1];if(tt!=null&&tt.parentNode)tt.parentNode.insertBefore(q,tt.nextSibling);else{let Tt=A.lastElementChild;Tt?Tt.appendChild(q):A.appendChild(q)}}if(g&&m==="inline"&&e.createdAt){let q=ng(e,l);q.classList.add("persona-ml-2","persona-inline"),A.appendChild(q)}if(E.length>0){let q=fx(E,!W&&!!L,()=>{W&&K&&(K.style.display="")});q?v.appendChild(q):W&&K&&(K.style.display="")}let fe=ux(e);if(fe.length>0){let q=hx(fe);q&&v.appendChild(q)}let ue=mx(e);if(ue.length>0){let q=bx(ue);q&&v.appendChild(q)}let ce=gx(e);if(ce.length>0){let q=yx(ce);q&&v.appendChild(q)}if(v.appendChild(A),g&&m==="below"&&e.createdAt){let q=ng(e,l);q.classList.add("persona-mt-1"),v.appendChild(q)}let ke=e.role==="assistant"?lx(e.stopReason,(We=(Qe=s==null?void 0:s.widgetConfig)==null?void 0:Qe.copy)==null?void 0:We.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let q=!!(S&&S.trim()),me=H.placeholder==="skeleton",tt=me&&H.buffer==="line"&&q;if(q)tt&&v.appendChild(la());else if(me)v.appendChild(la());else{let Tt=vx("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Tt&&v.appendChild(Tt)}}if(ke&&e.stopReason&&!e.streaming&&(L||(A.style.display="none"),v.appendChild(cx(e.stopReason,ke))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let q=Cx(e,o,r);v.appendChild(q)}if(!u||e.role==="system")return v;let He=b("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Se=xx(d,e.role);return f==="right"||f==="left"&&e.role==="user"?He.append(v,Se):He.append(Se,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),He};var hs=new Set,Sx=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Ax=(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
- `):""},rg=(e,t)=>{let n=hs.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let a=o.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=Ee(n?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},Yl=(e,t)=>{var ue,ce,ke,ve,He,Se,ie,Q,re,be,he;let n=e.reasoning,o=b("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let r=(ce=(ue=t==null?void 0:t.features)==null?void 0:ue.reasoningDisplay)!=null?ce:{},s=r.expandable!==!1,a=s&&hs.has(e.id),i=n.status!=="complete",d=Ax(e,(ke=r.previewMaxLines)!=null?ke:3),l=b("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",s&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let u=b("div","persona-flex persona-flex-col persona-text-left"),g=b("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",m=(ve=t==null?void 0:t.reasoning)!=null?ve:{},x=String((He=n.startedAt)!=null?He:Date.now()),v=()=>{let j=b("span","");return j.setAttribute("data-tool-elapsed",x),j.textContent=ci(n),j},E=(Se=m.renderCollapsedSummary)==null?void 0:Se.call(m,{message:e,reasoning:n,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:ci(n),createElapsedElement:v});typeof E=="string"&&E.trim()?(g.textContent=E,u.appendChild(g)):E instanceof HTMLElement?u.appendChild(E):(g.textContent=f,u.appendChild(g));let L=b("span","persona-text-xs persona-text-persona-primary");L.textContent=Sm(n),u.appendChild(L);let I=(ie=r.loadingAnimation)!=null?ie:"none",W=m.activeTextTemplate,H=m.completeTextTemplate,R=i?W:H,w=E instanceof HTMLElement,C=(j,se,Re)=>{let ne=Re;for(let Z of se){let oe=b("span","persona-tool-char");oe.style.setProperty("--char-index",String(ne)),oe.textContent=Z===" "?"\xA0":Z,j.appendChild(oe),ne++}return ne},k=(j,se)=>{g.textContent="";let Re=di(j,""),ne=0;for(let Z of Re){let oe=Z.styles.length>0?(()=>{let at=b("span",Z.styles.map(it=>`persona-tool-text-${it}`).join(" "));return g.appendChild(at),at})():g;if(Z.isDuration&&i)oe.appendChild(v());else{let at=Z.isDuration?ci(n):Z.text;se?ne=C(oe,at,ne):oe.appendChild(document.createTextNode(at))}}};if(!w&&R)if(L.style.display="none",g.style.display="",i&&I!=="none"){let j=(Q=m.loadingAnimationDuration)!=null?Q:2e3;g.setAttribute("data-preserve-animation","true"),I==="pulse"?(g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${j}ms`),k(R,!1)):(g.classList.add(`persona-tool-loading-${I}`),g.style.setProperty("--persona-tool-anim-duration",`${j}ms`),I==="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)),k(R,!0))}else k(R,!1);else if(!w&&i&&I!=="none"){g.style.display="";let j=(re=m.loadingAnimationDuration)!=null?re:2e3;if(g.setAttribute("data-preserve-animation","true"),I==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${j}ms`);else{g.classList.add(`persona-tool-loading-${I}`),g.style.setProperty("--persona-tool-anim-duration",`${j}ms`),I==="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 se=g.textContent||f;g.textContent="",C(g,se,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 se=Ee(a?"chevron-up":"chevron-down",16,"currentColor",2);se?A.appendChild(se):A.textContent=a?"Hide":"Show";let Re=b("div","persona-flex persona-items-center persona-ml-auto");Re.append(A),l.append(u,Re)}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 j=(he=(be=t==null?void 0:t.reasoning)==null?void 0:be.renderCollapsedPreview)==null?void 0:he.call(be,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});Sx(S,j)||(S.textContent=d),S.style.display=""}if(!a&&i&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(l,S),o;let _=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");_.style.display=a?"":"none";let V=n.chunks.join(""),K=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return K.textContent=V||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),_.appendChild(K),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),A){A.innerHTML="";let se=Ee(a?"chevron-up":"chevron-down",16,"currentColor",2);se?A.appendChild(se):A.textContent=a?"Hide":"Show"}_.style.display=a?"":"none",S.style.display=a?"none":S.textContent||S.childNodes.length?"":"none"})(),o.append(l,S,_),o};var bs=new Set,Tx=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),kx=(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=gs(n.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
26
- `):""},Ex=(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=kx(e,(f=o==null?void 0:o.previewMaxLines)!=null?f:3),a=n?Am(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=Dl(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Dl(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},sg=(e,t,n)=>{var u;let o=bs.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=Ee(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")},Ql=(e,t)=>{var V,K,fe,ue,ce,ke,ve,He,Se;let n=e.toolCall,o=(V=t==null?void 0:t.toolCall)!=null?V:{},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=(fe=(K=t==null?void 0:t.features)==null?void 0:K.toolCallDisplay)!=null?fe:{},a=s.expandable!==!1,i=a&&bs.has(e.id),{summary:d,previewText:l,isActive:u}=Ex(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((ue=n.startedAt)!=null?ue:Date.now()),v=()=>{let ie=b("span","");return ie.setAttribute("data-tool-elapsed",x),ie.textContent=Js(n),ie},E=(ke=o.renderCollapsedSummary)==null?void 0:ke.call(o,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(ce=s.collapsedMode)!=null?ce:"tool-call",isActive:u,config:t!=null?t:{},elapsed:Js(n),createElapsedElement:v});typeof E=="string"&&E.trim()?(m.textContent=E,f.appendChild(m)):E instanceof HTMLElement?f.appendChild(E):(m.textContent=d,f.appendChild(m));let L=(ve=s.loadingAnimation)!=null?ve:"none",I=o.activeTextTemplate,W=o.completeTextTemplate,H=u?I:W,R=E instanceof HTMLElement,w=(ie,Q,re)=>{let be=re;for(let he of Q){let j=b("span","persona-tool-char");j.style.setProperty("--char-index",String(be)),j.textContent=he===" "?"\xA0":he,ie.appendChild(j),be++}return be},C=(ie,Q)=>{var j;m.textContent="";let re=((j=n.name)==null?void 0:j.trim())||"tool",be=di(ie,re),he=0;for(let se of be){let Re=se.styles.length>0?(()=>{let ne=b("span",se.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return m.appendChild(ne),ne})():m;if(se.isDuration&&u)Re.appendChild(v());else{let ne=se.isDuration?Js(n):se.text;Q?he=w(Re,ne,he):Re.appendChild(document.createTextNode(ne))}}};if(!R)if(u&&L!=="none"){let ie=(He=o.loadingAnimationDuration)!=null?He:2e3;if(m.setAttribute("data-preserve-animation","true"),L==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),H&&C(H,!1);else if(m.classList.add(`persona-tool-loading-${L}`),m.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),L==="shimmer-color"&&(o.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),H)C(H,!0);else{let Q=m.textContent||d;m.textContent="",w(m,Q,0)}}else H&&C(H,!1);let k=null;if(a){k=b("div","persona-flex persona-items-center");let ie=o.toggleTextColor||o.headerTextColor||"currentColor",Q=Ee(i?"chevron-up":"chevron-down",16,ie,2);Q?k.appendChild(Q):k.textContent=i?"Hide":"Show";let re=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");re.append(k),g.append(f,re)}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 ie=(Se=o.renderCollapsedPreview)==null?void 0:Se.call(o,{message:e,toolCall:n,defaultPreview:l,isActive:u,config:t!=null?t:{}});Tx(A,ie)||(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 ie=b("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?ie.style.color=o.contentTextColor:o.headerTextColor&&(ie.style.color=o.headerTextColor),ie.textContent=n.name,S.appendChild(ie)}if(n.args!==void 0){let ie=b("div","persona-space-y-1"),Q=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Q.style.color=o.labelTextColor),Q.textContent="Arguments";let re=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(re.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(re.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(re.style.color=o.codeBlockTextColor),re.textContent=gs(n.args),ie.append(Q,re),S.appendChild(ie)}if(n.chunks&&n.chunks.length){let ie=b("div","persona-space-y-1"),Q=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Q.style.color=o.labelTextColor),Q.textContent="Activity";let re=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(re.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(re.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(re.style.color=o.codeBlockTextColor),re.textContent=n.chunks.join(""),ie.append(Q,re),S.appendChild(ie)}if(n.status==="complete"&&n.result!==void 0){let ie=b("div","persona-space-y-1"),Q=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(Q.style.color=o.labelTextColor),Q.textContent="Result";let re=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",o.codeBlockBackgroundColor&&(re.style.backgroundColor=o.codeBlockBackgroundColor),o.codeBlockBorderColor&&(re.style.borderColor=o.codeBlockBorderColor),o.codeBlockTextColor&&(re.style.color=o.codeBlockTextColor),re.textContent=gs(n.result),ie.append(Q,re),S.appendChild(ie)}if(n.status==="complete"&&typeof n.duration=="number"){let ie=b("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(ie.style.color=o.contentTextColor),ie.textContent=`Duration: ${n.duration}ms`,S.appendChild(ie)}return(()=>{if(g.setAttribute("aria-expanded",i?"true":"false"),k){k.innerHTML="";let ie=o.toggleTextColor||o.headerTextColor||"currentColor",Q=Ee(i?"chevron-up":"chevron-down",16,ie,2);Q?k.appendChild(Q):k.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 Fi=new Map,Mx=e=>{let n=(e.startsWith(Br)?e.slice(Br.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)},ag=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,ig=(e,t)=>{var o,r,s;let n=(r=(o=ag(t))==null?void 0:o.detailsDisplay)!=null?r:"collapsed";return(s=Fi.get(e))!=null?s:n==="expanded"},lg=(e,t,n)=>{var a,i;let o=ag(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?(a=o==null?void 0:o.hideDetailsLabel)!=null?a:"Hide details":(i=o==null?void 0:o.showDetailsLabel)!=null?i:"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=Ee(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},cg=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=ig(e,n);lg(o,s,n),r.style.display=s?"":"none"};var Ni=(e,t)=>{var C,k,A,S,_,V,K,fe,ue,ce,ke,ve,He,Se,ie;let n=e.approval,o=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,r=(n==null?void 0:n.status)==="pending",s=b("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(C=o==null?void 0:o.backgroundColor)!=null?C:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(k=o==null?void 0:o.borderColor)!=null?k:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(o==null?void 0:o.shadow)!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=b("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",l=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(A=o==null?void 0:o.titleColor)!=null?A:"currentColor",u=Ee(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 Q=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");Q.setAttribute("data-approval-status",n.status),n.status==="approved"?(Q.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",Q.style.color="var(--persona-palette-colors-success-700, #15803d)",Q.textContent="Approved"):n.status==="denied"?(Q.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",Q.style.color="var(--persona-palette-colors-error-700, #b91c1c)",Q.textContent="Denied"):n.status==="timeout"&&(Q.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",Q.style.color="var(--persona-palette-colors-warning-700, #b45309)",Q.textContent="Timeout"),f.appendChild(Q)}g.appendChild(f);let v=n.toolType==="webmcp"||n.toolName.startsWith(Br)?Tl(n.toolName):void 0,E=(_=o==null?void 0:o.formatDescription)==null?void 0:_.call(o,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...v?{displayTitle:v}:{},...n.reason?{reason:n.reason}:{}}),L=!n.toolName,I=E||(L?n.description:`The assistant wants to use \u201C${v!=null?v:Mx(n.toolName)}\u201D.`),W=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(W.setAttribute("data-approval-summary","true"),o!=null&&o.descriptionColor&&(W.style.color=o.descriptionColor),W.textContent=I,g.appendChild(W),n.reason){let Q=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");Q.setAttribute("data-approval-reason","true"),o!=null&&o.reasonColor?Q.style.color=o.reasonColor:o!=null&&o.descriptionColor&&(Q.style.color=o.descriptionColor);let re=b("span","persona-font-medium");re.textContent=`${(V=o==null?void 0:o.reasonLabel)!=null?V:"Agent's stated reason:"} `,Q.appendChild(re),Q.appendChild(document.createTextNode(n.reason)),g.appendChild(Q)}let H=(K=o==null?void 0:o.detailsDisplay)!=null?K:"collapsed",R=!!n.description&&!L,w=R||!!n.parameters;if(H!=="hidden"&&w){let Q=ig(e.id,t),re=b("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");re.type="button",re.setAttribute("data-expand-header","true"),re.setAttribute("data-bubble-type","approval"),o!=null&&o.descriptionColor&&(re.style.color=o.descriptionColor);let be=b("span");be.setAttribute("data-approval-details-label","true");let he=b("span","persona-inline-flex persona-items-center");he.setAttribute("data-approval-details-chevron","true"),re.append(be,he),lg(re,Q,t),g.appendChild(re);let j=b("div");if(j.setAttribute("data-approval-details","true"),j.style.display=Q?"":"none",R){let se=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o!=null&&o.descriptionColor&&(se.style.color=o.descriptionColor),se.textContent=n.description,j.appendChild(se)}if(n.parameters){let se=b("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o!=null&&o.parameterBackgroundColor&&(se.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(se.style.color=o.parameterTextColor),se.style.fontSize="0.75rem",se.style.lineHeight="1rem",se.textContent=gs(n.parameters),j.appendChild(se)}g.appendChild(j)}if(r){let Q=b("div","persona-flex persona-gap-2 persona-mt-2");Q.setAttribute("data-approval-buttons","true");let re=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");re.type="button",re.style.backgroundColor=(fe=o==null?void 0:o.approveButtonColor)!=null?fe:"var(--persona-approval-approve-bg, #22c55e)",re.style.color=(ue=o==null?void 0:o.approveButtonTextColor)!=null?ue:"#ffffff",re.setAttribute("data-approval-action","approve");let be=Ee("shield-check",14,(ce=o==null?void 0:o.approveButtonTextColor)!=null?ce:"#ffffff",2);be&&(be.style.marginRight="4px",re.appendChild(be));let he=document.createTextNode((ke=o==null?void 0:o.approveLabel)!=null?ke:"Approve");re.appendChild(he);let j=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");j.type="button",j.style.backgroundColor=(ve=o==null?void 0:o.denyButtonColor)!=null?ve:"transparent",j.style.color=(He=o==null?void 0:o.denyButtonTextColor)!=null?He:"var(--persona-feedback-error, #dc2626)",j.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,j.setAttribute("data-approval-action","deny");let se=Ee("shield-x",14,(Se=o==null?void 0:o.denyButtonTextColor)!=null?Se:"var(--persona-feedback-error, #dc2626)",2);se&&(se.style.marginRight="4px",j.appendChild(se));let Re=document.createTextNode((ie=o==null?void 0:o.denyLabel)!=null?ie:"Deny");j.appendChild(Re),Q.append(re,j),g.appendChild(Q)}return a.append(i,g),s.appendChild(a),s};var dg=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(E=>E.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 fa=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 Lx=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Ix=new Set(["step_start","execution_start"]),Rx=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Px=new Set(["step_complete","agent_turn_complete"]),Wx=new Set(["flow_complete","agent_complete"]),pg=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),mg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),oo=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Vr=(e,t)=>{let n=e[t];return mg(n)?n:void 0};function Xl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function _i(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Bx(e,t){return typeof t.type=="string"?t.type:e}function Hx(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 Dx(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 ug(e){var o,r,s,a,i;let t=Vr(e,"result"),n=[Vr(e,"tokens"),Vr(e,"totalTokens"),t?Vr(t,"tokens"):void 0,Vr(e,"usage"),t?Vr(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(r=(o=oo(d.output))!=null?o:oo(d.outputTokens))!=null?r:oo(d.completionTokens);if(l!==void 0)return l}return(i=(s=oo(e.outputTokens))!=null?s:oo(e.completionTokens))!=null?i:t?(a=oo(t.outputTokens))!=null?a:oo(t.completionTokens):void 0}function Ox(e){var n,o,r,s,a;let t=Vr(e,"result");return(a=(r=(o=(n=oo(e.executionTime))!=null?n:oo(e.executionTimeMs))!=null?o:oo(e.execution_time))!=null?r:oo(e.duration))!=null?a:t?(s=oo(t.executionTime))!=null?s:oo(t.executionTimeMs):void 0}function Fx(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ba=class{constructor(t=Fx){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:_i(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(!mg(n)){pg.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Bx(t,n),r=this.now();if(Lx.has(o)){this.startRun(r);return}if(Ix.has(o)){this.run||this.startRun(r);return}if(Rx.has(o)){if(!Dx(o,n))return;let a=Hx(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+Xl(i.visibleCharCount),l=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:_i(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Px.has(o)){if(!this.run)return;let a=this.run,i=ug(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Xl(a.visibleCharCount),u=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:_i(l,u),outputTokens:l,durationMs:u,source:d?"usage":"estimate"};return}if(Wx.has(o)){if(!this.run)return;let a=this.run,i=ug(n),d=i!=null?i:a.exactOutputTokens+Xl(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:_i(d,u),outputTokens:d,durationMs:u,source:l},this.run=null;return}if(pg.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=Ox(n);return s!=null?s:o-t.startedAt}};function ys(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Nx={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)"}},_x={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Vx=["flowName","stepName","reasoningText","text","name","tool","toolName"],$x=100;function Ux(e,t){let n={...Nx,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return _x}function zx(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function qx(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 jx(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 Kx(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 Gx(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 Yx(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Qx(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 Xx(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 Jl(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");ys(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 V,K;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"),E=Ee(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&v.appendChild(E);let L=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),I=(V=o.timestampFormat)!=null?V:"relative";L.textContent=I==="relative"?zx(e.timestamp,n):qx(e.timestamp);let W=null;o.showSequenceNumbers!==!1&&(W=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),W.textContent=String(t+1));let H=Ux(e.type,o.badgeColors),R=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");R.style.backgroundColor=H.bg,R.style.color=H.text,R.style.borderColor=H.text+"50",R.textContent=e.type;let w=(K=o.descriptionFields)!=null?K:Vx,C=jx(e.payload,w),k=null;C&&(k=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),k.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"),_=Ee("clipboard","12px","currentColor",1.5);return _&&S.appendChild(_),S.addEventListener("click",async fe=>{fe.stopPropagation(),await Kx(Gx(e)),S.innerHTML="";let ue=Ee("check","12px","currentColor",1.5);ue&&S.appendChild(ue),setTimeout(()=>{S.innerHTML="";let ce=Ee("clipboard","12px","currentColor",1.5);ce&&S.appendChild(ce)},1500)}),x.appendChild(v),x.appendChild(L),W&&x.appendChild(W),x.appendChild(R),k&&x.appendChild(k),x.appendChild(A),x.appendChild(S),m.appendChild(x),d&&m.appendChild(Xx(e,a,i)),m}}function gg(e){var x,v,E,L,I;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=(E=i==null?void 0:i.label)!=null?E:"",g=(I=(L=r==null?void 0:r.features)==null?void 0:L.eventStream)!=null?I:{},f=s.find(W=>W.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&r){let W=f.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>m().element,onClose:o});if(W)return{element:W,update:()=>{},destroy:()=>{}}}return m();function m(){let W=g.classNames,H=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ys(H,W==null?void 0:W.panel);let R=[],w="",C="",k=null,A=[],S={},_=0,V=Ci(),K=0,fe=0,ue=!1,ce=null,ke=!1,ve=0,He=new Set,Se=new Map,ie="",Q="",re=null,be,he,j,se,Re,ne=null,Z=null,oe=null;function at(){let Ce=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),le=b("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");ys(le,W==null?void 0:W.headerBar);let Ze=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Ze.textContent="Events",be=b("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),be.textContent="0",a){Z=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),Z.style.cursor="help";let Sn=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Sn.textContent="Throughput",ne=b("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),ne.textContent="-- tok/s",oe=b("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),oe.style.display="none",oe.style.pointerEvents="none";let An=Z,bn=oe,Mo=()=>{if(!bn.textContent)return;let zn=An.getBoundingClientRect(),qn=Ce.getBoundingClientRect();bn.style.left=`${zn.left-qn.left}px`,bn.style.top=`${zn.bottom-qn.top+4}px`,bn.style.display="block"},Ct=()=>{bn.style.display="none"};Z.addEventListener("mouseenter",Mo),Z.addEventListener("mouseleave",Ct),Z.appendChild(Sn),Z.appendChild(ne)}let Zt=b("div","persona-flex-1");he=b("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let jt=b("option","");jt.value="",jt.textContent="All events",he.appendChild(jt),j=b("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),j.type="button",j.title="Copy All";let xn=Ee("clipboard-copy","12px","currentColor",1.5);xn&&j.appendChild(xn);let ut=b("span","persona-text-xs");ut.textContent="Copy All",j.appendChild(ut),le.appendChild(Ze),le.appendChild(be),Z&&le.appendChild(Z),le.appendChild(Zt),le.appendChild(he),le.appendChild(j);let kt=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ys(kt,W==null?void 0:W.searchBar);let Xe=Ee("search","14px","var(--persona-muted, #9ca3af)",1.5),Ut=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Xe&&Ut.appendChild(Xe),se=b("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),ys(se,W==null?void 0:W.searchInput),se.type="text",se.placeholder="Search event payloads...",Re=b("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Re.type="button",Re.style.display="none";let ln=Ee("x","12px","currentColor",2);return ln&&Re.appendChild(ln),kt.appendChild(Ut),kt.appendChild(se),kt.appendChild(Re),Ce.appendChild(le),Ce.appendChild(kt),oe&&Ce.appendChild(oe),Ce}let it,Le=s.find(Ce=>Ce.renderEventStreamToolbar);if(Le!=null&&Le.renderEventStreamToolbar&&r){let Ce=Le.renderEventStreamToolbar({config:r,defaultRenderer:()=>at(),eventCount:t.getSize(),filteredCount:0,onFilterChange:le=>{w=le,an(),D()},onSearchChange:le=>{C=le,an(),D()}});it=Ce!=null?Ce:at()}else it=at();let de=b("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");de.style.display="none";function Qe(){if(!a||!ne||!Z)return;let Ce=a();ne.textContent=Yx(Ce);let le=Qx(Ce);oe&&(oe.textContent=le,le||(oe.style.display="none")),le?Z.setAttribute("aria-label",le):Z.removeAttribute("aria-label")}let We=b("div","persona-flex-1 persona-min-h-0 persona-relative"),q=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");q.style.height="100%";let me=b("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");ys(me,W==null?void 0:W.scrollIndicator),me.style.display="none",me.setAttribute("data-persona-scroll-to-bottom-has-label",u?"true":"false");let tt=Ee(l,"14px","currentColor",2);tt&&me.appendChild(tt);let Tt=b("span","");Tt.textContent=u,me.appendChild(Tt);let te=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");te.style.display="none",We.appendChild(q),We.appendChild(te),We.appendChild(me),H.setAttribute("tabindex","0"),H.appendChild(it),H.appendChild(de),H.appendChild(We);function ze(){let Ce=t.getAll(),le={};for(let ut of Ce)le[ut.type]=(le[ut.type]||0)+1;let Ze=Object.keys(le).sort(),Zt=Ze.length!==A.length||!Ze.every((ut,kt)=>ut===A[kt]),jt=!Zt&&Ze.some(ut=>le[ut]!==S[ut]),Rn=Ce.length!==Object.values(S).reduce((ut,kt)=>ut+kt,0);if(!Zt&&!jt&&!Rn||(A=Ze,S=le,!he))return;let xn=he.value;if(he.options[0].textContent="All events",Zt){for(;he.options.length>1;)he.remove(1);for(let ut of Ze){let kt=b("option","");kt.value=ut,kt.textContent=`${ut} (${le[ut]||0})`,he.appendChild(kt)}xn&&Ze.includes(xn)?he.value=xn:xn&&(he.value="",w="")}else for(let ut=1;ut<he.options.length;ut++){let kt=he.options[ut];kt.textContent=`${kt.value} (${le[kt.value]||0})`}}function Nn(){let Ce=t.getAll();if(w&&(Ce=Ce.filter(le=>le.type===w)),C){let le=C.toLowerCase();Ce=Ce.filter(Ze=>Ze.type.toLowerCase().includes(le)||Ze.payload.toLowerCase().includes(le))}return Ce}function Bt(){return w!==""||C!==""}function an(){_=0,K=0,V.resume(),me.style.display="none"}function ro(Ce){He.has(Ce)?He.delete(Ce):He.add(Ce),re=Ce;let le=q.scrollTop,Ze=V.isFollowing();ke=!0,V.pause(),D(),q.scrollTop=le,Ze&&V.resume(),ke=!1}function Eo(){return Nr(q,50)}function D(){fe=Date.now(),ue=!1,Qe(),ze();let Ce=t.getEvictedCount();Ce>0?(de.textContent=`${Ce.toLocaleString()} older events truncated`,de.style.display=""):de.style.display="none",R=Nn();let le=R.length,Ze=t.getSize()>0;be&&(be.textContent=String(t.getSize())),le===0&&Ze&&Bt()?(te.textContent=C?`No events matching '${C}'`:"No events matching filter",te.style.display="",q.style.display="none"):(te.style.display="none",q.style.display=""),j&&(j.title=Bt()?`Copy Filtered (${le})`:"Copy All"),d&&!V.isFollowing()&&le>_&&(K+=le-_,Tt.textContent=u?`${u}${K>0?` (${K})`:""}`:"",me.style.display=""),_=le;let Zt=t.getAll(),jt=Zt.length>0?Zt[0].timestamp:0,Rn=new Set(R.map(kt=>kt.id));for(let kt of He)Rn.has(kt)||He.delete(kt);let xn=w!==ie||C!==Q,ut=Se.size===0&&R.length>0;if(xn||ut||R.length===0){q.innerHTML="",Se.clear();let kt=document.createDocumentFragment();for(let Xe=0;Xe<R.length;Xe++){let Ut=Jl(R[Xe],Xe,jt,g,He,ro,s,r);Se.set(R[Xe].id,Ut),kt.appendChild(Ut)}q.appendChild(kt),ie=w,Q=C,re=null}else{if(re!==null){let Xe=Se.get(re);if(Xe&&Xe.parentNode===q){let Ut=R.findIndex(ln=>ln.id===re);if(Ut>=0){let ln=Jl(R[Ut],Ut,jt,g,He,ro,s,r);q.insertBefore(ln,Xe),Xe.remove(),Se.set(re,ln)}}re=null}let kt=new Set(R.map(Xe=>Xe.id));for(let[Xe,Ut]of Se)kt.has(Xe)||(Ut.remove(),Se.delete(Xe));for(let Xe=0;Xe<R.length;Xe++){let Ut=R[Xe];if(!Se.has(Ut.id)){let ln=Jl(Ut,Xe,jt,g,He,ro,s,r);Se.set(Ut.id,ln),q.appendChild(ln)}}}V.isFollowing()&&(q.scrollTop=q.scrollHeight)}function pe(){if(Date.now()-fe>=$x){ce!==null&&(cancelAnimationFrame(ce),ce=null),D();return}ue||(ue=!0,ce=requestAnimationFrame(()=>{ce=null,D()}))}let De=(Ce,le)=>{if(!j)return;j.innerHTML="";let Ze=Ee(Ce,"12px","currentColor",1.5);Ze&&j.appendChild(Ze);let Zt=b("span","persona-text-xs");Zt.textContent="Copy All",j.appendChild(Zt),setTimeout(()=>{j.innerHTML="";let jt=Ee("clipboard-copy","12px","currentColor",1.5);jt&&j.appendChild(jt);let Rn=b("span","persona-text-xs");Rn.textContent="Copy All",j.appendChild(Rn),j.disabled=!1},le)},Ke=async()=>{if(j){j.disabled=!0;try{let Ce;Bt()?Ce=R:n?(Ce=await n(),Ce.length===0&&(Ce=t.getAll())):Ce=t.getAll();let le=Ce.map(Ze=>{try{return JSON.parse(Ze.payload)}catch{return Ze.payload}});await navigator.clipboard.writeText(JSON.stringify(le,null,2)),De("check",1500)}catch{De("x",1500)}}},Ne=()=>{he&&(w=he.value,an(),D())},Ve=()=>{!se||!Re||(Re.style.display=se.value?"":"none",k&&clearTimeout(k),k=setTimeout(()=>{C=se.value,an(),D()},150))},ot=()=>{!se||!Re||(se.value="",C="",Re.style.display="none",k&&clearTimeout(k),an(),D())},It=()=>{if(ke)return;let Ce=q.scrollTop,{action:le,nextLastScrollTop:Ze}=Si({following:V.isFollowing(),currentScrollTop:Ce,lastScrollTop:ve,nearBottom:Eo(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ve=Ze,le==="resume"?(V.resume(),K=0,me.style.display="none"):le==="pause"&&(V.pause(),d&&(Tt.textContent=u,me.style.display=""))},qt=Ce=>{let le=Ai({following:V.isFollowing(),deltaY:Ce.deltaY,nearBottom:Eo(),resumeWhenNearBottom:!0});le==="pause"?(V.pause(),d&&(Tt.textContent=u,me.style.display="")):le==="resume"&&(V.resume(),K=0,me.style.display="none")},Xt=()=>{d&&(q.scrollTop=q.scrollHeight,V.resume(),K=0,me.style.display="none")},G=Ce=>{let le=Ce.target;if(!le||le.closest("button"))return;let Ze=le.closest("[data-event-id]");if(!Ze)return;let Zt=Ze.getAttribute("data-event-id");Zt&&ro(Zt)},yt=Ce=>{if((Ce.metaKey||Ce.ctrlKey)&&Ce.key==="f"){Ce.preventDefault(),se==null||se.focus(),se==null||se.select();return}Ce.key==="Escape"&&(se&&document.activeElement===se?(ot(),se.blur(),H.focus()):o&&o())};j&&j.addEventListener("click",Ke),he&&he.addEventListener("change",Ne),se&&se.addEventListener("input",Ve),Re&&Re.addEventListener("click",ot),q.addEventListener("scroll",It),q.addEventListener("wheel",qt,{passive:!0}),q.addEventListener("click",G),me.addEventListener("click",Xt),H.addEventListener("keydown",yt);function st(){k&&clearTimeout(k),ce!==null&&(cancelAnimationFrame(ce),ce=null),ue=!1,Se.clear(),j&&j.removeEventListener("click",Ke),he&&he.removeEventListener("change",Ne),se&&se.removeEventListener("input",Ve),Re&&Re.removeEventListener("click",ot),q.removeEventListener("scroll",It),q.removeEventListener("wheel",qt),q.removeEventListener("click",G),me.removeEventListener("click",Xt),H.removeEventListener("keydown",yt)}return{element:H,update:pe,destroy:st}}}function fg(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 hg=(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:()=>fg(e,t)});if(u)return u}return fg(e,t)};var Zl=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},$r=new Zl;$r.register("PersonaArtifactCard",hg);function Jx(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 bg(e,t){var he,j,se,Re;let n=(j=(he=e.features)==null?void 0:he.artifacts)==null?void 0:j.layout,r=((se=n==null?void 0:n.toolbarPreset)!=null?se:"default")==="document",s=(Re=n==null?void 0:n.panePadding)==null?void 0:Re.trim(),a=e.markdown?ti(e.markdown):null,i=ni(e.sanitize),d=ne=>{let Z=a?a(ne):Ks(ne);return i?i(Z):Z},l=typeof document!="undefined"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{l==null||l.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open"),_==null||_.hide()};l&&l.addEventListener("click",()=>{var ne;u(),(ne=t.onDismiss)==null||ne.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 ne;u(),(ne=t.onDismiss)==null||ne.call(t)});let v="rendered",E=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),L=r?In({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):In({icon:"eye",label:"Rendered view"}),I=r?In({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):In({icon:"code-2",label:"Source"}),W=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),H=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,R=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,w=n==null?void 0:n.documentToolbarCopyMenuItems,C=!!(R&&w&&w.length>0),k=null,A,S=null,_=null;if(r&&(H||R)&&!C){if(A=H?ql({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):In({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R){let ne=Ee("chevron-down",14,"currentColor",2);ne&&A.appendChild(ne)}}else r&&C?(k=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),A=H?ql({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):In({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),S=In({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),k.append(A,S)):r?A=In({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):A=In({icon:"copy",label:"Copy"});let V=r?In({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):In({icon:"refresh-cw",label:"Refresh"}),K=r?In({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):In({icon:"x",label:"Close"}),fe=()=>{var it,Le,de;let ne=(it=Se.find(Qe=>Qe.id===ie))!=null?it:Se[Se.length-1],Z=(Le=ne==null?void 0:ne.id)!=null?Le:null,oe=(ne==null?void 0:ne.artifactType)==="markdown"&&(de=ne.markdown)!=null?de:"",at=ne?JSON.stringify({component:ne.component,props:ne.props},null,2):"";return{markdown:oe,jsonPayload:at,id:Z}},ue=async()=>{var it;let{markdown:ne,jsonPayload:Z}=fe(),oe=(it=Se.find(Le=>Le.id===ie))!=null?it:Se[Se.length-1],at=(oe==null?void 0:oe.artifactType)==="markdown"?ne:oe?Z:"";try{await navigator.clipboard.writeText(at)}catch{}};if(A.addEventListener("click",async()=>{let ne=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(ne&&C){let{markdown:Z,jsonPayload:oe,id:at}=fe();try{await ne({actionId:"primary",artifactId:at,markdown:Z,jsonPayload:oe})}catch{}return}await ue()}),S&&(w!=null&&w.length)){let ne=()=>{var oe;return(oe=g.closest("[data-persona-root]"))!=null?oe:document.body},Z=()=>{_=fs({items:w.map(oe=>({id:oe.id,label:oe.label})),onSelect:async oe=>{let{markdown:at,jsonPayload:it,id:Le}=fe(),de=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{de?await de({actionId:oe,artifactId:Le,markdown:at,jsonPayload:it}):oe==="markdown"||oe==="md"?await navigator.clipboard.writeText(at):oe==="json"||oe==="source"?await navigator.clipboard.writeText(it):await navigator.clipboard.writeText(at||it)}catch{}},anchor:k!=null?k:S,position:"bottom-right",portal:ne()})};g.isConnected?Z():requestAnimationFrame(Z),S.addEventListener("click",oe=>{oe.stopPropagation(),_==null||_.toggle()})}V.addEventListener("click",async()=>{var ne;try{await((ne=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:ne.call(n))}catch{}re()}),K.addEventListener("click",()=>{var ne;u(),(ne=t.onDismiss)==null||ne.call(t)});let ce=()=>{r&&(L.setAttribute("aria-pressed",v==="rendered"?"true":"false"),I.setAttribute("aria-pressed",v==="source"?"true":"false"))};L.addEventListener("click",()=>{v="rendered",ce(),re()}),I.addEventListener("click",()=>{v="source",ce(),re()});let ke=b("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");r?(f.replaceChildren(),E.append(L,I),k?W.append(k,V,K):W.append(A,V,K),f.append(E,ke,W),ce()):(f.appendChild(m),f.appendChild(x)),s&&(f.style.paddingLeft=s,f.style.paddingRight=s);let ve=b("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),He=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(ve.style.paddingLeft=s,ve.style.paddingRight=s,He.style.padding=s),g.appendChild(f),g.appendChild(ve),g.appendChild(He);let Se=[],ie=null,Q=!1,re=()=>{var at,it,Le,de;let ne=r&&Se.length<=1;ve.classList.toggle("persona-hidden",ne),ve.replaceChildren();for(let Qe of Se){let We=b("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");We.type="button",We.textContent=Qe.title||Qe.id.slice(0,8),Qe.id===ie&&We.classList.add("persona-bg-persona-container","persona-border-persona-border"),We.addEventListener("click",()=>t.onSelect(Qe.id)),ve.appendChild(We)}He.replaceChildren();let Z=ie&&Se.find(Qe=>Qe.id===ie)||Se[Se.length-1];if(!Z)return;if(r){let Qe=Z.artifactType==="markdown"?"MD":(at=Z.component)!=null?at:"Component",q=(Z.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ke.textContent=`${q} \xB7 ${Qe}`}else m.textContent="Artifacts";if(Z.artifactType==="markdown"){if(r&&v==="source"){let We=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");We.textContent=(it=Z.markdown)!=null?it:"",He.appendChild(We);return}let Qe=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Qe.innerHTML=d((Le=Z.markdown)!=null?Le:""),He.appendChild(Qe);return}let oe=Z.component?$r.get(Z.component):void 0;if(oe){let We={message:{id:Z.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let q=oe((de=Z.props)!=null?de:{},We);if(q){He.appendChild(q);return}}catch{}}He.appendChild(Jx(Z))},be=()=>{var Z;let ne=Se.length>0;if(g.classList.toggle("persona-hidden",!ne),l){let oe=typeof g.closest=="function"?g.closest("[data-persona-root]"):null,it=((Z=oe==null?void 0:oe.classList.contains("persona-artifact-narrow-host"))!=null?Z:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;ne&&it&&Q?(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(ne){var Z,oe,at;Se=ne.artifacts,ie=(at=(oe=ne.selectedId)!=null?oe:(Z=ne.artifacts[ne.artifacts.length-1])==null?void 0:Z.id)!=null?at:null,Se.length>0&&(Q=!0),re(),be()},setMobileOpen(ne){Q=ne,!ne&&l?(l.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open")):be()}}}function fo(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 yg(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"),!fo(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 Zx(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 Vi(e,t){var d,l,u,g,f,m,x,v,E,L;if(!fo(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"),Zx(e),yg(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=(E=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:E.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(L=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:L.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),yg(e,t)}var vg=["panel","seamless"];function $i(e,t){var i,d,l,u,g,f;for(let m of vg)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"),!fo(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=vg.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 xg(e,t){var n,o,r;return!t||!fo(e)?!1:((r=(o=(n=e.features)==null?void 0:n.artifacts)==null?void 0:o.layout)==null?void 0:r.expandLauncherPanelWhenOpen)!==!1}function ew(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 tw(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 nw(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function ow(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function wg(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 Cg(e,t,n,o,r,s){let a=ew(r,200),i=ow(t,n,o,200);i=Math.max(a,i);let d=tw(s);return d!==null&&(i=Math.min(i,d)),nw(e,a,i)}var Sg={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"}},ec=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var x,v,E;if(s.dataset.enhanced==="true")return;let a=(x=s.dataset.tvForm)!=null?x:"init";s.dataset.enhanced="true";let i=(v=Sg[a])!=null?v:Sg.init;s.classList.add("persona-form-card","persona-space-y-4");let d=b("div","persona-space-y-1"),l=b("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let L=b("p","persona-text-sm persona-text-persona-muted");L.textContent=i.description,d.appendChild(L)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(L=>{var w,C;let I=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");I.htmlFor=`${t.id}-${a}-${L.name}`;let W=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");W.textContent=L.label,I.appendChild(W);let H=(w=L.type)!=null?w:"text",R;H==="textarea"?(R=document.createElement("textarea"),R.rows=3):(R=document.createElement("input"),R.type=H),R.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",R.id=`${t.id}-${a}-${L.name}`,R.name=L.name,R.placeholder=(C=L.placeholder)!=null?C:"",L.required&&(R.required=!0),I.appendChild(R),u.appendChild(I)});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=(E=i.submitLabel)!=null?E:"Submit",g.appendChild(f),g.appendChild(m),u.appendChild(g),s.replaceChildren(d,u),u.addEventListener("submit",async L=>{var R,w;L.preventDefault();let I=(R=n.formEndpoint)!=null?R:"/form",W=new FormData(u),H={};W.forEach((C,k)=>{H[k]=C}),H.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let C=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(H)});if(!C.ok)throw new Error(`Form submission failed (${C.status})`);let k=await C.json();f.textContent=(w=k.message)!=null?w:"Thanks! We'll be in touch soon.",k.success&&k.nextPrompt&&await o.sendMessage(String(k.nextPrompt))}catch(C){f.textContent=C instanceof Error?C.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var tc=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()}},nc=new tc;var Ag=()=>{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 rw=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},sw=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},rc=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=rw(e),n=sw(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}},oc=e=>typeof e=="string"?e:e==null?"":String(e),ya={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:oc(e.payload.text)},messageAndClick:(e,t)=>{var r;if(e.type!=="message_and_click")return;let n=e.payload,o=oc(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:oc(n.text)}}},Tg=e=>Array.isArray(e)?e.map(t=>String(t)):[],sc=e=>{let t=new Set(Tg(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Tg(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 aw=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}},iw=e=>e.map(t=>({...t,streaming:!1})),lw=e=>e.map(t=>({...t,status:"complete"})),kg=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?aw(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?iw(n.messages):void 0,artifacts:n.artifacts?lw(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};import{parse as mA,STR as gA,OBJ as fA}from"partial-json";function Eg(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=$r.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:i=>{r&&r(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Mg(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 Lg(e){let t=Mg(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 Ig(e){let t=Mg(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 cw=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Rg(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=cw}=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 E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let L=[];for(let w=1;w<=5;w++){let 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,L.forEach((k,A)=>{let S=A<w;k.classList.toggle("selected",S),k.setAttribute("aria-checked",A===w-1?"true":"false")})}),L.push(C),E.appendChild(C)}f.appendChild(E);let I=null;if(d){let w=document.createElement("div");w.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=s,I.rows=3,I.setAttribute("aria-label","Additional comments"),w.appendChild(I),f.appendChild(w)}let W=document.createElement("div");W.className="persona-feedback-actions";let H=document.createElement("button");H.type="button",H.className="persona-feedback-btn persona-feedback-btn-skip",H.textContent=i,H.addEventListener("click",()=>{n==null||n(),u.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=a,R.addEventListener("click",async()=>{if(g===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let w=(I==null?void 0:I.value.trim())||void 0;await t(g,w),u.remove()}catch(w){R.disabled=!1,R.textContent=a,console.error("[CSAT Feedback] Failed to submit:",w)}}),W.appendChild(H),W.appendChild(R),f.appendChild(W),u.appendChild(f),u}function Pg(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 E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=r,x.appendChild(E),m.appendChild(x);let L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-nps",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Likelihood rating from 0 to 10");let I=document.createElement("div");I.className="persona-feedback-labels";let W=document.createElement("span");W.className="persona-feedback-label-low",W.textContent=l;let H=document.createElement("span");H.className="persona-feedback-label-high",H.textContent=u,I.appendChild(W),I.appendChild(H);let R=document.createElement("div");R.className="persona-feedback-numbers";let w=[];for(let _=0;_<=10;_++){let V=document.createElement("button");V.type="button",V.className="persona-feedback-rating-btn persona-feedback-number-btn",V.setAttribute("role","radio"),V.setAttribute("aria-checked","false"),V.setAttribute("aria-label",`Rating ${_} out of 10`),V.textContent=String(_),V.dataset.rating=String(_),_<=6?V.classList.add("persona-feedback-detractor"):_<=8?V.classList.add("persona-feedback-passive"):V.classList.add("persona-feedback-promoter"),V.addEventListener("click",()=>{f=_,w.forEach((K,fe)=>{K.classList.toggle("selected",fe===_),K.setAttribute("aria-checked",fe===_?"true":"false")})}),w.push(V),R.appendChild(V)}L.appendChild(I),L.appendChild(R),m.appendChild(L);let C=null;if(d){let _=document.createElement("div");_.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"),_.appendChild(C),m.appendChild(_)}let k=document.createElement("div");k.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){R.classList.add("persona-feedback-shake"),setTimeout(()=>R.classList.remove("persona-feedback-shake"),500);return}S.disabled=!0,S.textContent="Submitting...";try{let _=(C==null?void 0:C.value.trim())||void 0;await t(f,_),g.remove()}catch(_){S.disabled=!1,S.textContent=a,console.error("[NPS Feedback] Failed to submit:",_)}}),k.appendChild(A),k.appendChild(S),m.appendChild(k),g.appendChild(m),g}var vs="persona-chat-history",dw=30*1e3,pw={"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 uw(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=pw[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 Ui(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 mw(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 gw(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var ac=e=>!e||typeof e!="object"?{}:{...e},Wg=e=>e.map(t=>({...t,streaming:!1})),Bg=(e,t,n)=>{let o=e!=null&&e.markdown?ti(e.markdown):null,r=ni(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=Ks(a),r?r(d):d}};function Hg(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=Ee(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 Dg=(e,t,n)=>{var Dc,Oc,Fc,Nc,_c,Vc,$c,Uc,zc,qc,jc,Kc,Gc,Yc,Qc,Xc,Jc,Zc,ed,td,nd,od,rd,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,bd,yd,vd,xd,wd,Cd,Sd,Ad,Td,kd,Ed,Md,Ld,Id,Rd;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=Wu(t),r=nc.getForInstance(o.plugins);o.components&&$r.registerAll(o.components);let s=Ag(),i=o.persistState===!1?null:(Dc=o.storageAdapter)!=null?Dc:kg(),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=ac(h.metadata)),(Oc=h.messages)!=null&&Oc.length&&(o={...o,initialMessages:h.messages}),(Fc=h.artifacts)!=null&&Fc.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:(Nc=h.selectedArtifactId)!=null?Nc: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:{}});(_c=c.messages)!=null&&_c.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:{},Xr()},x=o.actionParsers&&o.actionParsers.length?o.actionParsers:[rc],v=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ya.message,ya.messageAndClick],E=sc({parsers:x,handlers:v,getSessionMetadata:f,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null});E.syncFromMetadata();let L=($c=(Vc=o.launcher)==null?void 0:Vc.enabled)!=null?$c:!0,I=(zc=(Uc=o.launcher)==null?void 0:Uc.autoExpand)!=null?zc:!1,W=(qc=o.autoFocusInput)!=null?qc:!1,H=I,R=L,w=(Kc=(jc=o.layout)==null?void 0:jc.header)==null?void 0:Kc.layout,C=!1,k=()=>pa(o),A=()=>L||k(),S=k()?!1:L?I:!0,_=!1,V=null,K=()=>{_=!0,V&&clearTimeout(V),V=setTimeout(()=>{_&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),_=!1)},1e4)},fe=Bg(o,E,K),ue=(Yc=(Gc=o.features)==null?void 0:Gc.showReasoning)!=null?Yc:!0,ce=(Xc=(Qc=o.features)==null?void 0:Qc.showToolCalls)!=null?Xc:!0,ke=(Zc=(Jc=o.features)==null?void 0:Jc.showEventStreamToggle)!=null?Zc:!1,ve=(td=(ed=o.features)==null?void 0:ed.scrollToBottom)!=null?td:{},He=(od=(nd=o.features)==null?void 0:nd.scrollBehavior)!=null?od:{},ie=`${(sd=typeof o.persistState=="object"?(rd=o.persistState)==null?void 0:rd.keyPrefix:void 0)!=null?sd:"persona-"}event-stream`,Q=ke?new ha(ie):null,re=(ld=(id=(ad=o.features)==null?void 0:ad.eventStream)==null?void 0:id.maxEvents)!=null?ld:2e3,be=ke?new fa(re,Q):null,he=ke?new ba:null,j=null,se=!1,Re=null,ne=0;Q==null||Q.open().then(()=>be==null?void 0:be.restore()).catch(c=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let Z={onCopy:c=>{var p,h;s.emit("message:copy",c),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(c.id,"copy").catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",y)}),(h=(p=o.messageActions)==null?void 0:p.onCopy)==null||h.call(p,c)},onFeedback:c=>{var p,h;s.emit("message:feedback",c),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(c.messageId,c.type).catch(y=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",y)}),(h=(p=o.messageActions)==null?void 0:p.onFeedback)==null||h.call(p,c)}},oe=(cd=o.statusIndicator)!=null?cd:{},at=c=>{var p,h,y,M;return c==="idle"?(p=oe.idleText)!=null?p:Mn.idle:c==="connecting"?(h=oe.connectingText)!=null?h:Mn.connecting:c==="connected"?(y=oe.connectedText)!=null?y:Mn.connected:c==="error"?(M=oe.errorText)!=null?M:Mn.error:Mn[c]};function it(c,p,h,y){if(y==="idle"&&h.idleLink){c.textContent="";let M=document.createElement("a");M.href=h.idleLink,M.target="_blank",M.rel="noopener noreferrer",M.textContent=p,M.style.color="inherit",M.style.textDecoration="none",c.appendChild(M)}else c.textContent=p}let{wrapper:Le,panel:de,pillRoot:Qe}=eg(o),We=tg(o,A()),{container:q,body:me,messagesWrapper:tt,suggestions:Tt,textarea:te,sendButton:ze,sendButtonWrapper:Nn,composerForm:Bt,statusText:an,introTitle:ro,introSubtitle:Eo,closeButton:D,iconHolder:pe,headerTitle:De,headerSubtitle:Ke,header:Ne,footer:Ve,actionsRow:ot,leftActions:It,rightActions:qt}=We,Xt=We.setSendButtonMode,G=We.micButton,yt=We.micButtonWrapper,st=We.attachmentButton,Ce=We.attachmentButtonWrapper,le=We.attachmentInput,Ze=We.attachmentPreviewsContainer;q.classList.add("persona-relative"),me.classList.add("persona-relative");let Zt=12,jt=()=>{var c;return(c=ve.label)!=null?c:""},Rn=()=>{var c;return(c=ve.iconName)!=null?c:"arrow-down"},xn=()=>ve.enabled!==!1,ut=()=>{var c;return(c=He.mode)!=null?c:"follow"},kt=()=>{var c;return(c=He.anchorTopOffset)!=null?c:16},Xe=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");Xe.type="button",Xe.style.display="none",Xe.setAttribute("data-persona-scroll-to-bottom","true");let Ut=b("span","persona-flex persona-items-center"),ln=b("span",""),Sn=b("span","");Sn.setAttribute("data-persona-scroll-to-bottom-count",""),Sn.style.display="none",Xe.append(Ut,ln,Sn),q.appendChild(Xe);let An=b("div","persona-stream-anchor-spacer");An.setAttribute("aria-hidden","true"),An.setAttribute("data-persona-anchor-spacer",""),An.style.flexShrink="0",An.style.pointerEvents="none",An.style.height="0px",me.appendChild(An);let bn=()=>{let p=Ve.style.display==="none"?0:Ve.offsetHeight;Xe.style.bottom=`${p+Zt}px`};bn();let Mo=()=>{let c=!!jt();Xe.setAttribute("aria-label",jt()||"Jump to latest"),Xe.title=jt(),Xe.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Ut.innerHTML="";let p=Ee(Rn(),"14px","currentColor",2);p?(Ut.appendChild(p),Ut.style.display=""):Ut.style.display="none",ln.textContent=jt(),ln.style.display=c?"":"none"};Mo();let Ct=null,zn=null,qn=r.find(c=>c.renderHeader);if(qn!=null&&qn.renderHeader){let c=qn.renderHeader({config:o,defaultRenderer:()=>{let p=_r({config:o,showClose:A()});return ma(q,p,o),p.header},onClose:()=>Dt(!1,"user")});if(c){let p=q.querySelector(".persona-border-b-persona-divider");p&&(p.replaceWith(c),Ne=c)}}let No=()=>{var p,h,y,M;if(!be)return;if(se=!0,!j&&be&&(j=gg({buffer:be,getFullHistory:()=>be.getAllFromStore(),onClose:()=>ho(),config:o,plugins:r,getThroughput:()=>{var F;return(F=he==null?void 0:he.getMetric())!=null?F:{status:"idle"}}})),j&&(me.style.display="none",(p=Ve.parentNode)==null||p.insertBefore(j.element,Ve),j.update()),vt){vt.style.boxShadow=`inset 0 0 0 1.5px ${Fn.actionIconColor}`;let F=(M=(y=(h=o.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:M.toggleButtonActive;F&&F.split(/\s+/).forEach(N=>N&&vt.classList.add(N))}let c=()=>{if(!se)return;let F=Date.now();F-ne>=200&&(j==null||j.update(),ne=F),Re=requestAnimationFrame(c)};ne=0,Re=requestAnimationFrame(c),$n(),s.emit("eventStream:opened",{timestamp:Date.now()})},ho=()=>{var c,p,h;if(se){if(se=!1,j&&j.element.remove(),me.style.display="",vt){vt.style.boxShadow="";let y=(h=(p=(c=o.features)==null?void 0:c.eventStream)==null?void 0:p.classNames)==null?void 0:h.toggleButtonActive;y&&y.split(/\s+/).forEach(M=>M&&vt.classList.remove(M))}Re!==null&&(cancelAnimationFrame(Re),Re=null),$n(),s.emit("eventStream:closed",{timestamp:Date.now()})}},vt=null;if(ke){let c=(pd=(dd=o.features)==null?void 0:dd.eventStream)==null?void 0:pd.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:"");vt=b("button",p),vt.style.width="28px",vt.style.height="28px",vt.style.color=Fn.actionIconColor,vt.type="button",vt.setAttribute("aria-label","Event Stream"),vt.title="Event Stream";let h=Ee("activity","18px","currentColor",1.5);h&&vt.appendChild(h);let y=We.clearChatButtonWrapper,M=We.closeButtonWrapper,F=y||M;F&&F.parentNode===Ne?Ne.insertBefore(vt,F):Ne.appendChild(vt),vt.addEventListener("click",()=>{se?ho():No()})}let yr=c=>{var y,M,F;let p=o.attachments;if(!(p!=null&&p.enabled))return;let h=c.querySelector(".persona-attachment-previews");if(!h){h=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.style.display="none";let N=c.querySelector("[data-persona-composer-form]");N!=null&&N.parentNode?N.parentNode.insertBefore(h,N):c.insertBefore(h,c.firstChild)}if(!c.querySelector('input[type="file"]')){let N=b("input");N.type="file",N.accept=((y=p.allowedTypes)!=null?y:Qo).join(","),N.multiple=((M=p.maxFiles)!=null?M:4)>1,N.style.display="none",N.setAttribute("aria-label",(F=p.buttonTooltipText)!=null?F:"Attach files"),c.appendChild(N)}},Lo=r.find(c=>c.renderComposer);if(Lo!=null&&Lo.renderComposer){let c=o.composer,p=Lo.renderComposer({config:o,defaultRenderer:()=>Oi({config:o}).footer,onSubmit:h=>{var N;if(!$||$.isStreaming())return;let y=h.trim(),M=(N=Ct==null?void 0:Ct.hasAttachments())!=null?N:!1;if(!y&&!M)return;U();let F;M&&(F=[],F.push(...Ct.getContentParts()),y&&F.push(Fl(y))),$.sendMessage(y,{contentParts:F}),M&&Ct.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{le==null||le.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:((ud=o.voiceRecognition)==null?void 0:ud.enabled)===!0?()=>{zn==null||zn()}:void 0});p&&(Ve.replaceWith(p),Ve=p)}let vr=c=>{let p=c.querySelector("[data-persona-composer-form]"),h=c.querySelector("[data-persona-composer-input]"),y=c.querySelector("[data-persona-composer-submit]"),M=c.querySelector("[data-persona-composer-mic]"),F=c.querySelector("[data-persona-composer-status]");p&&(Bt=p),h&&(te=h),y&&(ze=y),M&&(G=M,yt=M.parentElement),F&&(an=F);let N=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");N&&(Tt=N);let z=c.querySelector(".persona-attachment-button");z&&(st=z,Ce=z.parentElement),le=c.querySelector('input[type="file"]'),Ze=c.querySelector(".persona-attachment-previews");let O=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");O&&(ot=O)};yr(Ve),vr(Ve);let _n=(bd=(md=o.layout)==null?void 0:md.contentMaxWidth)!=null?bd:k()?(hd=(fd=(gd=o.launcher)==null?void 0:gd.composerBar)==null?void 0:fd.contentMaxWidth)!=null?hd:"720px":void 0;if(_n&&(tt.style.maxWidth=_n,tt.style.marginLeft="auto",tt.style.marginRight="auto",tt.style.width="100%"),_n&&Bt&&!k()&&(Bt.style.maxWidth=_n,Bt.style.marginLeft="auto",Bt.style.marginRight="auto"),_n&&Tt&&!k()&&(Tt.style.maxWidth=_n,Tt.style.marginLeft="auto",Tt.style.marginRight="auto"),_n&&Ze&&!k()&&(Ze.style.maxWidth=_n,Ze.style.marginLeft="auto",Ze.style.marginRight="auto"),(yd=o.attachments)!=null&&yd.enabled&&le&&Ze){Ct=ra.fromConfig(o.attachments),Ct.setPreviewsContainer(Ze),le.addEventListener("change",h=>{let y=h.target;Ct==null||Ct.handleFileSelect(y.files),y.value=""});let c=o.attachments.dropOverlay,p=Hg(c);q.appendChild(p)}(()=>{var y,M;let c=(M=(y=o.layout)==null?void 0:y.slots)!=null?M:{},p=F=>{switch(F){case"body-top":return q.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return tt;case"footer-top":return Tt;case"composer":return Bt;case"footer-bottom":return an;default:return null}},h=(F,N)=>{var z;switch(F){case"header-left":case"header-center":case"header-right":if(F==="header-left")Ne.insertBefore(N,Ne.firstChild);else if(F==="header-right")Ne.appendChild(N);else{let O=Ne.querySelector(".persona-flex-col");O?(z=O.parentNode)==null||z.insertBefore(N,O.nextSibling):Ne.appendChild(N)}break;case"body-top":{let O=me.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");O?O.replaceWith(N):me.insertBefore(N,me.firstChild);break}case"body-bottom":me.appendChild(N);break;case"footer-top":Tt.replaceWith(N);break;case"footer-bottom":an.replaceWith(N);break;default:break}};for(let[F,N]of Object.entries(c))if(N)try{let z=N({config:o,defaultContent:()=>p(F)});z&&h(F,z)}catch(z){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${F}":`,z)}})();let Zo=c=>{var N,z;let h=c.target.closest('button[data-expand-header="true"]');if(!h)return;let y=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!y)return;let M=y.getAttribute("data-message-id");if(!M)return;let F=h.getAttribute("data-bubble-type");if(F==="reasoning")hs.has(M)?hs.delete(M):hs.add(M),rg(M,y);else if(F==="tool")bs.has(M)?bs.delete(M):bs.add(M),sg(M,y,o);else if(F==="approval"){let O=o.approval!==!1?o.approval:void 0,we=((N=O==null?void 0:O.detailsDisplay)!=null?N:"collapsed")==="expanded",ge=(z=Fi.get(M))!=null?z:we;Fi.set(M,!ge),cg(M,y,o)}Uo.delete(M)};tt.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Zo(c))}),tt.addEventListener("keydown",c=>{let p=c.target;(c.key==="Enter"||c.key===" ")&&p.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Zo(c))});let _o=new Map;tt.addEventListener("click",c=>{var N;let h=c.target.closest(".persona-message-action-btn[data-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.closest("[data-actions-for]");if(!y)return;let M=y.getAttribute("data-actions-for");if(!M)return;let F=h.getAttribute("data-action");if(F==="copy"){let O=$.getMessages().find(we=>we.id===M);if(O&&Z.onCopy){let we=O.content||"";navigator.clipboard.writeText(we).then(()=>{h.classList.add("persona-message-action-success");let ge=Ee("check",14,"currentColor",2);ge&&(h.innerHTML="",h.appendChild(ge)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let ee=Ee("copy",14,"currentColor",2);ee&&(h.innerHTML="",h.appendChild(ee))},2e3)}).catch(ge=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ge)}),Z.onCopy(O)}}else if(F==="upvote"||F==="downvote"){let O=((N=_o.get(M))!=null?N:null)===F,we=F==="upvote"?"thumbs-up":"thumbs-down";if(O){_o.delete(M),h.classList.remove("persona-message-action-active");let ge=Ee(we,14,"currentColor",2);ge&&(h.innerHTML="",h.appendChild(ge))}else{let ge=F==="upvote"?"downvote":"upvote",ee=y.querySelector(`[data-action="${ge}"]`);if(ee){ee.classList.remove("persona-message-action-active");let qe=Ee(ge==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);qe&&(ee.innerHTML="",ee.appendChild(qe))}_o.set(M,F),h.classList.add("persona-message-action-active");let Te=Ee(we,14,"currentColor",2);Te&&(Te.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(Te)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ae=$.getMessages().find(nt=>nt.id===M);Ae&&Z.onFeedback&&Z.onFeedback({type:F,messageId:Ae.id,message:Ae})}}}),tt.addEventListener("click",c=>{let h=c.target.closest("button[data-approval-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.closest(".persona-approval-bubble");if(!y)return;let M=y.getAttribute("data-message-id");if(!M)return;let F=h.getAttribute("data-approval-action");if(!F)return;let N=F==="approve"?"approved":"denied",O=$.getMessages().find(ge=>ge.id===M);if(!(O!=null&&O.approval))return;let we=y.querySelector("[data-approval-buttons]");we&&we.querySelectorAll("button").forEach(ee=>{ee.disabled=!0,ee.style.opacity="0.5",ee.style.cursor="not-allowed"}),O.approval.toolType==="webmcp"?$.resolveWebMcpApproval(M,N):$.resolveApproval(O.approval,N)});let St=null,jn=null,Kn={artifacts:[],selectedId:null},Pn=!1,Lt={current:null};tt.addEventListener("click",c=>{var ee,Te,_e,Ae,nt;let h=c.target.closest("[data-download-artifact]");if(!h)return;c.preventDefault(),c.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||((_e=(Te=(ee=o.features)==null?void 0:ee.artifacts)==null?void 0:Te.onArtifactAction)==null?void 0:_e.call(Te,{type:"download",artifactId:y}))===!0)return;let F=$.getArtifactById(y),N=F==null?void 0:F.markdown,z=(F==null?void 0:F.title)||"artifact";if(!N){let qe=h.closest("[data-open-artifact]"),ct=qe==null?void 0:qe.closest("[data-message-id]"),dt=ct==null?void 0:ct.getAttribute("data-message-id");if(dt){let Ie=$.getMessages().find(Ue=>Ue.id===dt);if(Ie!=null&&Ie.rawContent)try{let Ue=JSON.parse(Ie.rawContent);N=(Ae=Ue==null?void 0:Ue.props)==null?void 0:Ae.markdown,z=((nt=Ue==null?void 0:Ue.props)==null?void 0:nt.title)||z}catch{}}}if(!N)return;let O=new Blob([N],{type:"text/markdown"}),we=URL.createObjectURL(O),ge=document.createElement("a");ge.href=we,ge.download=`${z}.md`,ge.click(),URL.revokeObjectURL(we)}),tt.addEventListener("click",c=>{var F,N,z;let h=c.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||((z=(N=(F=o.features)==null?void 0:F.artifacts)==null?void 0:N.onArtifactAction)==null?void 0:z.call(N,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),Pn=!1,$.selectArtifact(y),Qn())}),tt.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let p=c.target;p.hasAttribute("data-open-artifact")&&(c.preventDefault(),p.click())});let so=We.composerOverlay,ao=(c,p,h)=>{var z,O,we,ge;let y=p.trim();if(!y||!Lt.current)return;let M=(z=c.getAttribute("data-tool-call-id"))!=null?z:"",F=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:M,answer:y,answers:h.structured,values:(O=h.values)!=null?O:h.source==="multi"?y.split(", "):[y],isFreeText:F,source:h.source},bubbles:!0,composed:!0})),ms(so,M);let N=Lt.current.getMessages().find(ee=>{var Te;return((Te=ee.toolCall)==null?void 0:Te.id)===M});(we=N==null?void 0:N.agentMetadata)!=null&&we.awaitingLocalTool?Lt.current.resolveAskUserQuestion(N,(ge=h.structured)!=null?ge:y):Lt.current.sendMessage(y)},Gn=c=>{var M;let p=Lt.current;if(!p)return;let h=(M=c.getAttribute("data-tool-call-id"))!=null?M:"",y=p.getMessages().find(F=>{var N;return((N=F.toolCall)==null?void 0:N.id)===h});y&&p.persistAskUserQuestionProgress(y,{answers:si(c,y),currentIndex:go(c)})},er=c=>Object.entries(c).map(([p,h])=>`${p}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Vo=c=>{var M,F,N;if(((F=(M=o.features)==null?void 0:M.askUserQuestion)==null?void 0:F.groupedAutoAdvance)===!1)return;let p=go(c),h=us(c);if(p>=h-1)return;let y=(N=Lt.current)==null?void 0:N.getMessages().find(z=>{var O;return((O=z.toolCall)==null?void 0:O.id)===c.getAttribute("data-tool-call-id")});y&&(ii(c,y,o,p+1),Gn(c))};so.addEventListener("click",c=>{var F,N,z,O,we,ge,ee,Te,_e,Ae,nt,qe,ct,dt;let h=c.target.closest("[data-ask-user-action]");if(!h)return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;let M=h.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),M==="dismiss"){let Pe=(F=y.getAttribute("data-tool-call-id"))!=null?F:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),ms(so,Pe);let Ie=(N=Lt.current)==null?void 0:N.getMessages().find(Ue=>{var Ge;return((Ge=Ue.toolCall)==null?void 0:Ge.id)===Pe});(z=Ie==null?void 0:Ie.agentMetadata)!=null&&z.awaitingLocalTool&&((O=Lt.current)==null||O.markAskUserQuestionResolved(Ie),(we=Lt.current)==null||we.resolveAskUserQuestion(Ie,"(dismissed)"));return}if(M==="pick"){let Pe=h.getAttribute("data-option-label");if(!Pe)return;let Ie=y.getAttribute("data-multi-select")==="true",Ue=gr(y);if(Ue&&Ie){let Ge=Dr(y)[go(y)],xt=new Set(Array.isArray(Ge)?Ge:[]);xt.has(Pe)?xt.delete(Pe):xt.add(Pe),fr(y,Array.from(xt)),Gn(y);return}if(Ue){fr(y,Pe),Gn(y),Vo(y);return}if(Ie){let Ge=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Ge?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Ge);let xt=y.querySelector('[data-ask-user-action="submit-multi"]');xt&&(xt.disabled=Pl(y).length===0);return}ao(y,Pe,{source:"pick",values:[Pe]});return}if(M==="submit-multi"){let Pe=Pl(y);if(Pe.length===0)return;ao(y,Pe.join(", "),{source:"multi",values:Pe});return}if(M==="open-free-text"){let Pe=y.querySelector('[data-ask-free-text-row="true"]');if(Pe){Pe.classList.remove("persona-hidden");let Ie=Pe.querySelector('[data-ask-free-text-input="true"]');Ie==null||Ie.focus()}return}if(M==="focus-free-text"){let Pe=y.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus();return}if(M==="submit-free-text"){let Pe=y.querySelector('[data-ask-free-text-input="true"]'),Ie=(ge=Pe==null?void 0:Pe.value)!=null?ge:"";if(!Ie.trim())return;if(gr(y)){fr(y,Ie.trim()),Gn(y),Vo(y);return}ao(y,Ie,{source:"free-text"});return}if(M==="next"||M==="back"){if(!Lt.current)return;let Pe=(ee=y.getAttribute("data-tool-call-id"))!=null?ee:"",Ie=Lt.current.getMessages().find(Be=>{var Oe;return((Oe=Be.toolCall)==null?void 0:Oe.id)===Pe});if(!Ie)return;let Ue=y.querySelector('[data-ask-free-text-input="true"]'),Ge=(_e=(Te=Ue==null?void 0:Ue.value)==null?void 0:Te.trim())!=null?_e:"";if(Ge){let Be=Dr(y)[go(y)];(typeof Be!="string"||Be!==Ge)&&fr(y,Ge)}let xt=M==="next"?1:-1,B=go(y)+xt;ii(y,Ie,o,B),Gn(y);return}if(M==="submit-all"){if(!Lt.current)return;let Pe=(Ae=y.getAttribute("data-tool-call-id"))!=null?Ae:"",Ie=Lt.current.getMessages().find(Be=>{var Oe;return((Oe=Be.toolCall)==null?void 0:Oe.id)===Pe});if(!Ie)return;let Ue=y.querySelector('[data-ask-free-text-input="true"]'),Ge=(qe=(nt=Ue==null?void 0:Ue.value)==null?void 0:nt.trim())!=null?qe:"";Ge&&fr(y,Ge);let xt=si(y,Ie);Lt.current.persistAskUserQuestionProgress(Ie,{answers:xt,currentIndex:go(y)});let B=er(xt);ao(y,B||"(submitted)",{source:"submit-all",structured:xt});return}if(M==="skip"){if(!Lt.current)return;let Pe=(ct=y.getAttribute("data-tool-call-id"))!=null?ct:"",Ie=Lt.current.getMessages().find(Oe=>{var ye;return((ye=Oe.toolCall)==null?void 0:ye.id)===Pe});if(!Ie)return;let Ue=gr(y),Ge=go(y),xt=us(y),B=Ge>=xt-1;if(!Ue){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),ms(so,Pe),(dt=Ie.agentMetadata)!=null&&dt.awaitingLocalTool&&(Lt.current.markAskUserQuestionResolved(Ie),Lt.current.resolveAskUserQuestion(Ie,"(dismissed)"));return}fr(y,"");let Be=y.querySelector('[data-ask-free-text-input="true"]');if(Be&&(Be.value=""),B){let Oe=si(y,Ie),ye=er(Oe);ao(y,ye||"(skipped)",{source:"submit-all",structured:Oe});return}ii(y,Ie,o,Ge+1),Gn(y);return}}),so.addEventListener("keydown",c=>{var F;if(c.key!=="Enter")return;let h=c.target;if(!((F=h.matches)!=null&&F.call(h,'[data-ask-free-text-input="true"]')))return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;c.preventDefault();let M=h.value;if(M.trim()){if(gr(y)){fr(y,M.trim()),Gn(y),Vo(y);return}ao(y,M,{source:"free-text"})}});let tr=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let p=c.target;if((p==null?void 0:p.tagName)==="INPUT"||(p==null?void 0:p.tagName)==="TEXTAREA"||p!=null&&p.isContentEditable)return;let h=so.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),F=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];F&&(c.preventDefault(),F.click())};document.addEventListener("keydown",tr);let Yn=null,Ht=null,Wn=null,io=null,nr=()=>{};function $o(){io==null||io(),io=null}let or=()=>{var N;if(!Yn||!Ht)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),h=((N=e.ownerDocument.defaultView)!=null?N:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||h){Ht.style.removeProperty("position"),Ht.style.removeProperty("left"),Ht.style.removeProperty("top"),Ht.style.removeProperty("bottom"),Ht.style.removeProperty("width"),Ht.style.removeProperty("z-index");return}let y=Yn.firstElementChild;if(!y||y===Ht)return;let M=10;Ht.style.position="absolute",Ht.style.top="0",Ht.style.bottom="0",Ht.style.width=`${M}px`,Ht.style.zIndex="5";let F=y.offsetWidth-M/2;Ht.style.left=`${Math.max(0,F)}px`},Io=()=>{},Qn=()=>{var h,y,M,F,N;if(!St||!fo(o))return;Vi(e,o),$i(e,o),Io();let c=(F=(M=(y=(h=o.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:M.narrowHostMaxWidth)!=null?F:520,p=de.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",p>0&&p<=c),St.update(Kn),Pn?(St.setMobileOpen(!1),St.element.classList.add("persona-hidden"),(N=St.backdrop)==null||N.classList.add("persona-hidden")):Kn.artifacts.length>0&&(St.element.classList.remove("persona-hidden"),St.setMobileOpen(!0)),nr()};if(fo(o)){de.style.position="relative";let c=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),p=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(q),St=bg(o,{onSelect:h=>{var y;return(y=Lt.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{Pn=!0,Qn()}}),St.element.classList.add("persona-hidden"),Yn=p,p.appendChild(c),p.appendChild(St.element),St.backdrop&&de.appendChild(St.backdrop),de.appendChild(p),nr=()=>{var y,M,F,N;if(!Yn||!St)return;if(!(((F=(M=(y=o.features)==null?void 0:y.artifacts)==null?void 0:M.layout)==null?void 0:F.resizable)===!0)){Wn==null||Wn(),Wn=null,$o(),Ht&&(Ht.remove(),Ht=null),St.element.style.removeProperty("width"),St.element.style.removeProperty("maxWidth");return}if(!Ht){let z=b("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");z.setAttribute("role","separator"),z.setAttribute("aria-orientation","vertical"),z.setAttribute("aria-label","Resize artifacts panel"),z.tabIndex=0;let O=e.ownerDocument,we=(N=O.defaultView)!=null?N:window,ge=ee=>{var ct,dt;if(!St||ee.button!==0||e.classList.contains("persona-artifact-narrow-host")||we.innerWidth<=640)return;ee.preventDefault(),$o();let Te=ee.clientX,_e=St.element.getBoundingClientRect().width,Ae=(dt=(ct=o.features)==null?void 0:ct.artifacts)==null?void 0:dt.layout,nt=Pe=>{let Ie=Yn.getBoundingClientRect().width,Ue=e.classList.contains("persona-artifact-appearance-seamless"),Ge=Ue?0:wg(Yn,we),xt=Ue?0:z.getBoundingClientRect().width||6,B=_e-(Pe.clientX-Te),Be=Cg(B,Ie,Ge,xt,Ae==null?void 0:Ae.resizableMinWidth,Ae==null?void 0:Ae.resizableMaxWidth);St.element.style.width=`${Be}px`,St.element.style.maxWidth="none",or()},qe=()=>{O.removeEventListener("pointermove",nt),O.removeEventListener("pointerup",qe),O.removeEventListener("pointercancel",qe),io=null;try{z.releasePointerCapture(ee.pointerId)}catch{}};io=qe,O.addEventListener("pointermove",nt),O.addEventListener("pointerup",qe),O.addEventListener("pointercancel",qe);try{z.setPointerCapture(ee.pointerId)}catch{}};z.addEventListener("pointerdown",ge),Ht=z,Yn.insertBefore(z,St.element),Wn=()=>{z.removeEventListener("pointerdown",ge)}}if(Ht){let z=Kn.artifacts.length>0&&!Pn;Ht.classList.toggle("persona-hidden",!z),or()}},Io=()=>{var we,ge,ee,Te,_e,Ae,nt,qe,ct,dt,Pe,Ie,Ue,Ge;if(!L||!St||((ge=(we=o.launcher)==null?void 0:we.sidebarMode)!=null?ge:!1)||Cn(o)&&To(o).reveal==="emerge")return;let y=(ee=e.ownerDocument.defaultView)!=null?ee:window,M=(_e=(Te=o.launcher)==null?void 0:Te.mobileFullscreen)!=null?_e:!0,F=(nt=(Ae=o.launcher)==null?void 0:Ae.mobileBreakpoint)!=null?nt:640;if(M&&y.innerWidth<=F||!xg(o,L))return;let N=(dt=(ct=(qe=o.launcher)==null?void 0:qe.width)!=null?ct:o.launcherWidth)!=null?dt:mo,z=(Ge=(Ue=(Ie=(Pe=o.features)==null?void 0:Pe.artifacts)==null?void 0:Ie.layout)==null?void 0:Ue.expandedPanelWidth)!=null?Ge:"min(720px, calc(100vw - 24px))";Kn.artifacts.length>0&&!Pn?(de.style.width=z,de.style.maxWidth=z):(de.style.width=N,de.style.maxWidth=N)},typeof ResizeObserver!="undefined"&&(jn=new ResizeObserver(()=>{Qn()}),jn.observe(de))}else de.appendChild(q),k()&&Qe&&(We.peekBanner&&Qe.appendChild(We.peekBanner),Qe.appendChild(Ve));e.appendChild(Le),Qe&&e.appendChild(Qe);let bo=()=>{var Be,Oe,ye,Ft,Ot,Kt,wt,zt,eo,sn,Ye,Rt,dn,uo,to,Tr,kr,os,rs,Yt,Er,ur,mr,Go,Mr,Co,et,mn;if(k()){de.style.width="100%",de.style.maxWidth="100%";let Vt=(Oe=(Be=o.launcher)==null?void 0:Be.composerBar)!=null?Oe:{},Nt=Le.dataset.state==="expanded",ht=(ye=Vt.expandedSize)!=null?ye:"anchored";if(!(Nt&&ht!=="fullscreen")){q.style.background="",q.style.border="",q.style.borderRadius="",q.style.overflow="",q.style.boxShadow="";return}let Et=(Ot=(Ft=o.theme)==null?void 0:Ft.components)==null?void 0:Ot.panel,kn=Va(o),Bn=(Dn,Lr)=>{var _s;return Dn==null||Dn===""?Lr:(_s=ss(kn,Dn))!=null?_s:Dn},Do="1px solid var(--persona-border)",vn="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Hn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";q.style.background="var(--persona-surface, #ffffff)",q.style.border=Bn(Et==null?void 0:Et.border,Do),q.style.borderRadius=Bn(Et==null?void 0:Et.borderRadius,Hn),q.style.boxShadow=Bn(Et==null?void 0:Et.shadow,vn),q.style.overflow="hidden";return}let c=Cn(o),p=(wt=(Kt=o.launcher)==null?void 0:Kt.sidebarMode)!=null?wt:!1,h=c||p||((eo=(zt=o.launcher)==null?void 0:zt.fullHeight)!=null?eo:!1),y=((sn=o.launcher)==null?void 0:sn.enabled)===!1,M=(Rt=(Ye=o.theme)==null?void 0:Ye.components)==null?void 0:Rt.panel,F=Va(o),N=(Vt,Nt)=>{var ht;return Vt==null||Vt===""?Nt:(ht=ss(F,Vt))!=null?ht:Vt},z=(dn=e.ownerDocument.defaultView)!=null?dn:window,O=(to=(uo=o.launcher)==null?void 0:uo.mobileFullscreen)!=null?to:!0,we=(kr=(Tr=o.launcher)==null?void 0:Tr.mobileBreakpoint)!=null?kr:640,ge=z.innerWidth<=we,ee=O&&ge&&L,Te=(rs=(os=o.launcher)==null?void 0:os.position)!=null?rs:"bottom-left",_e=Te==="bottom-left"||Te==="top-left",Ae=(Er=(Yt=o.launcher)==null?void 0:Yt.zIndex)!=null?Er:Ln,nt=p||ee?"none":"1px solid var(--persona-border)",qe=ee?"none":p?_e?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!ee&&(qe="none",nt="none");let ct=p||ee?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",dt=N(M==null?void 0:M.border,nt),Pe=N(M==null?void 0:M.shadow,qe),Ie=N(M==null?void 0:M.borderRadius,ct),Ue=me.scrollTop;e.style.cssText="",Le.style.cssText="",de.style.cssText="",q.style.cssText="",me.style.cssText="",Ve.style.cssText="";let Ge=()=>{var Nt;if(Ue<=0)return;((Nt=me.ownerDocument.defaultView)!=null?Nt:window).requestAnimationFrame(()=>{if(me.scrollTop===Ue)return;let ht=me.scrollHeight-me.clientHeight;ht<=0||(me.scrollTop=Math.min(Ue,ht))})};if(ee){Le.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Le.style.cssText=`
31
- 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: ${Ae} !important;
41
- background-color: var(--persona-surface, #ffffff) !important;
42
- `,de.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
- `,q.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
- `,me.style.flex="1 1 0%",me.style.minHeight="0",me.style.overflowY="auto",Ve.style.flexShrink="0",C=!0,Ge();return}let xt=(mr=(ur=o==null?void 0:o.launcher)==null?void 0:ur.width)!=null?mr:o==null?void 0:o.launcherWidth,B=xt!=null?xt:mo;if(!p&&!c)y&&h?(de.style.width="100%",de.style.maxWidth="100%"):(de.style.width=B,de.style.maxWidth=B);else if(c)if(To(o).reveal==="emerge"){let Nt=To(o).width;de.style.width=Nt,de.style.maxWidth=Nt}else de.style.width="100%",de.style.maxWidth="100%";if(Io(),de.style.boxShadow=Pe,de.style.borderRadius=Ie,q.style.border=dt,q.style.borderRadius=Ie,c&&!ee&&(M==null?void 0:M.border)===void 0&&(q.style.border="none",To(o).side==="right"?q.style.borderLeft="1px solid var(--persona-border)":q.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",y&&(e.style.width="100%"),Le.style.display="flex",Le.style.flexDirection="column",Le.style.flex="1 1 0%",Le.style.minHeight="0",Le.style.maxHeight="100%",Le.style.height="100%",y&&(Le.style.overflow="hidden"),de.style.display="flex",de.style.flexDirection="column",de.style.flex="1 1 0%",de.style.minHeight="0",de.style.maxHeight="100%",de.style.height="100%",de.style.overflow="hidden",q.style.display="flex",q.style.flexDirection="column",q.style.flex="1 1 0%",q.style.minHeight="0",q.style.maxHeight="100%",q.style.overflow="hidden",me.style.flex="1 1 0%",me.style.minHeight="0",me.style.overflowY="auto",Ve.style.flexShrink="0"),Le.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!p&&!y&&!c&&((Go=ko[Te])!=null?Go:ko["bottom-right"]).split(" ").forEach(Nt=>Le.classList.add(Nt)),p){let Vt=(Co=(Mr=o.launcher)==null?void 0:Mr.sidebarWidth)!=null?Co:"420px";Le.style.cssText=`
67
- position: fixed !important;
68
- top: 0 !important;
69
- bottom: 0 !important;
70
- width: ${Vt} !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: ${Ae} !important;
78
- ${_e?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
79
- `,de.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: ${Pe} !important;
91
- border-radius: ${Ie} !important;
92
- `,de.style.setProperty("width","100%","important"),de.style.setProperty("max-width","100%","important"),q.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: ${Ie} !important;
102
- border: ${dt} !important;
103
- `,Ve.style.cssText=`
104
- flex-shrink: 0 !important;
105
- border-top: none !important;
106
- padding: 8px 16px 12px 16px !important;
107
- `}if(!y&&!c){let Vt="max-height: -moz-available !important; max-height: stretch !important;",Nt=p?"":"padding-top: 1.25em !important;",ht=p?"":`z-index: ${(mn=(et=o.launcher)==null?void 0:et.zIndex)!=null?mn:Ln} !important;`;Le.style.cssText+=Vt+Nt+ht}Ge()};bo(),as(e,o),Vi(e,o),$i(e,o);let gt=[];gt.push(()=>{document.removeEventListener("keydown",tr)});let en=null,tn=null;gt.push(()=>{en==null||en(),en=null,tn==null||tn(),tn=null}),jn&&gt.push(()=>{jn==null||jn.disconnect(),jn=null}),gt.push(()=>{Wn==null||Wn(),Wn=null,$o(),Ht&&(Ht.remove(),Ht=null),St==null||St.element.style.removeProperty("width"),St==null||St.element.style.removeProperty("maxWidth")}),ke&&gt.push(()=>{Re!==null&&(cancelAnimationFrame(Re),Re=null),j==null||j.destroy(),j=null,be==null||be.destroy(),be=null,Q=null});let Xn=null,rr=()=>{Xn&&(Xn(),Xn=null),o.colorScheme==="auto"&&(Xn=Fu(()=>{as(e,o)}))};rr(),gt.push(()=>{Xn&&(Xn(),Xn=null)});let xe=(vd=o.features)==null?void 0:vd.streamAnimation;if(xe!=null&&xe.type&&xe.type!=="none"){let c=aa(xe.type,xe.plugins);c&&($l(c,e),gt.push(()=>Ym(e)))}let yo=dg(Tt),lo=null,$,jr=c=>{var y,M;if(!$)return;let p=c!=null?c:$.getMessages(),h=((M=(y=o.features)==null?void 0:y.suggestReplies)==null?void 0:M.enabled)!==!1?xm(p):null;h?yo.render(h,$,te,p,o.suggestionChipsConfig,{agentPushed:!0}):p.some(F=>F.role==="user")?yo.render([],$,te,p):yo.render(o.suggestionChips,$,te,p,o.suggestionChipsConfig)},Ro=!1,Uo=_m(),zo=new Map,Po=new Map,vo=new Map,As=0,Jn=Ci(),Zn=0,xo=null,wo=!1,xr=!1,qo=0,Tn=null,Wo=null,Kr=!1,wr=!1,Gr=null,Aa=4,Yr=24,Ta=80,Qr=new Map,bt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ts=(wd=(xd=o.voiceRecognition)==null?void 0:xd.autoResume)!=null?wd:!1,co=c=>{s.emit("voice:state",{active:bt.active,source:c,timestamp:Date.now()})},Vn=()=>{m(c=>({...c,voiceState:{active:bt.active,timestamp:Date.now(),manuallyDeactivated:bt.manuallyDeactivated}}))},ka=()=>{var y,M;if(((y=o.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=ac(d.voiceState),p=!!c.active,h=Number((M=c.timestamp)!=null?M:0);bt.manuallyDeactivated=!!c.manuallyDeactivated,p&&Date.now()-h<dw&&setTimeout(()=>{var F,N;bt.active||(bt.manuallyDeactivated=!1,((N=(F=o.voiceRecognition)==null?void 0:F.provider)==null?void 0:N.type)==="runtype"?$.toggleVoice().then(()=>{bt.active=$.isVoiceActive(),co("restore"),$.isVoiceActive()&&Os()}):Gt("restore"))},1e3)},Ea=()=>$?Wg($.getMessages()).filter(c=>!c.__skipPersist):[];function Xr(c){if(!(i!=null&&i.save))return;let h={messages:c?Wg(c):$?Ea():[],metadata:d,artifacts:Kn.artifacts,selectedArtifactId:Kn.selectedId};try{let y=i.save(h);y instanceof Promise&&y.catch(M=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",M)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let jo=null,ks=()=>Le.querySelector("#persona-scroll-container")||me,sr=()=>{jo!==null&&(cancelAnimationFrame(jo),jo=null),wo=!1},Es=()=>{xo!==null&&(cancelAnimationFrame(xo),xo=null),xr=!1,sr()},Ms=()=>{qo>0?(Sn.textContent=String(qo),Sn.style.display="",Xe.setAttribute("aria-label",`${jt()||"Jump to latest"} (${qo} new)`)):(Sn.textContent="",Sn.style.display="none",Xe.setAttribute("aria-label",jt()||"Jump to latest"))},Ls=()=>{qo!==0&&(qo=0,Ms())},Is=()=>ut()==="follow"?!Jn.isFollowing():!Nr(me,Yr),$n=()=>{if(!xn()||se){Xe.parentNode&&Xe.remove(),Xe.style.display="none";return}Xe.parentNode!==q&&q.appendChild(Xe),bn();let p=Xo(me)>0&&Is();p||Ls(),Xe.style.display=p?"":"none"},Jr=()=>{Jn.pause()&&(Es(),$n())},Bo=()=>{Jn.resume(),Ls(),$n()},Ho=(c=!1)=>{ut()==="follow"&&Jn.isFollowing()&&(!c&&!Ro||(xo!==null&&(cancelAnimationFrame(xo),xo=null),xr=!0,xo=requestAnimationFrame(()=>{xo=null,xr=!1,Jn.isFollowing()&&Ma(ks(),c?220:140)})))},Rs=(c,p,h,y=()=>!0)=>{let M=c.scrollTop,F=p(),N=F-M;sr();let z=performance.now();wo=!0;let O=ge=>1-Math.pow(1-ge,3),we=ge=>{if(!y()){sr();return}let ee=p();ee!==F&&(F=ee,N=F-M);let Te=ge-z,_e=Math.min(Te/h,1),Ae=O(_e),nt=M+N*Ae;c.scrollTop=nt,Zn=c.scrollTop,_e<1?jo=requestAnimationFrame(we):(c.scrollTop=F,Zn=c.scrollTop,jo=null,wo=!1)};jo=requestAnimationFrame(we)},Ma=(c,p=500)=>{let h=Xo(c)-c.scrollTop;if(Math.abs(h)<1){Zn=c.scrollTop;return}if(Math.abs(h)>=Ta){sr(),wo=!0,c.scrollTop=Xo(c),Zn=c.scrollTop,wo=!1;return}Rs(c,()=>Xo(c),p,()=>Jn.isFollowing())},Ps=()=>{let c=ks();wo=!0,c.scrollTop=Xo(c),Zn=c.scrollTop,wo=!1,$n()},Ws=c=>{An.style.height=`${Math.max(0,Math.round(c))}px`,Tn&&(Tn.spacerHeight=Math.max(0,c))},Cr=()=>{Wo!==null&&(cancelAnimationFrame(Wo),Wo=null),sr(),Tn=null,An.style.height="0px"},La=c=>{Wo!==null&&cancelAnimationFrame(Wo),Wo=requestAnimationFrame(()=>{var we;Wo=null;let p=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(c):c.replace(/"/g,'\\"'),h=me.querySelector(`[data-message-id="${p}"]`);if(!h)return;let y=0,M=h;for(;M&&M!==me;)y+=M.offsetTop,M=M.offsetParent;let F=(we=Tn==null?void 0:Tn.spacerHeight)!=null?we:0,N=me.scrollHeight-F,{targetScrollTop:z,spacerHeight:O}=qm({anchorOffsetTop:y,topOffset:kt(),viewportHeight:me.clientHeight,contentHeight:N});Tn={initialSpacerHeight:O,contentHeightAtAnchor:N,spacerHeight:O},Ws(O),Rs(me,()=>z,220)})},Ia=()=>{if(ut()==="follow"){if(!Jn.isFollowing()||Nr(me,1))return;Ho(!Ro);return}if(Tn&&Tn.initialSpacerHeight>0){let c=me.scrollHeight-Tn.spacerHeight,p=jm({initialSpacerHeight:Tn.initialSpacerHeight,contentHeightAtAnchor:Tn.contentHeightAtAnchor,currentContentHeight:c});p!==Tn.spacerHeight&&Ws(p)}$n()},Ra=c=>{let p=ut();p==="follow"?(Bo(),Ho(!0)):p==="anchor-top"&&La(c)},Pa=c=>{let p=new Map;c.forEach(h=>{let y=Qr.get(h.id);p.set(h.id,{streaming:h.streaming,role:h.role}),!y&&h.role==="assistant"&&(s.emit("assistant:message",h),!wr&&ut()!=="anchor-top"&&Is()&&(qo+=1,Ms(),$n())),h.role==="assistant"&&(y!=null&&y.streaming)&&h.streaming===!1&&s.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(y?h.approval.status!=="pending"&&s.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):s.emit("approval:requested",{approval:h.approval,message:h}))}),Qr.clear(),p.forEach((h,y)=>{Qr.set(y,h)})},Sr=(c,p,h)=>{var dt,Pe,Ie,Ue,Ge,xt;let y=document.createElement("div"),F=(()=>{var Be;let B=r.find(Oe=>Oe.renderLoadingIndicator);if(B!=null&&B.renderLoadingIndicator)return B.renderLoadingIndicator;if((Be=o.loadingIndicator)!=null&&Be.render)return o.loadingIndicator.render})(),N=(B,Be)=>Be==null?!1:typeof Be=="string"?(B.textContent=Be,!0):(B.appendChild(Be),!0),z=new Set,O=new Set,we=r.some(B=>B.renderAskUserQuestion),ge=[],ee=[],Te=o.enableComponentStreaming!==!1,_e=r.some(B=>B.renderApproval)&&o.approval!==!1,Ae=[];if(p.forEach(B=>{var Ye,Rt,dn,uo,to,Tr,kr,os,rs,Yt,Er,ur,mr,Go,Mr,Co;z.add(B.id);let Be=we&&Hr(B),Oe=_e&&B.variant==="approval"&&!!B.approval,ye=!Be&&B.role==="assistant"&&!B.variant&&Te&&Lg(B);if(!Oe&&vo.has(B.id)){let et=c.querySelector(`#wrapper-${B.id}`);et==null||et.removeAttribute("data-preserve-runtime"),vo.delete(B.id)}if(!ye&&Po.has(B.id)){let et=c.querySelector(`#wrapper-${B.id}`);et==null||et.removeAttribute("data-preserve-runtime"),Po.delete(B.id)}let Ft=Hr(B)?`:${(Ye=B.agentMetadata)!=null&&Ye.askUserQuestionAnswered?"a":"u"}:${(Rt=B.agentMetadata)!=null&&Rt.askUserQuestionAnswers?Object.keys(B.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ot=Nm(B,As)+Ft,Kt=Be||Oe||ye?null:Vm(Uo,B.id,Ot);if(Kt){y.appendChild(Kt.cloneNode(!0)),Hr(B)&&((dn=B.toolCall)!=null&&dn.id)&&((uo=B.agentMetadata)==null?void 0:uo.awaitingLocalTool)===!0&&!((to=B.agentMetadata)!=null&&to.askUserQuestionAnswered)&&(O.add(B.toolCall.id),ai(B,o,We.composerOverlay));return}let wt=null,zt=r.find(et=>!!(B.variant==="reasoning"&&et.renderReasoning||B.variant==="tool"&&et.renderToolCall||!B.variant&&et.renderMessage)),eo=(Tr=o.layout)==null?void 0:Tr.messages;if(Hr(B)&&((kr=B.agentMetadata)==null?void 0:kr.askUserQuestionAnswered)===!0){zo.delete(B.id);let et=c.querySelector(`#wrapper-${B.id}`);et==null||et.removeAttribute("data-preserve-runtime");return}if(Bl(B)&&((rs=(os=o.features)==null?void 0:os.suggestReplies)==null?void 0:rs.enabled)!==!1)return;if(Hr(B)&&((Er=(Yt=o.features)==null?void 0:Yt.askUserQuestion)==null?void 0:Er.enabled)!==!1){let et=r.find(mn=>typeof mn.renderAskUserQuestion=="function");if(et&&Lt.current){let mn=zo.get(B.id),Vt=mn!==Ot,Nt=null;if(Vt){let{payload:Et,complete:kn}=ps(B),Bn=B.id,Do=()=>{var vn;return(vn=Lt.current)==null?void 0:vn.getMessages().find(Hn=>Hn.id===Bn)};Nt=et.renderAskUserQuestion({message:B,payload:Et,complete:kn,resolve:vn=>{var Dn;let Hn=Do();Hn&&((Dn=Lt.current)==null||Dn.resolveAskUserQuestion(Hn,vn))},dismiss:()=>{var Hn,Dn,Lr;let vn=Do();(Hn=vn==null?void 0:vn.agentMetadata)!=null&&Hn.awaitingLocalTool&&((Dn=Lt.current)==null||Dn.markAskUserQuestionResolved(vn),(Lr=Lt.current)==null||Lr.resolveAskUserQuestion(vn,"(dismissed)"))},config:o})}let ht=mn!=null;if(Vt&&Nt===null&&!ht){((ur=B.agentMetadata)==null?void 0:ur.awaitingLocalTool)===!0&&!((mr=B.agentMetadata)!=null&&mr.askUserQuestionAnswered)&&(O.add(B.toolCall.id),ai(B,o,We.composerOverlay));return}let Qt=document.createElement("div");Qt.className="persona-flex",Qt.id=`wrapper-${B.id}`,Qt.setAttribute("data-wrapper-id",B.id),Qt.setAttribute("data-ask-plugin-stub","true"),Qt.setAttribute("data-preserve-runtime","true"),y.appendChild(Qt),ge.push({messageId:B.id,fingerprint:Ot,bubble:Nt});return}else{((Go=B.agentMetadata)==null?void 0:Go.awaitingLocalTool)===!0&&!((Mr=B.agentMetadata)!=null&&Mr.askUserQuestionAnswered)&&(O.add(B.toolCall.id),ai(B,o,We.composerOverlay));return}}else if(Oe){let et=r.find(ht=>typeof ht.renderApproval=="function"),Vt=vo.get(B.id)!==Ot,Nt=null;if(Vt&&(et!=null&&et.renderApproval)){let ht=B.id,Qt=(Et,kn)=>{var Do,vn,Hn;let Bn=(Do=Lt.current)==null?void 0:Do.getMessages().find(Dn=>Dn.id===ht);Bn!=null&&Bn.approval&&(Bn.approval.toolType==="webmcp"?(vn=Lt.current)==null||vn.resolveWebMcpApproval(Bn.id,Et):(Hn=Lt.current)==null||Hn.resolveApproval(Bn.approval,Et,kn))};Nt=et.renderApproval({message:B,defaultRenderer:()=>Ni(B,o),config:o,approve:Et=>Qt("approved",Et),deny:Et=>Qt("denied",Et)})}if(Vt&&Nt===null){let ht=c.querySelector(`#wrapper-${B.id}`);ht==null||ht.removeAttribute("data-preserve-runtime"),vo.delete(B.id),wt=Ni(B,o)}else{let ht=document.createElement("div");ht.className="persona-flex",ht.id=`wrapper-${B.id}`,ht.setAttribute("data-wrapper-id",B.id),ht.setAttribute("data-approval-plugin-stub","true"),ht.setAttribute("data-preserve-runtime","true"),y.appendChild(ht),Ae.push({messageId:B.id,fingerprint:Ot,bubble:Nt});return}}else if(zt)if(B.variant==="reasoning"&&B.reasoning&&zt.renderReasoning){if(!ue)return;wt=zt.renderReasoning({message:B,defaultRenderer:()=>Yl(B,o),config:o})}else if(B.variant==="tool"&&B.toolCall&&zt.renderToolCall){if(!ce)return;wt=zt.renderToolCall({message:B,defaultRenderer:()=>Ql(B,o),config:o})}else zt.renderMessage&&(wt=zt.renderMessage({message:B,defaultRenderer:()=>{let et=Gl(B,h,eo,o.messageActions,Z,{loadingIndicatorRenderer:F,widgetConfig:o});return B.role!=="user"&&ec(et,B,o,$),et},config:o}));if(!wt&&ye){let et=Ig(B);if(et){let mn=Po.get(B.id),Vt=mn!==Ot,Nt=o.wrapComponentDirectiveInBubble!==!1,ht=null;if(Vt){let Qt=Eg(et,{config:o,message:B,transform:h});if(Qt)if(Nt){let Et=document.createElement("div");if(Et.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Et.id=`bubble-${B.id}`,Et.setAttribute("data-message-id",B.id),B.content&&B.content.trim()){let kn=document.createElement("div");kn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",kn.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),Et.appendChild(kn)}Et.appendChild(Qt),ht=Et}else{let Et=document.createElement("div");if(Et.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Et.id=`bubble-${B.id}`,Et.setAttribute("data-message-id",B.id),Et.setAttribute("data-persona-component-directive","true"),B.content&&B.content.trim()){let kn=document.createElement("div");kn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",kn.innerHTML=h({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),Et.appendChild(kn)}Et.appendChild(Qt),ht=Et}}if(ht||mn!=null){let Qt=document.createElement("div");Qt.className="persona-flex",Qt.id=`wrapper-${B.id}`,Qt.setAttribute("data-wrapper-id",B.id),Qt.setAttribute("data-component-directive-stub","true"),Qt.setAttribute("data-preserve-runtime","true"),Nt||Qt.classList.add("persona-w-full"),y.appendChild(Qt),ee.push({messageId:B.id,fingerprint:Ot,bubble:ht});return}}}if(!wt)if(B.variant==="reasoning"&&B.reasoning){if(!ue)return;wt=Yl(B,o)}else if(B.variant==="tool"&&B.toolCall){if(!ce)return;wt=Ql(B,o)}else if(B.variant==="approval"&&B.approval){if(o.approval===!1)return;wt=Ni(B,o)}else{let et=(Co=o.layout)==null?void 0:Co.messages;et!=null&&et.renderUserMessage&&B.role==="user"?wt=et.renderUserMessage({message:B,config:o,streaming:!!B.streaming}):et!=null&&et.renderAssistantMessage&&B.role==="assistant"?wt=et.renderAssistantMessage({message:B,config:o,streaming:!!B.streaming}):wt=Gl(B,h,et,o.messageActions,Z,{loadingIndicatorRenderer:F,widgetConfig:o}),B.role!=="user"&&wt&&ec(wt,B,o,$)}let sn=document.createElement("div");sn.className="persona-flex",sn.id=`wrapper-${B.id}`,sn.setAttribute("data-wrapper-id",B.id),B.role==="user"&&sn.classList.add("persona-justify-end"),(wt==null?void 0:wt.getAttribute("data-persona-component-directive"))==="true"&&sn.classList.add("persona-w-full"),sn.appendChild(wt),$m(Uo,B.id,Ot,sn),y.appendChild(sn)}),We.composerOverlay&&We.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Be=>{let Oe=Be.getAttribute("data-persona-ask-sheet-for");Oe&&!O.has(Oe)&&ms(We.composerOverlay,Oe)}),(Pe=(dt=o.features)==null?void 0:dt.toolCallDisplay)!=null&&Pe.grouped){let B=[],Be=[];p.forEach(Oe=>{if(Oe.variant==="tool"&&Oe.toolCall&&ce){Be.push(Oe);return}Be.length>1&&B.push(Be),Be=[]}),Be.length>1&&B.push(Be),B.forEach((Oe,ye)=>{var Ye,Rt;let Ft=Oe.map(dn=>Array.from(y.children).find(uo=>uo instanceof HTMLElement&&uo.getAttribute("data-wrapper-id")===dn.id)).filter(dn=>!!dn);if(Ft.length<2)return;let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id=`wrapper-tool-group-${ye}-${Oe[0].id}`,Ot.setAttribute("data-wrapper-id",`tool-group-${ye}-${Oe[0].id}`);let Kt=document.createElement("div");Kt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Kt.setAttribute("data-persona-tool-group","true");let wt=document.createElement("div");wt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let zt=`Called ${Oe.length} tools`,eo=(Rt=(Ye=o.toolCall)==null?void 0:Ye.renderGroupedSummary)==null?void 0:Rt.call(Ye,{messages:Oe,toolCalls:Oe.map(dn=>dn.toolCall).filter(dn=>!!dn),defaultSummary:zt,config:o});N(wt,eo)||(wt.textContent=zt);let sn=document.createElement("div");sn.className="persona-tool-group-stack persona-flex persona-flex-col",Kt.append(wt,sn),Ot.appendChild(Kt),Ft[0].before(Ot),Ft.forEach((dn,uo)=>{let to=document.createElement("div");to.className="persona-tool-group-item persona-relative",to.setAttribute("data-persona-tool-group-item","true"),uo<Ft.length-1&&to.setAttribute("data-persona-tool-group-connector","true"),to.appendChild(dn),sn.appendChild(to)})})}Um(Uo,z);let nt=p.some(B=>B.role==="assistant"&&B.streaming),qe=p[p.length-1],ct=(qe==null?void 0:qe.role)==="assistant"&&!qe.streaming&&qe.variant!=="approval";if(Ro&&p.some(B=>B.role==="user")&&!nt&&!ct){let B={config:o,streaming:!0,location:"standalone",defaultRenderer:ga},Be=r.find(ye=>ye.renderLoadingIndicator),Oe=null;if(Be!=null&&Be.renderLoadingIndicator&&(Oe=Be.renderLoadingIndicator(B)),Oe===null&&((Ie=o.loadingIndicator)!=null&&Ie.render)&&(Oe=o.loadingIndicator.render(B)),Oe===null&&(Oe=ga()),Oe){let ye=document.createElement("div"),Ft=((Ue=o.loadingIndicator)==null?void 0:Ue.showBubble)!==!1;ye.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-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),ye.setAttribute("data-typing-indicator","true"),ye.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",ye.appendChild(Oe);let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id="wrapper-typing-indicator",Ot.setAttribute("data-wrapper-id","typing-indicator"),Ot.appendChild(ye),y.appendChild(Ot)}}if(!Ro&&p.length>0){let B=p[p.length-1],Be={config:o,lastMessage:B,messageCount:p.length},Oe=r.find(Ft=>Ft.renderIdleIndicator),ye=null;if(Oe!=null&&Oe.renderIdleIndicator&&(ye=Oe.renderIdleIndicator(Be)),ye===null&&((Ge=o.loadingIndicator)!=null&&Ge.renderIdle)&&(ye=o.loadingIndicator.renderIdle(Be)),ye){let Ft=document.createElement("div"),Ot=((xt=o.loadingIndicator)==null?void 0:xt.showBubble)!==!1;Ft.className=Ot?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ft.setAttribute("data-idle-indicator","true"),Ft.appendChild(ye);let Kt=document.createElement("div");Kt.className="persona-flex",Kt.id="wrapper-idle-indicator",Kt.setAttribute("data-wrapper-id","idle-indicator"),Kt.appendChild(Ft),y.appendChild(Kt)}}if(xi(c,y),ge.length>0)for(let{messageId:B,fingerprint:Be,bubble:Oe}of ge){let ye=c.querySelector(`#wrapper-${B}`);ye&&Oe!==null&&(ye.replaceChildren(Oe),ye.setAttribute("data-bubble-fp",Be),zo.set(B,Be))}if(zo.size>0)for(let B of zo.keys())z.has(B)||zo.delete(B);if(ee.length>0)for(let{messageId:B,fingerprint:Be,bubble:Oe}of ee){let ye=c.querySelector(`#wrapper-${B}`);ye&&Oe!==null&&(ye.replaceChildren(Oe),ye.setAttribute("data-bubble-fp",Be),Po.set(B,Be))}if(Po.size>0)for(let B of Po.keys())z.has(B)||Po.delete(B);if(Ae.length>0)for(let{messageId:B,fingerprint:Be,bubble:Oe}of Ae){let ye=c.querySelector(`#wrapper-${B}`);ye&&Oe!==null&&(ye.replaceChildren(Oe),ye.setAttribute("data-bubble-fp",Be),vo.set(B,Be))}if(vo.size>0)for(let B of vo.keys())z.has(B)||vo.delete(B)},ar=null,Wa=()=>{var h;if(ar)return;let c=y=>{let M=y.composedPath();M.includes(Le)||Qe&&M.includes(Qe)||Dt(!1,"user")};ar=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},Bs=()=>{var p;if(!ar)return;((p=e.ownerDocument)!=null?p:document).removeEventListener("pointerdown",ar,!0),ar=null};gt.push(()=>Bs());let ir=null,Ba=()=>{var h;if(ir)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Dt(!1,"user"))};ir=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},Hs=()=>{var p;if(!ir)return;((p=e.ownerDocument)!=null?p:document).removeEventListener("keydown",ir,!0),ir=null};gt.push(()=>Hs());let lr=!1,Ds=new Set,Ha=()=>{var p,h,y,M;let c=(y=(h=(p=o.launcher)==null?void 0:p.composerBar)==null?void 0:h.peek)==null?void 0:y.streamAnimation;return c||((M=o.features)==null?void 0:M.streamAnimation)},Ko=()=>{var ct,dt,Pe,Ie;if(!k())return;let c=We.peekBanner,p=We.peekTextNode;if(!c||!p)return;if(S){c.classList.remove("persona-pill-peek--visible");return}let h=(ct=$==null?void 0:$.getMessages())!=null?ct:[],y;for(let Ue=h.length-1;Ue>=0;Ue--){let Ge=h[Ue];if(Ge.role==="assistant"&&Ge.content){y=Ge;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let M=y.content,F=!!y.streaming,N=Ha(),z=Ti(N),O=z.type!=="none"?aa(z.type,N==null?void 0:N.plugins):null,we=((dt=O==null?void 0:O.isAnimating)==null?void 0:dt.call(O,y))===!0,ge=O!==null&&(F||we);ge&&O&&!Ds.has(O.name)&&($l(O,e),Ds.add(O.name));let ee=ge&&(O!=null&&O.containerClass)?O.containerClass:null,Te=(Pe=p.dataset.personaPeekStreamClass)!=null?Pe:null;Te&&Te!==ee&&(p.classList.remove(Te),delete p.dataset.personaPeekStreamClass),ee&&Te!==ee&&(p.classList.add(ee),p.dataset.personaPeekStreamClass=ee),ge?(p.style.setProperty("--persona-stream-step",`${z.speed}ms`),p.style.setProperty("--persona-stream-duration",`${z.duration}ms`)):(p.style.removeProperty("--persona-stream-step"),p.style.removeProperty("--persona-stream-duration"));let _e=ge?ki(M,z.buffer,O,y,F):M;if(ge&&z.placeholder==="skeleton"&&F&&(!_e||!_e.trim())){let Ue=document.createElement("div"),Ge=la();Ge.classList.add("persona-pill-peek__skeleton"),Ue.appendChild(Ge),xi(p,Ue)}else{let Ue=Math.max(0,_e.length-100),Ge=_e.length>100?_e.slice(-100):_e,xt=Ks(Ge);if(!ge||!O){let B=_e.length>100?`\u2026${Ge}`:Ge;p.textContent!==B&&(p.textContent=B)}else{let B=xt;(O.wrap==="char"||O.wrap==="word")&&(B=ia(xt,O.wrap,`peek-${y.id}`,{skipTags:O.skipTags,startIndex:Ue}));let Be=document.createElement("div");if(Be.innerHTML=B,O.useCaret&&Ge.length>0){let Oe=Ei(),ye=Be.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ft=ye[ye.length-1];Ft!=null&&Ft.parentNode?Ft.parentNode.insertBefore(Oe,Ft.nextSibling):Be.appendChild(Oe)}xi(p,Be),(Ie=O.onAfterRender)==null||Ie.call(O,{container:p,bubble:c,messageId:y.id,message:y,speed:z.speed,duration:z.duration})}}let qe=Ro||lr;c.classList.toggle("persona-pill-peek--visible",qe)};if(k()){let c=We.peekBanner;if(c){let y=M=>{M.preventDefault(),M.stopPropagation(),Dt(!0,"user")};c.addEventListener("pointerdown",y),gt.push(()=>{c.removeEventListener("pointerdown",y)})}let p=()=>{lr||(lr=!0,Ko())},h=()=>{lr&&(lr=!1,Ko())};de.addEventListener("pointerenter",p),de.addEventListener("pointerleave",h),gt.push(()=>{de.removeEventListener("pointerenter",p),de.removeEventListener("pointerleave",h)}),Qe&&(Qe.addEventListener("pointerenter",p),Qe.addEventListener("pointerleave",h),gt.push(()=>{Qe.removeEventListener("pointerenter",p),Qe.removeEventListener("pointerleave",h)}))}let Da=c=>{var Te,_e,Ae,nt,qe,ct,dt,Pe;let p=(_e=(Te=o.launcher)==null?void 0:Te.composerBar)!=null?_e:{},h=(Ae=p.expandedSize)!=null?Ae:"anchored",y=(nt=p.bottomOffset)!=null?nt:"16px",M=p.collapsedMaxWidth,F=(qe=p.expandedMaxWidth)!=null?qe:"880px",N=(ct=p.expandedTopOffset)!=null?ct:"5vh",z=(dt=p.modalMaxWidth)!=null?dt:"880px",O=(Pe=p.modalMaxHeight)!=null?Pe:"min(90vh, 800px)",we="calc(100vw - 32px)",ge="var(--persona-pill-area-height, 80px)",ee=Le.style;if(ee.left="",ee.right="",ee.top="",ee.bottom="",ee.transform="",ee.width="",ee.maxWidth="",ee.height="",ee.maxHeight="",Qe){let Ie=Qe.style;Ie.bottom=y,Ie.width=M!=null?M:""}if(c&&h!=="fullscreen"){if(h==="modal"){ee.top="50%",ee.left="50%",ee.transform="translate(-50%, -50%)",ee.bottom="auto",ee.right="auto",ee.width=z,ee.maxWidth=we,ee.maxHeight=O,ee.height=O;return}ee.left="50%",ee.transform="translateX(-50%)",ee.bottom=`calc(${y} + ${ge})`,ee.top=N,ee.width=F,ee.maxWidth=we}},cr=()=>{var O,we,ge,ee,Te,_e,Ae,nt;if(!A())return;if(k()){let ct=(ge=((we=(O=o.launcher)==null?void 0:O.composerBar)!=null?we:{}).expandedSize)!=null?ge:"anchored",dt=S?"expanded":"collapsed";Le.dataset.state=dt,Le.dataset.expandedSize=ct,Qe&&(Qe.dataset.state=dt,Qe.dataset.expandedSize=ct),Le.style.removeProperty("display"),Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Da(S),q.style.display=S?"flex":"none",bo(),S?(Wa(),Ba()):(Bs(),Hs()),Ko();return}let c=Cn(o),p=(ee=e.ownerDocument.defaultView)!=null?ee:window,h=(_e=(Te=o.launcher)==null?void 0:Te.mobileBreakpoint)!=null?_e:640,y=(nt=(Ae=o.launcher)==null?void 0:Ae.mobileFullscreen)!=null?nt:!0,M=p.innerWidth<=h,F=y&&M&&L,N=To(o).reveal;S?(Le.style.removeProperty("display"),Le.style.display=c?"flex":"",Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-95","persona-opacity-0"),de.classList.add("persona-scale-100","persona-opacity-100"),nn?nn.element.style.display="none":on&&(on.style.display="none")):(c?c&&(N==="overlay"||N==="push")&&!F?(Le.style.removeProperty("display"),Le.style.display="flex",Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Le.style.setProperty("display","none","important"),Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Le.style.display="",Le.classList.add("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100"),de.classList.add("persona-scale-95","persona-opacity-0")),nn?nn.element.style.display=c?"none":"":on&&(on.style.display=c?"none":""))},Dt=(c,p="user")=>{var F,N;if(!A()||S===c)return;let h=S;S=c,cr();let y=(()=>{var Ae,nt,qe,ct,dt,Pe,Ie,Ue,Ge,xt;let z=(nt=(Ae=o.launcher)==null?void 0:Ae.sidebarMode)!=null?nt:!1,O=(qe=e.ownerDocument.defaultView)!=null?qe:window,we=(dt=(ct=o.launcher)==null?void 0:ct.mobileFullscreen)!=null?dt:!0,ge=(Ie=(Pe=o.launcher)==null?void 0:Pe.mobileBreakpoint)!=null?Ie:640,ee=O.innerWidth<=ge,Te=Cn(o)&&we&&ee,_e=k()&&((xt=(Ge=(Ue=o.launcher)==null?void 0:Ue.composerBar)==null?void 0:Ge.expandedSize)!=null?xt:"fullscreen")==="fullscreen";return z||we&&ee&&L||Te||_e})();if(S&&y){if(!en){let z=e.getRootNode(),O=z instanceof ShadowRoot?z.host:e.closest(".persona-host");O&&(en=Ul(O,(N=(F=o.launcher)==null?void 0:F.zIndex)!=null?N:Ln))}tn||(tn=zl(e.ownerDocument))}else S||(en==null||en(),en=null,tn==null||tn(),tn=null);S&&(Fs(),ut()==="follow"?Ho(!0):Ps());let M={open:S,source:p,timestamp:Date.now()};S&&!h?s.emit("widget:opened",M):!S&&h&&s.emit("widget:closed",M),s.emit("widget:state",{open:S,launcherEnabled:L,voiceActive:bt.active,streaming:$.isStreaming()})},Zr=c=>{Xt(c?"stop":"send"),G&&(G.disabled=c),yo.buttons.forEach(p=>{p.disabled=c}),Ve.dataset.personaComposerStreaming=c?"true":"false",Ve.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(p=>{(p instanceof HTMLButtonElement||p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement||p instanceof HTMLSelectElement)&&(p.disabled=c)})},es=()=>{bt.active||te&&te.focus()};s.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>es(),200)});let Ar=()=>{var h,y,M,F,N,z,O,we,ge,ee,Te;ro.textContent=(y=(h=o.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",Eo.textContent=(F=(M=o.copy)==null?void 0:M.welcomeSubtitle)!=null?F:"Ask anything about your account or products.",te.placeholder=(z=(N=o.copy)==null?void 0:N.inputPlaceholder)!=null?z:"How can I help...";let c=me.querySelector("[data-persona-intro-card]");if(c){let _e=((O=o.copy)==null?void 0:O.showWelcomeCard)!==!1;c.style.display=_e?"":"none",_e?(me.classList.remove("persona-gap-3"),me.classList.add("persona-gap-6")):(me.classList.remove("persona-gap-6"),me.classList.add("persona-gap-3"))}!((ge=(we=o.sendButton)==null?void 0:we.useIcon)!=null&&ge)&&!($!=null&&$.isStreaming())&&(ze.textContent=(Te=(ee=o.copy)==null?void 0:ee.sendButtonLabel)!=null?Te:"Send"),te.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',te.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{m(p=>({...p,sessionId:c}))}});let $e=null,T=()=>{$e==null&&($e=setInterval(()=>{let c=tt.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval($e),$e=null;return}let p=Date.now();c.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=li(p-y))})},100))};if($=new yi(o,{onMessagesChanged(c){var y;Sr(tt,c,fe),T(),jr(c),Ho(!Ro),Pa(c);let p=[...c].reverse().find(M=>M.role==="user");c.length===0&&Cr(),!Kr||wr?(Kr=!0,Gr=(y=p==null?void 0:p.id)!=null?y:null):p&&p.id!==Gr&&(Gr=p.id,Ra(p.id));let h=bt.lastUserMessageId;p&&p.id!==h&&(bt.lastUserMessageId=p.id,s.emit("user:message",p)),bt.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),Xr(c),Ko()},onStatusChanged(c){var y;let p=(y=o.statusIndicator)!=null?y:{};it(an,(M=>{var F,N,z,O;return M==="idle"?(F=p.idleText)!=null?F:Mn.idle:M==="connecting"?(N=p.connectingText)!=null?N:Mn.connecting:M==="connected"?(z=p.connectedText)!=null?z:Mn.connected:M==="error"?(O=p.errorText)!=null?O:Mn.error:Mn[M]})(c),p,c)},onStreamingChanged(c){Ro=c,Zr(c),$&&Sr(tt,$.getMessages(),fe),c||Ho(!0),Ko()},onVoiceStatusChanged(c){var p,h;if(((h=(p=o.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype")switch(c){case"listening":break;case"processing":dr(),lf();break;case"speaking":dr(),cf();break;default:c==="idle"&&$.isBargeInActive()?(dr(),Os(),G==null||G.setAttribute("aria-label","End voice session")):(bt.active=!1,dr(),co("system"),Vn());break}},onArtifactsState(c){Kn=c,Qn(),Xr()}}),Lt.current=$,Kr=!0,((Sd=(Cd=o.voiceRecognition)==null?void 0:Cd.provider)==null?void 0:Sd.type)==="runtype")try{$.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}o.clientToken&&$.initClientSession().catch(c=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(be||o.onSSEEvent)&&$.setSSEEventCallback((c,p)=>{var h;(h=o.onSSEEvent)==null||h.call(o,c,p),he==null||he.processEvent(c,p),be==null||be.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(p)})}),l&&l.then(c=>{var p,h,y;if(c){if(c.metadata&&(d=ac(c.metadata),E.syncFromMetadata()),(p=c.messages)!=null&&p.length){wr=!0;try{$.hydrateMessages(c.messages)}finally{wr=!1}}(h=c.artifacts)!=null&&h.length&&$.hydrateArtifacts(c.artifacts,(y=c.selectedArtifactId)!=null?y:null)}}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let U=()=>{var p,h,y;!k()||S||!((y=(h=(p=o.launcher)==null?void 0:p.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||Dt(!0,"auto")},P=c=>{var M;if(c.preventDefault(),$.isStreaming()){$.cancel(),he==null||he.reset(),j==null||j.update();return}let p=te.value.trim(),h=(M=Ct==null?void 0:Ct.hasAttachments())!=null?M:!1;if(!p&&!h)return;U();let y;h&&(y=[],y.push(...Ct.getContentParts()),p&&y.push(Fl(p))),te.value="",te.style.height="auto",Me(),$.sendMessage(p,{contentParts:y}),h&&Ct.clearAttachments()},J=()=>{var c;return((c=o.features)==null?void 0:c.composerHistory)!==!1},ae={...wi},Y=!1,Me=()=>{ae={...wi}},Fe=()=>$.getMessages().filter(c=>c.role==="user").map(c=>{var p;return(p=c.content)!=null?p:""}).filter(c=>c.length>0),lt=c=>{if(!te)return;Y=!0,te.value=c,te.dispatchEvent(new Event("input",{bubbles:!0})),Y=!1;let p=te.value.length;te.setSelectionRange(p,p)},Je=()=>{Y||Me()},Wt=c=>{if(te){if(J()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let p=te.selectionStart===0&&te.selectionEnd===0,h=Fm({direction:c.key==="ArrowUp"?"up":"down",history:Fe(),currentValue:te.value,atStart:p,state:ae});if(ae=h.state,h.handled){c.preventDefault(),h.value!==void 0&&lt(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if($.isStreaming()){c.preventDefault();return}Me(),c.preventDefault(),ze.click()}}},_t=c=>{c.key!=="Escape"||c.isComposing||$.isStreaming()&&c.composedPath().includes(q)&&($.cancel(),he==null||he.reset(),j==null||j.update(),Me(),c.preventDefault(),c.stopImmediatePropagation())},un=async c=>{var h;if(((h=o.attachments)==null?void 0:h.enabled)!==!0||!Ct)return;let p=uw(c.clipboardData);p.length!==0&&(c.preventDefault(),await Ct.handleFiles(p))},rt=null,ft=!1,Jt=null,je=null,wn=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Gt=(c="user")=>{var F,N,z,O,we,ge,ee;if(ft||$.isStreaming())return;let p=wn();if(!p)return;rt=new p;let y=(N=((F=o.voiceRecognition)!=null?F:{}).pauseDuration)!=null?N:2e3;rt.continuous=!0,rt.interimResults=!0,rt.lang="en-US";let M=te.value;rt.onresult=Te=>{let _e="",Ae="";for(let qe=0;qe<Te.results.length;qe++){let ct=Te.results[qe],dt=ct[0].transcript;ct.isFinal?_e+=dt+" ":Ae=dt}let nt=M+_e+Ae;te.value=nt,Jt&&clearTimeout(Jt),(_e||Ae)&&(Jt=window.setTimeout(()=>{let qe=te.value.trim();qe&&rt&&ft&&(yn(),te.value="",te.style.height="auto",$.sendMessage(qe,{viaVoice:!0}))},y))},rt.onerror=Te=>{Te.error!=="no-speech"&&yn()},rt.onend=()=>{if(ft){let Te=te.value.trim();Te&&Te!==M.trim()&&(te.value="",te.style.height="auto",$.sendMessage(Te,{viaVoice:!0})),yn()}};try{if(rt.start(),ft=!0,bt.active=!0,c!=="system"&&(bt.manuallyDeactivated=!1),co(c),Vn(),G){let Te=(z=o.voiceRecognition)!=null?z:{};je={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:(O=Te.iconName)!=null?O:"mic",iconSize:parseFloat((ee=(ge=Te.iconSize)!=null?ge:(we=o.sendButton)==null?void 0:we.size)!=null?ee:"40")||24};let _e=Te.recordingBackgroundColor,Ae=Te.recordingIconColor,nt=Te.recordingBorderColor;if(G.classList.add("persona-voice-recording"),G.style.backgroundColor=_e!=null?_e:"var(--persona-voice-recording-bg, #ef4444)",G.style.color=Ae!=null?Ae:"var(--persona-voice-recording-indicator, #ffffff)",Ae){let qe=G.querySelector("svg");qe&&qe.setAttribute("stroke",Ae)}nt&&(G.style.borderColor=nt),G.setAttribute("aria-label","Stop voice recognition")}}catch{yn("system")}},yn=(c="user")=>{if(ft){if(ft=!1,Jt&&(clearTimeout(Jt),Jt=null),rt){try{rt.stop()}catch{}rt=null}if(bt.active=!1,co(c),Vn(),G){if(G.classList.remove("persona-voice-recording"),je){G.style.backgroundColor=je.backgroundColor,G.style.color=je.color,G.style.borderColor=je.borderColor;let p=G.querySelector("svg");p&&p.setAttribute("stroke",je.color||"currentColor"),je=null}G.setAttribute("aria-label","Start voice recognition")}}},af=(c,p)=>{var ct,dt,Pe,Ie,Ue,Ge,xt,B;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((ct=c==null?void 0:c.provider)==null?void 0:ct.type)==="runtype";if(!(h||y))return null;let F=b("div","persona-send-button-wrapper"),N=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");N.type="button",N.setAttribute("aria-label","Start voice recognition");let z=(dt=c==null?void 0:c.iconName)!=null?dt:"mic",O=(Pe=p==null?void 0:p.size)!=null?Pe:"40px",we=(Ie=c==null?void 0:c.iconSize)!=null?Ie:O,ge=parseFloat(we)||24,ee=(Ue=c==null?void 0:c.backgroundColor)!=null?Ue:p==null?void 0:p.backgroundColor,Te=(Ge=c==null?void 0:c.iconColor)!=null?Ge:p==null?void 0:p.textColor;N.style.width=we,N.style.height=we,N.style.minWidth=we,N.style.minHeight=we,N.style.fontSize="18px",N.style.lineHeight="1",Te?N.style.color=Te:N.style.color="var(--persona-text, #111827)";let Ae=Ee(z,ge,Te||"currentColor",1.5);Ae?N.appendChild(Ae):N.textContent="\u{1F3A4}",ee?N.style.backgroundColor=ee:N.style.backgroundColor="",c!=null&&c.borderWidth&&(N.style.borderWidth=c.borderWidth,N.style.borderStyle="solid"),c!=null&&c.borderColor&&(N.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(N.style.paddingLeft=c.paddingX,N.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(N.style.paddingTop=c.paddingY,N.style.paddingBottom=c.paddingY),F.appendChild(N);let nt=(xt=c==null?void 0:c.tooltipText)!=null?xt:"Start voice recognition";if(((B=c==null?void 0:c.showTooltip)!=null?B:!1)&&nt){let Be=b("div","persona-send-button-tooltip");Be.textContent=nt,F.appendChild(Be)}return{micButton:N,micButtonWrapper:F}},sl=()=>{var p,h,y,M,F;if(!G||je)return;let c=(p=o.voiceRecognition)!=null?p:{};je={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:(h=c.iconName)!=null?h:"mic",iconSize:parseFloat((F=(M=c.iconSize)!=null?M:(y=o.sendButton)==null?void 0:y.size)!=null?F:"40")||24}},al=(c,p)=>{var F,N,z,O,we;if(!G)return;let h=G.querySelector("svg");h&&h.remove();let y=(we=je==null?void 0:je.iconSize)!=null?we:parseFloat((O=(z=(F=o.voiceRecognition)==null?void 0:F.iconSize)!=null?z:(N=o.sendButton)==null?void 0:N.size)!=null?O:"40")||24,M=Ee(c,y,p,1.5);M&&G.appendChild(M)},Oa=()=>{G&&G.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Os=()=>{var M;if(!G)return;sl();let c=(M=o.voiceRecognition)!=null?M:{},p=c.recordingBackgroundColor,h=c.recordingIconColor,y=c.recordingBorderColor;if(Oa(),G.classList.add("persona-voice-recording"),G.style.backgroundColor=p!=null?p:"var(--persona-voice-recording-bg, #ef4444)",G.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let F=G.querySelector("svg");F&&F.setAttribute("stroke",h)}y&&(G.style.borderColor=y),G.setAttribute("aria-label","Stop voice recognition")},lf=()=>{var z,O,we,ge,ee,Te,_e,Ae;if(!G)return;sl();let c=(z=o.voiceRecognition)!=null?z:{},p=$.getVoiceInterruptionMode(),h=(O=c.processingIconName)!=null?O:"loader",y=(ge=(we=c.processingIconColor)!=null?we:je==null?void 0:je.color)!=null?ge:"",M=(Te=(ee=c.processingBackgroundColor)!=null?ee:je==null?void 0:je.backgroundColor)!=null?Te:"",F=(Ae=(_e=c.processingBorderColor)!=null?_e:je==null?void 0:je.borderColor)!=null?Ae:"";Oa(),G.classList.add("persona-voice-processing"),G.style.backgroundColor=M,G.style.borderColor=F;let N=y||"currentColor";G.style.color=N,al(h,N),G.setAttribute("aria-label","Processing voice input"),p==="none"&&(G.style.cursor="default")},cf=()=>{var we,ge,ee,Te,_e,Ae,nt,qe,ct,dt,Pe,Ie;if(!G)return;sl();let c=(we=o.voiceRecognition)!=null?we:{},p=$.getVoiceInterruptionMode(),h=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",y=(ge=c.speakingIconName)!=null?ge:h,M=(Ae=c.speakingIconColor)!=null?Ae:p==="barge-in"?(Te=(ee=c.recordingIconColor)!=null?ee:je==null?void 0:je.color)!=null?Te:"":(_e=je==null?void 0:je.color)!=null?_e:"",F=(ct=c.speakingBackgroundColor)!=null?ct:p==="barge-in"?(nt=c.recordingBackgroundColor)!=null?nt:"var(--persona-voice-recording-bg, #ef4444)":(qe=je==null?void 0:je.backgroundColor)!=null?qe:"",N=(Ie=c.speakingBorderColor)!=null?Ie:p==="barge-in"?(dt=c.recordingBorderColor)!=null?dt:"":(Pe=je==null?void 0:je.borderColor)!=null?Pe:"";Oa(),G.classList.add("persona-voice-speaking"),G.style.backgroundColor=F,G.style.borderColor=N;let z=M||"currentColor";G.style.color=z,al(y,z);let O=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";G.setAttribute("aria-label",O),p==="none"&&(G.style.cursor="default"),p==="barge-in"&&G.classList.add("persona-voice-recording")},dr=()=>{var c,p,h;G&&(Oa(),je&&(G.style.backgroundColor=(c=je.backgroundColor)!=null?c:"",G.style.color=(p=je.color)!=null?p:"",G.style.borderColor=(h=je.borderColor)!=null?h:"",al(je.iconName,je.color||"currentColor"),je=null),G.style.cursor="",G.setAttribute("aria-label","Start voice recognition"))},Fa=()=>{var c,p;if(((p=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:p.type)==="runtype"){let h=$.getVoiceStatus(),y=$.getVoiceInterruptionMode();if(y==="none"&&(h==="processing"||h==="speaking"))return;if(y==="cancel"&&(h==="processing"||h==="speaking")){$.stopVoicePlayback();return}if($.isBargeInActive()){$.stopVoicePlayback(),$.deactivateBargeIn().then(()=>{bt.active=!1,bt.manuallyDeactivated=!0,Vn(),co("user"),dr()});return}$.toggleVoice().then(()=>{bt.active=$.isVoiceActive(),bt.manuallyDeactivated=!$.isVoiceActive(),Vn(),co("user"),$.isVoiceActive()?Os():dr()});return}if(ft){let h=te.value.trim();bt.manuallyDeactivated=!0,Vn(),yn("user"),h&&(te.value="",te.style.height="auto",$.sendMessage(h))}else bt.manuallyDeactivated=!1,Vn(),Gt("user")};zn=Fa,G&&(G.addEventListener("click",Fa),gt.push(()=>{var c,p;((p=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:p.type)==="runtype"?($.isVoiceActive()&&$.toggleVoice(),dr()):yn("system"),G&&G.removeEventListener("click",Fa)}));let df=s.on("assistant:complete",()=>{Ts&&(bt.active||bt.manuallyDeactivated||Ts==="assistant"&&!bt.lastUserMessageWasVoice||setTimeout(()=>{var c,p;!bt.active&&!bt.manuallyDeactivated&&(((p=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:p.type)==="runtype"?$.toggleVoice().then(()=>{bt.active=$.isVoiceActive(),co("auto"),$.isVoiceActive()&&Os()}):Gt("auto"))},600))});gt.push(df);let pf=s.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});gt.push(pf);let ts=()=>{Dt(!S,"user")},nn=null,on=null;if(L&&!k()){let c=r.find(p=>p.renderLauncher);if(c!=null&&c.renderLauncher){let p=c.renderLauncher({config:o,defaultRenderer:()=>ua(o,ts).element,onToggle:ts});p&&(on=p)}on||(nn=ua(o,ts))}nn?e.appendChild(nn.element):on&&e.appendChild(on),cr(),jr(),Ar(),Zr($.isStreaming()),ut()==="follow"?Ho(!0):Ps(),ka(),W&&(!L||k()?setTimeout(()=>es(),0):S&&setTimeout(()=>es(),200));let Fs=()=>{var O,we,ge,ee,Te,_e,Ae,nt,qe,ct,dt,Pe,Ie,Ue,Ge,xt,B,Be,Oe,ye,Ft,Ot;if(k()){bn(),cr();return}let c=Cn(o),p=(we=(O=o.launcher)==null?void 0:O.sidebarMode)!=null?we:!1,h=c||p||((ee=(ge=o.launcher)==null?void 0:ge.fullHeight)!=null?ee:!1),y=(Te=e.ownerDocument.defaultView)!=null?Te:window,M=(Ae=(_e=o.launcher)==null?void 0:_e.mobileFullscreen)!=null?Ae:!0,F=(qe=(nt=o.launcher)==null?void 0:nt.mobileBreakpoint)!=null?qe:640,N=y.innerWidth<=F,z=M&&N&&L;try{if(z){bo(),as(e,o);return}if(C&&(C=!1,bo(),as(e,o)),!L&&!c){de.style.height="",de.style.width="";return}if(!p&&!c){let Kt=(dt=(ct=o==null?void 0:o.launcher)==null?void 0:ct.width)!=null?dt:o==null?void 0:o.launcherWidth,wt=Kt!=null?Kt:mo;de.style.width=wt,de.style.maxWidth=wt}if(Io(),!h){let Kt=y.innerHeight,wt=64,zt=(Ie=(Pe=o.launcher)==null?void 0:Pe.heightOffset)!=null?Ie:0,eo=Math.max(200,Kt-wt),sn=Math.min(640,eo),Ye=Math.max(200,sn-zt);de.style.height=`${Ye}px`}}finally{if(bn(),cr(),S&&L){let wt=((Ue=e.ownerDocument.defaultView)!=null?Ue:window).innerWidth<=((xt=(Ge=o.launcher)==null?void 0:Ge.mobileBreakpoint)!=null?xt:640),zt=(Be=(B=o.launcher)==null?void 0:B.sidebarMode)!=null?Be:!1,eo=(ye=(Oe=o.launcher)==null?void 0:Oe.mobileFullscreen)!=null?ye:!0,sn=Cn(o)&&eo&&wt,Ye=zt||eo&&wt&&L||sn;if(Ye&&!tn){let Rt=e.getRootNode(),dn=Rt instanceof ShadowRoot?Rt.host:e.closest(".persona-host");dn&&!en&&(en=Ul(dn,(Ot=(Ft=o.launcher)==null?void 0:Ft.zIndex)!=null?Ot:Ln)),tn=zl(e.ownerDocument)}else Ye||(en==null||en(),en=null,tn==null||tn(),tn=null)}}};Fs();let wc=(Ad=e.ownerDocument.defaultView)!=null?Ad:window;if(wc.addEventListener("resize",Fs),gt.push(()=>wc.removeEventListener("resize",Fs)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{bn()});c.observe(Ve),gt.push(()=>c.disconnect())}Zn=me.scrollTop;let Cc=Xo(me),uf=()=>{let c=me.getRootNode(),p=typeof c.getSelection=="function"?c.getSelection():null;return p!=null?p:me.ownerDocument.getSelection()},il=()=>zm(uf(),me),Sc=()=>{let c=me.scrollTop,p=Xo(me),h=p<Cc;if(Cc=p,ut()!=="follow"){Zn=c,$n();return}let{action:y,nextLastScrollTop:M}=Si({following:Jn.isFollowing(),currentScrollTop:c,lastScrollTop:Zn,nearBottom:Nr(me,Yr),userScrollThreshold:Aa,isAutoScrolling:wo||xr||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Zn=M,y==="resume"){il()||Bo();return}y==="pause"&&Jr()};if(me.addEventListener("scroll",Sc,{passive:!0}),gt.push(()=>me.removeEventListener("scroll",Sc)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Ia()});c.observe(tt),c.observe(me),gt.push(()=>c.disconnect())}let Ac=()=>{ut()==="follow"&&Jn.isFollowing()&&il()&&Jr()},Tc=me.ownerDocument;Tc.addEventListener("selectionchange",Ac),gt.push(()=>{Tc.removeEventListener("selectionchange",Ac)});let kc=c=>{if(ut()!=="follow")return;let p=Ai({following:Jn.isFollowing(),deltaY:c.deltaY,nearBottom:Nr(me,Yr),resumeWhenNearBottom:!0});p==="pause"?Jr():p==="resume"&&!il()&&Bo()};me.addEventListener("wheel",kc,{passive:!0}),gt.push(()=>me.removeEventListener("wheel",kc)),Xe.addEventListener("click",()=>{Cr(),me.scrollTop=me.scrollHeight,Zn=me.scrollTop,Bo(),Ho(!0),$n()}),gt.push(()=>Xe.remove()),gt.push(()=>{Es(),Cr()});let Ec=()=>{D&&(lo&&(D.removeEventListener("click",lo),lo=null),A()?(D.style.display="",lo=()=>{Dt(!1,"user")},D.addEventListener("click",lo)):D.style.display="none")};Ec(),(()=>{let{clearChatButton:c}=We;c&&c.addEventListener("click",()=>{$.clearMessages(),Uo.clear(),Bo(),ms(We.composerOverlay);try{localStorage.removeItem(vs),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${vs}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==vs)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let p=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}d={},E.syncFromMetadata(),be==null||be.clear(),he==null||he.reset(),j==null||j.update()})})(),Bt&&Bt.addEventListener("submit",P),te==null||te.addEventListener("keydown",Wt),te==null||te.addEventListener("input",Je),te==null||te.addEventListener("paste",un);let Mc=(Td=e.ownerDocument)!=null?Td:document;Mc.addEventListener("keydown",_t,!0);let Lc="persona-attachment-drop-active",Ns=0,ll=()=>{Ns=0,q.classList.remove(Lc)},ns=()=>{var c;return((c=o.attachments)==null?void 0:c.enabled)===!0&&Ct!==null},Ic=c=>{!Ui(c.dataTransfer)||!ns()||(Ns++,Ns===1&&q.classList.add(Lc))},Rc=c=>{!Ui(c.dataTransfer)||!ns()||(Ns--,Ns<=0&&ll())},Pc=c=>{!Ui(c.dataTransfer)||!ns()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Wc=c=>{var h;if(!Ui(c.dataTransfer)||!ns())return;c.preventDefault(),c.stopPropagation(),ll();let p=Array.from((h=c.dataTransfer.files)!=null?h:[]);p.length!==0&&Ct.handleFiles(p)},pr=!0;q.addEventListener("dragenter",Ic,pr),q.addEventListener("dragleave",Rc,pr),e.addEventListener("dragover",Pc,pr),e.addEventListener("drop",Wc,pr);let Na=e.ownerDocument,Bc=c=>{ns()&&c.preventDefault()},Hc=c=>{ns()&&c.preventDefault()};Na.addEventListener("dragover",Bc),Na.addEventListener("drop",Hc),gt.push(()=>{Bt&&Bt.removeEventListener("submit",P),te==null||te.removeEventListener("keydown",Wt),te==null||te.removeEventListener("input",Je),te==null||te.removeEventListener("paste",un),Mc.removeEventListener("keydown",_t,!0)}),gt.push(()=>{q.removeEventListener("dragenter",Ic,pr),q.removeEventListener("dragleave",Rc,pr),e.removeEventListener("dragover",Pc,pr),e.removeEventListener("drop",Wc,pr),Na.removeEventListener("dragover",Bc),Na.removeEventListener("drop",Hc),ll()}),gt.push(()=>{$.cancel()}),nn?gt.push(()=>{nn==null||nn.destroy()}):on&&gt.push(()=>{on==null||on.remove()});let cn={update(c){var kn,Bn,Do,vn,Hn,Dn,Lr,_s,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,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;let p=o.toolCall,h=o.messageActions,y=(kn=o.layout)==null?void 0:kn.messages,M=o.colorScheme,F=o.loadingIndicator,N=o.iterationDisplay,z=(Bn=o.features)==null?void 0:Bn.showReasoning,O=(Do=o.features)==null?void 0:Do.showToolCalls,we=(vn=o.features)==null?void 0:vn.toolCallDisplay,ge=(Hn=o.features)==null?void 0:Hn.reasoningDisplay;o={...o,...c},bo(),as(e,o),Vi(e,o),$i(e,o),Qn(),o.colorScheme!==M&&rr();let ee=nc.getForInstance(o.plugins);r.length=0,r.push(...ee),L=(Lr=(Dn=o.launcher)==null?void 0:Dn.enabled)!=null?Lr:!0,I=(Pd=(_s=o.launcher)==null?void 0:_s.autoExpand)!=null?Pd:!1,ue=(Bd=(Wd=o.features)==null?void 0:Wd.showReasoning)!=null?Bd:!0,ce=(Dd=(Hd=o.features)==null?void 0:Hd.showToolCalls)!=null?Dd:!0,ve=(Fd=(Od=o.features)==null?void 0:Od.scrollToBottom)!=null?Fd:{};let Te=ut();He=(_d=(Nd=o.features)==null?void 0:Nd.scrollBehavior)!=null?_d:{},Te!==ut()&&(Cr(),Bo()),Mo(),$n();let _e=ke;if(ke=($d=(Vd=o.features)==null?void 0:Vd.showEventStreamToggle)!=null?$d:!1,ke&&!_e){if(be||(Q=new ha(ie),be=new fa(re,Q),he=he!=null?he:new ba,Q.open().then(()=>be==null?void 0:be.restore()).catch(()=>{}),$.setSSEEventCallback((X,At)=>{var $t;($t=o.onSSEEvent)==null||$t.call(o,X,At),he==null||he.processEvent(X,At),be.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:X,timestamp:Date.now(),payload:JSON.stringify(At)})})),!vt&&Ne){let X=(zd=(Ud=o.features)==null?void 0:Ud.eventStream)==null?void 0:zd.classNames,At="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(X!=null&&X.toggleButton?" "+X.toggleButton:"");vt=b("button",At),vt.style.width="28px",vt.style.height="28px",vt.style.color=Fn.actionIconColor,vt.type="button",vt.setAttribute("aria-label","Event Stream"),vt.title="Event Stream";let $t=Ee("activity","18px","currentColor",1.5);$t&&vt.appendChild($t);let pt=We.clearChatButtonWrapper,Pt=We.closeButtonWrapper,gn=pt||Pt;gn&&gn.parentNode===Ne?Ne.insertBefore(vt,gn):Ne.appendChild(vt),vt.addEventListener("click",()=>{se?ho():No()})}}else!ke&&_e&&(ho(),vt&&(vt.remove(),vt=null),be==null||be.clear(),Q==null||Q.destroy(),be=null,Q=null,he==null||he.reset(),he=null);if(((qd=o.launcher)==null?void 0:qd.enabled)===!1&&nn&&(nn.destroy(),nn=null),((jd=o.launcher)==null?void 0:jd.enabled)===!1&&on&&(on.remove(),on=null),((Kd=o.launcher)==null?void 0:Kd.enabled)!==!1&&!nn&&!on){let X=r.find(At=>At.renderLauncher);if(X!=null&&X.renderLauncher){let At=X.renderLauncher({config:o,defaultRenderer:()=>ua(o,ts).element,onToggle:ts});At&&(on=At,e.appendChild(on))}on||(nn=ua(o,ts),e.appendChild(nn.element))}nn&&nn.update(o),De&&((Gd=o.launcher)==null?void 0:Gd.title)!==void 0&&(De.textContent=o.launcher.title),Ke&&((Yd=o.launcher)==null?void 0:Yd.subtitle)!==void 0&&(Ke.textContent=o.launcher.subtitle);let Ae=(Qd=o.layout)==null?void 0:Qd.header;if((Ae==null?void 0:Ae.layout)!==w&&Ne){let X=Ae?Ii(o,Ae,{showClose:A(),onClose:()=>Dt(!1,"user")}):_r({config:o,showClose:A(),onClose:()=>Dt(!1,"user")});Ne.replaceWith(X.header),Ne=X.header,pe=X.iconHolder,De=X.headerTitle,Ke=X.headerSubtitle,D=X.closeButton,w=Ae==null?void 0:Ae.layout}else if(Ae&&(pe&&(pe.style.display=Ae.showIcon===!1?"none":""),De&&(De.style.display=Ae.showTitle===!1?"none":""),Ke&&(Ke.style.display=Ae.showSubtitle===!1?"none":""),D&&(D.style.display=Ae.showCloseButton===!1?"none":""),We.clearChatButtonWrapper)){let X=Ae.showClearChat;if(X!==void 0){We.clearChatButtonWrapper.style.display=X?"":"none";let{closeButtonWrapper:At}=We;At&&!At.classList.contains("persona-absolute")&&(X?At.classList.remove("persona-ml-auto"):At.classList.add("persona-ml-auto"))}}let qe=((Xd=o.layout)==null?void 0:Xd.showHeader)!==!1;Ne&&(Ne.style.display=qe?"":"none");let ct=((Jd=o.layout)==null?void 0:Jd.showFooter)!==!1;Ve&&(Ve.style.display=ct?"":"none"),bn(),$n(),L!==R?L?Dt(I,"auto"):(S=!0,cr()):I!==H&&Dt(I,"auto"),H=I,R=L,Fs(),Ec();let Ie=JSON.stringify(c.toolCall)!==JSON.stringify(p),Ue=JSON.stringify(o.messageActions)!==JSON.stringify(h),Ge=JSON.stringify((Zd=o.layout)==null?void 0:Zd.messages)!==JSON.stringify(y),xt=((ep=o.loadingIndicator)==null?void 0:ep.render)!==(F==null?void 0:F.render)||((tp=o.loadingIndicator)==null?void 0:tp.renderIdle)!==(F==null?void 0:F.renderIdle)||((np=o.loadingIndicator)==null?void 0:np.showBubble)!==(F==null?void 0:F.showBubble),B=o.iterationDisplay!==N,Be=((rp=(op=o.features)==null?void 0:op.showReasoning)!=null?rp:!0)!==(z!=null?z:!0)||((ap=(sp=o.features)==null?void 0:sp.showToolCalls)!=null?ap:!0)!==(O!=null?O:!0)||JSON.stringify((ip=o.features)==null?void 0:ip.toolCallDisplay)!==JSON.stringify(we)||JSON.stringify((lp=o.features)==null?void 0:lp.reasoningDisplay)!==JSON.stringify(ge);(Ie||Ue||Ge||xt||B||Be)&&$&&(As++,Sr(tt,$.getMessages(),fe));let ye=(cp=o.launcher)!=null?cp:{},Ft=(dp=ye.headerIconHidden)!=null?dp:!1,Ot=(up=(pp=o.layout)==null?void 0:pp.header)==null?void 0:up.showIcon,Kt=Ft||Ot===!1,wt=ye.headerIconName,zt=(mp=ye.headerIconSize)!=null?mp:"48px";if(pe){let X=q.querySelector(".persona-border-b-persona-divider"),At=X==null?void 0:X.querySelector(".persona-flex-col");if(Kt)pe.style.display="none",X&&At&&!X.contains(At)&&X.insertBefore(At,X.firstChild);else{if(pe.style.display="",pe.style.height=zt,pe.style.width=zt,X&&At&&(X.contains(pe)?pe.nextSibling!==At&&(pe.remove(),X.insertBefore(pe,At)):X.insertBefore(pe,At)),wt){let pt=parseFloat(zt)||24,Pt=Ee(wt,pt*.6,"#ffffff",2);Pt?pe.replaceChildren(Pt):pe.textContent=(gp=ye.agentIconText)!=null?gp:"\u{1F4AC}"}else if(ye.iconUrl){let pt=pe.querySelector("img");if(pt)pt.src=ye.iconUrl,pt.style.height=zt,pt.style.width=zt;else{let Pt=document.createElement("img");Pt.src=ye.iconUrl,Pt.alt="",Pt.className="persona-rounded-xl persona-object-cover",Pt.style.height=zt,Pt.style.width=zt,pe.replaceChildren(Pt)}}else{let pt=pe.querySelector("svg"),Pt=pe.querySelector("img");(pt||Pt)&&pe.replaceChildren(),pe.textContent=(fp=ye.agentIconText)!=null?fp:"\u{1F4AC}"}let $t=pe.querySelector("img");$t&&($t.style.height=zt,$t.style.width=zt)}}let eo=(bp=(hp=o.layout)==null?void 0:hp.header)==null?void 0:bp.showTitle,sn=(vp=(yp=o.layout)==null?void 0:yp.header)==null?void 0:vp.showSubtitle;if(De&&(De.style.display=eo===!1?"none":""),Ke&&(Ke.style.display=sn===!1?"none":""),D){((wp=(xp=o.layout)==null?void 0:xp.header)==null?void 0:wp.showCloseButton)===!1?D.style.display="none":D.style.display="";let At=(Cp=ye.closeButtonSize)!=null?Cp:"32px",$t=(Sp=ye.closeButtonPlacement)!=null?Sp:"inline";D.style.height=At,D.style.width=At;let{closeButtonWrapper:pt}=We,Pt=$t==="top-right",gn=pt==null?void 0:pt.classList.contains("persona-absolute");if(pt&&Pt!==gn)if(pt.remove(),Pt)pt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",q.style.position="relative",q.appendChild(pt);else{let mt=(Tp=(Ap=ye.clearChat)==null?void 0:Ap.placement)!=null?Tp:"inline",fn=(Ep=(kp=ye.clearChat)==null?void 0:kp.enabled)!=null?Ep:!0;pt.className=fn&&mt==="inline"?"":"persona-ml-auto";let Un=q.querySelector(".persona-border-b-persona-divider");Un&&Un.appendChild(pt)}if(D.style.color=ye.closeButtonColor||Fn.actionIconColor,ye.closeButtonBackgroundColor?(D.style.backgroundColor=ye.closeButtonBackgroundColor,D.classList.remove("hover:persona-bg-gray-100")):(D.style.backgroundColor="",D.classList.add("hover:persona-bg-gray-100")),ye.closeButtonBorderWidth||ye.closeButtonBorderColor){let mt=ye.closeButtonBorderWidth||"0px",fn=ye.closeButtonBorderColor||"transparent";D.style.border=`${mt} solid ${fn}`,D.classList.remove("persona-border-none")}else D.style.border="",D.classList.add("persona-border-none");ye.closeButtonBorderRadius?(D.style.borderRadius=ye.closeButtonBorderRadius,D.classList.remove("persona-rounded-full")):(D.style.borderRadius="",D.classList.add("persona-rounded-full")),ye.closeButtonPaddingX?(D.style.paddingLeft=ye.closeButtonPaddingX,D.style.paddingRight=ye.closeButtonPaddingX):(D.style.paddingLeft="",D.style.paddingRight=""),ye.closeButtonPaddingY?(D.style.paddingTop=ye.closeButtonPaddingY,D.style.paddingBottom=ye.closeButtonPaddingY):(D.style.paddingTop="",D.style.paddingBottom="");let En=(Mp=ye.closeButtonIconName)!=null?Mp:"x",So=(Lp=ye.closeButtonIconText)!=null?Lp:"\xD7";D.innerHTML="";let On=Ee(En,"28px","currentColor",1);On?D.appendChild(On):D.textContent=So;let rn=(Ip=ye.closeButtonTooltipText)!=null?Ip:"Close chat",no=(Rp=ye.closeButtonShowTooltip)!=null?Rp:!0;if(D.setAttribute("aria-label",rn),pt&&(pt._cleanupTooltip&&(pt._cleanupTooltip(),delete pt._cleanupTooltip),no&&rn)){let mt=null,fn=()=>{if(mt||!D)return;let Ir=D.ownerDocument,Vs=Ir.body;if(!Vs)return;mt=Fo(Ir,"div","persona-clear-chat-tooltip"),mt.textContent=rn;let $s=Fo(Ir,"div");$s.className="persona-clear-chat-tooltip-arrow",mt.appendChild($s);let Rr=D.getBoundingClientRect();mt.style.position="fixed",mt.style.zIndex=String(hr),mt.style.left=`${Rr.left+Rr.width/2}px`,mt.style.top=`${Rr.top-8}px`,mt.style.transform="translate(-50%, -100%)",Vs.appendChild(mt)},Un=()=>{mt&&mt.parentNode&&(mt.parentNode.removeChild(mt),mt=null)};pt.addEventListener("mouseenter",fn),pt.addEventListener("mouseleave",Un),D.addEventListener("focus",fn),D.addEventListener("blur",Un),pt._cleanupTooltip=()=>{Un(),pt&&(pt.removeEventListener("mouseenter",fn),pt.removeEventListener("mouseleave",Un)),D&&(D.removeEventListener("focus",fn),D.removeEventListener("blur",Un))}}}let{clearChatButton:Ye,clearChatButtonWrapper:Rt}=We;if(Ye){let X=(Pp=ye.clearChat)!=null?Pp:{},At=(Wp=X.enabled)!=null?Wp:!0,$t=(Hp=(Bp=o.layout)==null?void 0:Bp.header)==null?void 0:Hp.showClearChat,pt=$t!==void 0?$t:At,Pt=(Dp=X.placement)!=null?Dp:"inline";if(Rt){Rt.style.display=pt?"":"none";let{closeButtonWrapper:gn}=We;!k()&&gn&&!gn.classList.contains("persona-absolute")&&(pt?gn.classList.remove("persona-ml-auto"):gn.classList.add("persona-ml-auto"));let En=Pt==="top-right",So=Rt.classList.contains("persona-absolute");if(!k()&&En!==So&&pt){if(Rt.remove(),En)Rt.className="persona-absolute persona-top-4 persona-z-50",Rt.style.right="48px",q.style.position="relative",q.appendChild(Rt);else{Rt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Rt.style.right="";let rn=q.querySelector(".persona-border-b-persona-divider"),no=We.closeButtonWrapper;rn&&no&&no.parentElement===rn?rn.insertBefore(Rt,no):rn&&rn.appendChild(Rt)}let On=We.closeButtonWrapper;On&&!On.classList.contains("persona-absolute")&&(En?On.classList.add("persona-ml-auto"):On.classList.remove("persona-ml-auto"))}}if(pt){if(!k()){let mt=(Op=X.size)!=null?Op:"32px";Ye.style.height=mt,Ye.style.width=mt}let gn=(Fp=X.iconName)!=null?Fp:"refresh-cw",En=(Np=X.iconColor)!=null?Np:"";Ye.style.color=En||Fn.actionIconColor,Ye.innerHTML="";let So=k()?"14px":"20px",On=Ee(gn,So,"currentColor",2);if(On&&Ye.appendChild(On),X.backgroundColor?(Ye.style.backgroundColor=X.backgroundColor,Ye.classList.remove("hover:persona-bg-gray-100")):(Ye.style.backgroundColor="",Ye.classList.add("hover:persona-bg-gray-100")),X.borderWidth||X.borderColor){let mt=X.borderWidth||"0px",fn=X.borderColor||"transparent";Ye.style.border=`${mt} solid ${fn}`,Ye.classList.remove("persona-border-none")}else Ye.style.border="",Ye.classList.add("persona-border-none");X.borderRadius?(Ye.style.borderRadius=X.borderRadius,Ye.classList.remove("persona-rounded-full")):(Ye.style.borderRadius="",Ye.classList.add("persona-rounded-full")),X.paddingX?(Ye.style.paddingLeft=X.paddingX,Ye.style.paddingRight=X.paddingX):(Ye.style.paddingLeft="",Ye.style.paddingRight=""),X.paddingY?(Ye.style.paddingTop=X.paddingY,Ye.style.paddingBottom=X.paddingY):(Ye.style.paddingTop="",Ye.style.paddingBottom="");let rn=(_p=X.tooltipText)!=null?_p:"Clear chat",no=(Vp=X.showTooltip)!=null?Vp:!0;if(Ye.setAttribute("aria-label",rn),Rt&&(Rt._cleanupTooltip&&(Rt._cleanupTooltip(),delete Rt._cleanupTooltip),no&&rn)){let mt=null,fn=()=>{if(mt||!Ye)return;let Ir=Ye.ownerDocument,Vs=Ir.body;if(!Vs)return;mt=Fo(Ir,"div","persona-clear-chat-tooltip"),mt.textContent=rn;let $s=Fo(Ir,"div");$s.className="persona-clear-chat-tooltip-arrow",mt.appendChild($s);let Rr=Ye.getBoundingClientRect();mt.style.position="fixed",mt.style.zIndex=String(hr),mt.style.left=`${Rr.left+Rr.width/2}px`,mt.style.top=`${Rr.top-8}px`,mt.style.transform="translate(-50%, -100%)",Vs.appendChild(mt)},Un=()=>{mt&&mt.parentNode&&(mt.parentNode.removeChild(mt),mt=null)};Rt.addEventListener("mouseenter",fn),Rt.addEventListener("mouseleave",Un),Ye.addEventListener("focus",fn),Ye.addEventListener("blur",Un),Rt._cleanupTooltip=()=>{Un(),Rt&&(Rt.removeEventListener("mouseenter",fn),Rt.removeEventListener("mouseleave",Un)),Ye&&(Ye.removeEventListener("focus",fn),Ye.removeEventListener("blur",Un))}}}}let dn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[rc],uo=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ya.message,ya.messageAndClick];E=sc({parsers:dn,handlers:uo,getSessionMetadata:f,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),fe=Bg(o,E,K),$.updateConfig(o),Sr(tt,$.getMessages(),fe),jr(),Ar(),Zr($.isStreaming());let to=(($p=o.voiceRecognition)==null?void 0:$p.enabled)===!0,Tr=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),kr=((zp=(Up=o.voiceRecognition)==null?void 0:Up.provider)==null?void 0:zp.type)==="runtype";if(to&&(Tr||kr))if(!G||!yt){let X=af(o.voiceRecognition,o.sendButton);X&&(G=X.micButton,yt=X.micButtonWrapper,qt.insertBefore(yt,Nn),G.addEventListener("click",Fa),G.disabled=$.isStreaming())}else{let X=(qp=o.voiceRecognition)!=null?qp:{},At=(jp=o.sendButton)!=null?jp:{},$t=(Kp=X.iconName)!=null?Kp:"mic",pt=(Gp=At.size)!=null?Gp:"40px",Pt=(Yp=X.iconSize)!=null?Yp:pt,gn=parseFloat(Pt)||24;G.style.width=Pt,G.style.height=Pt,G.style.minWidth=Pt,G.style.minHeight=Pt;let En=(Xp=(Qp=X.iconColor)!=null?Qp:At.textColor)!=null?Xp:"currentColor";G.innerHTML="";let So=Ee($t,gn,En,2);So?G.appendChild(So):G.textContent="\u{1F3A4}";let On=(Jp=X.backgroundColor)!=null?Jp:At.backgroundColor;On?G.style.backgroundColor=On:G.style.backgroundColor="",En?G.style.color=En:G.style.color="var(--persona-text, #111827)",X.borderWidth?(G.style.borderWidth=X.borderWidth,G.style.borderStyle="solid"):(G.style.borderWidth="",G.style.borderStyle=""),X.borderColor?G.style.borderColor=X.borderColor:G.style.borderColor="",X.paddingX?(G.style.paddingLeft=X.paddingX,G.style.paddingRight=X.paddingX):(G.style.paddingLeft="",G.style.paddingRight=""),X.paddingY?(G.style.paddingTop=X.paddingY,G.style.paddingBottom=X.paddingY):(G.style.paddingTop="",G.style.paddingBottom="");let rn=yt==null?void 0:yt.querySelector(".persona-send-button-tooltip"),no=(Zp=X.tooltipText)!=null?Zp:"Start voice recognition";if(((eu=X.showTooltip)!=null?eu:!1)&&no)if(rn)rn.textContent=no,rn.style.display="";else{let fn=document.createElement("div");fn.className="persona-send-button-tooltip",fn.textContent=no,yt==null||yt.insertBefore(fn,G)}else rn&&(rn.style.display="none");yt.style.display="",G.disabled=$.isStreaming()}else G&&yt&&(yt.style.display="none",((nu=(tu=o.voiceRecognition)==null?void 0:tu.provider)==null?void 0:nu.type)==="runtype"?$.isVoiceActive()&&$.toggleVoice():ft&&yn());if(((ou=o.attachments)==null?void 0:ou.enabled)===!0)if(!Ce||!st){let X=(ru=o.attachments)!=null?ru:{},$t=(au=((su=o.sendButton)!=null?su:{}).size)!=null?au:"40px";Ze||(Ze=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ze.style.display="none",Bt.insertBefore(Ze,te)),le||(le=document.createElement("input"),le.type="file",le.accept=((iu=X.allowedTypes)!=null?iu:Qo).join(","),le.multiple=((lu=X.maxFiles)!=null?lu:4)>1,le.style.display="none",le.setAttribute("aria-label","Attach files"),Bt.insertBefore(le,te)),Ce=b("div","persona-send-button-wrapper"),st=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),st.type="button",st.setAttribute("aria-label",(cu=X.buttonTooltipText)!=null?cu:"Attach file");let pt=(du=X.buttonIconName)!=null?du:"paperclip",Pt=$t,gn=parseFloat(Pt)||40,En=Math.round(gn*.6);st.style.width=Pt,st.style.height=Pt,st.style.minWidth=Pt,st.style.minHeight=Pt,st.style.fontSize="18px",st.style.lineHeight="1",st.style.backgroundColor="transparent",st.style.color="var(--persona-primary, #111827)",st.style.border="none",st.style.borderRadius="6px",st.style.transition="background-color 0.15s ease",st.addEventListener("mouseenter",()=>{st.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),st.addEventListener("mouseleave",()=>{st.style.backgroundColor="transparent"});let So=Ee(pt,En,"currentColor",1.5);So?st.appendChild(So):st.textContent="\u{1F4CE}",st.addEventListener("click",no=>{no.preventDefault(),le==null||le.click()}),Ce.appendChild(st);let On=(pu=X.buttonTooltipText)!=null?pu:"Attach file",rn=b("div","persona-send-button-tooltip");rn.textContent=On,Ce.appendChild(rn),It.append(Ce),!Ct&&le&&Ze&&(Ct=ra.fromConfig(X),Ct.setPreviewsContainer(Ze),le.addEventListener("change",async()=>{Ct&&(le!=null&&le.files)&&(await Ct.handleFileSelect(le.files),le.value="")})),q.querySelector(".persona-attachment-drop-overlay")||q.appendChild(Hg(X.dropOverlay))}else{Ce.style.display="";let X=(uu=o.attachments)!=null?uu:{};le&&(le.accept=((mu=X.allowedTypes)!=null?mu:Qo).join(","),le.multiple=((gu=X.maxFiles)!=null?gu:4)>1),Ct&&Ct.updateConfig({allowedTypes:X.allowedTypes,maxFileSize:X.maxFileSize,maxFiles:X.maxFiles})}else Ce&&(Ce.style.display="none"),Ct&&Ct.clearAttachments(),(fu=q.querySelector(".persona-attachment-drop-overlay"))==null||fu.remove();let Yt=(hu=o.sendButton)!=null?hu:{},Er=(bu=Yt.useIcon)!=null?bu:!1,ur=(yu=Yt.iconText)!=null?yu:"\u2191",mr=Yt.iconName,Go=(vu=Yt.tooltipText)!=null?vu:"Send message",Mr=(xu=Yt.showTooltip)!=null?xu:!1,Co=(wu=Yt.size)!=null?wu:"40px",et=Yt.backgroundColor,mn=Yt.textColor;if(Er){if(ze.style.width=Co,ze.style.height=Co,ze.style.minWidth=Co,ze.style.minHeight=Co,ze.style.fontSize="18px",ze.style.lineHeight="1",ze.innerHTML="",mn?ze.style.color=mn:ze.style.color="var(--persona-button-primary-fg, #ffffff)",mr){let X=parseFloat(Co)||24,At=(mn==null?void 0:mn.trim())||"currentColor",$t=Ee(mr,X,At,2);$t?ze.appendChild($t):ze.textContent=ur}else ze.textContent=ur;ze.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",et?(ze.style.backgroundColor=et,ze.classList.remove("persona-bg-persona-primary")):(ze.style.backgroundColor="",ze.classList.add("persona-bg-persona-primary"))}else ze.textContent=(Su=(Cu=o.copy)==null?void 0:Cu.sendButtonLabel)!=null?Su:"Send",ze.style.width="",ze.style.height="",ze.style.minWidth="",ze.style.minHeight="",ze.style.fontSize="",ze.style.lineHeight="",ze.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",et?(ze.style.backgroundColor=et,ze.classList.remove("persona-bg-persona-accent")):ze.classList.add("persona-bg-persona-accent"),mn?ze.style.color=mn:ze.classList.add("persona-text-white");Yt.borderWidth?(ze.style.borderWidth=Yt.borderWidth,ze.style.borderStyle="solid"):(ze.style.borderWidth="",ze.style.borderStyle=""),Yt.borderColor?ze.style.borderColor=Yt.borderColor:ze.style.borderColor="",Yt.paddingX?(ze.style.paddingLeft=Yt.paddingX,ze.style.paddingRight=Yt.paddingX):(ze.style.paddingLeft="",ze.style.paddingRight=""),Yt.paddingY?(ze.style.paddingTop=Yt.paddingY,ze.style.paddingBottom=Yt.paddingY):(ze.style.paddingTop="",ze.style.paddingBottom="");let Vt=Nn==null?void 0:Nn.querySelector(".persona-send-button-tooltip");if(Mr&&Go)if(Vt)Vt.textContent=Go,Vt.style.display="";else{let X=document.createElement("div");X.className="persona-send-button-tooltip",X.textContent=Go,Nn==null||Nn.insertBefore(X,ze)}else Vt&&(Vt.style.display="none");let Nt=(Mu=(Au=o.layout)==null?void 0:Au.contentMaxWidth)!=null?Mu:k()?(Eu=(ku=(Tu=o.launcher)==null?void 0:Tu.composerBar)==null?void 0:ku.contentMaxWidth)!=null?Eu:"720px":void 0;Nt?(tt.style.maxWidth=Nt,tt.style.marginLeft="auto",tt.style.marginRight="auto",tt.style.width="100%",Bt&&(Bt.style.maxWidth=Nt,Bt.style.marginLeft="auto",Bt.style.marginRight="auto"),Tt&&(Tt.style.maxWidth=Nt,Tt.style.marginLeft="auto",Tt.style.marginRight="auto")):(tt.style.maxWidth="",tt.style.marginLeft="",tt.style.marginRight="",tt.style.width="",Bt&&(Bt.style.maxWidth="",Bt.style.marginLeft="",Bt.style.marginRight=""),Tt&&(Tt.style.maxWidth="",Tt.style.marginLeft="",Tt.style.marginRight=""));let ht=(Lu=o.statusIndicator)!=null?Lu:{},Qt=(Iu=ht.visible)!=null?Iu:!0;if(an.style.display=Qt?"":"none",$){let X=$.getStatus();it(an,($t=>{var pt,Pt,gn,En;return $t==="idle"?(pt=ht.idleText)!=null?pt:Mn.idle:$t==="connecting"?(Pt=ht.connectingText)!=null?Pt:Mn.connecting:$t==="connected"?(gn=ht.connectedText)!=null?gn:Mn.connected:$t==="error"?(En=ht.errorText)!=null?En:Mn.error:Mn[$t]})(X),ht,X)}an.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Et=ht.align==="left"?"persona-text-left":ht.align==="center"?"persona-text-center":"persona-text-right";an.classList.add(Et)},open(){A()&&Dt(!0,"api")},close(){A()&&Dt(!1,"api")},toggle(){A()&&Dt(!S,"api")},clearChat(){Pn=!1,$.clearMessages(),Uo.clear(),Bo();try{localStorage.removeItem(vs),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${vs}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==vs)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let p=i.clear();p instanceof Promise&&p.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}d={},E.syncFromMetadata(),be==null||be.clear(),he==null||he.reset(),j==null||j.update()},setMessage(c){return!te||$.isStreaming()?!1:(!S&&A()&&Dt(!0,"system"),te.value=c,te.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if($.isStreaming())return!1;let p=(c==null?void 0:c.trim())||te.value.trim();return p?(!S&&A()&&Dt(!0,"system"),te.value="",te.style.height="auto",$.sendMessage(p),!0):!1},startVoiceRecognition(){var p,h;return $.isStreaming()?!1:((h=(p=o.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype"?($.isVoiceActive()||(!S&&A()&&Dt(!0,"system"),bt.manuallyDeactivated=!1,Vn(),$.toggleVoice().then(()=>{bt.active=$.isVoiceActive(),co("user"),$.isVoiceActive()&&Os()})),!0):ft?!0:wn()?(!S&&A()&&Dt(!0,"system"),bt.manuallyDeactivated=!1,Vn(),Gt("user"),!0):!1},stopVoiceRecognition(){var c,p;return((p=(c=o.voiceRecognition)==null?void 0:c.provider)==null?void 0:p.type)==="runtype"?$.isVoiceActive()?($.toggleVoice().then(()=>{bt.active=!1,bt.manuallyDeactivated=!0,Vn(),co("user"),dr()}),!0):!1:ft?(bt.manuallyDeactivated=!0,Vn(),yn("user"),!0):!1},injectMessage(c){return!S&&A()&&Dt(!0,"system"),$.injectMessage(c)},injectAssistantMessage(c){!S&&A()&&Dt(!0,"system");let p=$.injectAssistantMessage(c);return _&&(_=!1,V&&(clearTimeout(V),V=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),p},injectUserMessage(c){return!S&&A()&&Dt(!0,"system"),$.injectUserMessage(c)},injectSystemMessage(c){return!S&&A()&&Dt(!0,"system"),$.injectSystemMessage(c)},injectMessageBatch(c){return!S&&A()&&Dt(!0,"system"),$.injectMessageBatch(c)},injectComponentDirective(c){return!S&&A()&&Dt(!0,"system"),$.injectComponentDirective(c)},injectTestMessage(c){!S&&A()&&Dt(!0,"system"),$.injectTestEvent(c)},async connectStream(c,p){return $.connectStream(c,p)},__pushEventStreamEvent(c){be&&(he==null||he.processEvent(c.type,c.payload),be.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!ke||!be||No()},hideEventStream(){se&&ho()},isEventStreamVisible(){return se},showArtifacts(){fo(o)&&(Pn=!1,Qn(),St==null||St.setMobileOpen(!0))},hideArtifacts(){fo(o)&&(Pn=!0,Qn())},upsertArtifact(c){return fo(o)?(Pn=!1,$.upsertArtifact(c)):null},selectArtifact(c){fo(o)&&$.selectArtifact(c)},clearArtifacts(){fo(o)&&$.clearArtifacts()},getArtifacts(){var c;return(c=$==null?void 0:$.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=$==null?void 0:$.getSelectedArtifactId())!=null?c:null},focusInput(){return L&&!S&&!k()||!te?!1:(te.focus(),!0)},async resolveApproval(c,p,h){let M=$.getMessages().find(F=>{var N;return F.variant==="approval"&&((N=F.approval)==null?void 0:N.id)===c});if(!(M!=null&&M.approval))throw new Error(`Approval not found: ${c}`);if(M.approval.toolType==="webmcp"){$.resolveWebMcpApproval(M.id,p);return}return $.resolveApproval(M.approval,p,h)},getMessages(){return $.getMessages()},getStatus(){return $.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){m(c)},on(c,p){return s.on(c,p)},off(c,p){s.off(c,p)},isOpen(){return A()&&S},isVoiceActive(){return bt.active},getState(){return{open:A()&&S,launcherEnabled:L,voiceActive:bt.active,streaming:$.isStreaming()}},showCSATFeedback(c){!S&&A()&&Dt(!0,"system");let p=tt.querySelector(".persona-feedback-container");p&&p.remove();let h=Rg({onSubmit:async(y,M)=>{var F;$.isClientTokenMode()&&await $.submitCSATFeedback(y,M),(F=c==null?void 0:c.onSubmit)==null||F.call(c,y,M)},onDismiss:c==null?void 0:c.onDismiss,...c});tt.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!S&&A()&&Dt(!0,"system");let p=tt.querySelector(".persona-feedback-container");p&&p.remove();let h=Pg({onSubmit:async(y,M)=>{var F;$.isClientTokenMode()&&await $.submitNPSFeedback(y,M),(F=c==null?void 0:c.onSubmit)==null||F.call(c,y,M)},onDismiss:c==null?void 0:c.onDismiss,...c});tt.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,p){return $.submitCSATFeedback(c,p)},async submitNPSFeedback(c,p){return $.submitNPSFeedback(c,p)},destroy(){$e!=null&&(clearInterval($e),$e=null),gt.forEach(c=>c()),Le.remove(),Qe==null||Qe.remove(),nn==null||nn.destroy(),on==null||on.remove(),lo&&D.removeEventListener("click",lo)}};if((((kd=n==null?void 0:n.debugTools)!=null?kd:!1)||!!o.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,p={controller:cn,getMessages:cn.getMessages,getStatus:cn.getStatus,getMetadata:cn.getPersistentMetadata,updateMetadata:cn.updatePersistentMetadata,clearHistory:()=>cn.clearChat(),setVoiceActive:h=>h?cn.startVoiceRecognition():cn.stopVoiceRecognition()};window.AgentWidgetBrowser=p,gt.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),p=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&cn.focusInput()};if(window.addEventListener("persona:focusInput",p),gt.push(()=>{window.removeEventListener("persona:focusInput",p)}),ke){let z=we=>{let ge=we.detail;(!(ge!=null&&ge.instanceId)||ge.instanceId===c)&&cn.showEventStream()},O=we=>{let ge=we.detail;(!(ge!=null&&ge.instanceId)||ge.instanceId===c)&&cn.hideEventStream()};window.addEventListener("persona:showEventStream",z),window.addEventListener("persona:hideEventStream",O),gt.push(()=>{window.removeEventListener("persona:showEventStream",z),window.removeEventListener("persona:hideEventStream",O)})}let h=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&cn.showArtifacts()},y=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&cn.hideArtifacts()},M=z=>{let O=z.detail;O!=null&&O.instanceId&&O.instanceId!==c||O!=null&&O.artifact&&cn.upsertArtifact(O.artifact)},F=z=>{let O=z.detail;O!=null&&O.instanceId&&O.instanceId!==c||typeof(O==null?void 0:O.id)=="string"&&cn.selectArtifact(O.id)},N=z=>{let O=z.detail;(!(O!=null&&O.instanceId)||O.instanceId===c)&&cn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",M),window.addEventListener("persona:selectArtifact",F),window.addEventListener("persona:clearArtifacts",N),gt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",M),window.removeEventListener("persona:selectArtifact",F),window.removeEventListener("persona:clearArtifacts",N)})}let po=mw(o.persistState);if(po&&A()){let c=gw(po.storage),p=`${po.keyPrefix}widget-open`,h=`${po.keyPrefix}widget-voice`,y=`${po.keyPrefix}widget-voice-mode`;if(c){let M=((Ed=po.persist)==null?void 0:Ed.openState)&&c.getItem(p)==="true",F=((Md=po.persist)==null?void 0:Md.voiceState)&&c.getItem(h)==="true",N=((Ld=po.persist)==null?void 0:Ld.voiceState)&&c.getItem(y)==="true";if(M&&setTimeout(()=>{cn.open(),setTimeout(()=>{var z;if(F||N)cn.startVoiceRecognition();else if((z=po.persist)!=null&&z.focusInput){let O=e.querySelector("textarea");O&&O.focus()}},100)},0),(Id=po.persist)!=null&&Id.openState&&(s.on("widget:opened",()=>{c.setItem(p,"true")}),s.on("widget:closed",()=>{c.setItem(p,"false")})),(Rd=po.persist)!=null&&Rd.voiceState&&(s.on("voice:state",z=>{c.setItem(h,z.active?"true":"false")}),s.on("user:message",z=>{c.setItem(y,z.viaVoice?"true":"false")})),po.clearOnChatClear){let z=()=>{c.removeItem(p),c.removeItem(h),c.removeItem(y)},O=()=>z();window.addEventListener("persona:clear-chat",O),gt.push(()=>{window.removeEventListener("persona:clear-chat",O)})}}}return u&&A()&&setTimeout(()=>{cn.open()},0),Ko(),cn};var fw=(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},hw=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},bw=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},yw=(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.")},Og=(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=""},Fg=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",dc(e)},ic=e=>{e.style.transition=""},lc=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},cc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},zi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},vw=(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))},xw=(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)},Ng=(e,t,n,o,r,s,a)=>{var x,v,E,L,I,W;let i=To(s),d=i.reveal==="push";vw(e,t,n,o,d),xw(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=(L=(E=s==null?void 0:s.launcher)==null?void 0:E.mobileBreakpoint)!=null?L:640,f=l!=null?l.innerWidth<=g:!1;if(u&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),lc(t),ic(o),Fg(o),cc(n),zi(r,o),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String((W=(I=s==null?void 0:s.launcher)==null?void 0:I.zIndex)!=null?W:Ln),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"),Fg(o),hw(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",lc(t),ic(o),cc(n),zi(r,o);let H=i.animate?"transform 180ms ease":"none",R=i.side==="right"?"translateX(100%)":"translateX(-100%)",w=a?"translateX(0)":R;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=H,o.style.transform=w,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",i.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",ic(o),dc(o),zi(r,o);let H=fw(i.width,e.clientWidth),R=Math.max(0,e.clientWidth),w=i.animate?"margin-left 180ms ease":"none",C=i.side==="right"?a?-H:0:a?0:-H;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=`${R+H}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=`${R}px`,n.style.maxWidth=`${R}px`,n.style.minWidth=`${R}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="",lc(t),dc(o),cc(n),zi(r,o);let H=i.reveal==="emerge";H?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let R=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 ${R}`,o.style.width=R,o.style.maxWidth=R,o.style.minWidth=R,o.style.minHeight="0",bw(o,i.maxHeight),o.style.overflow=H||C?"hidden":"visible",o.style.transition=w,H&&(o.style.alignItems=i.side==="right"?"flex-start":"flex-end",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.boxSizing="border-box")}},ww=(e,t)=>{let n=e.ownerDocument.createElement("div");return Og(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Og(n,o)},destroy(){n.remove()}}},Cw=(e,t)=>{var W,H,R,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=(H=(W=t==null?void 0:t.launcher)==null?void 0:W.enabled)==null||H?(w=(R=t==null?void 0:t.launcher)==null?void 0:R.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(),To(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Ng(a,i,d,l,u,t,g)}),f.observe(a))},v=!1,E=()=>{Ng(a,i,d,l,u,t,g),x(),g&&!v&&a.dataset.personaDockMobileFullscreen!=="true"&&(v=!0,yw(a,To(t)))},L=a.ownerDocument.defaultView,I=()=>{E()};return L==null||L.addEventListener("resize",I),To(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),E(),{mode:"docked",host:u,shell:a,syncWidgetState(C){let k=C.launcherEnabled?C.open:!0;g!==k&&(g=k,E())},updateConfig(C){var k,A;t=C,((A=(k=t==null?void 0:t.launcher)==null?void 0:k.enabled)!=null?A:!0)===!1&&(g=!0),E()},destroy(){L==null||L.removeEventListener("resize",I),m(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},_g=(e,t)=>Cn(t)?Cw(e,t):ww(e,t);var xs={desktop:{w:1280,h:800},mobile:{w:390,h:844}},pc=.15,uc=1.5,qi="persona-preview-shell-theme",Vg={load:()=>null,save:()=>{},clear:()=>{}},$g=["How do I get started?","Pricing & plans","Talk to support"];function ji(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ug(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 mc(e){let t=Ug(e);return`* { box-sizing: border-box; }
1
+ var _="min(440px, calc(100vw - 24px))",Q="440px",Lt={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:_,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)"},M={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Lt,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 Bt={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"}},Dt={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"}},_t={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:_,maxWidth:Q,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 Mt(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 qe(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]=qe(n,r):o[a]=r}return o}function Wt(e,t){return t?qe(e,t):e}function S(e,t={}){var r,n,l,i,c,m,g,w,k,C,A,B,D;let o={palette:Bt,semantic:Dt,components:_t},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,...(B=e==null?void 0:e.semantic)==null?void 0:B.spacing},typography:{...o.semantic.typography,...(D=e==null?void 0:e.semantic)==null?void 0:D.typography}},components:Wt(o.components,e==null?void 0:e.components)};if(t.validate!==!1){let U=Mt(a);if(!U.valid)throw new Error(`Theme validation failed: ${U.errors.map(Ue=>Ue.message).join(", ")}`)}if(t.plugins)for(let U of t.plugins)a=U.transform(a);return a}function Re(e,t){let o=t.split("."),a=e;for(let r of o){if(a==null)return;a=a[r]}return a}function V(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]:V((i=l==null?void 0:l[r])!=null?i:{},n.join("."),o)}}var Ce=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?{...M,...o}:o!=null?o:M,this.theme=S(t,{validate:!1}),this.syncThemeIntoConfig(),this.pushHistorySnapshot(this.exportSnapshot(),!0)}get(t){var o;return t.startsWith("theme.")?Re(this.theme,t.replace("theme.","")):t.startsWith("darkTheme.")?Re((o=this.config.darkTheme)!=null?o:{},t.replace("darkTheme.","")):Re(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=V(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:V(n,r,o)}}else this.config=V(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=V(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:V(m,c,i)},a=!0}else this.config=V(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={...M},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 Ae(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 Ee(e,t){return t==="rem"?`${e}rem`:`${e}px`}function Ft(e,t){return t==="rem"?e*16:e}function Nt(e,t){return t==="rem"?e/16:e}function j(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 Ie(e){return/^#[0-9A-Fa-f]{6}$/.test(e)}function Pe(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 ee(e,t){let o=n=>{var m;let l=j(n),i=l.startsWith("rgb")?(m=Pe(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 Ye(e){var k;let t=j(e),o=t.startsWith("rgb")?(k=Pe(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 Ke(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 Ve(e){let{h:t,s:o,l:a}=Ye(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]=Ke(t,m,c)}return l}var W=["50","100","200","300","400","500","600","700","800","900","950"],Oe=["primary","secondary","accent","gray","success","warning","error","info"];function Ht(e,t){return`palette.colors.${e}.${t}`}function Ze(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.")?Ze(e,`theme.${a}`,o+1):"#cbd5e1"}function $t(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"}],te=["primary","secondary","accent","gray"],zt={primary:"Primary",secondary:"Secondary",accent:"Accent",gray:"Neutral"},oe={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"}]},ae={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"}]},re={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"}]},ne={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"}]},se={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"}]},le={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"}]},ie={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"}]},ce={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"}]},de={roleId:"role-borders",helper:"Borders, dividers, and separators",intensities:E,targets:[{path:"semantic.colors.border",kind:"border"},{path:"semantic.colors.divider",kind:"border"}]},O=[oe,ae,re,ne,se,le,ie,ce,de];function pe(e,t,o){let a={},r=e==="neutral"?"gray":e;for(let n of o.targets){let l=Ut(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 Ut(e,t,o,a){let r=t==="solid";if(a==="role-header")return jt(e,r,o);if(a==="role-input")return Gt(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 jt(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 Gt(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 qt=/^palette\.colors\.(\w+)\.(\d+)$/;function Le(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(qt);if(!r)return null;let n=r[1],l=te.includes(n)?n:null;if(!l)return null;for(let m of["solid","soft"]){let g=pe(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 Yt={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"}]}]},Kt={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"}]},Zt={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"}}]},Xt={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)"}]}]},Jt={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"}]}]},Qt={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"}}]},eo={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)"}]},to={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"}]}]},N=[Kt,Zt,Jt,Xt,Yt,Qt,eo,to];function Je(){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:Oe.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 Qe={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"}}]},oo=Je(),ao=Qe,ro=[Je(),Qe],no={id:"comp-panel",title:"Panel",collapsed:!1,fields:[{id:"panel-width",label:"Width",type:"text",path:"theme.components.panel.width",defaultValue:_},{id:"panel-max-width",label:"Max Width",type:"text",path:"theme.components.panel.maxWidth",defaultValue:Q},{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"}]}]},so={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"}]}]},lo={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"}]}]},co={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"}]}]},po={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"}}]},uo={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"}}]},mo={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"}}]},ho={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"}}]},go={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"}]},F=[{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"}],Be="0 5px 15px rgba(15, 23, 42, 0.08)",Xe=[{value:Be,label:"Default"},...F],fo={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:F},{id:"shadow-msg-assistant",label:"Assistant Message",type:"select",path:"theme.components.message.assistant.shadow",defaultValue:"palette.shadows.sm",options:F},{id:"shadow-tool-bubble",label:"Tool Call Bubble",type:"select",path:"theme.components.toolBubble.shadow",defaultValue:"palette.shadows.sm",options:F},{id:"shadow-reasoning-bubble",label:"Reasoning Bubble",type:"select",path:"theme.components.reasoningBubble.shadow",defaultValue:"palette.shadows.sm",options:F},{id:"shadow-approval",label:"Approval Bubble",type:"select",path:"theme.components.approval.requested.shadow",defaultValue:Be,options:Xe},{id:"shadow-intro-card",label:"Intro Card",type:"select",path:"theme.components.introCard.shadow",defaultValue:Be,options:Xe},{id:"shadow-composer",label:"Composer",type:"select",path:"theme.components.composer.shadow",defaultValue:"palette.shadows.none",options:F}]},et=[no,so,lo,io,co,fo],tt=[po,uo,mo,ho,go],ot=[...et,...tt],De=1024*1024,bo=["What can you help me with?","Tell me about your features","How does this work?"],G={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 yo(e){return Number(e)*De}function wo(e){let t=Number(e);return Number.isFinite(t)?t>1024?String(Math.round(t/De)):String(t):"10"}function ko(e){var t;return(t=G[String(e)])!=null?t:G.images}function xo(e){let t=Array.isArray(e)?e:G.images,o=[...new Set(t)].sort();for(let[a,r]of Object.entries(G)){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 vo={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"}]},So={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:bo}]},To={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:""}]},Ro={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}]},Co={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"}]}]},Ao={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"}]}]},Eo={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:_},{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"}]},Io={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:""}]},Po={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"}]},Vo={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"}]},Oo={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"}]},Lo={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"}]},Bo={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:""}]},Do={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)}]},_o={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*De,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:wo,parseValue:yo},{id:"attach-types",label:"Allowed File Types",type:"select",path:"attachments.allowedTypes",defaultValue:G.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:xo,parseValue:ko}]},Mo={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"}]}]},Wo={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}]},Fo={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"}]}]},No={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}]},Ho={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}]},ue=[{label:"Content",sections:[vo,So]},{label:"Layout",sections:[To,Ro,Co,Ao]},{label:"Widget",sections:[Eo,Io,Po,Vo,Oo,Lo]},{label:"Features",sections:[Bo,Do,_o,Mo,Wo]},{label:"Developer",collapsedByDefault:!0,sections:[Fo,No,Ho]}],at=ue.flatMap(e=>e.sections),rt={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"}]}]},nt={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"}]},st={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"}]},lt={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:oe},{id:"role-header",label:"Header",type:"role-assignment",path:"theme.components.header.background",roleAssignment:ae},{id:"role-user-messages",label:"User Messages",type:"role-assignment",path:"theme.components.message.user.background",roleAssignment:re},{id:"role-assistant-messages",label:"Assistant Messages",type:"role-assignment",path:"theme.components.message.assistant.background",roleAssignment:ne},{id:"role-primary-actions",label:"Primary Actions",type:"role-assignment",path:"theme.components.button.primary.background",roleAssignment:se},{id:"role-scroll-to-bottom",label:"Scroll To Bottom",type:"role-assignment",path:"theme.components.scrollToBottom.background",roleAssignment:le},{id:"role-input",label:"Input Field",type:"role-assignment",path:"theme.components.input.background",roleAssignment:ie},{id:"role-links-focus",label:"Links & Focus",type:"role-assignment",path:"theme.semantic.colors.accent",roleAssignment:ce},{id:"role-borders",label:"Borders & Dividers",type:"role-assignment",path:"theme.semantic.colors.border",roleAssignment:de}]},it={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"}}]},ct={id:"advanced-tokens",title:"Advanced Tokens",description:"Override individual semantic and component values when you need precise control.",collapsed:!0,fields:[]},$o=[rt,nt,st,lt,it,ct],_e=[{id:"style",label:"Style",sections:N},{id:"design-system",label:"Design System",sections:ot},{id:"configure",label:"Configure",sections:at}];function dt(e,t){return e.startsWith("theme.")?e.replace(/^theme\./,`${t}.`):e}function zo(e,t,o){return{...e,id:`${o}-${e.id}`,path:dt(e.path,t)}}function Uo(e,t){let o=e.find(a=>a.id===t);if(!o)throw new Error(`Section "${t}" not found in definitions`);return o}function jo(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=>zo(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])=>[dt(c,t),m]))}))}}var pt=[{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"]}],q=[...pt];function Me(e){return q.find(t=>t.id===e)}var Go={desktop:{w:1280,h:800},mobile:{w:390,h:844}},qo=.15,Yo=1.5,me="persona-preview-shell-theme",ut={load:()=>null,save:()=>{},clear:()=>{}},mt=["How do I get started?","Pricing & plans","Talk to support"];function ht(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function gt(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 We(e){let t=gt(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 oa=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 gc(e,t){let n=e.contentDocument;if(!(n!=null&&n.documentElement))return;let o=n.getElementById(qi);o||(o=n.createElement("style"),o.id=qi,n.head.appendChild(o)),o.textContent=mc(t)}var zg=`
25
+ .preview-workspace-card.short { height: 96px; }`}function Ko(e,t){let o=e.contentDocument;if(!(o!=null&&o.documentElement))return;let a=o.getElementById(me);a||(a=o.createElement("style"),a.id=me,o.head.appendChild(a)),a.textContent=We(t)}var ft=`
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 oa=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>`,qg=`
44
+ </div>`,bt=`
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 oa=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 fc(e,t,n,o){let r=`
164
- ${zg}
165
- <div style="position:fixed;inset:0;z-index:9999;"><div id="${e}" data-mount-id="${e}"></div></div>`,s=`
57
+ </div>`;function Zo(e,t,o,a){let r=`
58
+ ${ft}
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 oa=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
- ${qg}
70
+ ${bt}
177
71
  </div>
178
72
  </div>
179
73
  </div>`;return`<!DOCTYPE html>
@@ -181,24 +75,13 @@ _Details: ${n.message}_`:o}var oa=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="${ji(o)}">
185
- <style id="${qi}">${mc(t)}</style>
78
+ <link rel="stylesheet" href="${ht(a)}">
79
+ <style id="${me}">${We(t)}</style>
186
80
  </head>
187
81
  <body>
188
- ${n?s:r}
82
+ ${o?n:r}
189
83
  </body>
190
- </html>`}var Sw={"user-message":"User message","assistant-message":"Assistant message","assistant-code-block":"Assistant \u2014 code block","assistant-markdown-table":"Assistant \u2014 markdown table","assistant-image":"Assistant \u2014 image","reasoning-streaming":"Reasoning (streaming)","reasoning-complete":"Reasoning (complete)","tool-running":"Tool call (running)","tool-complete":"Tool call (complete)","approval-request":"Approval request"};function Aw(e){return Sw[e]}function hc(e,t=0){let n=new Date(Date.now()-Math.max(0,60-t)*1e3).toISOString(),o=`${e}-${t}`;switch(e){case"user-message":return{id:`preview-seq-user-${o}`,role:"user",content:"Can you continue with the next step?",createdAt:n};case"assistant-message":return{id:`preview-seq-assistant-${o}`,role:"assistant",content:"Absolutely. I can keep going and explain what happens next.",createdAt:n};case"assistant-code-block":return{id:`preview-seq-assistant-code-${o}`,role:"assistant",content:["Here's how you'd wire up a streaming animation:","","```ts","import { createAgentExperience } from '@runtypelabs/persona';","","createAgentExperience(el, {"," features: {",' streamAnimation: { type: "letter-rise", speed: 120 },'," },","});","```","","Swap the `type` value to try the other presets."].join(`
191
- `),createdAt:n};case"assistant-markdown-table":return{id:`preview-seq-assistant-table-${o}`,role:"assistant",content:["Here are the built-in streaming animations at a glance:","","| Preset | Wrap unit | Best for |","| ------------ | --------- | --------------------------- |","| Typewriter | Character | Classic terminal feel |","| Letter rise | Character | Soft, staggered entrance |","| Word fade | Word | Longer-form assistant replies |","| Pop bubble | Bubble | Short, punchy affirmations |"].join(`
192
- `),createdAt:n};case"assistant-image":return{id:`preview-seq-assistant-image-${o}`,role:"assistant",content:["Here's the reference diagram you asked for \u2014 let me know if you'd like a different view:","","![Stream animation reference](https://placehold.co/320x200/png?text=Stream+Animation)","","The gradient shows how per-unit delays stagger across the reply."].join(`
193
- `),createdAt:n};case"reasoning-streaming":return{id:`preview-seq-reasoning-stream-${o}`,role:"assistant",content:"",createdAt:n,streaming:!0,variant:"reasoning",reasoning:{id:`preview-reasoning-stream-${o}`,status:"streaming",chunks:["Thinking through the next step in the workflow..."]}};case"reasoning-complete":return{id:`preview-seq-reasoning-complete-${o}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"reasoning",reasoning:{id:`preview-reasoning-complete-${o}`,status:"complete",chunks:["Reviewed the requirements and finalized the reasoning output."],durationMs:1200}};case"approval-request":{let r=`preview-approval-${o}`;return{id:`approval-${r}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"approval",approval:{id:r,status:"pending",agentId:"preview-agent",executionId:`preview-exec-${o}`,toolName:"add_to_cart",description:"Add the selected item to the shopping cart. Approve to let the assistant continue.",parameters:{items:[{productEntityId:129,quantity:1}]}}}}case"tool-complete":return{id:`preview-seq-tool-complete-${o}`,role:"assistant",content:"",createdAt:n,streaming:!1,variant:"tool",toolCall:{id:`preview-tool-complete-${o}`,name:"Create build instructions",status:"complete",chunks:["Prepared the build instructions and validated the inputs."],result:{ok:!0},duration:420}};default:return{id:`preview-seq-tool-running-${o}`,role:"assistant",content:"",createdAt:n,streaming:!0,variant:"tool",toolCall:{id:`preview-tool-running-${o}`,name:"Get platform documentation",status:"running",chunks:["Fetching the relevant platform documentation..."]}}}}function Tw(e,t){return[...e,hc(t,e.length)]}function jg(e){return e==="assistant-message"||e==="assistant-code-block"||e==="assistant-markdown-table"||e==="assistant-image"}function kw(e,t,n){var d,l;let o=hc(e,t);if(!jg(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 Ew=()=>[{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()}],Mw=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 Kg(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"&&Mw(t)?[...Ew(),...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 bc(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:$g:e.suggestionChips,initialMessages:Kg(t,e,n),storageAdapter:Vg};return t==="artifact"&&(r.features={...r.features,artifacts:{...(a=r.features)==null?void 0:a.artifacts,enabled:!0}}),r}function Ur(e,t){var s,a,i,d;let n=e.theme?pn(e.theme,{validate:!1}):pn(),o=(s=e.scene)!=null?s:"conversation",r={...Mt,...e.config,theme:n,darkTheme:e.darkTheme,colorScheme:(i=t!=null?t:(a=e.config)==null?void 0:a.colorScheme)!=null?i:"light"};return bc(r,o,(d=e.appendedMessages)!=null?d:[])}function Lw(e,t,n){var a,i,d;let o=e.theme?pn(e.theme,{validate:!1}):pn(),r=(a=e.scene)!=null?a:"conversation",s={...Mt,...e.config,theme:o,darkTheme:e.darkTheme,colorScheme:(d=n!=null?n:(i=e.config)==null?void 0:i.colorScheme)!=null?d:"light"};return bc(s,r,t)}function Gg(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:Ur(e,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Ur(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:Ur(d,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Ur(e,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Ur(e,n),shellMode:n}]}function Iw(e,t){let n={...t},o=[],r=[],s=null,a=!1,i=1,d=1,l=0;function u(){var I;return(I=n.device)!=null?I:"desktop"}function g(){var I;return(I=n.zoom)!=null?I:i}function f(){var S,_;let I=getComputedStyle(e),W=parseFloat(I.paddingLeft)+parseFloat(I.paddingRight),H=parseFloat(I.paddingTop)+parseFloat(I.paddingBottom),R=40,w=((S=n.compareMode)!=null?S:"off")!=="off",C=(e.clientWidth-W-R)/(w?2:1),k=e.clientHeight-H-R;if(C<=0||k<=0)return 1;let A=(_=xs[u()])!=null?_:xs.desktop;return Math.min(C/A.w,k/A.h,1)}function m(){var H,R,w;i=f();let I=Math.max(pc,Math.min(uc,g()));d=I;let W=Array.from(e.querySelectorAll(".preview-iframe-wrapper"));for(let C of W){let k=(H=C.dataset.device)!=null?H:"desktop",A=(R=xs[k])!=null?R:xs.desktop;C.style.width=`${A.w*I}px`,C.style.height=`${A.h*I}px`,k==="mobile"&&(C.style.borderRadius=`${32*I}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(${I})`)}(w=n.onScaleChange)==null||w.call(n,I)}function x(){var I;(I=n.onBeforeDestroy)==null||I.call(n);for(let W of o)W.destroy();for(let W of r)W();o=[],r=[]}function v(){return Array.from(e.querySelectorAll("iframe[data-mount-id]"))}function E(){var ce,ke,ve,He;if(a)return;x();let I=++l,W=Gg(n),H=u(),R=((ce=n.compareMode)!=null?ce:"off")!=="off",w=((ke=n.scene)!=null?ke:"conversation")==="minimized",C=(ve=n.widgetCssPath)!=null?ve:"/widget-dist/widget.css",k=(He=n.buildSrcdoc)!=null?He:fc,A=H==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",S=Se=>`<div class="${A}" data-mount-id="${Se.mountId}" data-device="${H}" data-shell-mode="${Se.shellMode}">
194
- ${R?`<div class="preview-frame-meta"><span class="preview-frame-label">${ji(Se.label)}</span></div>`:""}
195
- <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${Se.mountId}"></iframe>
196
- </div>`,_=R?`<div class="preview-compare-grid">${W.map(Se=>`<div class="preview-compare-cell">${S(Se)}</div>`).join("")}</div>`:`<div class="preview-single">${S(W[0])}</div>`;n.morphContainer?n.morphContainer(e,_):e.innerHTML=_,m();let V=v(),K=0,fe=V.length,ue=()=>{var ie,Q,re,be,he;if(a||I!==l)return;for(let j of V){let se=j.dataset.mountId;if(!se||!j.contentDocument)continue;let Re=W.find(it=>it.mountId===se);if(!Re)continue;let ne=()=>{},Z=Cn(Re.config),oe=Z?(()=>{var q;let it=(q=j.contentDocument)==null?void 0:q.getElementById(`preview-content-${se}`);if(!it)return null;let Le=_g(it,Re.config),de=j.contentDocument.createElement("div");de.id=se,de.style.height="100%",de.style.display="flex",de.style.flexDirection="column",de.style.flex="1",de.style.minHeight="0",Le.host.appendChild(de);let Qe=()=>Le.syncWidgetState(at.getState()),We=ne;return ne=()=>{Le.destroy(),We()},de.__syncDock=Qe,de.__hostLayout=Le,de})():j.contentDocument.getElementById(se);if(!oe)continue;let at=Dg(oe,Re.config);if(o.push(at),Z&&oe.__syncDock){let it=oe.__syncDock,Le=at.on("widget:opened",it),de=at.on("widget:closed",it),Qe=ne;ne=()=>{Le(),de(),Qe()},it()}r.push(ne),w&&at.close()}if(((ie=n.scene)!=null?ie:"conversation")==="artifact"||(be=(re=(Q=n.config)==null?void 0:Q.features)==null?void 0:re.artifacts)!=null&&be.enabled)for(let j of o)j.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
197
-
198
- This is a preview of the artifact sidebar.
199
-
200
- ## Features
201
-
202
- - Markdown rendering
203
- - Document toolbar
204
- - Resizable panes`});(he=n.onAfterMount)==null||he.call(n,{iframes:V,controllers:[...o]})};for(let Se of V){let ie=Se.dataset.mountId;if(!ie)continue;let Q=W.find(re=>re.mountId===ie);Q&&(Se.addEventListener("load",()=>{K++,K>=fe&&ue()},{once:!0}),Se.srcdoc=k(ie,Q.shellMode,Cn(Q.config),C))}fe===0&&ue()}function L(){var H;if(a)return;let I=Gg(n);if(o.length!==I.length){E();return}if(I.some(R=>{let w=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${R.mountId}"]`);return!w||w.dataset.shellMode!==R.shellMode})){E();return}o.forEach((R,w)=>{var C;R.update(I[w].config),((C=n.scene)!=null?C:"conversation")==="minimized"&&R.close()});for(let R of I){let w=e.querySelector(`iframe[data-mount-id="${R.mountId}"]`);w&&gc(w,R.shellMode)}(H=n.onAfterUpdate)==null||H.call(n,{iframes:v(),controllers:[...o]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||m()}),s.observe(e)),E(),{update(I){if(a)return;let W=I.device!==void 0&&I.device!==n.device||I.scene!==void 0&&I.scene!==n.scene||I.compareMode!==void 0&&I.compareMode!==n.compareMode||I.widgetCssPath!==void 0&&I.widgetCssPath!==n.widgetCssPath;n={...n,...I},W?E():L()},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(I){a||(n={...n,zoom:I},m())}}}function Jo(e){return{content:[{type:"text",text:JSON.stringify(e)}],structuredContent:e}}var Gi={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"},Rw=/^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 Pw(e){return Rw.test(e)}function ws(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=Gi[t];if(n)return n;let o=zs(t);if(gl(o)||o==="transparent"||Pw(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(Gi).slice(0,6).join(", ")}).`)}var Yi=Ua.map(e=>e==="gray"?"neutral":e),Ww={...Object.fromEntries(Yi.map(e=>[e,e])),gray:"neutral",grey:"neutral"};function Qi(e,t=!0){let n=String(e!=null?e:"").trim().toLowerCase(),o=Ww[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 Xi(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 Ji(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 Bw={sharp:"sharp",square:"sharp",none:"sharp",default:"default",normal:"default",rounded:"rounded",round:"rounded",soft:"rounded",pill:"pill",circle:"pill",full:"pill"};function Zi(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=Bw[t];if(!n)throw new Error(`Unknown roundness "${e}". Valid: sharp, default, rounded, pill.`);return n}function el(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=ul(t);return ml(n.value,n.unit)}throw new Error('Radius must be a number (px) or a CSS length string like "0.5rem".')}function tl(e){for(let t of cs){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 Yg=tl("typo-font-family"),va=tl("typo-font-size"),xa=tl("typo-font-weight"),Ki=tl("typo-line-height"),Qg={...Yg,monospace:Yg.mono},Xg={...va,small:va.sm,md:va.base,medium:va.base,large:va.lg},Jg={...xa,400:xa.normal,500:xa.medium,600:xa.semibold,700:xa.bold},Zg={...Ki,"1.25":Ki.tight,"1.5":Ki.normal,"1.625":Ki.relaxed};function ef(e,t,n){let o=String(e!=null?e:"").trim().toLowerCase(),r=t[o];if(!r){let s=[...new Set(Object.values(t).map(a=>a.split(".").pop()))].join(", ");throw new Error(`Unknown ${n} "${e}". Valid: ${s}.`)}return r}var tf="theme.palette.radius.";function Hw(){var t;let e={pill:{sm:"9999px",md:"9999px",lg:"9999px",xl:"9999px",full:"9999px"}};for(let n of cs)for(let o of(t=n.presets)!=null?t:[]){let r=o.id.match(/^radius-(\w+)$/);if(!r)continue;let s={};for(let[a,i]of Object.entries(o.values))a.startsWith(tf)&&typeof i=="string"&&(s[a.slice(tf.length)]=i);e[r[1]]=s}return e}var Ca=Hw(),nf=["sm","md","lg","xl","full"];function ol(e,t,n="theme",o=0){if(o>6)return null;let r=e.get(`${n}.${t}`);return typeof r!="string"||r===""?n==="darkTheme"?ol(e,t,"theme",o):null:r.startsWith("#")||r.startsWith("rgb")||r==="transparent"?r:r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components.")?ol(e,r,n,o+1):null}function nl(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 Cs(e){return e.replace(/^role-/,"")}function Dw(e){for(let[t,n]of Object.entries(Ca))if(nf.every(o=>e[o]===n[o]))return t;return"custom"}function zr(e){var o,r;let t={};for(let s of nf)t[s]=String((o=e.get(`theme.palette.radius.${s}`))!=null?o:"");let n={};for(let s of Wr)n[Cs(s.roleId)]=yl(a=>e.get(`theme.${a}`),s);return{brand:{primary:yc(e.get("theme.palette.colors.primary.500")),secondary:yc(e.get("theme.palette.colors.secondary.500")),accent:yc(e.get("theme.palette.colors.accent.500"))},roles:n,typography:{fontFamily:nl(e,"theme.semantic.typography.fontFamily"),fontSize:nl(e,"theme.semantic.typography.fontSize"),fontWeight:nl(e,"theme.semantic.typography.fontWeight"),lineHeight:nl(e,"theme.semantic.typography.lineHeight")},roundness:{style:Dw(t),radius:t},colorScheme:String((r=e.get("colorScheme"))!=null?r:"light"),history:{index:e.getHistoryIndex(),canUndo:e.canUndo(),canRedo:e.canRedo()}}}function yc(e){return typeof e=="string"&&e!==""?e:null}var wa=[{key:"user-message",label:"User message text",fg:"components.message.user.text",bg:"components.message.user.background"},{key:"assistant-message",label:"Assistant message text",fg:"components.message.assistant.text",bg:"components.message.assistant.background"},{key:"header",label:"Header title",fg:"components.header.titleForeground",bg:"components.header.background"},{key:"primary-button",label:"Primary button label",fg:"components.button.primary.foreground",bg:"components.button.primary.background"},{key:"input",label:"Input placeholder",fg:"components.input.placeholder",bg:"components.input.background"},{key:"link",label:"Link text",fg:"components.markdown.link.foreground",bg:"semantic.colors.background"},{key:"scroll",label:"Scroll-to-bottom icon",fg:"components.scrollToBottom.foreground",bg:"components.scrollToBottom.background"},{key:"body",label:"Body text on background",fg:"semantic.colors.text",bg:"semantic.colors.background"},{key:"surface",label:"Body text on surface",fg:"semantic.colors.text",bg:"semantic.colors.surface"}];function of(e){let t=new Set(e.targets.map(n=>n.path));return wa.filter(n=>t.has(n.fg)||t.has(n.bg)).map(n=>n.key)}var Ow={AA:4.5,AAA:7};function Fw(e){return Math.round(e*100)/100}function Nw(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=is.indexOf(a[2]),l=null,u=1/0;return is.forEach((g,f)=>{let m=e.get(`${r}.palette.colors.${i}.${g}`);if(!(typeof m!="string"||!(m.startsWith("#")||m.startsWith("rgb")))&&$a(m,n)>=o){let x=d>=0?Math.abs(f-d):f;x<u&&(u=x,l=`palette.colors.${i}.${g}`)}}),l}function Sa(e,t="AA",n="both",o){let r=Ow[t],s=n==="both"?["light","dark"]:[n],a=o?wa.filter(d=>o.includes(d.key)):wa,i=[];for(let d of s){let l=d==="light"?"theme":"darkTheme";for(let u of a){let g=ol(e,u.fg,l),f=ol(e,u.bg,l);if(!g||!f)continue;let m=Fw($a(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 E=Nw(e,u.fg,f,r,l);E&&(v.suggestion=E)}i.push(v)}}return{level:t,checks:i,failures:i.filter(d=>!d.passes)}}function Ss(e,t,n="light",o="AA"){return t.length===0?[]:Sa(e,o,n,t).failures.map(s=>({code:"contrast",pair:s.pair,variant:s.variant,ratio:s.ratio,threshold:s.threshold,message:`${s.label} (${s.variant}) has a contrast ratio of ${s.ratio}:1, below the ${o} threshold of ${s.threshold}:1${s.suggestion?`. Try ${s.suggestion} for the foreground.`:"."}`}))}var hn={};for(let e of Wr){let t=Cs(e.roleId);hn[t]=e,hn[e.roleId]=e}Object.assign(hn,{surface:hn.surfaces,background:hn.surfaces,backgrounds:hn.surfaces,user:hn["user-messages"],"user-message":hn["user-messages"],assistant:hn["assistant-messages"],"assistant-message":hn["assistant-messages"],actions:hn["primary-actions"],buttons:hn["primary-actions"],composer:hn.input,links:hn["links-focus"],focus:hn["links-focus"],border:hn.borders,dividers:hn.borders,scroll:hn["scroll-to-bottom"]});function _w(e){let t=String(e!=null?e:"").trim().toLowerCase(),n=hn[t];if(!n){let o=Wr.map(r=>Cs(r.roleId)).join(", ");throw new Error(`Unknown role "${e}". Valid roles: ${o}.`)}return n}function rf(){let e=new Map,t=n=>{for(let o of n)for(let r of o.fields)e.has(r.id)||e.set(r.id,r)};for(let n of wl)t(n.sections);for(let n of ei)t(n.sections);return e}var Vw={voice:"voiceRecognition.enabled",artifacts:"features.artifacts.enabled",attachments:"attachments.enabled",toolCalls:"features.showToolCalls",reasoning:"features.showReasoning",feedback:"messageActions.enabled"},$w={avatars:"layout.messages.avatar.show",timestamps:"layout.messages.timestamp.show",showHeader:"layout.showHeader",messageStyle:"layout.messages.layout"},vc=["bottom-right","bottom-left","top-right","top-left"],xc=["bubble","flat","minimal"],Uw={title:"copy.welcomeTitle",subtitle:"copy.welcomeSubtitle",placeholder:"copy.inputPlaceholder",sendLabel:"copy.sendButtonLabel"};function sf(e,t){var R;let n=(R=t==null?void 0:t.editTarget)!=null?R:"both",o=null,r=w=>w&&typeof w=="object"?w:{},s=(w,C,k=n)=>{let A={};return(k==="light"||k==="both")&&(A[`theme.${w}`]=C),(k==="dark"||k==="both")&&(A[`darkTheme.${w}`]=C),A},a=w=>{if(n==="both")return w;let C={};for(let[k,A]of Object.entries(w))(n==="light"&&k.startsWith("theme.")||n==="dark"&&k.startsWith("darkTheme."))&&(C[k]=A);return C},i=()=>n==="dark"?"dark":"light",d=(w,C=[])=>Jo({ok:!0,summary:zr(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),k={summary:zr(e),availableRoles:Wr.map(A=>({role:Cs(A.roleId),helper:A.helper})),availableFamilies:Yi,presets:js.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=rf()),k.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(_=>_.value)}})),Jo(k)}},{name:"set_brand_colors",title:"Set brand colors",description:'Set one or more brand colors (primary, secondary, accent). Each color auto-generates a full 50\u2013950 shade scale and applies to the light and dark themes (per the current edit target). Accepts hex ("#2563eb", "2563eb", "#18f"), rgb()/rgba() ("rgb(37, 99, 235)"), or CSS color names ("blue", "slateblue").',inputSchema:{type:"object",properties:{primary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},secondary:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."},accent:{type:"string",description:"Hex, rgb()/rgba(), or CSS color name."}},additionalProperties:!1},execute(w){let C=r(w),k=["primary","secondary","accent"],A={},S={};for(let V of k){if(C[V]===void 0)continue;let K=ws(C[V]);S[V]=K;let fe=hl(K);for(let ue of is){let ce=fe[ue];ce!==void 0&&Object.assign(A,s(`palette.colors.${V}.${ue}`,ce))}}if(Object.keys(S).length===0)throw new Error("Provide at least one of: primary, secondary, accent.");e.setBatch(A);let _=Ss(e,["primary-button","user-message"],i());return d(S,_)}},{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:Yi},intensity:{type:"string",enum:["solid","soft"],description:"Defaults to 'solid'."}},required:["role","family"],additionalProperties:!1},execute(w){let C=r(w),k=_w(C.role),A=Qi(C.family,!0),S=Xi(C.intensity),_=a(Za(A,S,k)),V=Object.keys(_).length;e.setBatch(_);let K=Ss(e,of(k),i());return d({role:Cs(k.roleId),family:A,intensity:S,tokensWritten:V},K)}},{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),k={},A={},S=(_,V)=>{var fe;if(C[_]===void 0)return;let K=ef(C[_],V,_);A[_]=(fe=K.split(".").pop())!=null?fe:K,Object.assign(k,s(`semantic.typography.${_}`,K))};if(S("fontFamily",Qg),S("fontSize",Xg),S("fontWeight",Jg),S("lineHeight",Zg),Object.keys(A).length===0)throw new Error("Provide at least one of: fontFamily, fontSize, fontWeight, lineHeight.");return e.setBatch(k),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),k={},A={};if(C.style!==void 0){let S=Zi(C.style);A.style=S;for(let[_,V]of Object.entries(Ca[S]))Object.assign(k,s(`palette.radius.${_}`,V))}if(C.radius!==void 0){let S=r(C.radius),_={};for(let V of["sm","md","lg","xl","full"]){if(S[V]===void 0)continue;let K=el(S[V]);_[V]=K,Object.assign(k,s(`palette.radius.${V}`,K))}A.radius=_}if(Object.keys(k).length===0)throw new Error("Provide `style` (sharp|default|rounded|pill) or a `radius` object.");return e.setBatch(k),d(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),k={};if(C.scheme!==void 0){let A=Ji(C.scheme);e.set("colorScheme",A),k.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,k.editTarget=A}if(Object.keys(k).length===0)throw new Error("Provide `scheme` and/or `editTarget`.");return Jo({ok:!0,summary:zr(e),warnings:[],applied:k,editTarget:n})}},{name:"apply_preset",title:"Apply a built-in theme preset",description:"Apply a complete built-in preset, replacing theme tokens. Call get_theme_overview to list preset ids.",inputSchema:{type:"object",properties:{presetId:{type:"string"}},required:["presetId"],additionalProperties:!1},execute(w){let{presetId:C}=r(w),k=Cl(String(C!=null?C:""));if(!k){let V=js.map(K=>K.id).join(", ");throw new Error(`Unknown preset "${C}". Valid presets: ${V}.`)}let A=pn(k.theme,{validate:!1}),S={...e.getConfig()};k.darkTheme&&(S.darkTheme=pn(k.darkTheme,{validate:!1})),k.toolCall&&(S.toolCall=k.toolCall),e.setFullConfig(S,A);let _=Ss(e,["body","assistant-message"],"light");return d({appliedPreset:{id:k.id,name:k.name}},_)}},{name:"configure_widget",title:"Configure launcher, features, and layout",description:"Toggle non-theme widget configuration. launcherPosition: bottom-right|bottom-left|top-right|top-left. features: { voice, artifacts, attachments, toolCalls, reasoning, feedback } booleans. layout: { avatars, timestamps, showHeader } booleans and messageStyle: bubble|flat|minimal.",inputSchema:{type:"object",properties:{launcherPosition:{type:"string",enum:vc},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:xc}},additionalProperties:!1}},additionalProperties:!1},execute(w){var V,K,fe;let C=r(w),k={},A={};if(C.launcherPosition!==void 0){let ue=String(C.launcherPosition);if(!vc.includes(ue))throw new Error(`Unknown launcherPosition "${ue}". Valid: ${vc.join(", ")}.`);k["launcher.position"]=ue,A.launcherPosition=ue}let S=r(C.features);for(let[ue,ce]of Object.entries(Vw))S[ue]!==void 0&&(k[ce]=!!S[ue],(V=A.features)!=null||(A.features={}),A.features[ue]=!!S[ue]);let _=r(C.layout);for(let[ue,ce]of Object.entries($w))if(_[ue]!==void 0)if(ue==="messageStyle"){let ke=String(_[ue]);if(!xc.includes(ke))throw new Error(`Unknown messageStyle "${ke}". Valid: ${xc.join(", ")}.`);k[ce]=ke,(K=A.layout)!=null||(A.layout={}),A.layout[ue]=ke}else k[ce]=!!_[ue],(fe=A.layout)!=null||(A.layout={}),A.layout[ue]=!!_[ue];if(Object.keys(k).length===0)throw new Error("Provide launcherPosition, features, and/or layout.");return e.setBatch(k),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),k={},A={};for(let[S,_]of Object.entries(Uw))C[S]!==void 0&&(k[_]=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(_=>typeof _=="string");k.suggestionChips=S,A.suggestions=S}if(Object.keys(k).length===0)throw new Error("Provide at least one of: title, subtitle, placeholder, sendLabel, suggestions.");return e.setBatch(k),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 _;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=rf());let k={},A=[];for(let V of C){let K=r(V),fe=String((_=K.field)!=null?_:"");try{let ue=o.get(fe),ce=ue?ue.path:fe;if(!ue&&!/^(theme|darkTheme)\.|\./.test(ce))throw new Error(`Unknown field "${fe}". Pass a known field id or a dot-path (e.g. theme.palette.radius.md).`);let ke=zw(ue,K.value);if(ue&&ce.startsWith("theme.")){let ve=s(ce.slice(6),ke);Object.assign(k,ve),A.push({field:fe,resolvedPath:Object.keys(ve),ok:!0})}else k[ce]=ke,A.push({field:fe,resolvedPath:ce,ok:!0})}catch(ue){A.push({field:fe,ok:!1,error:ue.message})}}let S=A.filter(V=>V.ok);return Object.keys(k).length>0&&e.setBatch(k),Jo({ok:S.length>0,summary:zr(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),k=C.level==="AAA"?"AAA":"AA",A=C.variant==="light"||C.variant==="dark"?C.variant:"both",S=Sa(e,k,A);return Jo({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 Jo({ok:!0,snapshot:e.exportSnapshot()});default:throw new Error(`Unknown action "${C}". Valid: undo, redo, reset, export.`)}}}]}function zw(e,t){if(!e)return t;switch(e.type){case"color":return e.parseValue?e.parseValue(ws(t)):ws(t);case"toggle":return typeof t=="boolean"?t:t==="true"||t===1;case"slider":{let n=Number(t);if(!Number.isFinite(n))throw new Error(`"${e.id}" expects a number.`);if(e.slider){let{min:o,max:r}=e.slider;if(n<o||n>r)throw new Error(`"${e.id}" must be between ${o} and ${r}.`)}return e.parseValue?e.parseValue(n):n}case"select":{let n=String(t);if(e.options&&!e.options.some(o=>o.value===n))throw new Error(`"${e.id}" must be one of: ${e.options.map(o=>o.value).join(", ")}.`);return e.parseValue?e.parseValue(n):n}default:return e.parseValue?e.parseValue(t):t}}export{em as ADVANCED_TOKENS_SECTION,Wr as ALL_ROLES,wl as ALL_TABS,Qu as BRAND_PALETTE_SECTION,nm as BUILT_IN_PRESETS,Uf as COLORS_SECTIONS,bl as COLOR_FAMILIES,Ku as COMPONENTS_SECTIONS,ju as COMPONENT_COLOR_SECTIONS,qu as COMPONENT_SHAPE_SECTIONS,Gu as CONFIGURE_SECTIONS,ei as CONFIGURE_SUB_GROUPS,wa as CONTRAST_PAIRS,Gi as CSS_NAMED_COLORS,xs as DEVICE_DIMENSIONS,$g as HOME_SUGGESTION_CHIPS,Ju as INTERFACE_ROLES_SECTION,zg as MOCK_BROWSER_CONTENT,qg as MOCK_WORKSPACE_CONTENT,Vf as PALETTE_SECTION,Vg as PREVIEW_STORAGE_ADAPTER,Ca as RADIUS_PRESETS,Ka as ROLE_ASSISTANT_MESSAGES,Ja as ROLE_BORDERS,Ua as ROLE_FAMILIES,Mf as ROLE_FAMILY_LABELS,qa as ROLE_HEADER,Qa as ROLE_INPUT,Oo as ROLE_INTENSITIES,Xa as ROLE_LINKS_FOCUS,Ga as ROLE_PRIMARY_ACTIONS,Ya as ROLE_SCROLL_TO_BOTTOM,za as ROLE_SURFACES,ja as ROLE_USER_MESSAGES,$f as SEMANTIC_COLORS_SECTION,is as SHADE_KEYS,qi as SHELL_STYLE_ID,Zu as STATUS_COLORS_SECTION,Xu as STATUS_PALETTE_SECTION,cs as STYLE_SECTIONS,kh as STYLE_SECTIONS_V2,js as THEME_EDITOR_PRESETS,Yu as THEME_SECTION,pl as ThemeEditorState,uc as ZOOM_MAX,pc as ZOOM_MIN,Tw as appendPreviewTranscriptEntry,bc as applySceneConfig,gc as applyShellTheme,Ur as buildPreviewConfig,Lw as buildPreviewConfigWithMessages,mc as buildShellCss,fc as buildSrcdoc,zr as buildSummary,kw as buildTranscriptStreamFrames,ws as coerceColor,Qi as coerceFamily,Xi as coerceIntensity,el as coerceRadius,Zi as coerceRoundnessStyle,Ji as coerceScheme,Tf as convertFromPx,Af as convertToPx,Kg as createPreviewMessages,hc as createPreviewTranscriptEntry,sf as createThemeEditorTools,Iw as createThemePreview,yl as detectRoleAssignment,ji as escapeHtml,Mh as findSection,ml as formatCssValue,hl as generateColorScale,Aw as getPreviewTranscriptPresetLabel,Ug as getShellPalette,Cl as getThemeEditorPreset,Nu as hexToHsl,_u as hslToHex,gl as isValidHex,zs as normalizeColorValue,kf as paletteColorPath,ul as parseCssValue,jg as presetStreamsText,Ss as quickContrastWarnings,Za as resolveRoleAssignment,Vu as resolveThemeColorPath,fl as rgbToHex,Sa as runContrastChecks,Lh as scopeSection,Ef as tokenRefDisplayName,Jo as toolResult,$a as wcagContrastRatio};
84
+ </html>`}var Xo={"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 Jo(e){return Xo[e]}function Fe(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:","","![Stream animation reference](https://placehold.co/320x200/png?text=Stream+Animation)","","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 Qo(e,t){return[...e,Fe(t,e.length)]}function yt(e){return e==="assistant-message"||e==="assistant-code-block"||e==="assistant-markdown-table"||e==="assistant-image"}function ea(e,t,o){var c,m;let a=Fe(e,t);if(!yt(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 ta=()=>[{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()}],oa=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 wt(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"&&oa(t)?[...ta(),...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 Ne(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:mt:e.suggestionChips,initialMessages:wt(t,e,o),storageAdapter:ut};return t==="artifact"&&(r.features={...r.features,artifacts:{...(l=r.features)==null?void 0:l.artifacts,enabled:!0}}),r}function kt(e,t){var a,r;let o=e.theme?S(e.theme,{validate:!1}):S();return{...M,...e.config,theme:o,darkTheme:e.darkTheme,colorScheme:(r=t!=null?t:(a=e.config)==null?void 0:a.colorScheme)!=null?r:"light"}}function aa(e,t){var a,r;let o=(a=e.scene)!=null?a:"conversation";return Ne(kt(e,t),o,(r=e.appendedMessages)!=null?r:[])}function ra(e,t,o){var r;let a=(r=e.scene)!=null?r:"conversation";return Ne(kt(e,o),a,t)}function I(e){return{content:[{type:"text",text:JSON.stringify(e)}],structuredContent:e}}var ge={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"},na=/^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 sa(e){return na.test(e)}function H(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=ge[t];if(o)return o;let a=j(t);if(Ie(a)||a==="transparent"||sa(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(ge).slice(0,6).join(", ")}).`)}var fe=te.map(e=>e==="gray"?"neutral":e),la={...Object.fromEntries(fe.map(e=>[e,e])),gray:"neutral",grey:"neutral"};function be(e,t=!0){let o=String(e!=null?e:"").trim().toLowerCase(),a=la[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 ye(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 we(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 ia={sharp:"sharp",square:"sharp",none:"sharp",default:"default",normal:"default",rounded:"rounded",round:"rounded",soft:"rounded",pill:"pill",circle:"pill",full:"pill"};function ke(e){let t=String(e!=null?e:"").trim().toLowerCase(),o=ia[t];if(!o)throw new Error(`Unknown roundness "${e}". Valid: sharp, default, rounded, pill.`);return o}function xe(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=Ae(t);return Ee(o.value,o.unit)}throw new Error('Radius must be a number (px) or a CSS length string like "0.5rem".')}function ve(e){for(let t of N){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 xt=ve("typo-font-family"),Y=ve("typo-font-size"),K=ve("typo-font-weight"),he=ve("typo-line-height"),vt={...xt,monospace:xt.mono},St={...Y,small:Y.sm,md:Y.base,medium:Y.base,large:Y.lg},Tt={...K,400:K.normal,500:K.medium,600:K.semibold,700:K.bold},Rt={...he,"1.25":he.tight,"1.5":he.normal,"1.625":he.relaxed};function Ct(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 At="theme.palette.radius.";function ca(){var t;let e={pill:{sm:"9999px",md:"9999px",lg:"9999px",xl:"9999px",full:"9999px"}};for(let o of N)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(At)&&typeof i=="string"&&(n[l.slice(At.length)]=i);e[r[1]]=n}return e}var X=ca(),Et=["sm","md","lg","xl","full"];function Te(e,t,o="theme",a=0){if(a>6)return null;let r=e.get(`${o}.${t}`);return typeof r!="string"||r===""?o==="darkTheme"?Te(e,t,"theme",a):null:r.startsWith("#")||r.startsWith("rgb")||r==="transparent"?r:r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components.")?Te(e,r,o,a+1):null}function Se(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 $(e){return e.replace(/^role-/,"")}function da(e){for(let[t,o]of Object.entries(X))if(Et.every(a=>e[a]===o[a]))return t;return"custom"}function L(e){var a,r;let t={};for(let n of Et)t[n]=String((a=e.get(`theme.palette.radius.${n}`))!=null?a:"");let o={};for(let n of O)o[$(n.roleId)]=Le(l=>e.get(`theme.${l}`),n);return{brand:{primary:He(e.get("theme.palette.colors.primary.500")),secondary:He(e.get("theme.palette.colors.secondary.500")),accent:He(e.get("theme.palette.colors.accent.500"))},roles:o,typography:{fontFamily:Se(e,"theme.semantic.typography.fontFamily"),fontSize:Se(e,"theme.semantic.typography.fontSize"),fontWeight:Se(e,"theme.semantic.typography.fontWeight"),lineHeight:Se(e,"theme.semantic.typography.lineHeight")},roundness:{style:da(t),radius:t},colorScheme:String((r=e.get("colorScheme"))!=null?r:"light"),history:{index:e.getHistoryIndex(),canUndo:e.canUndo(),canRedo:e.canRedo()}}}function He(e){return typeof e=="string"&&e!==""?e:null}var Z=[{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 It(e){let t=new Set(e.targets.map(o=>o.path));return Z.filter(o=>t.has(o.fg)||t.has(o.bg)).map(o=>o.key)}var pa={AA:4.5,AAA:7};function ua(e){return Math.round(e*100)/100}function ma(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=W.indexOf(l[2]),m=null,g=1/0;return W.forEach((w,k)=>{let C=e.get(`${r}.palette.colors.${i}.${w}`);if(!(typeof C!="string"||!(C.startsWith("#")||C.startsWith("rgb")))&&ee(C,o)>=a){let A=c>=0?Math.abs(k-c):k;A<g&&(g=A,m=`palette.colors.${i}.${w}`)}}),m}function J(e,t="AA",o="both",a){let r=pa[t],n=o==="both"?["light","dark"]:[o],l=a?Z.filter(c=>a.includes(c.key)):Z,i=[];for(let c of n){let m=c==="light"?"theme":"darkTheme";for(let g of l){let w=Te(e,g.fg,m),k=Te(e,g.bg,m);if(!w||!k)continue;let C=ua(ee(w,k)),A=C>=r,B={pair:g.key,label:g.label,variant:c,fg:w,bg:k,ratio:C,threshold:r,passes:A};if(!A){let D=ma(e,g.fg,k,r,m);D&&(B.suggestion=D)}i.push(B)}}return{level:t,checks:i,failures:i.filter(c=>!c.passes)}}function z(e,t,o="light",a="AA"){return t.length===0?[]:J(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 O){let t=$(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 ha(e){let t=String(e!=null?e:"").trim().toLowerCase(),o=v[t];if(!o){let a=O.map(r=>$(r.roleId)).join(", ");throw new Error(`Unknown role "${e}". Valid roles: ${a}.`)}return o}function Pt(){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 _e)t(o.sections);for(let o of ue)t(o.sections);return e}var ga={voice:"voiceRecognition.enabled",artifacts:"features.artifacts.enabled",attachments:"attachments.enabled",toolCalls:"features.showToolCalls",reasoning:"features.showReasoning",feedback:"messageActions.enabled"},fa={avatars:"layout.messages.avatar.show",timestamps:"layout.messages.timestamp.show",showHeader:"layout.showHeader",messageStyle:"layout.messages.layout"},$e=["bottom-right","bottom-left","top-right","top-left"],ze=["bubble","flat","minimal"],ba={title:"copy.welcomeTitle",subtitle:"copy.welcomeSubtitle",placeholder:"copy.inputPlaceholder",sendLabel:"copy.sendButtonLabel"};function Vt(e,t){var je;let o=(je=t==null?void 0:t.editTarget)!=null?je:"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:L(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:L(e),availableRoles:O.map(s=>({role:$(s.roleId),helper:s.helper})),availableFamilies:fe,presets:q.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=Pt()),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=H(d[y]);u[y]=x;let T=Ve(x);for(let b of W){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=z(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:fe},intensity:{type:"string",enum:["solid","soft"],description:"Default: solid."}},required:["role","family"],additionalProperties:!1},execute(h){let d=r(h),p=ha(d.role),s=be(d.family,!0),u=ye(d.intensity),f=l(pe(s,u,p)),y=Object.keys(f).length;e.setBatch(f);let x=z(e,It(p),i());return c({role:$(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=Ct(d[f],y,f);s[f]=(T=x.split(".").pop())!=null?T:x,Object.assign(p,n(`semantic.typography.${f}`,x))};if(u("fontFamily",vt),u("fontSize",St),u("fontWeight",Tt),u("lineHeight",Rt),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=ke(d.style);s.style=u;for(let[f,y]of Object.entries(X[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=xe(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=we(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:L(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=Me(String(d!=null?d:""));if(!p){let y=q.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=z(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:$e},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:ze}},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(!$e.includes(b))throw new Error(`Unknown launcherPosition "${b}". Valid: ${$e.join(", ")}.`);p["launcher.position"]=b,s.launcherPosition=b}let u=r(d.features);for(let[b,R]of Object.entries(ga))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(fa))if(f[b]!==void 0)if(b==="messageStyle"){let P=String(f[b]);if(!ze.includes(P))throw new Error(`Unknown messageStyle "${P}". Valid: ${ze.join(", ")}.`);p[R]=P,(x=s.layout)!=null||(s.layout={}),s.layout[b]=P}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(ba))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=Pt());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 P=ya(b,x.value);if(b&&R.startsWith("theme.")){let Ge=n(R.slice(6),P);Object.assign(p,Ge),s.push({field:T,resolvedPath:Object.keys(Ge),ok:!0})}else p[R]=P,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:L(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=J(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 ya(e,t){if(!e)return t;switch(e.type){case"color":return e.parseValue?e.parseValue(H(t)):H(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}}export{ct as ADVANCED_TOKENS_SECTION,O as ALL_ROLES,_e as ALL_TABS,nt as BRAND_PALETTE_SECTION,pt as BUILT_IN_PRESETS,ro as COLORS_SECTIONS,Oe as COLOR_FAMILIES,ot as COMPONENTS_SECTIONS,tt as COMPONENT_COLOR_SECTIONS,et as COMPONENT_SHAPE_SECTIONS,at as CONFIGURE_SECTIONS,ue as CONFIGURE_SUB_GROUPS,Z as CONTRAST_PAIRS,ge as CSS_NAMED_COLORS,Go as DEVICE_DIMENSIONS,mt as HOME_SUGGESTION_CHIPS,lt as INTERFACE_ROLES_SECTION,ft as MOCK_BROWSER_CONTENT,bt as MOCK_WORKSPACE_CONTENT,oo as PALETTE_SECTION,ut as PREVIEW_STORAGE_ADAPTER,X as RADIUS_PRESETS,ne as ROLE_ASSISTANT_MESSAGES,de as ROLE_BORDERS,te as ROLE_FAMILIES,zt as ROLE_FAMILY_LABELS,ae as ROLE_HEADER,ie as ROLE_INPUT,E as ROLE_INTENSITIES,ce as ROLE_LINKS_FOCUS,se as ROLE_PRIMARY_ACTIONS,le as ROLE_SCROLL_TO_BOTTOM,oe as ROLE_SURFACES,re as ROLE_USER_MESSAGES,ao as SEMANTIC_COLORS_SECTION,W as SHADE_KEYS,me as SHELL_STYLE_ID,it as STATUS_COLORS_SECTION,st as STATUS_PALETTE_SECTION,N as STYLE_SECTIONS,$o as STYLE_SECTIONS_V2,q as THEME_EDITOR_PRESETS,rt as THEME_SECTION,Ce as ThemeEditorState,Yo as ZOOM_MAX,qo as ZOOM_MIN,Qo as appendPreviewTranscriptEntry,Ne as applySceneConfig,Ko as applyShellTheme,aa as buildPreviewConfig,ra as buildPreviewConfigWithMessages,We as buildShellCss,Zo as buildSrcdoc,L as buildSummary,ea as buildTranscriptStreamFrames,H as coerceColor,be as coerceFamily,ye as coerceIntensity,xe as coerceRadius,ke as coerceRoundnessStyle,we as coerceScheme,Nt as convertFromPx,Ft as convertToPx,wt as createPreviewMessages,Fe as createPreviewTranscriptEntry,Vt as createThemeEditorTools,Le as detectRoleAssignment,ht as escapeHtml,Uo as findSection,Ee as formatCssValue,Ve as generateColorScale,Jo as getPreviewTranscriptPresetLabel,gt as getShellPalette,Me as getThemeEditorPreset,Ye as hexToHsl,Ke as hslToHex,Ie as isValidHex,j as normalizeColorValue,Ht as paletteColorPath,Ae as parseCssValue,yt as presetStreamsText,z as quickContrastWarnings,pe as resolveRoleAssignment,Ze as resolveThemeColorPath,Pe as rgbToHex,J as runContrastChecks,jo as scopeSection,$t as tokenRefDisplayName,I as toolResult,ee as wcagContrastRatio};