@runtypelabs/persona 4.25.0 → 4.26.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 (236) hide show
  1. package/dist/animations/glyph-cycle.d.cts +1 -1
  2. package/dist/animations/glyph-cycle.d.ts +1 -1
  3. package/dist/animations/{types-Db61aI9J.d.cts → types-BwKTZhg9.d.cts} +14 -0
  4. package/dist/animations/{types-Db61aI9J.d.ts → types-BwKTZhg9.d.ts} +14 -0
  5. package/dist/animations/wipe.d.cts +1 -1
  6. package/dist/animations/wipe.d.ts +1 -1
  7. package/dist/animations-extra.d.cts +14 -0
  8. package/dist/animations-extra.d.ts +14 -0
  9. package/dist/approval-ui-QAKWNFNM.js +1 -0
  10. package/dist/approval-ui.cjs +2 -2
  11. package/dist/approval-ui.d.cts +180 -8
  12. package/dist/approval-ui.d.ts +180 -8
  13. package/dist/approval-ui.js +2 -2
  14. package/dist/{artifacts-ui-IGB5YKLO.js → artifacts-ui-NJGMM27I.js} +1 -1
  15. package/dist/artifacts-ui.cjs +4 -4
  16. package/dist/artifacts-ui.d.cts +180 -8
  17. package/dist/artifacts-ui.d.ts +180 -8
  18. package/dist/artifacts-ui.js +5 -5
  19. package/dist/chunk-2ANTRKTV.js +1 -0
  20. package/dist/chunk-4HPTPUC6.js +1 -0
  21. package/dist/chunk-6V3MNEKB.js +1 -0
  22. package/dist/chunk-HGUCGM3K.js +9 -0
  23. package/dist/chunk-IO5VVUKP.js +3 -0
  24. package/dist/chunk-J4J3Y2P2.js +1 -0
  25. package/dist/chunk-K6HKIP5K.js +1 -0
  26. package/dist/chunk-K7NA7G7J.js +1 -0
  27. package/dist/chunk-MXUTS3LB.js +1 -0
  28. package/dist/chunk-PDPVORUF.js +1 -0
  29. package/dist/chunk-QPPJUSZH.js +1 -0
  30. package/dist/chunk-QRKGQPU7.js +1 -0
  31. package/dist/chunk-S6PBWE75.js +1 -0
  32. package/dist/chunk-T7QM7YMF.js +1 -0
  33. package/dist/chunk-TR2H475E.js +1 -0
  34. package/dist/chunk-UPO4GUFC.js +1 -0
  35. package/dist/chunk-ZC66NAIR.js +1 -0
  36. package/dist/client-history-YPEG45Q4.js +1 -0
  37. package/dist/client-history.js +1 -0
  38. package/dist/client-stream-42FOI3EC.js +4 -0
  39. package/dist/client-stream.js +5 -0
  40. package/dist/codegen.cjs +1 -1
  41. package/dist/codegen.js +1 -1
  42. package/dist/context-mentions-E7HJYWO6.js +161 -0
  43. package/dist/{context-mentions-inline-I2RDEBAK.js → context-mentions-inline-QVESLW55.js} +1 -1
  44. package/dist/context-mentions.cjs +7 -7
  45. package/dist/context-mentions.d.cts +180 -8
  46. package/dist/context-mentions.d.ts +180 -8
  47. package/dist/context-mentions.js +8 -8
  48. package/dist/event-stream-view-FOIJHFQO.js +1 -0
  49. package/dist/event-stream-view.cjs +1 -1
  50. package/dist/event-stream-view.d.cts +183 -31
  51. package/dist/event-stream-view.d.ts +183 -31
  52. package/dist/event-stream-view.js +1 -1
  53. package/dist/forms-ui.d.cts +221 -667
  54. package/dist/forms-ui.d.ts +221 -667
  55. package/dist/history-shell-QDQ44PSE.js +3 -0
  56. package/dist/history-shell.js +3 -0
  57. package/dist/{history-view-BD6OXLNA.js → history-view-NCFBI5GR.js} +2 -2
  58. package/dist/history-view.cjs +2 -2
  59. package/dist/history-view.d.cts +35 -1
  60. package/dist/history-view.d.ts +35 -1
  61. package/dist/history-view.js +2 -2
  62. package/dist/index.cjs +80 -74
  63. package/dist/index.cjs.map +1 -1
  64. package/dist/index.d.cts +227 -738
  65. package/dist/index.d.ts +227 -738
  66. package/dist/index.global.js +3 -215
  67. package/dist/index.global.js.map +1 -1
  68. package/dist/index.js +81 -75
  69. package/dist/index.js.map +1 -1
  70. package/dist/install.global.js +1 -1
  71. package/dist/install.global.js.map +1 -1
  72. package/dist/launcher.global.js +3 -67
  73. package/dist/launcher.global.js.map +1 -1
  74. package/dist/markdown-parsers.js +22 -22
  75. package/dist/runtype-tts-entry-NFBVWR7N.js +1 -0
  76. package/dist/runtype-tts.js +1 -1
  77. package/dist/session-actions-ISSKSI66.js +1 -0
  78. package/dist/session-actions.js +1 -0
  79. package/dist/session-reconnect.d.cts +180 -8
  80. package/dist/session-reconnect.d.ts +180 -8
  81. package/dist/smart-dom-reader.cjs +13 -13
  82. package/dist/smart-dom-reader.d.cts +180 -8
  83. package/dist/smart-dom-reader.d.ts +180 -8
  84. package/dist/smart-dom-reader.js +11 -11
  85. package/dist/theme-editor-preview.cjs +116 -98
  86. package/dist/theme-editor-preview.d.cts +182 -8
  87. package/dist/theme-editor-preview.d.ts +182 -8
  88. package/dist/theme-editor-preview.js +49 -54
  89. package/dist/theme-editor.cjs +2 -2
  90. package/dist/theme-editor.d.cts +181 -23
  91. package/dist/theme-editor.d.ts +181 -23
  92. package/dist/theme-editor.js +2 -2
  93. package/dist/theme-reference.d.cts +14 -0
  94. package/dist/theme-reference.d.ts +14 -0
  95. package/dist/ui-extras-entry-WAYFKVNW.js +3 -0
  96. package/dist/ui-extras.js +72 -0
  97. package/dist/voice-runtime-UOQOFAFY.js +17 -0
  98. package/dist/voice-runtime.cjs +17 -1
  99. package/dist/voice-runtime.d.cts +11650 -232
  100. package/dist/voice-runtime.d.ts +11650 -232
  101. package/dist/voice-runtime.js +17 -1
  102. package/dist/voice-worklet-player.cjs +19 -4
  103. package/dist/voice-worklet-player.d.cts +9 -10
  104. package/dist/voice-worklet-player.d.ts +9 -10
  105. package/dist/voice-worklet-player.js +19 -4
  106. package/dist/webmcp-polyfill.js +1 -1
  107. package/dist/webmcp-runtime-V6ZWW3PI.js +6 -0
  108. package/dist/webmcp-runtime.cjs +2 -2
  109. package/dist/webmcp-runtime.d.cts +1 -33
  110. package/dist/webmcp-runtime.d.ts +1 -33
  111. package/dist/webmcp-runtime.js +2 -2
  112. package/dist/widget.css +1 -1
  113. package/package.json +11 -5
  114. package/src/approval-paused-tool-settle.test.ts +221 -0
  115. package/src/client-approve.test.ts +311 -0
  116. package/src/client-history-eager.ts +9 -0
  117. package/src/client-history-loader.ts +23 -0
  118. package/src/client-history.ts +579 -0
  119. package/src/client-resume.ts +177 -0
  120. package/src/client-stream-eager.ts +12 -0
  121. package/src/client-stream-loader.ts +25 -0
  122. package/src/client-stream.ts +1880 -0
  123. package/src/client.test.ts +31 -1
  124. package/src/client.ts +293 -2607
  125. package/src/components/approval-actions.test.ts +27 -0
  126. package/src/components/approval-actions.ts +27 -3
  127. package/src/components/message-bubble.test.ts +19 -0
  128. package/src/components/message-bubble.ts +2 -0
  129. package/src/components/registry.ts +6 -6
  130. package/src/components/tool-bubble.test.ts +9 -0
  131. package/src/components/tool-bubble.ts +1 -0
  132. package/src/history-shell-bundle.test.ts +54 -0
  133. package/src/history-shell-eager.ts +12 -0
  134. package/src/history-shell-loader.ts +27 -0
  135. package/src/history-shell.ts +2362 -0
  136. package/src/history-view-loader.ts +2 -0
  137. package/src/history-view.ts +3 -0
  138. package/src/index-core.ts +6 -0
  139. package/src/index-global.ts +90 -248
  140. package/src/index.ts +13 -0
  141. package/src/install.ts +6 -4
  142. package/src/internal/runtype-history-provider.test.ts +1 -0
  143. package/src/internal/runtype-history-provider.ts +28 -13
  144. package/src/plugins/registry.ts +8 -8
  145. package/src/session-actions-chunk.test.ts +55 -0
  146. package/src/session-actions-eager.ts +11 -0
  147. package/src/session-actions-loader.ts +37 -0
  148. package/src/session-actions.ts +909 -0
  149. package/src/session-history.test.ts +3 -1
  150. package/src/session.ts +852 -1536
  151. package/src/session.voice.test.ts +1170 -5
  152. package/src/styles/widget.css +58 -0
  153. package/src/theme-editor/state.ts +91 -91
  154. package/src/types.ts +198 -5
  155. package/src/ui-ask-user-sheet.ts +382 -0
  156. package/src/ui-extras-eager.ts +10 -0
  157. package/src/ui-extras-entry.ts +9 -0
  158. package/src/ui-extras-loader.ts +26 -0
  159. package/src/ui.artifact-rail-resize.test.ts +2 -1
  160. package/src/ui.ask-user-chunk.test.ts +93 -0
  161. package/src/ui.history-chunk.test.ts +2 -1
  162. package/src/ui.history-config-provider.test.ts +2 -1
  163. package/src/ui.history-confirm-fallback.test.ts +142 -0
  164. package/src/ui.history-controller.test.ts +2 -1
  165. package/src/ui.history-lifecycle.test.ts +2 -1
  166. package/src/ui.history-render-hooks.test.ts +2 -1
  167. package/src/ui.history-shell.test.ts +2 -1
  168. package/src/ui.rail-overlay.test.ts +2 -1
  169. package/src/ui.rail-resize.test.ts +2 -1
  170. package/src/ui.rail-trigger-pending.test.ts +2 -1
  171. package/src/ui.ts +340 -2770
  172. package/src/utils/attachment-manager.ts +67 -67
  173. package/src/utils/constants.ts +3 -0
  174. package/src/utils/context-mention-controller.ts +323 -323
  175. package/src/utils/context-mention-manager.ts +40 -40
  176. package/src/utils/context-mention-orchestrator.ts +28 -0
  177. package/src/utils/event-stream-buffer.ts +50 -50
  178. package/src/utils/event-stream-store.ts +43 -43
  179. package/src/utils/throughput-tracker.ts +34 -34
  180. package/src/utils/virtual-scroller.ts +67 -67
  181. package/src/utils/visitor-store.test.ts +50 -0
  182. package/src/utils/visitor-store.ts +23 -5
  183. package/src/voice/__fixtures__/voice-wire/README.md +1 -0
  184. package/src/voice/__fixtures__/voice-wire/client/cancel.json +3 -0
  185. package/src/voice/__fixtures__/voice-wire/client/context.json +4 -0
  186. package/src/voice/__fixtures__/voice-wire/client/delegation_result.json +6 -0
  187. package/src/voice/__fixtures__/voice-wire/client/delegation_update.json +6 -0
  188. package/src/voice/__fixtures__/voice-wire/client/ping.json +3 -0
  189. package/src/voice/__fixtures__/voice-wire/client/playback_progress.json +5 -0
  190. package/src/voice/__fixtures__/voice-wire/client/start.json +3 -0
  191. package/src/voice/__fixtures__/voice-wire/server/artifact.json +11 -0
  192. package/src/voice/__fixtures__/voice-wire/server/attached.json +4 -0
  193. package/src/voice/__fixtures__/voice-wire/server/audio_clear.json +4 -0
  194. package/src/voice/__fixtures__/voice-wire/server/audio_end.json +3 -0
  195. package/src/voice/__fixtures__/voice-wire/server/delegation_cancelled.json +5 -0
  196. package/src/voice/__fixtures__/voice-wire/server/delegation_completed.json +8 -0
  197. package/src/voice/__fixtures__/voice-wire/server/delegation_started.json +15 -0
  198. package/src/voice/__fixtures__/voice-wire/server/error.json +6 -0
  199. package/src/voice/__fixtures__/voice-wire/server/metrics.json +10 -0
  200. package/src/voice/__fixtures__/voice-wire/server/pong.json +3 -0
  201. package/src/voice/__fixtures__/voice-wire/server/session_config.json +16 -0
  202. package/src/voice/__fixtures__/voice-wire/server/transcript_final.json +7 -0
  203. package/src/voice/__fixtures__/voice-wire/server/transcript_interim.json +4 -0
  204. package/src/voice/__fixtures__/voice-wire/server/transcript_partial.json +6 -0
  205. package/src/voice/__fixtures__/voice-wire/server/transcript_update.json +10 -0
  206. package/src/voice/__fixtures__/voice-wire/server/warning.json +5 -0
  207. package/src/voice/audio-playback-manager.test.ts +57 -0
  208. package/src/voice/audio-playback-manager.ts +120 -98
  209. package/src/voice/browser-voice-provider.ts +37 -37
  210. package/src/voice/fallback-speech-engine.ts +22 -16
  211. package/src/voice/keyed-voice-transcript.ts +314 -0
  212. package/src/voice/mic-state-styles.ts +182 -0
  213. package/src/voice/read-aloud-controller.ts +46 -44
  214. package/src/voice/runtype-speech-engine.ts +35 -33
  215. package/src/voice/runtype-voice-provider.ts +670 -189
  216. package/src/voice/session-voice-wiring.ts +266 -0
  217. package/src/voice/voice-delegation.test.ts +71 -0
  218. package/src/voice/voice-delegation.ts +364 -0
  219. package/src/voice/voice-turn-tracker.ts +6 -6
  220. package/src/voice/voice.test.ts +981 -8
  221. package/src/voice/worklet-playback-engine.test.ts +81 -0
  222. package/src/voice/worklet-playback-engine.ts +21 -3
  223. package/src/voice-runtime-loader.ts +4 -1
  224. package/src/voice-runtime.ts +7 -0
  225. package/src/webmcp-runtime-entry.ts +41 -39
  226. package/dist/approval-ui-3NMYNXBD.js +0 -1
  227. package/dist/chunk-5EIIHQLQ.js +0 -1
  228. package/dist/chunk-7CO4T5KB.js +0 -1
  229. package/dist/chunk-EFJBUH5F.js +0 -1
  230. package/dist/chunk-R2TMIMDI.js +0 -3
  231. package/dist/chunk-UTVLOTWB.js +0 -9
  232. package/dist/context-mentions-45MODWOY.js +0 -161
  233. package/dist/event-stream-view-GL3ADRY2.js +0 -1
  234. package/dist/runtype-tts-entry-UJAEF7NZ.js +0 -1
  235. package/dist/voice-runtime-7DA7MJH4.js +0 -1
  236. package/dist/webmcp-runtime-JI7T4QYF.js +0 -6
@@ -1,22 +1,17 @@
1
- import{a as Ic,b as ib,c as Du,d as Ta,e as Hc,f as Ea,g as Rc,h as Pa,i as ab,j as ka}from"./chunk-CPVD5P5B.js";import{b as _y,c as Ac,d as Oy,e as yi,f as Ny,g as bi,h as Fy,i as Uy,j as $y,k as Vy,l as Mc,m as Tc,n as Ru,o as Ec,p as Ma,q as qy,r as zy,s as jy,t as Ky}from"./chunk-NQLDCJAP.js";import{a as eb,b as tb,c as er,d as As,e as nb,f as ob,g as rb,h as Bu,i as sb}from"./chunk-VK6JOIYJ.js";import{a as Ht,c as Hy,d as Ry,e as de,f as Wy,g as xc,i as hi,j as By,k as Sc,l as Dy,m as Rt,n as ln,o as Pc,p as lb,q as cb,u as db,v as vi,w as tr}from"./chunk-7CO4T5KB.js";import{a as Ss,d as _u}from"./chunk-EFJBUH5F.js";import{a as Gy,c as Qy,d as Lc,e as Wu,f as Zy}from"./chunk-UTVLOTWB.js";import{a as Yy,c as Xy,d as Jy}from"./chunk-R2TMIMDI.js";import{a as $t}from"./chunk-7NQ4ZTHF.js";import{b as kc}from"./chunk-Q735PSZL.js";import{a as P,c as G,d as Nn}from"./chunk-76IELU7F.js";import{Circle as BA,Clock as DA}from"lucide";var pb=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function fo(t,e){if(!t)return e;if(!e)return t;let n={...t};for(let[o,s]of Object.entries(e)){let i=n[o];pb(i)&&pb(s)?n[o]=fo(i,s):n[o]=s}return n}var Ou=Symbol("persona.defaultsProvenance"),Nu=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function Wc(t,e=""){return Object.entries(t).flatMap(([n,o])=>{let s=e?`${e}.${n}`:n;return Nu(o)?Wc(o,s):[s]})}function ub(t,e){for(let n of e.split(".")){if(!Nu(t)||!Object.prototype.hasOwnProperty.call(t,n))return"absent";if(t=t[n],t===void 0)return"clear"}return"explicit"}function gb(t,e){return t?.[Ou]??e.filter(n=>ub(t,n)==="explicit")}function Fu(t,e){return Object.defineProperty(t,Ou,{value:e,enumerable:!0,configurable:!0}),t}function Uu(t,e,n){return Fu(t,gb(e,Wc(n)))}function fb(t,e,n){let o=e[Ou];if(o)return o;let s=new Set(gb(t,n));for(let i of n){let l=ub(e,i);l==="clear"&&s.delete(i),l==="explicit"&&s.add(i)}return[...s]}function mb(t,e,n){let o={...t};for(let s of e){if(n.includes(s))continue;let i=s.split("."),l=o;for(let c of i.slice(0,-1)){let d=l[c];if(!Nu(d)){l=void 0;break}l[c]={...d},l=l[c]}l&&delete l[i[i.length-1]]}return o}var hb="var(--persona-components-panel-width)",$u=Symbol("persona.panelAliasProvenance"),Ms=(t,e)=>t!=null&&Object.prototype.hasOwnProperty.call(t,e),Bc=(t,e)=>Ms(t,e)&&t[e]!==void 0,AA=t=>({launcherWidth:Bc(t?.launcher,"width"),legacyLauncherWidth:Bc(t,"launcherWidth"),sidebarWidth:Bc(t?.launcher,"sidebarWidth"),dockWidth:Bc(t?.launcher?.dock,"width")}),nr=t=>{let e=t?.[$u];return e?{...e}:AA(t)},Vu=(t,e)=>(Object.defineProperty(t,$u,{value:e,enumerable:!0,configurable:!0}),t),qu=(t,e)=>Vu(t,nr(e)),yb=(t,e)=>{let n=e[$u];if(n)return{...n};let o=nr(t);return Ms(e,"launcherWidth")&&(o.legacyLauncherWidth=e.launcherWidth!==void 0),Ms(e,"launcher")&&e.launcher===void 0?(o.launcherWidth=!1,o.sidebarWidth=!1,o.dockWidth=!1,o):(Ms(e.launcher,"width")&&(o.launcherWidth=e.launcher?.width!==void 0),Ms(e.launcher,"sidebarWidth")&&(o.sidebarWidth=e.launcher?.sidebarWidth!==void 0),Ms(e.launcher,"dock")&&e.launcher?.dock===void 0?o.dockWidth=!1:Ms(e.launcher?.dock,"width")&&(o.dockWidth=e.launcher?.dock?.width!==void 0),o)};var zu="min(440px, calc(100vw - 24px))";var Ha="40px",ju="How can I help...",or={collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},Es={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},MA={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:zu,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:Ha,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",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)"},TA={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",tooltip:{delayMs:200,skipDelayMs:300},launcher:MA,copy:{inputPlaceholder:ju,sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",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",borderWidth:"0px",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:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:or,reasoningDisplay:Es,streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"},history:{enabled:!1,presentation:"panel",showScopeStatus:!0,showDelete:!0,showDeleteAll:!0}},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"],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},EA={},PA={variant:"circle",width:"min(400px, calc(100vw - 24px))",headerIconSize:"20px"},Ts={launcher:PA,features:{toolCallDisplay:{variant:"row",iconVisibility:"active",autoExpand:!1,grouped:!0,groupedMode:"collapsible",loadingAnimation:"shimmer"},reasoningDisplay:{variant:"row",iconVisibility:"active",autoExpand:!1,loadingAnimation:"shimmer"}},composer:{layout:"single-row",placement:"overlay"},sendButton:{iconName:"arrow-up"},statusIndicator:{mode:"transient"},layout:{contentMaxWidth:"768px",topFade:!0,header:{showSubtitle:!1},messages:{assistant:{width:"full"}}}};function Rr(t){return t?.future?.v5Defaults===!0?"v5":"v4"}function Dc(t){let e=Rr(t)==="v5"?Ts:EA;return fo(TA,e)}var VP=Dc();function bb(t,e){if(!(!t&&!e))return t?e?fo(t,e):t:e}function _c(t){let e=Dc(t);return t?Uu(qu({...e,...t,theme:bb(e.theme,t.theme),darkTheme:bb(e.darkTheme,t.darkTheme),launcher:{...e.launcher,...t.launcher,dock:{...e.launcher?.dock,...t.launcher?.dock},clearChat:{...e.launcher?.clearChat,...t.launcher?.clearChat}},...e.composer||t.composer?{composer:{...e.composer,...t.composer}}:{},tooltip:{...e.tooltip,...t.tooltip},copy:{...e.copy,...t.copy},sendButton:{...e.sendButton,...t.sendButton},statusIndicator:{...e.statusIndicator,...t.statusIndicator},voiceRecognition:{...e.voiceRecognition,...t.voiceRecognition},features:(()=>{let n=e.features?.artifacts,o=t.features?.artifacts,s=e.features?.scrollToBottom,i=t.features?.scrollToBottom,l=e.features?.scrollBehavior,c=t.features?.scrollBehavior,d=e.features?.streamAnimation,g=t.features?.streamAnimation,u=e.features?.askUserQuestion,m=t.features?.askUserQuestion,y=e.features?.history,b=t.features?.history,C=n===void 0&&o===void 0?void 0:{...n,...o,layout:{...n?.layout,...o?.layout}},S=s===void 0&&i===void 0?void 0:{...s,...i},E=l===void 0&&c===void 0?void 0:{...l,...c},H=d===void 0&&g===void 0?void 0:{...d,...g},I=u===void 0&&m===void 0?void 0:{...u,...m,styles:{...u?.styles,...m?.styles}},N=y===void 0&&b===void 0?void 0:{...y,...b,copy:{...y?.copy,...b?.copy}};return{...e.features,...t.features,toolCallDisplay:{...e.features?.toolCallDisplay,...t.features?.toolCallDisplay},reasoningDisplay:{...e.features?.reasoningDisplay,...t.features?.reasoningDisplay},...S!==void 0?{scrollToBottom:S}:{},...E!==void 0?{scrollBehavior:E}:{},...C!==void 0?{artifacts:C}:{},...H!==void 0?{streamAnimation:H}:{},...I!==void 0?{askUserQuestion:I}:{},...N!==void 0?{history:N}:{}}})(),suggestionChips:t.suggestionChips??e.suggestionChips,suggestionChipsConfig:{...e.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...e.layout,...t.layout,header:{...e.layout?.header,...t.layout?.header},messages:{...e.layout?.messages,...t.layout?.messages,...e.layout?.messages?.user||t.layout?.messages?.user?{user:{...e.layout?.messages?.user,...t.layout?.messages?.user}}:{},...e.layout?.messages?.assistant||t.layout?.messages?.assistant?{assistant:{...e.layout?.messages?.assistant,...t.layout?.messages?.assistant}}:{},avatar:{...e.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...e.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...e.layout?.slots,...t.layout?.slots}},markdown:{...e.markdown,...t.markdown,options:{...e.markdown?.options,...t.markdown?.options}},messageActions:{...e.messageActions,...t.messageActions}},t),t,Ts):Uu(qu(e),void 0,Ts)}import{ChevronDown as kA,ChevronUp as LA}from"lucide";var IA=["persona-w-full","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"],HA="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",RA="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",WA=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),Oc=(t,e)=>{let n=P("div",["persona-message-bubble",t,...IA].join(" "));return n.id=`bubble-${e}`,n.setAttribute("data-message-id",e),n},Nc=t=>{let e=P("button",t.expandable?HA:RA);return e.type="button",t.expandable&&(e.setAttribute("aria-expanded",t.expanded?"true":"false"),e.setAttribute("data-expand-header","true")),e.setAttribute("data-bubble-type",t.bubbleType),e},Ku=(t,e,n)=>{t.innerHTML="";let o=$t(e?LA:kA,16,n,2);o?t.appendChild(o):t.textContent=e?"Hide":"Show"},Ci=(t,e,n)=>{if(!n.expandable)return t.append(e),null;let o=P("div","persona-flex persona-items-center");Ku(o,n.expanded,n.iconColor);let s=P("div",n.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return s.append(o),t.append(e,s),o},Fc=t=>{let e=P("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(e.setAttribute("data-persona-collapsed-preview",t.previewKind),e.style.display="none",e.style.whiteSpace="pre-wrap",!t.expanded&&t.isActive&&t.activePreview&&t.previewText){let n=t.renderPreview?.();WA(e,n)||(e.textContent=t.previewText),e.style.display=""}return!t.expanded&&t.isActive&&t.activeMinHeight&&(t.bubble.style.minHeight=t.activeMinHeight),e},Uc=t=>{t.header.setAttribute("aria-expanded",t.expanded?"true":"false"),t.toggleIcon&&Ku(t.toggleIcon,t.expanded,t.iconColor),t.content.style.display=t.expanded?"":"none",t.collapsedPreview.style.display=t.expanded?"none":t.collapsedPreview.textContent||t.collapsedPreview.childNodes.length?"":"none"},$c=(t,e,n)=>{let o=n.stateSet.has(t),s=e.querySelector('button[data-expand-header="true"]'),i=e.querySelector(".persona-border-t"),l=e.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!s||!i)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");d&&Ku(d,o,n.iconColor),i.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")};function Vc(t,e){let n=e==="tool"?"toolCallDisplay":"reasoningDisplay";return{...t,features:{...t?.features,[n]:{...e==="tool"?or:Es,...t?.future?.v5Defaults===!0?Ts.features?.[n]:{},...t?.features?.[n]}}}}function Wr(t,e){let n=e==="tool"?"toolCallDisplay":"reasoningDisplay";return t?.features?.[n]?.variant??(t?.future?.v5Defaults?"row":"card")}function Ra(t){let e=Math.max(0,Math.floor((t??0)/1e3));return e<1?"a moment":e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function rr(t,e,n,o){if(Wr(n,o)!=="row")return t;t.className=`persona-message-bubble persona-${o}-bubble persona-activity-row`,t.dataset.activityKind=o,o==="tool"&&n.toolCall?.shadow===void 0&&(t.style.boxShadow="var(--persona-tool-bubble-shadow, none)");let s=t.querySelector(":scope > button");if(!s)return t;s.className="persona-activity-header";let i=o==="tool"?e.toolCall:e.reasoning,l=i?.status!=="complete",c=e.approval?.status??e.toolCall?.approvalStatus,d=c==="denied"?"denied":c==="pending"?"awaiting-approval":e.toolCall?.success===!1?"error":l?i?.status==="pending"?"pending":"running":"done";t.dataset.activityState=d;let g=P("span","persona-activity-icon");g.dataset.activityIcon=d;let u={pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x","awaiting-approval":"clock"},m=o==="reasoning"?n.features?.reasoningDisplay?.iconName:void 0,y=m?de(m,16,"currentColor",2):d==="pending"?$t(BA,16,"currentColor",2):d==="awaiting-approval"?$t(DA,16,"currentColor",2):de(u[d],16,"currentColor",2);y&&g.appendChild(y),s.querySelector(".persona-reasoning-header-icon")?.remove();let b=o==="tool"?"toolCallDisplay":"reasoningDisplay",C=n.features?.[b]?.iconVisibility??(n.future?.v5Defaults?"active":"always");if((C==="always"||C==="active"&&d!=="done")&&s.prepend(g),o==="tool"&&i){let I=P("span","persona-activity-duration");l&&i.startedAt&&I.setAttribute("data-tool-elapsed",String(i.startedAt));let N=(o==="tool"?e.toolCall?.duration:void 0)??i.durationMs??(i.completedAt!==void 0&&i.startedAt!==void 0?i.completedAt-i.startedAt:void 0);I.textContent=N===void 0?"":Ra(N),s.appendChild(I)}s.querySelector(":scope > div:not(.persona-ml-auto)")?.classList.add("persona-activity-label"),s.querySelector(".persona-ml-auto")?.classList.add("persona-activity-chevron");let H=t.querySelector(":scope > .persona-border-t");return H?.classList.add("persona-activity-body"),H&&(H.id=`activity-details-${e.id}`,s.setAttribute("aria-controls",H.id)),t}function vb(t){let e=new Set,n=new Set,o=new Set,s=new Map,i=l=>{clearTimeout(s.get(l)),s.delete(l)};return{observe(l,c,d,g={}){let u=c==="tool"?l.toolCall:l.reasoning;if(!(!u||n.has(l.id))&&(!e.has(l.id)&&u.status!=="complete"&&u.chunks?.some(Boolean)&&(e.add(l.id),g.autoExpand!==!1&&d.add(l.id)),e.has(l.id)&&u.status==="complete"&&!o.has(l.id))){if(o.add(l.id),g.autoCollapseDelay===!1)return;s.set(l.id,setTimeout(()=>{s.delete(l.id),d.delete(l.id),t(l.id,c)},g.autoCollapseDelay??1e3))}},manual(l){n.add(l),i(l)},prune(l){for(let c of new Set([...e,...n,...o]))l.has(c)||(i(c),e.delete(c),n.delete(c),o.delete(c))},clear(){for(let l of s.keys())i(l);e.clear(),n.clear(),o.clear()}}}function Cb(t,e,n,o){let s=P("div","");s.id=`bubble-${t.id}`,s.dataset.messageId=t.id;let i=P("button","");i.type="button",i.dataset.expandHeader="true",i.dataset.bubbleType="tool",i.setAttribute("aria-expanded",String(n));let l=P("div","");typeof o=="string"?l.textContent=o:l.appendChild(o),Ci(i,l,{expandable:!0,expanded:n,iconColor:e.toolCall?.toggleTextColor||e.toolCall?.headerTextColor||"currentColor",metaGap:!0});let c=P("div","persona-border-t");return c.id=`activity-details-${t.id}`,c.style.display=n?"":"none",i.setAttribute("aria-controls",c.id),s.append(i,c),rr(s,t,{...e,features:{...e.features,toolCallDisplay:{...e.features?.toolCallDisplay,variant:"row"}}},"tool"),s.dataset.personaToolGroup="true",e.features?.toolCallDisplay?.loadingAnimation==="shimmer"&&(s.dataset.activityGroupShimmer="true"),{bubble:s,body:c}}var _A=(t,e)=>t.visible!==!1&&(t.mode!=="transient"||e==="connecting"||e==="paused"||e==="resuming"||e==="error"),Ps=(t,e,n)=>{let o=e.mode==="transient",s=t.hasAttribute("data-persona-composer-reason")||t.hasAttribute("data-persona-composer-notice");t.style.display=_A(e,n)||o&&s&&e.visible!==!1?"":"none",t.classList.toggle("persona-mt-2",!o),t.classList.toggle("persona-mb-2",o)},Gu=(t,e,n)=>{!e.parentElement||t.parentElement!==e.parentElement||(n.mode==="transient"?t.nextElementSibling!==e&&e.before(t):e.nextElementSibling!==t&&e.after(t))};function wb(t,e){let n=t.voiceRecognition,o=e.voiceRecognition;return n?.enabled===!0!=(o?.enabled===!0)||n?.provider?.type!==o?.provider?.type||n?.provider?.custom!==o?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==o?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(o?.provider?.runtype)||t.agentId!==e.agentId||t.clientToken!==e.clientToken||t.apiUrl!==e.apiUrl}function gn(t){return t?.type==="runtype"||t?.type==="custom"}var OA=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function xb(t){try{if(t?.type==="custom"&&t.custom){let e=t.custom,n=typeof e=="function"?e():e;return!!n&&typeof n.startListening=="function"}return t?.type==="runtype"&&t.runtype?!0:OA()}catch{return!1}}var Sb=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Ab=t=>t.includes("|"),Mb=t=>{let e=t.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(n=>n.trim())},NA=t=>`| ${t.join(" | ")} |`,FA=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,UA=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),Tb=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
2
- `),n=!1;for(let o=0;o<e.length-1;o++){let s=e[o],i=e[o+1];if(!Ab(s)||Sb.test(s)||!Sb.test(i))continue;let l=Mb(s).length;if(l<1)continue;let c=FA(l);e[o+1]!==c&&(e[o+1]=c,n=!0);let d=o+2;for(;d<e.length;d++){let g=e[d];if(g.trim()===""||!Ab(g))break;let u=NA(UA(Mb(g),l));e[d]!==u&&(e[d]=u,n=!0)}o=d-1}return n?e.join(`
3
- `):t};var Eb="var(--persona-md-table-scroll-fade, 24px)",Pb=new WeakSet;function Lb(t){t.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let s=document.createElement("div");s.className="persona-table-scroll",n.replaceWith(s),s.appendChild(n)})}function kb(t){let e=t.scrollWidth-t.clientWidth;if(e<=1){t.removeAttribute("data-persona-scroll-x");return}t.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(t).direction==="rtl"?e+t.scrollLeft:t.scrollLeft,s=e-o;t.style.setProperty("--persona-fade-l",o<=1?"0px":Eb),t.style.setProperty("--persona-fade-r",s<=1?"0px":Eb)}function Qu(t){Pb.has(t)||(Pb.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&kb(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(kb)}var{setLoader:ak,load:$A}=Ht({fallbackImport:()=>import("./webmcp-runtime-JI7T4QYF.js")});var Ib=$A;function to(t){return t==="card"?"collapsed":t}function wi(t){return t.split(";",1)[0].trim().toLowerCase()}function VA(t,e){if(!t)return;let n=Object.entries(t);for(let[s,i]of n)if(wi(s)===e)return{mode:to(i),selector:wi(s)};let o=`${e.split("/",1)[0]}/*`;for(let[s,i]of n)if(wi(s)===o)return{mode:to(i),selector:o}}function qA(t,e){let n=t?.display,o=typeof n=="string"?{default:n}:n??{};if(e.file&&o.files){if(typeof o.files=="string")return{mode:to(o.files),matchedBy:{type:"files"}};let c=e.file.mimeType?wi(e.file.mimeType):void 0,d=c?VA(o.files.byMediaType,c):void 0;if(c&&d)return{mode:d.mode,matchedBy:{type:"mediaType",mediaType:c,selector:d.selector}};if(o.files.default)return{mode:to(o.files.default),matchedBy:{type:"files"}}}let s=o.byKind?.[e.artifactType];if(s)return{mode:to(s),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byKind"}};let i=o.byType?.[e.artifactType];if(i)return{mode:to(i),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byType"}};let l=e.presentation?.preferredMode;return l?{mode:to(l),matchedBy:{type:"preferredMode"}}:o.default?{mode:to(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Br(t,e){return qA(t,e).mode}function Wa(t,e){return JSON.stringify({component:t==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:e.artifactId,title:e.title,artifactType:e.artifactType,status:e.status,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...t==="inline"&&e.component?{component:e.component}:{},...t==="inline"&&e.componentProps?{componentProps:e.componentProps}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}})}var zA="agent_",jA="flow_";function Hb(t){return t.startsWith(zA)?{kind:"agentId",agentId:t}:t.startsWith(jA)?{kind:"flowId",flowId:t}:null}function Rb(t,e){let n=t.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let l=n.slice(0,o),c=n.slice(o+1);if(l==="runtype"){let g=Hb(c);if(g)return g;throw new Error(`[Persona] target "runtype:${c}" is not a valid Runtype agent_/flow_ id.`)}let d=e?.[l];if(!d)throw new Error(`[Persona] No target provider registered for "${l}". Add a \`targetProviders.${l}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(c).payload}}let s=Hb(n);if(s)return s;let i=e?.default;if(i)return{kind:"payload",payload:i(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}function qc(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function xi(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}function Wb(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`turn_${t}_${e}`}import{parse as KA,ARR as GA,OBJ as QA,STR as YA}from"partial-json";var Yu="ask_user_question",Ba=8,Si="data-persona-ask-sheet-for",XA="Other",JA="Other\u2026",Db="Type your own answer here",_b="Send",ZA="Next",eM="Back",tM="Submit all",nM="Skip",oM=3,Xu="data-ask-current-index",Ju="data-ask-question-count",Ob="data-ask-answers",Zu="data-ask-grouped",Nb="data-ask-layout",rM=t=>t.layout==="pills"?"pills":"rows",sM=t=>t.getAttribute(Nb)==="pills"?"pills":"rows",Bb=!1,Fb=t=>t.replace(/["\\]/g,"\\$&"),ks=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===Yu,eg=t=>t?.features?.askUserQuestion??{},Ai=t=>{let e=t.toolCall;if(!e)return{payload:null,complete:!1};let n=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:n};let o=e.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let s=o.join(""),i=KA(s,YA|QA|GA);if(i&&typeof i=="object")return{payload:i,complete:n}}catch{}return{payload:null,complete:n}},Da=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>Ba&&!Bb&&(Bb=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Ba}.`)),e.slice(0,Ba)},iM=t=>Da(t)[0]??null,aM=(t,e)=>Da(t)[e]??null,lM=(t,e)=>{let n=e.styles;n&&(n.sheetBackground&&t.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&t.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&t.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&t.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&t.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&t.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&t.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&t.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&t.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},Ub=(t,e,n)=>{if(t!=="rows")return null;let o=P("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),e){let s=P("span","persona-ask-row-check");o.appendChild(s)}else{let s=P("span","persona-ask-row-badge");s.textContent=String(n+1),o.appendChild(s)}return o},cM=(t,e,n,o)=>{let i=P("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(i.type="button",i.setAttribute("role",o?"checkbox":"button"),i.setAttribute("aria-pressed","false"),i.setAttribute("data-ask-user-action","pick"),i.setAttribute("data-option-index",String(e)),i.setAttribute("data-option-label",t.label),n==="rows"){let l=P("span","persona-ask-row-content"),c=P("span","persona-ask-row-label");if(c.textContent=t.label,l.appendChild(c),t.description){let g=P("span","persona-ask-row-description");g.textContent=t.description,l.appendChild(g)}i.appendChild(l);let d=Ub(n,o,e);d&&i.appendChild(d)}else i.textContent=t.label,t.description&&(i.title=t.description);return i},dM=t=>{let n=P("span",t==="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},pM=(t,e,n,o)=>{let i=P("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");i.setAttribute("role","group"),i.setAttribute("data-ask-pill-list","true");let l=!!t?.multiSelect,d=(Array.isArray(t?.options)?t.options:[]).filter(u=>u&&typeof u.label=="string"&&u.label.length>0);if(d.length===0&&!n){for(let u=0;u<oM;u++)i.appendChild(dM(o));return i}if(d.forEach((u,m)=>{i.appendChild(cM(u,m,o,l))}),t?.allowFreeText!==!1){let u=o==="rows"?XA:JA;if(o==="rows"){let m=P("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");m.setAttribute("data-ask-user-action","focus-free-text"),m.setAttribute("data-option-index",String(d.length)),m.setAttribute("data-ask-other-row","true");let y=P("span","persona-ask-row-content"),b=document.createElement("input");b.type="text",b.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",b.placeholder=e.freeTextPlaceholder??Db,b.setAttribute("data-ask-free-text-input","true"),b.setAttribute("aria-label",e.freeTextLabel??u),y.appendChild(b),m.appendChild(y);let C=Ub(o,l,d.length);C&&m.appendChild(C),i.appendChild(m)}else{let m=P("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");m.type="button",m.setAttribute("data-ask-user-action","open-free-text"),m.textContent=e.freeTextLabel??u,i.appendChild(m)}}return i},$b=(t,e)=>{let o=P("div",e==="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 s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=t.freeTextPlaceholder??Db,s.setAttribute("data-ask-free-text-input","true"),o.appendChild(s),e!=="rows"){let i=P("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=t.submitLabel??_b,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},uM=t=>{let e=P("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let n=P("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=t.submitLabel??_b,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},gM=(t,e,n)=>{let o=P("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 s=P("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=n.backLabel??eM,s.setAttribute("data-ask-user-action","back"),s.disabled=t===0,o.appendChild(s);let i=P("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),l=P("button","persona-ask-nav-skip persona-pointer-events-auto");l.type="button",l.textContent=n.skipLabel??nM,l.setAttribute("data-ask-user-action","skip"),i.appendChild(l);let c=P("button","persona-ask-nav-next persona-pointer-events-auto");c.type="button";let d=t===e-1;return c.textContent=d?n.submitAllLabel??tM:n.nextLabel??ZA,c.setAttribute("data-ask-user-action",d?"submit-all":"next"),c.disabled=!0,i.appendChild(c),o.appendChild(i),o},Ls=t=>{let e=t.getAttribute(Ob);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},Vb=(t,e)=>{t.setAttribute(Ob,JSON.stringify(e))},no=t=>{let e=Number(t.getAttribute(Xu)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},fM=(t,e)=>{t.setAttribute(Xu,String(Math.max(0,Math.floor(e))))},Mi=t=>{let e=Number(t.getAttribute(Ju)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},Dr=t=>t.getAttribute(Zu)==="true",mM=(t,e)=>{let n=t.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return e.forEach((s,i)=>{let l=typeof s?.question=="string"?s.question:"";if(l&&Object.prototype.hasOwnProperty.call(n,l)){let c=n[l];(typeof c=="string"||Array.isArray(c))&&(o[i]=c)}}),o},hM=(t,e)=>{let n=t.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(e-1,Math.floor(n)))},zc=(t,e)=>{let{payload:n}=Ai(e),o=Da(n),s=Ls(t),i={},l=new Set;return o.forEach((c,d)=>{let g=typeof c?.question=="string"?c.question:"";g&&(l.has(g)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${g}"; later answer wins.`),l.add(g),Object.prototype.hasOwnProperty.call(s,d)&&(i[g]=s[d]))}),i},qb=t=>{let e=Ls(t),n=no(t),o=e[n],s=new Set;typeof o=="string"?s.add(o):Array.isArray(o)&&o.forEach(d=>s.add(d));let i=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');i.forEach(d=>{let g=d.getAttribute("data-option-label")??"",u=s.has(g);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let l=new Set(Array.from(i).map(d=>d.getAttribute("data-option-label")??"")),c=t.querySelector('[data-ask-free-text-input="true"]');c&&(typeof o=="string"&&o.length>0&&!l.has(o)?(c.value=o,c.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):c.value="")},zb=t=>{if(!Dr(t))return;let e=Ls(t),n=no(t),o=e[n],s=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,i=t.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');i&&(i.disabled=!s);let l=t.querySelector('[data-ask-user-action="submit-multi"]');if(l){let c=Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]'));l.disabled=c.length===0}},tg=(t,e,n)=>{let o=eg(n),s=sM(t),{payload:i,complete:l}=Ai(e),c=Dr(t),d=no(t),g=Mi(t),u=c?aM(i,d):iM(i),m=!!u?.multiSelect,y=t.querySelector('[data-ask-step-inline="true"]');y&&(y.textContent=c?`${d+1}/${g}`:"");let b=t.querySelector('[data-ask-stepper="true"]');b&&b.remove();let C=t.querySelector('[data-ask-question="true"]');if(C){let I=typeof u?.question=="string"?u.question:"";C.textContent=I,C.classList.toggle("persona-ask-question-skeleton",!I&&!l)}let S=t.querySelector('[data-ask-pill-list="true"]');if(S){let I=pM(u,o,l,s);S.replaceWith(I)}if(s!=="rows"){let I=t.querySelector('[data-ask-free-text-row="true"]');I&&I.replaceWith($b(o,s))}let E=t.querySelector('[data-ask-multi-actions="true"]');!c&&m&&!E?t.appendChild(uM(o)):(!m||c)&&E&&E.remove(),t.setAttribute("data-multi-select",m?"true":"false");let H=t.querySelector('[data-ask-nav-row="true"]');if(c){let I=gM(d,g,o);H?H.replaceWith(I):t.appendChild(I)}else H&&H.remove();qb(t),zb(t)},yM=(t,e,n)=>{let o=eg(e),s=rM(o),i=t.toolCall.id,l=Da(n),c=Math.max(1,l.length),d=c>1,g=mM(t,l),u=d?hM(t,c):0,m=P("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(Si,i),m.setAttribute("data-tool-call-id",i),m.setAttribute("data-message-id",t.id),m.setAttribute(Ju,String(c)),m.setAttribute(Xu,String(u)),m.setAttribute(Zu,d?"true":"false"),m.setAttribute(Nb,s),Vb(m,g),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),lM(m,o);let y=P("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),b=P("div","persona-ask-sheet-question persona-flex-1");b.setAttribute("data-ask-question","true"),b.textContent="",y.appendChild(b);let C=P("span","persona-ask-sheet-step-inline");C.setAttribute("data-ask-step-inline","true"),C.textContent="",y.appendChild(C),m.appendChild(y);let E=P("div",s==="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"),m.appendChild(E),s!=="rows"&&m.appendChild($b(o,s)),tg(m,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},bM=(t,e,n)=>{let{payload:o}=Ai(e),s=Math.max(1,Da(o).length);s>Mi(t)&&(t.setAttribute(Ju,String(s)),s>1&&!Dr(t)&&t.setAttribute(Zu,"true")),tg(t,e,n)};var jc=(t,e,n)=>{if(!n||!ks(t)||eg(e).enabled===!1)return;let s=t.toolCall.id;n.querySelectorAll(`[${Si}]`).forEach(g=>{g.getAttribute(Si)!==s&&g.remove()});let l=n.querySelector(`[${Si}="${Fb(s)}"]`);if(l){bM(l,t,e);return}let{payload:c}=Ai(t),d=yM(t,e,c);n.appendChild(d)},Ti=(t,e)=>{if(!t)return;let n=e?`[${Si}="${Fb(e)}"]`:`[${Si}]`;t.querySelectorAll(n).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let i=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(i)?i:180)})},ng=t=>Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),_r=(t,e)=>{let n=Ls(t),o=no(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,Vb(t,n),qb(t),zb(t)},Kc=(t,e,n,o)=>{let s=Mi(t),i=Math.max(0,Math.min(s-1,o));fM(t,i),tg(t,e,n)};var Or="suggest_replies";var vM={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:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},Kb={name:Or,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. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts 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: do not add further commentary after calling this tool; end your turn.",parametersSchema:vM,origin:"sdk",annotations:{readOnlyHint:!0}},Gb=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),_a=t=>t.variant==="tool"&&t.toolCall?.name===Or,CM=t=>{let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let n=e?.suggestions;if(!Array.isArray(n))return[];let o=n.flatMap(s=>{if(typeof s=="string"){let c=s.trim();return c?[c]:[]}if(!s||typeof s!="object")return[];let i=s;if(typeof i.label!="string"||!i.label.trim())return[];let l={label:i.label.trim()};return typeof i.prompt=="string"&&i.prompt.trim()&&(l.prompt=i.prompt.trim()),typeof i.description=="string"&&i.description.trim()&&(l.description=i.description.trim()),[l]});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},Qb=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!_a(n))continue;let o=CM(n.toolCall?.args);return o.length>0?o:null}return null},jb=new Set,wM=(t,e,n)=>{let o=`${t}:${e}:${n}`;jb.has(o)||(jb.add(o),console.warn(`[persona] suggestions.followUps.${t} and features.suggestReplies.${t} disagree; suggestions.followUps.${t} wins.`))},Nr=t=>{let e=t?.suggestions?.followUps,n=t?.features?.suggestReplies,o=l=>{let c=e?.[l],d=n?.[l];c===void 0||d===void 0||c!==d&&wM(l,d,c)};t&&(o("enabled"),o("expose"));let s=e?.enabled??n?.enabled??!0,i=s?e?.expose??n?.expose??!1:!1;return{enabled:s,expose:i}};var xM={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ba,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: 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},SM={name:Yu,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: 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:xM,origin:"sdk",annotations:{readOnlyHint:!0}},Gc=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(SM),Nr(t).expose&&e.push(Kb),e};var AM=t=>t.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),MM=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),TM=t=>{if(t.variant!=="tool")return null;let e=t.agentMetadata?.clientToolAnswer;if(!e||!e.toolCallId||e.result===void 0)return null;let n=AM(e.toolName);return n?{call:{toolCallId:e.toolCallId,toolName:n,args:MM(e.args)?e.args:{}},result:{toolCallId:e.toolCallId,toolName:n,result:e.result}}:null},og=(t,e)=>{let n=[],o=[],s=[],i="",l,c=()=>{o.length!==0&&(n.push({role:"assistant",content:"",createdAt:i,toolCalls:o},{role:"tool",content:"",createdAt:i,toolResults:s}),o=[],s=[])};for(let d of t){let g=TM(d);if(g){let m=d.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(m===void 0||m!==l)&&c(),o.length===0&&(i=d.createdAt,l=m),o.some(y=>y.toolCallId===g.call.toolCallId)||(o.push(g.call),s.push(g.result));continue}let u=e(d);u&&(c(),n.push(u))}return c(),n};var Yb="4.25.0";var Is=Yb;var Ei="[Image]";function Xb(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join("")}function Qc(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function Io(t){return{type:"text",text:t}}function Jb(t,e){return{type:"image",image:t,...e?.mimeType&&{mimeType:e.mimeType},...e?.alt&&{alt:e.alt}}}var Zb=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],PM=["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"],sr=[...Zb,...PM];function kM(t){return Zb.includes(t)||t.startsWith("image/")}function Yc(t){return kM(t.type)}function ev(t,e,n){return{type:"file",data:t,mimeType:e,filename:n}}async function tv(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let s=o.result;Yc(t)?e({type:"image",image:s,mimeType:t.type,alt:t.name}):e({type:"file",data:s,mimeType:t.type,filename:t.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(t)})}function nv(t,e=sr,n=10*1024*1024){return e.includes(t.type)?t.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${e.join(", ")}`}}function LM(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function ov(t,e){let n=LM(e).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"}[t]||n||"FILE"}var IM=["user","assistant","system"],HM=0;function rv(t){if(typeof t!="string"||t==="")return null;let e=Date.parse(t);return Number.isNaN(e)?null:e}function Xc(t){return typeof t=="string"?t:void 0}function RM(t){if(typeof t!="object"||t===null)return null;let e=t;switch(e.type){case"text":return typeof e.text=="string"?Io(e.text):null;case"image":return typeof e.image=="string"?Jb(e.image,{mimeType:Xc(e.mimeType),alt:Xc(e.alt)}):null;case"file":return typeof e.data=="string"&&typeof e.mimeType=="string"&&typeof e.filename=="string"?ev(e.data,e.mimeType,e.filename):null;case"audio":return typeof e.audio=="string"?{type:"audio",audio:e.audio,...Xc(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;case"video":return typeof e.video=="string"?{type:"video",video:e.video,...Xc(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;default:return null}}function WM(t,e){let n=rv(e),o=t.map(l=>rv(l.timestamp)),s=new Array(t.length),i=0;for(;i<o.length;){let l=o[i];if(l!==null){s[i]=l,i+=1;continue}let c=i;for(;c+1<o.length&&o[c+1]===null;)c+=1;let d=c-i+1,g=i>0?s[i-1]:null,u=c+1<o.length?o[c+1]:null,m=u!==null&&n!==null?Math.min(u,n):u??n;for(let y=0;y<d;y+=1)s[i+y]=m!==null?m-(d-y):g!==null?g+y+1:HM+y;i=c+1}return s.map(l=>new Date(l).toISOString())}function sv(t,e){let n=WM(t,e?.beforeCreatedAt),o=[];return t.forEach((s,i)=>{if(typeof s?.id!="string"||s.id===""||!IM.includes(s.role))return;let l=s.role,c=n[i];if(s.displayAvailable===!1){let d={historyDisplayUnavailable:!0};o.push({id:s.id,role:l,content:"",createdAt:c,agentMetadata:d});return}if(typeof s.displayContent=="string"){o.push({id:s.id,role:l,content:s.displayContent,createdAt:c});return}if(typeof s.content=="string"){o.push({id:s.id,role:l,content:s.content,createdAt:c});return}if(Array.isArray(s.content)){let d=s.content.map(RM).filter(u=>u!==null),g=Xb(d);o.push({id:s.id,role:l,content:g||(Qc(d)?Ei:""),createdAt:c,...d.length>0&&{contentParts:d}});return}o.push({id:s.id,role:l,content:"",createdAt:c})}),o}function Oa(t){let e=t.content;if(typeof e!="string"||e==="")return;let n=t.contentParts??t.llmContent??t.rawContent??e;if(!(typeof n=="string"&&n===e))return e}function Na(t,e){let n=new Map;for(let o of t)n.set(o.id,o);for(let o of e)n.set(o.id,o);return[...n.values()].sort((o,s)=>{let i=new Date(o.createdAt).getTime(),l=new Date(s.createdAt).getTime();if(!Number.isNaN(i)&&!Number.isNaN(l)&&i!==l)return i-l;let c=o.sequence??0,d=s.sequence??0;return c!==d?c-d:o.id.localeCompare(s.id)})}var BM="https://api.runtype.com/v1/dispatch",iv="https://api.runtype.com",Oe=class extends Error{constructor(e,n,o){super(n),this.name="HistoryClientError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},av=32768,rg=49152,lv=t=>{let e=t??{},n=typeof e.targetId=="string"?e.targetId:null;return{id:typeof e.id=="string"?e.id:"",title:typeof e.title=="string"?e.title:"",targetId:n,preview:typeof e.preview=="string"?e.preview:null,messageCount:typeof e.messageCount=="number"?e.messageCount:0,createdAt:typeof e.createdAt=="string"?e.createdAt:"",updatedAt:typeof e.updatedAt=="string"?e.updatedAt:""}},cv=t=>"reason"in t?t.reason:void 0,dv="The identity proof was not admitted; account history is unavailable",sg="The identity proof was rejected",pv="The request carried no visitor credential",uv="The stored visitor belongs to a different signed-in user",ig=(t,e)=>t instanceof Oe&&t.code===e;function DM(t){let e=t.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(o)return`attachment.${o}`;let s=e.indexOf("/");if(s>0){let i=e.slice(s+1).split(";")[0]?.trim()??"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var ag=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0),gv=t=>t.slice().sort((e,n)=>new Date(e.createdAt).getTime()-new Date(n.createdAt).getTime()),fv=t=>({role:t.role,content:t.contentParts??t.llmContent??t.rawContent??t.content,createdAt:t.createdAt});function _M(t){switch(t){case"json":return jy;case"regex-json":return zy;case"xml":return Ky;default:return qy}}var mv=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function OM(t,e){if(!t)return e;let n=t.trim(),o=e.trim();if(n.length===0)return e;if(o.length===0)return t;let s=mv(n);if(!mv(o))return t;if(!s||o===n||o.startsWith(n))return e;let l=Ma(t);return Ma(e)!==null&&l===null?e:t}var Fa=class{constructor(e={},n={}){this.config=e;this.historyInternals=n;this.currentClientTurnId=null;this.clientSession=null;this.sessionInitPromise=null;this.sessionWarmLatch=!1;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;this.historyUnavailable=!1;this.historyUnavailableWarned=!1;this.claimInFlight=!1;this.historyIdentityStatus=null;this.historyIdentitySubscribers=new Set;this.historyAvailabilitySubscribers=new Set;this.webMcpBridge=null;this.webMcpBridgePromise=null;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=e.apiUrl??BM,this.headers={"Content-Type":"application/json","X-Persona-Version":Is,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??_M(e.parserType),this.contextProviders=e.contextProviders??[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,e.webmcp?.enabled===!0&&(this.webMcpBridgePromise=this.createWebMcpBridge(e.webmcp))}createWebMcpBridge(e){return Ib().then(n=>{let o=new n.WebMcpBridge(e,{recordToolDisplayTitles:_y,getToolDisplayTitle:Ac,loadPolyfill:Ny});return this.pendingWebMcpConfirmHandler!==void 0&&o.setConfirmHandler(this.pendingWebMcpConfirmHandler),this.webMcpBridge=o,o}).catch(n=>(this.webMcpBridgePromise=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),null))}getWebMcpBridge(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.webMcpBridgePromise||(this.webMcpBridgePromise=this.createWebMcpBridge(this.config.webmcp)),this.webMcpBridgePromise)}updateConfig(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){this.pendingWebMcpConfirmHandler=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.config.webmcp?.enabled!==!0?null:this.getWebMcpBridge().then(s=>s?s.executeToolCall(e,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:n,target:o,targetProviders:s}=this.config;if(!o)return{agentId:e,flowId:n};let i=Rb(o,s);return i.kind==="agentId"?{agentId:i.agentId}:i.kind==="flowId"?{flowId:i.flowId}:{targetPayload:i.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}clientApiBase(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||iv}getClientApiUrl(e){return`${this.clientApiBase()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let n=await this.initSession(),o=!1;for(;;){let s=n.conversationId,i=await this.readVisitorToken();if(n.durableRecovery?.enabled!==!0||!s||!i)throw new Oe("visitor_token_missing","Durable recovery is not enabled for this client session");let l=`${this.clientApiBase()}/v1/client/conversations/${encodeURIComponent(s)}/executions/${encodeURIComponent(e.executionId)}/events`,c=new URLSearchParams({sessionId:n.sessionId,after:e.after}),d=await fetch(`${l}?${c}`,{method:"GET",headers:{"X-Persona-Version":Is,"X-Visitor-Token":i},signal:e.signal});if(d.status===401&&!o){o=!0,n=await this.recoverFromUnauthorized(await this.readErrorCode(d),null,!0);continue}if(!d.ok)throw await this.historyErrorFor(d,!0);return d}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.sessionInitPromise||e&&new Date<e.expiresAt||this.sessionWarmLatch===e?null:(this.sessionWarmLatch=e,this.initSession().catch(()=>null))}async initSession(){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;let e=this.sessionInitPromise=this._doInitSession().then(n=>this.sessionInitPromise!==e?this.initSession():(this.clientSession=n,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(n),n)).finally(()=>{this.sessionInitPromise===e&&(this.sessionInitPromise=null)});return e}isHistoryCapable(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.historyUnavailable}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.get()??null):null}markHistoryUnavailable(){if(!this.historyUnavailable){this.setHistoryIdentityStatus({state:"unavailable",reason:"history_disabled"}),this.historyUnavailable=!0,!this.historyUnavailableWarned&&typeof console<"u"&&(this.historyUnavailableWarned=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.historyAvailabilitySubscribers])e(!1)}}getHistoryIdentityStatus(){return this.historyIdentityStatus??this.restingIdentityStatus()}subscribeHistoryIdentityStatus(e){return this.historyIdentitySubscribers.add(e),()=>{this.historyIdentitySubscribers.delete(e)}}subscribeHistoryAvailability(e){return this.historyAvailabilitySubscribers.add(e),this.historyUnavailable&&e(!1),()=>{this.historyAvailabilitySubscribers.delete(e)}}restingIdentityStatus(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.historyUnavailable?{state:"unavailable",reason:"history_disabled"}:this.browserOnlyStatus():{state:"unavailable",reason:"ineligible_mode"}}browserOnlyStatus(){let e=this.historyIdentityStatus;return e?.state==="browser_only"?e:this.derivedBrowserOnly()}derivedBrowserOnly(){return this.config.features?.history?.scope==="browser"?{state:"browser_only",reason:"configured_browser_scope"}:this.config.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}setHistoryIdentityStatus(e){let n=this.getHistoryIdentityStatus(),o=n.state===e.state&&cv(n)===cv(e);if(this.historyIdentityStatus=e,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let s of[...this.historyIdentitySubscribers])s(e)}}async createClientSession(e){let n=this.isHistoryCapable()&&!e.omitVisitorFields,o=!e.omitVisitorFields,s=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,s=await this.readVisitorToken());let i=this.routing(),l=i.agentId??i.flowId,c=n||e.durableResume?e.conversationId:void 0,d={token:this.config.clientToken,...l&&{flowId:l},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&s?{visitorToken:s}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...c?{conversationId:c}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let g=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Is},body:JSON.stringify(d),signal:e.signal});if(!g.ok){let m=await g.json().catch(()=>({error:"Session initialization failed"}));if(n&&g.status===403&&m.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),c)throw new Oe("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...e,omitVisitorFields:!0})}throw g.status===403&&m.error==="durable_recovery_disabled"?new Oe("history_disabled","Durable recovery is disabled for this surface"):(n||e.durableResume)&&g.status===401&&m.error==="visitor_required"?new Oe("visitor_required","Visitor credential no longer resolves"):c&&g.status===404?new Oe("not_found","Conversation not found"):g.status===401?new Error(`Invalid client token: ${m.hint||m.error}`):g.status===403?new Error(`Origin not allowed: ${m.hint||m.error}`):new Error(m.error||"Failed to initialize session")}let u=await g.json();return u.visitor?.token&&await this.historyInternals.visitorStore?.set(u.visitor.token),{sessionId:u.sessionId,expiresAt:new Date(u.expiresAt),flow:u.flow,...u.conversationId?{conversationId:u.conversationId}:{},...u.targetId?{targetId:u.targetId}:{},...u.conversationRevision?{conversationRevision:u.conversationRevision}:{},...u.durableRecovery?{durableRecovery:u.durableRecovery}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async _doInitSession(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.isHistoryCapable()&&!n)return this.ordinaryInit(e,!1);let o=await this.readVisitorToken();if(e&&o)try{let s=await this.createClientSession({conversationId:e,durableResume:n});return n&&s.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.finishInit(s,e,!1)}catch(s){if(!ig(s,"not_found")&&!ig(s,"visitor_required")&&!ig(s,"history_disabled"))throw s;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.ordinaryInit(e,!0)}return this.ordinaryInit(e,!1)}async ordinaryInit(e,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.doOrdinaryInit(e,n)):this.doOrdinaryInit(e,n)}async doOrdinaryInit(e,n){let o=this.config.getStoredSessionId?.()||null,s=await this.createClientSession({storedSessionId:o}),i=await this.claimFirstConversation(s);return this.finishInit(i,e,n)}async reinitWithProof(e){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,s=await this.createClientSession({storedSessionId:n,identityProof:e}),i=this.finishInit(s,o,!1);return this.clientSession=i,this.sessionInitPromise=null,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint(),i}async claimFirstConversation(e){if(!e.visitor?.token||this.claimInFlight||!this.isHistoryCapable()&&e.durableRecovery?.enabled!==!0)return e;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:e.sessionId})}catch{return e}finally{this.claimInFlight=!1}}finishInit(e,n,o){let s=e.conversationId;return s&&n&&(o||s!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:s}),this.config.setStoredSessionId?.(e.sessionId),s&&(this.config.setStoredConversationId?.(s),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}prepared(e){let n=!1;return{session:e,commit:()=>{n||(n=!0,this.clientSession=e,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(e,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new Oe("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new Oe("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let i=await this.createClientSession({conversationId:e,identityProof:o});return this.prepared(i)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let e=await this.createClientSession({});return this.prepared(e)}handleExternalCredentialChange(){this.clearClientSession(),this.isHistoryCapable()&&this.setHistoryIdentityStatus(this.derivedBrowserOnly())}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.clientApiBase()}/v1/client/feedback`}async sendFeedback(e){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(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let s={...e,...this.config.clientToken&&{token:this.config.clientToken}},i=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Is},body:JSON.stringify(s)});if(!i.ok){let l=await i.json().catch(()=>({error:"Feedback submission failed"}));throw i.status===401?(this.clientSession=null,this.sessionWarmLatch=!1,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(l.error||"Failed to submit feedback")}}async submitMessageFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:e,comment:n})}async submitNPSFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:e,comment:n})}historyUrl(e,n){let o=new URLSearchParams;for(let[i,l]of Object.entries(n))l===void 0||l===""||o.set(i,String(l));let s=o.toString();return`${this.clientApiBase()}/v1/client/${e}${s?`?${s}`:""}`}resolveHistoryScope(e){if(e)return e;let n=this.config.features?.history?.scope;return n||(this.config.getIdentityProof?"verified-user":"browser")}async resolveChatIdentityProof(e){e?.throwIfAborted();let n=this.config.identityProvider;if(n===void 0)return;let o=this.config.getIdentityProof;if(!n.trim()||!o)throw new Error("Chat identity requires identityProvider and getIdentityProof.");let s,i;try{let l=Promise.resolve().then(()=>o());s=e?await Promise.race([l,new Promise((c,d)=>{i=()=>d(e.reason),e.addEventListener("abort",i,{once:!0}),e.aborted&&i()})]):await l}catch{throw e?.throwIfAborted(),new Error("The identity proof provider failed.")}finally{i&&e?.removeEventListener("abort",i)}if(typeof s!="string"||!s.trim())throw new Error("A fresh identity proof is required to send this message.");return{provider:n,token:s}}async resolveIdentityProof(e,n){let o=this.config.getIdentityProof;if(!o)return n&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;n&&this.setHistoryIdentityStatus({state:"verifying"});let s;try{s=await o()??null}catch{throw n&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new Oe("identity_provider_failed","The identity proof provider failed")}if(s)return s;if(e.visitor?.endUserId!=null)throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new Oe("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return n&&this.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async bindIdentity(e,n,o){if(e.visitor?.endUserId!=null)return e;let s=await this.reinitWithProof(n);if(!(s.visitor?.identityStatus==="admitted"&&s.visitor?.endUserId!=null))throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new Oe("proof_not_admitted",dv);return s}async readErrorCode(e){let n=await e.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async recoverFromUnauthorized(e,n,o){let s=e.toLowerCase();if(s.includes("invalid_identity_proof"))throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new Oe("invalid_identity_proof",sg);if(s.includes("visitor token required"))throw new Oe("visitor_token_missing",pv);if(s.includes("visitor_identity_mismatch")){if(!n)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new Oe("visitor_identity_mismatch",uv);return this.reinitWithProof(n)}if(s.includes("expired")||s.includes("not found"))return this.clearClientSession(),this.initSession();throw new Oe("unauthorized",e||"History request was not authorized")}async historyErrorFor(e,n){let o=await this.readErrorCode(e);if(e.status===404)return new Oe("not_found","Conversation not found");if(e.status===429){let s=Number.parseInt(e.headers.get("Retry-After")??"",10);return new Oe("rate_limited","Too many history requests",{...Number.isFinite(s)?{retryAfterSeconds:s}:{}})}if(e.status===503&&o.includes("identity_proof_not_admitted"))return n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new Oe("proof_not_admitted",dv);if(e.status===401){let s=o.toLowerCase();return s.includes("invalid_identity_proof")?(n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new Oe("invalid_identity_proof",sg)):s.includes("visitor token required")?new Oe("visitor_token_missing",pv):s.includes("visitor_identity_mismatch")?new Oe("visitor_identity_mismatch",uv):new Oe("unauthorized",o||"History request was not authorized")}return new Oe("request_failed",o||`History request failed (${e.status})`)}commitIdentityAcknowledgement(e,n,o){let s=e?.toLowerCase()??null;if(n){if(s==="admitted"){o&&this.setHistoryIdentityStatus({state:"verified"});return}throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),s==="ignored"?new Oe("identity_contract_violation","Server reported an ignored identity proof on a success response"):new Oe("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(s==="admitted")throw new Oe("identity_contract_violation","Server admitted an identity proof that was never sent");o&&this.setHistoryIdentityStatus(this.browserOnlyStatus())}async historyFetch(e,n){this.assertHistoryUsable();let o=n.trackIdentity!==!1,s=await this.initSession(),i=null;this.resolveHistoryScope(n.scope)==="verified-user"&&(i=await this.resolveIdentityProof(s,o),i&&(s=await this.bindIdentity(s,i,o)));let l=this.historyInternals.visitorStore,c=!1;for(;;){let d=l?.revision()??0,g=await this.readVisitorToken();if(!g&&!n.visitorTokenOptional)throw new Oe("visitor_token_missing","No visitor credential is stored for this browser");let u=await fetch(this.historyUrl(e,{...n.query,sessionId:s.sessionId}),{method:n.method,headers:{"X-Persona-Version":Is,...g?{"X-Visitor-Token":g}:{},...i?{"X-Identity-Proof":i}:{},...n.body!==void 0?{"Content-Type":"application/json"}:{}},...n.body!==void 0?{body:JSON.stringify(n.body)}:{},...n.keepalive?{keepalive:!0}:{}});if(u.status===401&&!c){c=!0,s=await this.recoverFromUnauthorized(await this.readErrorCode(u),i,o);continue}if(!u.ok)throw await this.historyErrorFor(u,o);let m=u.headers.get("X-History-Identity-Status"),y=await u.json().catch(()=>{});if(l&&l.revision()!==d)throw new Oe("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(m,i!==null,o),y}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new Oe("history_disabled","Visitor history is disabled for this surface")}async listConversations(e){let n=await this.historyFetch("conversations",{method:"GET",query:{...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(lv),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async getConversation(e,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(e)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:lv(o),messages:Array.isArray(o?.messages)?o.messages:[],nextMessageCursor:typeof o?.nextMessageCursor=="string"?o.nextMessageCursor:null,conversationRevision:typeof o?.conversationRevision=="string"?o.conversationRevision:null}}async finalizeDisplayProjections(e,n){this.assertHistoryUsable();let o=0;for(let d of n){let g=d.displayContent.length;if(g>av)throw new Oe("payload_too_large",`displayContent exceeds the ${av} character limit`);o+=g}if(o>rg)throw new Oe("payload_too_large",`Display projection batch exceeds the ${rg} character limit`);await this.initSession();let s=this.historyInternals.visitorStore,i=s?.revision()??0,l=await this.historyFetch(`conversations/${encodeURIComponent(e)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=rg,trackIdentity:!1}),c=typeof l?.conversationRevision=="string"?l.conversationRevision:null;return c&&this.clientSession?.conversationId===e&&(s?.revision()??0)===i&&this.historyInternals.setStoredConversationRevision?.(c),{conversationRevision:c}}async deleteConversation(e,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(e)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async deleteAllConversations(e){let n=await this.historyFetch("conversations",{method:"DELETE",query:{...e?.targetId!==void 0?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.deleted:0}}async resetVisitor(){this.assertHistoryUsable(),this.setHistoryIdentityStatus({state:"resetting"});try{await this.historyFetch("visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await this.historyInternals.visitorStore?.clear(),this.setHistoryIdentityStatus(this.derivedBrowserOnly())}return{reset:!0}}async dispatch(e,n){return e.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(e,n):this.isAgentMode()?this.dispatchAgent(e,n):this.dispatchProxy(e,n)}async dispatchClientToken(e,n){let o=Wb();this.currentClientTurnId=o;let s=()=>this.currentClientTurnId===o,i=l=>{s()&&n(l)};n({type:"status",status:"connecting"});try{let l=()=>{if(e.signal?.throwIfAborted(),!s())throw new DOMException("Turn superseded","AbortError")},c=this.clientSession??await this.initSession();l();let d=async()=>{l();let H=c,I=H.durableRecovery?.enabled===!0;if(I&&(!H.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");l();let N=await this.createClientSession({...I||this.isHistoryCapable()?{conversationId:H.conversationId,durableResume:I}:{storedSessionId:H.sessionId},signal:e.signal});if(l(),H.conversationId&&N.conversationId!==H.conversationId||I&&N.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");c=this.finishInit(N,H.conversationId??null,!1),this.clientSession=c,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(c)};Date.now()>=c.expiresAt.getTime()-6e4&&await d();let g=await this.buildPayload(e.messages),u=g.metadata?Object.fromEntries(Object.entries(g.metadata).filter(([H])=>H!=="sessionId"&&H!=="session_id")):void 0,m=this.isHistoryCapable(),y={sessionId:c.sessionId,messages:e.messages.filter(ag).map(H=>{let I=m?Oa(H):void 0;return{id:H.id,role:H.role,content:H.contentParts??H.llmContent??H.rawContent??H.content,...I!==void 0&&{displayContent:I}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...g.inputs&&Object.keys(g.inputs).length>0&&{inputs:g.inputs},...g.context&&{context:g.context},turnId:o,...e.interrupt&&{submitMode:"interrupt"}},b=async()=>{l();let H=c.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return l(),this.sendWithClientToolsDiff(c.sessionId,g.clientTools,async I=>{l();let N=await this.resolveChatIdentityProof(e.signal);l();let x={...y,sessionId:c.sessionId,...I,...N&&{identityProof:N}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...x,...N&&{identityProof:{provider:N.provider,token:"[REDACTED]"}}}),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Is,...H?{"X-Visitor-Token":H}:{}},body:JSON.stringify(x),signal:e.signal})})},C=await b();if(l(),C.response.status===401){let H=await C.response.clone().json().catch(()=>null);l(),H?.error==="Session not found or expired"&&(await d(),C=await b(),l())}let{response:S,commit:E}=C;if(!S.ok){let H=await S.json().catch(()=>({error:"Chat request failed"}));if(S.status===401&&H.error==="invalid_identity_proof"){let N=new Oe("invalid_identity_proof",sg);throw i({type:"error",error:N}),N}if(S.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let N=new Error("Session expired. Please refresh to continue.");throw i({type:"error",error:N}),N}if(S.status===429){let N=new Error(H.hint||"Message limit reached for this session.");throw i({type:"error",error:N}),N}if(S.status===410&&H.error==="conversation_deleted"){let N=new Oe("conversation_deleted","This conversation was deleted");throw i({type:"error",error:N}),N}let I=new Error(H.error||"Failed to send message");throw i({type:"error",error:I}),I}if(!S.body){let H=new Error("No response body received");throw i({type:"error",error:H}),H}E(),i({type:"status",status:"connected"});try{await this.streamResponse(S.body,i,e.assistantMessageId)}finally{i({type:"status",status:"idle"})}}catch(l){let c=l instanceof Error?l:new Error(String(l));throw!(c instanceof Oe)&&!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&i({type:"error",error:c}),c}}async dispatchProxy(e,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let l=await this.getHeaders();s={...s,...l}}catch(l){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal},o)}catch(l){let c=l instanceof Error?l:new Error(String(l));throw n({type:"error",error:c}),c}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let l=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw n({type:"error",error:l}),l}n({type:"status",status:"connected"});try{await this.streamResponse(i.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(e,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let l=await this.getHeaders();s={...s,...l}}catch(l){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal},o)}catch(l){let c=l instanceof Error?l:new Error(String(l));throw n({type:"error",error:c}),c}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let l=new Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw n({type:"error",error:l}),l}n({type:"status",status:"connected"});try{await this.streamResponse(i.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,o,s){n({type:"status",status:"connected"});try{await this.streamResponse(e,n,o,s)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){let o=`${this.clientApiBase()}/v1/agents/${e.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(e,n,o,s){let i=!!(n&&n.length>0),l=i?Oy(n):void 0,c=this.clientToolsFingerprintSessionId===e,d=i&&c&&this.lastSentClientToolsFingerprint===l,g=!i&&s?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===e,u=!1,m;for(let y=0;;y++){if(m=await o({...i&&(u||!d)&&n?{clientTools:n}:{},...g?{clientTools:[]}:{},...l?{clientToolsFingerprint:l}:{}}),m.status===409&&y===0&&i&&(await m.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){u=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:m,commit:()=>{this.lastSentClientToolsFingerprint=l??null,this.clientToolsFingerprintSessionId=e,i?this.sentNonEmptyClientToolsSessionId=e:g&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(e,n,o){let s=this.isClientTokenMode(),i=s?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||iv}/resume`,l,c=null;if(s){let u=await this.initSession();l=u.sessionId,u.durableRecovery?.enabled===!0&&(c=await this.readVisitorToken())}let d={"Content-Type":"application/json",...c?{"X-Visitor-Token":c}:{},...this.headers};this.getHeaders&&Object.assign(d,await this.getHeaders());let g={executionId:e,toolOutputs:n,streamResponse:o?.streamResponse??!0,...o?.after?{after:o.after}:{}};if(l&&(g.sessionId=l),s&&l){let u=[...Gc(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:m,commit:y}=await this.sendWithClientToolsDiff(l,u,b=>{let C={...g,...b};return this.debug&&console.debug("[AgentWidgetClient] client token resume",C),fetch(i,{method:"POST",headers:d,body:JSON.stringify(C),signal:o?.signal})},{emptyMeansReplace:!0});return m.ok&&y(),m}return fetch(i,{method:"POST",headers:d,body:JSON.stringify(g),signal:o?.signal})}latestMentionContext(e){for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(e){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:e,config:this.config});i&&typeof i=="object"&&Object.assign(n,i)}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",i)}}));let o=this.latestMentionContext(e);return o&&Object.assign(n,o),Object.keys(n).length?n:null}normalizeComposerOptions(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n:void 0}applyInlineAgentModel(e,n){let o=n?.selectedModelId;return!o||!("model"in e)?e:this.config.composer?.models?.some(i=>i.id===o)?{...e,model:o}:e}async buildAgentPayload(e,n){let o=this.routing().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let s=og(gv(e),g=>ag(g)&&(g.role==="user"||g.role==="assistant"||g.role==="system")&&(!g.variant||g.variant==="assistant")?fv(g):null),i=this.normalizeComposerOptions(n),l={agent:this.applyInlineAgentModel(this.config.agent??{agentId:o},i),messages:s,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};i&&(l.composerOptions=i);let c=[...Gc(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];c.length>0&&(l.clientTools=c);let d=await this.buildContextAggregate(e);return d&&(l.context=d),l}async buildPayload(e,n){let o=og(gv(e),g=>ag(g)?fv(g):null),s=this.routing(),i={messages:o,...s.agentId?{agent:{agentId:s.agentId}}:s.flowId?{flowId:s.flowId}:{}};if(s.targetPayload)for(let[g,u]of Object.entries(s.targetPayload))g!=="messages"&&(i[g]=u);let l=[...Gc(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];l.length>0&&(i.clientTools=l);let c=await this.buildContextAggregate(e);c&&(i.context=c);let d=this.normalizeComposerOptions(n);if(d&&(i.composerOptions=d),this.requestMiddleware)try{let g=await this.requestMiddleware({payload:{...i},config:this.config});if(g&&typeof g=="object"){let u=g;return i.clientTools!==void 0&&!("clientTools"in u)&&(u.clientTools=i.clientTools),u}}catch(g){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",g)}return i}async handleCustomSSEEvent(e,n,o,s,i,l){if(!this.parseSSEEvent)return!1;try{let c=await this.parseSSEEvent(e);if(c===null)return!1;let d=u=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:i(),...u!==void 0&&{partId:u}};return o.current=m,s(m),m},g=u=>o.current?o.current:d(u);if(c.text!==void 0){c.partId!==void 0&&l.current!==null&&c.partId!==l.current&&(o.current&&(o.current.streaming=!1,s(o.current)),d(c.partId)),c.partId!==void 0&&(l.current=c.partId);let u=g(c.partId);c.partId!==void 0&&!u.partId&&(u.partId=c.partId),u.content+=c.text,s(u)}return c.done&&(o.current&&(o.current.streaming=!1,s(o.current)),l.current=null,n({type:"status",status:"idle"})),c.error&&(l.current=null,n({type:"error",error:new Error(c.error)})),!0}catch(c){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",c),!1}}async streamResponse(e,n,o,s){let i=e.getReader(),l=new TextDecoder,c="",d=Date.now(),g=0,u=()=>d+g++,m=V=>{let w=V.reasoning?{...V.reasoning,chunks:[...V.reasoning.chunks]}:void 0,O=V.toolCall?{...V.toolCall,chunks:V.toolCall.chunks?[...V.toolCall.chunks]:void 0}:void 0,j=V.tools?V.tools.map(X=>({...X,chunks:X.chunks?[...X.chunks]:void 0})):void 0;return{...V,reasoning:w,toolCall:O,tools:j}},y=V=>{if(V.role!=="assistant"||V.variant)return!0;let w=Array.isArray(V.contentParts)&&V.contentParts.length>0,O=typeof V.rawContent=="string"&&V.rawContent.trim()!=="";return typeof V.content=="string"&&V.content.trim()!==""||w||O||!!V.stopReason},b=V=>{y(V)&&n({type:"message",message:m(V)})},C=null,S=null,E={current:null},H={current:null},I=null,N="",x=new Map,D=new Map,L=new Map,$=new Map,K=new Map,se=o,ne=!1,M=()=>{if(C)return C;let V,w="",O=I;return!ne&&se?(V=se,ne=!0,w=s??""):se&&O?V=`${se}_${O}`:V=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,C={id:V,role:"assistant",content:w,createdAt:new Date().toISOString(),streaming:!0,sequence:u()},b(C),C},T=V=>{let w=$.get(V);if(w)return w;let O={id:`reason-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:V,status:"streaming",chunks:[]}};return $.set(V,O),b(O),O},_=new Set,k=new Map,Z=new Set,F=new Map,ie=V=>{if(!V)return!1;let w=V.replace(/_+/g,"_").replace(/^_|_$/g,"");return w==="emit_artifact_markdown"||w==="emit_artifact_component"},le=V=>{let w=K.get(V);if(w)return w;let O={id:`tool-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:V,status:"pending"}};return K.set(V,O),b(O),O},pe=V=>{if(typeof V=="number"&&Number.isFinite(V))return V;if(typeof V=="string"){let w=Number(V);if(!Number.isNaN(w)&&Number.isFinite(w))return w;let O=Date.parse(V);if(!Number.isNaN(O))return O}return Date.now()},ve=V=>{if(typeof V=="string")return V;if(V==null)return"";try{return JSON.stringify(V)}catch{return String(V)}},Ce=new Map,me=new Map,vt=(V,w)=>{let O=ve(w),j=me.get(V.id),X=OM(j,O);V.rawContent=X;let Y=Ce.get(V.id),ge=Xe=>{let $e=V.content??"";Xe.trim()!==""&&($e.trim().length===0||Xe.startsWith($e)||Xe.trimStart().startsWith($e.trim()))&&(V.content=Xe)},xe=()=>{if(Y){let Xe=Y.close?.();Xe instanceof Promise&&Xe.catch(()=>{})}Ce.delete(V.id),me.delete(V.id),V.streaming=!1,b(V)};if(!Y){ge(O),xe();return}let Se=Ma(X);if(Se!==null&&Se.trim()!==""){ge(Se),xe();return}let dt=Xe=>{let $e=typeof Xe=="string"?Xe:Xe?.text??null;if($e!==null&&$e.trim()!=="")return $e;let pt=Y.getExtractedText();return pt!==null&&pt.trim()!==""?pt:O},Wt;try{Wt=Y.processChunk(X)}catch{ge(O),xe();return}if(Wt instanceof Promise){Wt.then(Xe=>{ge(dt(Xe)),xe()}).catch(()=>{ge(O),xe()});return}ge(dt(Wt)),xe()},st=null,he=(V,w,O,j)=>{V.rawContent=w,Ce.has(V.id)||Ce.set(V.id,this.createStreamParser());let X=Ce.get(V.id),Y=w.trim().startsWith("{")||w.trim().startsWith("[");if(Y&&me.set(V.id,w),X.__isPlainTextParser===!0){V.content=j!==void 0?w:V.content+O,me.delete(V.id),Ce.delete(V.id),V.rawContent=void 0,b(V);return}let xe=X.processChunk(w);if(xe instanceof Promise)xe.then(Se=>{let dt=typeof Se=="string"?Se:Se?.text??null;dt!==null&&dt.trim()!==""?(V.content=dt,b(V)):!Y&&!w.trim().startsWith("<")&&(V.content=j!==void 0?w:V.content+O,me.delete(V.id),Ce.delete(V.id),V.rawContent=void 0,b(V))}).catch(()=>{V.content=j!==void 0?w:V.content+O,me.delete(V.id),Ce.delete(V.id),V.rawContent=void 0,b(V)});else{let Se=typeof xe=="string"?xe:xe?.text??null;Se!==null&&Se.trim()!==""?(V.content=Se,b(V)):!Y&&!w.trim().startsWith("<")&&(V.content=j!==void 0?w:V.content+O,me.delete(V.id),Ce.delete(V.id),V.rawContent=void 0,b(V))}},W=(V,w)=>{let O=w??V.content;if(O==null||O===""){V.streaming=!1,b(V);return}let X=me.get(V.id)??ve(O);V.rawContent=X;let Y=Ce.get(V.id),ge=null,xe=!1;if(Y&&(ge=Y.getExtractedText(),ge===null&&(ge=Ma(X)),ge===null)){let Se=Y.processChunk(X);Se instanceof Promise?(xe=!0,Se.then(dt=>{let Wt=typeof dt=="string"?dt:dt?.text??null;Wt!==null&&(V.content=Wt,V.streaming=!1,Ce.delete(V.id),me.delete(V.id),b(V))}).catch(()=>{})):ge=typeof Se=="string"?Se:Se?.text??null}if(!xe){ge!==null&&ge.trim()!==""?V.content=ge:me.has(V.id)||(V.content=ve(O));let Se=Ce.get(V.id);if(Se){let dt=Se.close?.();dt instanceof Promise&&dt.catch(()=>{}),Ce.delete(V.id)}me.delete(V.id),V.streaming=!1,b(V)}},We=(V,w,O)=>{let j=D.get(V);if(j)return j;let X={id:`nested-${w}-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),...O?{variant:O}:{},...O==="reasoning"?{reasoning:{id:V,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:w}};return D.set(V,X),b(X),X},Fe=[],bn,sn=new Map,Kt=0,kn="agent",Be=!1,Ge=null,Pe=null,Bo=this.config.iterationDisplay??"separate";for(bn=()=>{for(let V=0;V<Fe.length;V++){let w=Fe[V];if(!Be&&kn!=="flow"&&typeof w.stepType=="string"&&(kn="flow"),w.type==="reasoning_start"){let O=typeof w.id=="string"?w.id:null,j=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(O&&j){x.set(O,j),We(O,j,"reasoning");continue}let X=w.id,Y=T(X);Y.reasoning=Y.reasoning??{id:X,status:"streaming",chunks:[]},Y.reasoning.startedAt=Y.reasoning.startedAt??Date.now(),Y.reasoning.completedAt=void 0,Y.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(Y.reasoning.scope=w.scope),Y.streaming=!0,Y.reasoning.status="streaming",b(Y)}else if(w.type==="reasoning_delta"){let O=typeof w.id=="string"?w.id:null;if(O&&x.has(O)&&D.has(O)){let Y=D.get(O),ge=w.delta;ge&&Y.reasoning&&(Y.reasoning.chunks.push(String(ge)),b(Y));continue}let j=w.id,X=T(j);X.reasoning=X.reasoning??{id:j,status:"streaming",chunks:[]},X.reasoning.startedAt=X.reasoning.startedAt??Date.now(),w.delta&&X.reasoning.chunks.push(w.delta),X.reasoning.status="streaming",X.streaming=!0,b(X)}else if(w.type==="reasoning_complete"){let O=typeof w.id=="string"?w.id:null;if(O&&x.has(O)&&D.has(O)){let ge=D.get(O);if(ge.reasoning){let xe=typeof w.text=="string"?w.text:"";xe&&ge.reasoning.chunks.length===0&&ge.reasoning.chunks.push(xe),ge.reasoning.status="complete",ge.streaming=!1,b(ge)}x.delete(O),D.delete(O);continue}let j=w.id,X=typeof w.text=="string"?w.text:"";!$.get(j)&&(X||w.scope==="loop")&&T(j);let Y=$.get(j);if(Y?.reasoning){(w.scope==="loop"||w.scope==="turn")&&(Y.reasoning.scope=w.scope),X&&Y.reasoning.chunks.length===0&&Y.reasoning.chunks.push(X),Y.reasoning.status="complete",Y.reasoning.completedAt=Date.now();let ge=Y.reasoning.startedAt??Date.now();Y.reasoning.durationMs=Math.max(0,(Y.reasoning.completedAt??Date.now())-ge),Y.streaming=!1,b(Y)}}else if(w.type==="tool_start"){C&&(C.streaming=!1,b(C),C=null),typeof w.iteration=="number"&&(Kt=w.iteration);let O=w.toolCallId,j=w.toolName;if(ie(j)){_.add(O);continue}let X=le(O),Y=X.toolCall??{id:O,status:"pending"};Y.name=j??Y.name,Y.status="running",Y.success=void 0,Y.error=void 0,Y.duration=void 0,w.parameters!==void 0&&(Y.args=w.parameters),Y.startedAt=Y.startedAt??pe(w.startedAt),Y.completedAt=void 0,Y.durationMs=void 0,X.toolCall=Y,X.streaming=!0,w.executionId&&(X.agentMetadata={executionId:w.executionId,iteration:w.iteration}),b(X)}else if(w.type==="tool_output_delta"){let O=w.toolCallId;if(_.has(O))continue;let j=le(O),X=j.toolCall??{id:O,status:"running"};X.startedAt=X.startedAt??Date.now();let Y=w.delta;Y&&(X.chunks=X.chunks??[],X.chunks.push(String(Y))),X.status="running",j.toolCall=X,j.streaming=!0,w.executionId&&(j.agentMetadata=j.agentMetadata??{executionId:w.executionId,iteration:Kt}),b(j)}else if(w.type==="tool_complete"){let O=w.toolCallId;if(_.has(O)){_.delete(O);continue}let j=le(O),X=j.toolCall??{id:O,status:"running"};X.status="complete",w.result!==void 0&&(X.result=w.result),X.name=w.toolName??X.name,X.success=w.success,X.error=w.error,X.completedAt=Date.now();let Y=w.executionTime;if(typeof Y=="number")X.durationMs=Y,X.duration=Y;else{let ge=X.startedAt??Date.now();X.durationMs=Math.max(0,(X.completedAt??Date.now())-ge)}j.toolCall=X,j.streaming=!1,w.executionId&&(j.agentMetadata=j.agentMetadata??{executionId:w.executionId,iteration:w.iteration??Kt}),b(j)}else if(w.type==="await"&&w.toolName){let O=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,j=O??w.toolId??`local-${u()}`,X=le(j),Y=w.toolName,ge=w.origin==="webmcp"&&!yi(Y)?`webmcp:${Y}`:Y,xe=yi(ge),Se=X.toolCall??{id:j,status:"pending"};Se.name=ge,Se.args=w.parameters,Se.status=xe?"running":"complete",Se.chunks=Se.chunks??[],Se.startedAt=Se.startedAt??pe(w.awaitedAt),xe?(Se.completedAt=void 0,Se.duration=void 0,Se.durationMs=void 0):Se.completedAt=Se.completedAt??Se.startedAt,X.toolCall=Se,X.streaming=!1,X.agentMetadata={...X.agentMetadata,executionId:w.executionId??X.agentMetadata?.executionId,awaitingLocalTool:!0,...O?{webMcpToolCallId:O}:{}},b(X)}else if(w.type==="text_start"){let O=typeof w.id=="string"?w.id:null,j=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(O&&j){x.set(O,j);continue}let X=C;X&&(kn==="flow"?(W(X),st=X):(X.streaming=!1,b(X)),C=null),I=typeof w.id=="string"?w.id:I,N=""}else if(w.type==="text_delta"){let O=typeof w.id=="string"?w.id:null,j=O?x.get(O):void 0;if(O&&j){let ge=typeof w.delta=="string"?w.delta:"",xe=(L.get(O)??"")+ge;if(L.set(O,xe),xe.trim()==="")continue;let Se=We(O,j);Se.agentMetadata={...Se.agentMetadata,executionId:w.executionId,parentToolId:j},he(Se,xe,ge,void 0);continue}if(I=typeof w.id=="string"?w.id:I,kn==="flow"){let ge=typeof w.delta=="string"?w.delta:"";if(N+=ge,N.trim()==="")continue;let xe=M();xe.agentMetadata={executionId:w.executionId,iteration:Kt},he(xe,N,ge,void 0),S=xe;continue}let X=typeof w.delta=="string"?w.delta:"";N+=X;let Y=M();Y.agentMetadata={executionId:w.executionId,iteration:Kt,turnId:Ge??void 0,agentName:Pe?.agentName},he(Y,N,X,void 0),S=Y}else if(w.type==="text_complete"){let O=typeof w.id=="string"?w.id:null;if(O&&x.has(O)){let X=D.get(O);X&&W(X),x.delete(O),L.delete(O),D.delete(O);continue}let j=C;j&&(kn==="flow"?(W(j),st=j):((j.content??"")===""&&typeof w.text=="string"&&(j.content=w.text),j.streaming=!1,b(j)),C=null),I=null,N=""}else if(w.type==="step_complete"){if(w.stepType==="tool")continue;if(w.success===!1){let O=w.error||"Step failed";n({type:"error",error:new Error(O)});let j=C;j&&j.streaming&&(j.streaming=!1,b(j)),n({type:"status",status:"idle"});continue}{let O=st;st=null;let j=w.stopReason,Y=(w.result&&typeof w.result=="object"?w.result:null)?.response;if(O)j&&(O.stopReason=j),Y!=null?vt(O,Y):O.streaming!==!1&&(Ce.delete(O.id),me.delete(O.id),O.streaming=!1,b(O));else{let ge=Y!=null&&Y!=="";if(ge||j){let xe=M();j&&(xe.stopReason=j),ge?W(xe,Y):(xe.streaming=!1,b(xe))}}continue}}else if(w.type==="execution_start")kn=w.kind==="flow"?"flow":"agent",Be=!0,kn==="agent"&&(Pe={executionId:w.executionId,agentId:w.agentId??"virtual",agentName:w.agentName??""});else if(w.type==="turn_start"){let O=typeof w.iteration=="number"?w.iteration:Kt;if(O!==Kt){if(Bo==="separate"&&O>1){let j=C;j&&(j.streaming=!1,b(j),C=null)}Kt=O}Ge=typeof w.id=="string"?w.id:null,S=null}else if(w.type==="tool_input_delta"){let O=w.toolCallId;if(O){let j=K.get(O);j?.toolCall&&(j.toolCall.chunks=j.toolCall.chunks??[],j.toolCall.chunks.push(w.delta??""),b(j))}}else if(w.type==="tool_input_complete"){if(_.has(w.toolCallId))continue;let O=le(w.toolCallId),j=O.toolCall;j.args=w.parameters,j.name=w.toolName??j.name,b(O)}else if(w.type==="turn_complete"){let O=w.stopReason,j=C??S;if(O&&j!==null){let X=w.id;(!X||j.agentMetadata?.turnId===X)&&(j.stopReason=O,b(j))}Ge===w.id&&(Ge=null)}else if(w.type==="media_start"){let O=String(w.id);sn.set(O,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,toolCallId:w.toolCallId,parts:[]})}else if(w.type==="media_delta"){let O=sn.get(String(w.id));O&&typeof w.delta=="string"&&O.parts.push(w.delta)}else if(w.type==="media_complete"){let O=String(w.id),j=sn.get(O);sn.delete(O);let X=(typeof w.mediaType=="string"?w.mediaType:void 0)??j?.mediaType??"application/octet-stream",Y=typeof w.data=="string"?w.data:void 0,ge=typeof w.url=="string"?w.url:j&&j.parts.length>0?j.parts.join(""):void 0,xe=null;if(Y)xe={type:"media",data:Y,mediaType:X};else if(ge){let Xe=X.toLowerCase();xe={type:Xe==="image"||Xe.startsWith("image/")?"image-url":"file-url",url:ge,mediaType:X}}let Se=w.toolCallId??j?.toolCallId,dt=xe?[xe]:[],Wt=[];for(let Xe of dt){if(!Xe||typeof Xe!="object")continue;let $e=Xe,pt=typeof $e.type=="string"?$e.type:void 0,Gt=typeof $e.mediaType=="string"?$e.mediaType.toLowerCase():"",Mt=null,cn="";if(pt==="media"){let ut=typeof $e.data=="string"?$e.data:void 0;if(!ut)continue;cn=Gt.length>0?Gt:"application/octet-stream",Mt=`data:${cn};base64,${ut}`}else if(pt==="image-url"){let ut=typeof $e.url=="string"?$e.url:void 0;if(!ut)continue;cn=Gt,Mt=ut}else if(pt==="file-url"){let ut=typeof $e.url=="string"?$e.url:void 0;if(!ut)continue;cn=Gt,Mt=ut}else continue;if(Mt)if(pt==="image-url"||cn.startsWith("image/"))Wt.push({type:"image",image:Mt,...cn.includes("/")?{mimeType:cn}:{}});else if(cn.startsWith("audio/"))Wt.push({type:"audio",audio:Mt,mimeType:cn});else if(cn.startsWith("video/"))Wt.push({type:"video",video:Mt,mimeType:cn});else{let ut=cn||"application/octet-stream";Wt.push({type:"file",data:Mt,mimeType:ut,filename:DM(ut)})}}if(Wt.length>0){let Xe=u(),$e=Se,Gt={id:`agent-media-${typeof $e=="string"&&$e.length>0?`${$e}-${Xe}`:String(Xe)}`,role:"assistant",content:"",contentParts:Wt,createdAt:new Date().toISOString(),streaming:!1,sequence:Xe,agentMetadata:{executionId:w.executionId,iteration:Kt}};b(Gt);let Mt=C;Mt&&(Mt.streaming=!1,b(Mt)),C=null,E.current=null}}else if(w.type==="execution_complete"){let O=C;O&&(w.kind==="flow"&&O.streaming!==!1?W(O):(O.streaming=!1,b(O)),C=null),I=null,N="",st=null,n({type:"status",status:"idle",terminal:!0})}else if(w.type==="execution_error"){let O=typeof w.error=="string"?w.error:w.error?.message??"Execution error";n({type:"error",error:new Error(O)})}else if(w.type!=="ping"){if(w.type==="approval_start"){let O=w.approvalId??`approval-${u()}`,j={id:`approval-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:O,status:"pending",agentId:Pe?.agentId??"virtual",executionId:w.executionId??Pe?.executionId??"",toolName:w.toolName??"",toolType:w.toolType,description:w.description??`Execute ${w.toolName??"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};b(j)}else if(w.type==="approval_complete"){let O=w.approvalId;if(O){let X={id:`approval-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:O,status:w.decision??"approved",agentId:Pe?.agentId??"virtual",executionId:w.executionId??Pe?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};b(X)}}else if(w.type==="artifact_start"||w.type==="artifact_delta"||w.type==="artifact_update"||w.type==="artifact_complete"){if(w.type==="artifact_start"){let O=w.artifactType,j=String(w.id),X=typeof w.title=="string"?w.title:void 0,Y=w.file,ge;if(Y&&typeof Y=="object"&&!Array.isArray(Y)&&typeof Y.path=="string"&&typeof Y.mimeType=="string"&&(ge={path:Y.path,mimeType:Y.mimeType,...typeof Y.language=="string"?{language:Y.language}:{}}),n({type:"artifact_start",id:j,artifactType:O,title:X,component:typeof w.component=="string"?w.component:void 0,...ge?{file:ge}:{}}),F.set(j,{markdown:"",title:X,file:ge}),!Z.has(j)){Z.add(j);let xe=Br(this.config.features?.artifacts,{artifactType:O,...ge?{file:ge}:{}}),Se=typeof w.component=="string"?w.component:void 0,dt={id:`artifact-ref-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),rawContent:Wa(xe,{artifactId:j,title:X,artifactType:O,status:"streaming",...ge?{file:ge}:{},...Se?{component:Se}:{}})};k.set(j,dt),b(dt)}}else if(w.type==="artifact_delta"){let O=String(w.id),j=typeof w.delta=="string"?w.delta:String(w.delta??"");n({type:"artifact_delta",id:O,artDelta:j});let X=F.get(O);X&&(X.markdown+=j)}else if(w.type==="artifact_update"){let O=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:O,component:typeof w.component=="string"?w.component:void 0});let j=F.get(String(w.id));j&&(j.props={...j.props??{},...O})}else if(w.type==="artifact_complete"){let O=String(w.id);n({type:"artifact_complete",id:O});let j=k.get(O);if(j){j.streaming=!1;try{let X=JSON.parse(j.rawContent??"{}");if(X.props){X.props.status="complete";let Y=F.get(O);Y?.markdown&&(X.props.markdown=Y.markdown),Y?.file&&(X.props.file=Y.file),X.component==="PersonaArtifactInline"&&Y?.props&&Object.keys(Y.props).length>0&&(X.props.componentProps=Y.props)}j.rawContent=JSON.stringify(X)}catch{}F.delete(O),b(j),k.delete(O)}}}else if(w.type==="error"&&w.recoverable===!1&&w.error!=null&&w.error!==""){let O=typeof w.error=="string"?w.error:w.error?.message!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(O)});let j=C;j&&j.streaming&&(j.streaming=!1,b(j)),n({type:"status",status:"idle"})}}}Fe.length=0};;){let{done:V,value:w}=await i.read();if(V)break;c+=l.decode(w,{stream:!0});let O=c.split(`
1
+ import{a as Om,b as qa,d as is,e as _m,f as ja,g as Fm,h as Wf,i as Bf,m as Df,n as ms,o as go}from"./chunk-QRKGQPU7.js";import{a as el}from"./chunk-4HPTPUC6.js";import{b as gi,c as Td,e as xf,f as Af,g as Mf}from"./chunk-J4J3Y2P2.js";import{A as uf,B as gf,C as mf,D as Pd,E as Uo,F as Mr,G as ff,H as qn,I as tl,J as nl,K as hf,L as ol,M as gs,N as rl,O as sl,P as il,Q as yf,R as wf,S as Sf,T as Id,a as Sr,b as Em,c as Tm,d as km,e as Pm,f as Lm,g as xr,h as Im,i as Hm,j as Rm,k as $a,l as $o,m as rs,n as za,o as Ar,p as Wm,q as Ua,r as ui,s as vd,t as af,u as lf,v as cf,w as vn,x as df,y as pf,z as kd}from"./chunk-T7QM7YMF.js";import{a as je,c as Bm,d as Dm,e as se}from"./chunk-ZC66NAIR.js";import{a as Za,c as nf,d as zo,f as us,g as Ed,i as of,j as rf,k as sf}from"./chunk-S6PBWE75.js";import{a as cl,b as Hf,c as Rd,d as mi,e as dl,f as fi,g as pl,h as hi,i as Rf,j as yi}from"./chunk-CPVD5P5B.js";import{a as Ef,b as Tf,c as uo,d as Er,e as kf,f as Pf,g as Lf,h as Hd,i as If}from"./chunk-VK6JOIYJ.js";import{a as Ga,b as zm,c as as,d as wd,e as Md}from"./chunk-K6HKIP5K.js";import{c as cs,d as Jm,j as Zm,k as xd}from"./chunk-K7NA7G7J.js";import{a as gt,b as Dt,d as tf}from"./chunk-2ANTRKTV.js";import{a as Ad,d as Ja,e as ef,f as ds}from"./chunk-TR2H475E.js";import{b as Nm,c as Ka,d as Vm,e as Cd,f as $m,g as ls,h as Um,i as qm,j as jm,k as Km,l as Ya,m as Qa,n as Sd,o as Xa,q as Gm,r as Ym,s as Qm,t as Xm}from"./chunk-NQLDCJAP.js";import{a as ps}from"./chunk-QPPJUSZH.js";import{a as bf,b as al,c as Ld,d as vf}from"./chunk-HGUCGM3K.js";import{b as ll}from"./chunk-Q735PSZL.js";import{a as yt}from"./chunk-7NQ4ZTHF.js";import{a as P,c as Y,d as ss}from"./chunk-76IELU7F.js";import{a as Cf}from"./chunk-UPO4GUFC.js";import{Circle as EC,Clock as TC}from"lucide";import{ChevronDown as CC,ChevronUp as wC}from"lucide";var SC=["persona-w-full","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"],xC="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",AC="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",MC=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),ul=(t,e)=>{let n=P("div",["persona-message-bubble",t,...SC].join(" "));return n.id=`bubble-${e}`,n.setAttribute("data-message-id",e),n},gl=t=>{let e=P("button",t.expandable?xC:AC);return e.type="button",t.expandable&&(e.setAttribute("aria-expanded",t.expanded?"true":"false"),e.setAttribute("data-expand-header","true")),e.setAttribute("data-bubble-type",t.bubbleType),e},Wd=(t,e,n)=>{t.innerHTML="";let o=yt(e?wC:CC,16,n,2);o?t.appendChild(o):t.textContent=e?"Hide":"Show"},fs=(t,e,n)=>{if(!n.expandable)return t.append(e),null;let o=P("div","persona-flex persona-items-center");Wd(o,n.expanded,n.iconColor);let s=P("div",n.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return s.append(o),t.append(e,s),o},ml=t=>{let e=P("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(e.setAttribute("data-persona-collapsed-preview",t.previewKind),e.style.display="none",e.style.whiteSpace="pre-wrap",!t.expanded&&t.isActive&&t.activePreview&&t.previewText){let n=t.renderPreview?.();MC(e,n)||(e.textContent=t.previewText),e.style.display=""}return!t.expanded&&t.isActive&&t.activeMinHeight&&(t.bubble.style.minHeight=t.activeMinHeight),e},fl=t=>{t.header.setAttribute("aria-expanded",t.expanded?"true":"false"),t.toggleIcon&&Wd(t.toggleIcon,t.expanded,t.iconColor),t.content.style.display=t.expanded?"":"none",t.collapsedPreview.style.display=t.expanded?"none":t.collapsedPreview.textContent||t.collapsedPreview.childNodes.length?"":"none"},hl=(t,e,n)=>{let o=n.stateSet.has(t),s=e.querySelector('button[data-expand-header="true"]'),i=e.querySelector(".persona-border-t"),l=e.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!s||!i)return;s.setAttribute("aria-expanded",o?"true":"false");let u=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");u&&Wd(u,o,n.iconColor),i.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")};function yl(t,e){let n=e==="tool"?"toolCallDisplay":"reasoningDisplay";return{...t,features:{...t?.features,[n]:{...e==="tool"?$o:rs,...t?.future?.v5Defaults===!0?za.features?.[n]:{},...t?.features?.[n]}}}}function qo(t,e){let n=e==="tool"?"toolCallDisplay":"reasoningDisplay";return t?.features?.[n]?.variant??(t?.future?.v5Defaults?"row":"card")}function bi(t){let e=Math.max(0,Math.floor((t??0)/1e3));return e<1?"a moment":e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function mo(t,e,n,o){if(qo(n,o)!=="row")return t;t.className=`persona-message-bubble persona-${o}-bubble persona-activity-row`,t.dataset.activityKind=o,o==="tool"&&n.toolCall?.shadow===void 0&&(t.style.boxShadow="var(--persona-tool-bubble-shadow, none)");let s=t.querySelector(":scope > button");if(!s)return t;s.className="persona-activity-header";let i=o==="tool"?e.toolCall:e.reasoning,l=i?.status!=="complete",c=e.approval?.status??e.toolCall?.approvalStatus,u=c==="denied"?"denied":c==="pending"?"awaiting-approval":e.toolCall?.success===!1?"error":l?i?.status==="pending"?"pending":"running":"done";t.dataset.activityState=u;let p=P("span","persona-activity-icon");p.dataset.activityIcon=u;let g={pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x","awaiting-approval":"clock"},y=o==="reasoning"?n.features?.reasoningDisplay?.iconName:void 0,h=y?se(y,16,"currentColor",2):u==="pending"?yt(EC,16,"currentColor",2):u==="awaiting-approval"?yt(TC,16,"currentColor",2):se(g[u],16,"currentColor",2);h&&p.appendChild(h),s.querySelector(".persona-reasoning-header-icon")?.remove();let C=o==="tool"?"toolCallDisplay":"reasoningDisplay",E=n.features?.[C]?.iconVisibility??(n.future?.v5Defaults?"active":"always");if((E==="always"||E==="active"&&u!=="done")&&s.prepend(p),o==="tool"&&i){let k=P("span","persona-activity-duration");l&&i.startedAt&&k.setAttribute("data-tool-elapsed",String(i.startedAt));let R=(o==="tool"?e.toolCall?.duration:void 0)??i.durationMs??(i.completedAt!==void 0&&i.startedAt!==void 0?i.completedAt-i.startedAt:void 0);k.textContent=R===void 0?"":bi(R),s.appendChild(k)}s.querySelector(":scope > div:not(.persona-ml-auto)")?.classList.add("persona-activity-label"),s.querySelector(".persona-ml-auto")?.classList.add("persona-activity-chevron");let L=t.querySelector(":scope > .persona-border-t");return L?.classList.add("persona-activity-body"),L&&(L.id=`activity-details-${e.id}`,s.setAttribute("aria-controls",L.id)),t}function Of(t){let e=new Set,n=new Set,o=new Set,s=new Map,i=l=>{clearTimeout(s.get(l)),s.delete(l)};return{observe(l,c,u,p={}){let g=c==="tool"?l.toolCall:l.reasoning;if(!(!g||n.has(l.id))&&(!e.has(l.id)&&g.status!=="complete"&&g.chunks?.some(Boolean)&&(e.add(l.id),p.autoExpand!==!1&&u.add(l.id)),e.has(l.id)&&g.status==="complete"&&!o.has(l.id))){if(o.add(l.id),p.autoCollapseDelay===!1)return;s.set(l.id,setTimeout(()=>{s.delete(l.id),u.delete(l.id),t(l.id,c)},p.autoCollapseDelay??1e3))}},manual(l){n.add(l),i(l)},prune(l){for(let c of new Set([...e,...n,...o]))l.has(c)||(i(c),e.delete(c),n.delete(c),o.delete(c))},clear(){for(let l of s.keys())i(l);e.clear(),n.clear(),o.clear()}}}function _f(t,e,n,o){let s=P("div","");s.id=`bubble-${t.id}`,s.dataset.messageId=t.id;let i=P("button","");i.type="button",i.dataset.expandHeader="true",i.dataset.bubbleType="tool",i.setAttribute("aria-expanded",String(n));let l=P("div","");typeof o=="string"?l.textContent=o:l.appendChild(o),fs(i,l,{expandable:!0,expanded:n,iconColor:e.toolCall?.toggleTextColor||e.toolCall?.headerTextColor||"currentColor",metaGap:!0});let c=P("div","persona-border-t");return c.id=`activity-details-${t.id}`,c.style.display=n?"":"none",i.setAttribute("aria-controls",c.id),s.append(i,c),mo(s,t,{...e,features:{...e.features,toolCallDisplay:{...e.features?.toolCallDisplay,variant:"row"}}},"tool"),s.dataset.personaToolGroup="true",e.features?.toolCallDisplay?.loadingAnimation==="shimmer"&&(s.dataset.activityGroupShimmer="true"),{bubble:s,body:c}}function Ff(t,e){let n=t.voiceRecognition,o=e.voiceRecognition;return n?.enabled===!0!=(o?.enabled===!0)||n?.provider?.type!==o?.provider?.type||n?.provider?.custom!==o?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==o?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(o?.provider?.runtype)||t.agentId!==e.agentId||t.clientToken!==e.clientToken||t.apiUrl!==e.apiUrl}function Nt(t){return t?.type==="runtype"||t?.type==="custom"}var kC=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function Nf(t){try{if(t?.type==="custom"&&t.custom){let e=t.custom,n=typeof e=="function"?e():e;return!!n&&typeof n.startListening=="function"}return t?.type==="runtype"&&t.runtype?!0:kC()}catch{return!1}}var Vf=/^\s*\|?[\s:|-]*-[\s:|-]*$/,$f=t=>t.includes("|"),zf=t=>{let e=t.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(n=>n.trim())},PC=t=>`| ${t.join(" | ")} |`,LC=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,IC=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),Uf=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
2
+ `),n=!1;for(let o=0;o<e.length-1;o++){let s=e[o],i=e[o+1];if(!$f(s)||Vf.test(s)||!Vf.test(i))continue;let l=zf(s).length;if(l<1)continue;let c=LC(l);e[o+1]!==c&&(e[o+1]=c,n=!0);let u=o+2;for(;u<e.length;u++){let p=e[u];if(p.trim()===""||!$f(p))break;let g=PC(IC(zf(p),l));e[u]!==g&&(e[u]=g,n=!0)}o=u-1}return n?e.join(`
3
+ `):t};var qf="var(--persona-md-table-scroll-fade, 24px)",jf=new WeakSet;function Gf(t){t.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let s=document.createElement("div");s.className="persona-table-scroll",n.replaceWith(s),s.appendChild(n)})}function Kf(t){let e=t.scrollWidth-t.clientWidth;if(e<=1){t.removeAttribute("data-persona-scroll-x");return}t.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(t).direction==="rtl"?e+t.scrollLeft:t.scrollLeft,s=e-o;t.style.setProperty("--persona-fade-l",o<=1?"0px":qf),t.style.setProperty("--persona-fade-r",s<=1?"0px":qf)}function Bd(t){jf.has(t)||(jf.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&Kf(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(Kf)}var{setLoader:UA,load:HC,provide:qA,getSync:RC}=je({fallbackImport:()=>import("./client-stream-42FOI3EC.js")});var Tr=HC;var Yf=RC;var{setLoader:GA,load:WC}=je({fallbackImport:()=>import("./webmcp-runtime-V6ZWW3PI.js")});var Qf=WC;var BC="agent_",DC="flow_";function Xf(t){return t.startsWith(BC)?{kind:"agentId",agentId:t}:t.startsWith(DC)?{kind:"flowId",flowId:t}:null}function Jf(t,e){let n=t.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let l=n.slice(0,o),c=n.slice(o+1);if(l==="runtype"){let p=Xf(c);if(p)return p;throw new Error(`[Persona] target "runtype:${c}" is not a valid Runtype agent_/flow_ id.`)}let u=e?.[l];if(!u)throw new Error(`[Persona] No target provider registered for "${l}". Add a \`targetProviders.${l}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:u(c).payload}}let s=Xf(n);if(s)return s;let i=e?.default;if(i)return{kind:"payload",payload:i(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}function bl(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function hs(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}function Zf(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`turn_${t}_${e}`}var OC=t=>t.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),_C=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),FC=t=>{if(t.variant!=="tool")return null;let e=t.agentMetadata?.clientToolAnswer;if(!e||!e.toolCallId||e.result===void 0)return null;let n=OC(e.toolName);return n?{call:{toolCallId:e.toolCallId,toolName:n,args:_C(e.args)?e.args:{}},result:{toolCallId:e.toolCallId,toolName:n,result:e.result}}:null},Dd=(t,e)=>{let n=[],o=[],s=[],i="",l,c=()=>{o.length!==0&&(n.push({role:"assistant",content:"",createdAt:i,toolCalls:o},{role:"tool",content:"",createdAt:i,toolResults:s}),o=[],s=[])};for(let u of t){let p=FC(u);if(p){let y=u.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(y===void 0||y!==l)&&c(),o.length===0&&(i=u.createdAt,l=y),o.some(h=>h.toolCallId===p.call.toolCallId)||(o.push(p.call),s.push(p.result));continue}let g=e(u);g&&(c(),n.push(g))}return c(),n};var{setLoader:eM,load:NC,provide:tM}=je({fallbackImport:()=>import("./client-history-YPEG45Q4.js")});var fo=NC;var VC="https://api.runtype.com/v1/dispatch",bt=class extends Error{constructor(e,n,o){super(n),this.name="HistoryClientError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},eh=t=>"reason"in t?t.reason:void 0,$C="The identity proof was rejected",Od=(t,e)=>t instanceof bt&&t.code===e,_d=t=>t.voiceCaption?!1:!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0),th=t=>t.slice().sort((e,n)=>new Date(e.createdAt).getTime()-new Date(n.createdAt).getTime()),nh=t=>({role:t.role,content:t.contentParts??t.llmContent??t.rawContent??t.content,createdAt:t.createdAt});function zC(t){switch(t){case"json":return Qm;case"regex-json":return Ym;case"xml":return Xm;default:return Gm}}var vi=class{constructor(e={},n={}){this.config=e;this.historyInternals=n;this.#N=null;this.clientSession=null;this.#n=null;this.#l=!1;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.#h=null;this.#D=!1;this.#O=!1;this.#V=!1;this.#o=null;this.#c=new Set;this.#g=new Set;this.webMcpBridge=null;this.#C=null;this.#me=null;this.#fe=null;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.#e=e.apiUrl??VC,this.#t={"Content-Type":"application/json","X-Persona-Version":ps,...e.headers},this.debug=!!e.debug,this.#s=e.streamParser??zC(e.parserType),this.#r=e.contextProviders??[],this.#a=e.requestMiddleware,this.#f=e.customFetch,this.#i=e.parseSSEEvent,this.#u=e.getHeaders,e.webmcp?.enabled===!0&&(this.#C=this.#y(e.webmcp))}#e;#t;#s;#r;#a;#f;#i;#u;#v;#N;#n;#l;#h;#D;#O;#V;#o;#c;#g;#C;#L;#y(e){return Qf().then(n=>{let o=new n.WebMcpBridge(e,{recordToolDisplayTitles:Nm,getToolDisplayTitle:Ka,loadPolyfill:$m});return this.#L!==void 0&&o.setConfirmHandler(this.#L),this.webMcpBridge=o,o}).catch(n=>(this.#C=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),null))}#d(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.#C||(this.#C=this.#y(this.config.webmcp)),this.#C)}updateConfig(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.#v=e}setWebMcpConfirmHandler(e){this.#L=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.config.webmcp?.enabled!==!0?null:this.#d().then(s=>s?s.executeToolCall(e,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.#v}isClientTokenMode(){return!!this.config.clientToken}#x(){let{agentId:e,flowId:n,target:o,targetProviders:s}=this.config;if(!o)return{agentId:e,flowId:n};let i=Jf(o,s);return i.kind==="agentId"?{agentId:i.agentId}:i.kind==="flowId"?{flowId:i.flowId}:{targetPayload:i.payload}}isAgentMode(){return!!(this.config.agent||this.#x().agentId)}#E(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||tf}#b(e){return`${this.#E()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let n=await this.initSession(),o=!1;for(;;){let s=n.conversationId,i=await this.readVisitorToken();if(n.durableRecovery?.enabled!==!0||!s||!i)throw new bt("visitor_token_missing","Durable recovery is not enabled for this client session");let l=`${this.#E()}/v1/client/conversations/${encodeURIComponent(s)}/executions/${encodeURIComponent(e.executionId)}/events`,c=new URLSearchParams({sessionId:n.sessionId,after:e.after}),u=await fetch(`${l}?${c}`,{method:"GET",headers:{"X-Persona-Version":ps,"X-Visitor-Token":i},signal:e.signal});if(u.status===401&&!o){o=!0;let p=await fo();n=await p.recoverFromUnauthorized(this.#T(),await p.readErrorCode(this.#T(),u),null,!0);continue}if(!u.ok)throw await(await fo()).historyErrorFor(this.#T(),u,!0);return u}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.#n||e&&new Date<e.expiresAt||this.#l===e?null:(this.#l=e,this.initSession().catch(()=>null))}async initSession(){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.#n)return this.#n;let e=this.#n=this.#z().then(n=>this.#n!==e?this.initSession():(this.clientSession=n,this.#l=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(n),n)).finally(()=>{this.#n===e&&(this.#n=null)});return e}#m(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#D}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.get()??null):null}#re(){if(!this.#D){this.#$({state:"unavailable",reason:"history_disabled"}),this.#D=!0,!this.#O&&typeof console<"u"&&(this.#O=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.#g])e(!1)}}getHistoryIdentityStatus(){return this.#o??this.#se()}subscribeHistoryIdentityStatus(e){return this.#c.add(e),()=>{this.#c.delete(e)}}subscribeHistoryAvailability(e){return this.#g.add(e),this.#D&&e(!1),()=>{this.#g.delete(e)}}#se(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.#D?{state:"unavailable",reason:"history_disabled"}:this.#K():{state:"unavailable",reason:"ineligible_mode"}}#K(){let e=this.#o;return e?.state==="browser_only"?e:this.#I()}#I(){return this.config.features?.history?.scope==="browser"?{state:"browser_only",reason:"configured_browser_scope"}:this.config.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}#$(e){let n=this.getHistoryIdentityStatus(),o=n.state===e.state&&eh(n)===eh(e);if(this.#o=e,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let s of[...this.#c])s(e)}}async#S(e){let n=this.#m()&&!e.omitVisitorFields,o=!e.omitVisitorFields,s=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,s=await this.readVisitorToken());let i=this.#x(),l=i.agentId??i.flowId,c=n||e.durableResume?e.conversationId:void 0,u={token:this.config.clientToken,...l&&{flowId:l},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&s?{visitorToken:s}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...c?{conversationId:c}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let p=await fetch(this.#b("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ps},body:JSON.stringify(u),signal:e.signal});if(!p.ok){let y=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&y.error==="visitor_history_disabled"){if(this.#re(),c)throw new bt("history_disabled","Visitor history is disabled for this surface");return this.#S({...e,omitVisitorFields:!0})}throw p.status===403&&y.error==="durable_recovery_disabled"?new bt("history_disabled","Durable recovery is disabled for this surface"):(n||e.durableResume)&&p.status===401&&y.error==="visitor_required"?new bt("visitor_required","Visitor credential no longer resolves"):c&&p.status===404?new bt("not_found","Conversation not found"):p.status===401?new Error(`Invalid client token: ${y.hint||y.error}`):p.status===403?new Error(`Origin not allowed: ${y.hint||y.error}`):new Error(y.error||"Failed to initialize session")}let g=await p.json();return g.visitor?.token&&await this.historyInternals.visitorStore?.set(g.visitor.token),{sessionId:g.sessionId,expiresAt:new Date(g.expiresAt),flow:g.flow,...g.conversationId?{conversationId:g.conversationId}:{},...g.targetId?{targetId:g.targetId}:{},...g.conversationRevision?{conversationRevision:g.conversationRevision}:{},...g.durableRecovery?{durableRecovery:g.durableRecovery}:{},...g.visitor?{visitor:g.visitor}:{},config:{welcomeMessage:g.config.welcomeMessage,placeholder:g.config.placeholder,theme:g.config.theme}}}async#z(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.#m()&&!n)return this.#te(e,!1);let o=await this.readVisitorToken();if(e&&o)try{let s=await this.#S({conversationId:e,durableResume:n});return n&&s.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.#H(s,e,!1)}catch(s){if(!Od(s,"not_found")&&!Od(s,"visitor_required")&&!Od(s,"history_disabled"))throw s;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.#te(e,!0)}return this.#te(e,!1)}async#te(e,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.#ie(e,n)):this.#ie(e,n)}async#ie(e,n){let o=this.config.getStoredSessionId?.()||null,s=await this.#S({storedSessionId:o}),i=await this.#Y(s);return this.#H(i,e,n)}async#G(e){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,s=await this.#S({storedSessionId:n,identityProof:e}),i=this.#H(s,o,!1);return this.clientSession=i,this.#n=null,this.#l=!1,this.resetClientToolsFingerprint(),i}async#Y(e){if(!e.visitor?.token||this.#V||!this.#m()&&e.durableRecovery?.enabled!==!0)return e;this.#V=!0;try{return await this.#S({storedSessionId:e.sessionId})}catch{return e}finally{this.#V=!1}}#H(e,n,o){let s=e.conversationId;return s&&n&&(o||s!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:s}),this.config.setStoredSessionId?.(e.sessionId),s&&(this.config.setStoredConversationId?.(s),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}#ne(e){let n=!1;return{session:e,commit:()=>{n||(n=!0,this.clientSession=e,this.#l=!1,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(e,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.#m())throw new bt("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new bt("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let i=await this.#S({conversationId:e,identityProof:o});return this.#ne(i)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let e=await this.#S({});return this.#ne(e)}handleExternalCredentialChange(){this.clearClientSession(),this.#m()&&this.#$(this.#I())}clearClientSession(){this.clientSession=null,this.#n=null,this.#l=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#h=null}#U(){return`${this.#E()}/v1/client/feedback`}async sendFeedback(e){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(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let s={...e,...this.config.clientToken&&{token:this.config.clientToken}},i=await fetch(this.#U(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ps},body:JSON.stringify(s)});if(!i.ok){let l=await i.json().catch(()=>({error:"Feedback submission failed"}));throw i.status===401?(this.clientSession=null,this.#l=!1,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(l.error||"Failed to submit feedback")}}async submitMessageFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:e,comment:n})}async submitNPSFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:e,comment:n})}async#R(e){e?.throwIfAborted();let n=this.config.identityProvider;if(n===void 0)return;let o=this.config.getIdentityProof;if(!n.trim()||!o)throw new Error("Chat identity requires identityProvider and getIdentityProof.");let s,i;try{let l=Promise.resolve().then(()=>o());s=e?await Promise.race([l,new Promise((c,u)=>{i=()=>u(e.reason),e.addEventListener("abort",i,{once:!0}),e.aborted&&i()})]):await l}catch{throw e?.throwIfAborted(),new Error("The identity proof provider failed.")}finally{i&&e?.removeEventListener("abort",i)}if(typeof s!="string"||!s.trim())throw new Error("A fresh identity proof is required to send this message.");return{provider:n,token:s}}#me;#ae(){let e=this;return this.#me??={get config(){return e.config},headers:this.#t,getHeaders:this.#u,debug:this.debug,clientApiBase:()=>e.#E(),getClientApiUrl:n=>e.#b(n),getWebMcpBridge:()=>e.#d(),sendWithClientToolsDiff:(n,o,s,i)=>e.#W(n,o,s,i),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#fe;#T(){let e=this;return this.#fe??={HistoryClientError:bt,get config(){return e.config},get historyInternals(){return e.historyInternals},get clientSession(){return e.clientSession},clientApiBase:()=>e.#E(),setHistoryIdentityStatus:n=>e.#$(n),browserOnlyStatus:()=>e.#K(),derivedBrowserOnly:()=>e.#I(),reinitWithProof:n=>e.#G(n),isHistoryCapable:()=>e.#m(),clearClientSession:()=>e.clearClientSession(),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}async listConversations(e){return(await fo()).listConversations(this.#T(),e)}async getConversation(e,n){return(await fo()).getConversation(this.#T(),e,n)}async finalizeDisplayProjections(e,n){return(await fo()).finalizeDisplayProjections(this.#T(),e,n)}async deleteConversation(e,n){return(await fo()).deleteConversation(this.#T(),e,n)}async deleteAllConversations(e){return(await fo()).deleteAllConversations(this.#T(),e)}async resetVisitor(){return(await fo()).resetVisitor(this.#T())}async dispatch(e,n){return e.signal?.throwIfAborted(),Tr().catch(()=>{}),this.isClientTokenMode()?this.#le(e,n):this.isAgentMode()?this.#de(e,n):this.#ce(e,n)}async#le(e,n){let o=Zf();this.#N=o;let s=()=>this.#N===o,i=l=>{s()&&n(l)};n({type:"status",status:"connecting"});try{let l=()=>{if(e.signal?.throwIfAborted(),!s())throw new DOMException("Turn superseded","AbortError")},c=this.clientSession??await this.initSession();l();let u=async()=>{l();let L=c,k=L.durableRecovery?.enabled===!0;if(k&&(!L.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");l();let R=await this.#S({...k||this.#m()?{conversationId:L.conversationId,durableResume:k}:{storedSessionId:L.sessionId},signal:e.signal});if(l(),L.conversationId&&R.conversationId!==L.conversationId||k&&R.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");c=this.#H(R,L.conversationId??null,!1),this.clientSession=c,this.#l=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(c)};Date.now()>=c.expiresAt.getTime()-6e4&&await u();let p=await this.#pe(e.messages),g=p.metadata?Object.fromEntries(Object.entries(p.metadata).filter(([L])=>L!=="sessionId"&&L!=="session_id")):void 0,y=this.#m(),h={sessionId:c.sessionId,messages:e.messages.filter(_d).map(L=>{let k=y?gi(L):void 0;return{id:L.id,role:L.role,content:L.contentParts??L.llmContent??L.rawContent??L.content,...k!==void 0&&{displayContent:k}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...g&&Object.keys(g).length>0&&{metadata:g},...p.inputs&&Object.keys(p.inputs).length>0&&{inputs:p.inputs},...p.context&&{context:p.context},turnId:o,...e.interrupt&&{submitMode:"interrupt"}},C=async()=>{l();let L=c.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return l(),this.#W(c.sessionId,p.clientTools,async k=>{l();let R=await this.#R(e.signal);l();let B={...h,sessionId:c.sessionId,...k,...R&&{identityProof:R}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...B,...R&&{identityProof:{provider:R.provider,token:"[REDACTED]"}}}),fetch(this.#b("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ps,...L?{"X-Visitor-Token":L}:{}},body:JSON.stringify(B),signal:e.signal})})},E=await C();if(l(),E.response.status===401){let L=await E.response.clone().json().catch(()=>null);l(),L?.error==="Session not found or expired"&&(await u(),E=await C(),l())}let{response:A,commit:I}=E;if(!A.ok){let L=await A.json().catch(()=>({error:"Chat request failed"}));if(A.status===401&&L.error==="invalid_identity_proof"){let R=new bt("invalid_identity_proof",$C);throw i({type:"error",error:R}),R}if(A.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let R=new Error("Session expired. Please refresh to continue.");throw i({type:"error",error:R}),R}if(A.status===429){let R=new Error(L.hint||"Message limit reached for this session.");throw i({type:"error",error:R}),R}if(A.status===410&&L.error==="conversation_deleted"){let R=new bt("conversation_deleted","This conversation was deleted");throw i({type:"error",error:R}),R}let k=new Error(L.error||"Failed to send message");throw i({type:"error",error:k}),k}if(!A.body){let L=new Error("No response body received");throw i({type:"error",error:L}),L}I(),i({type:"status",status:"connected"});try{await this.#F(A.body,i,e.assistantMessageId)}finally{i({type:"status",status:"idle"})}}catch(l){let c=l instanceof Error?l:new Error(String(l));throw!(c instanceof bt)&&!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&i({type:"error",error:c}),c}}async#ce(e,n){n({type:"status",status:"connecting"});let o=await this.#pe(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.#t};if(this.#u)try{let l=await this.#u();s={...s,...l}}catch(l){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.#f)try{i=await this.#f(this.#e,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal},o)}catch(l){let c=l instanceof Error?l:new Error(String(l));throw n({type:"error",error:c}),c}else i=await fetch(this.#e,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let l=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw n({type:"error",error:l}),l}n({type:"status",status:"connected"});try{await this.#F(i.body,n)}finally{n({type:"status",status:"idle"})}}async#de(e,n){n({type:"status",status:"connecting"});let o=await this.#he(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.#t};if(this.#u)try{let l=await this.#u();s={...s,...l}}catch(l){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.#f)try{i=await this.#f(this.#e,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal},o)}catch(l){let c=l instanceof Error?l:new Error(String(l));throw n({type:"error",error:c}),c}else i=await fetch(this.#e,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let l=new Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw n({type:"error",error:l}),l}n({type:"status",status:"connected"});try{await this.#F(i.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,o,s){n({type:"status",status:"connected"});try{await this.#F(e,n,o,s)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){return(await Tr()).resolveApproval(this.#ae(),e,n)}async#W(e,n,o,s){let i=!!(n&&n.length>0),l=i?Vm(n):void 0,c=this.clientToolsFingerprintSessionId===e,u=i&&c&&this.lastSentClientToolsFingerprint===l,p=!i&&s?.emptyMeansReplace===!0&&this.#h===e,g=!1,y;for(let h=0;;h++){if(y=await o({...i&&(g||!u)&&n?{clientTools:n}:{},...p?{clientTools:[]}:{},...l?{clientToolsFingerprint:l}:{}}),y.status===409&&h===0&&i&&(await y.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){g=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:y,commit:()=>{this.lastSentClientToolsFingerprint=l??null,this.clientToolsFingerprintSessionId=e,i?this.#h=e:p&&(this.#h=null)}}}async resumeFlow(e,n,o){return(await Tr()).resumeFlow(this.#ae(),e,n,o)}#k(e){for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async#A(e){let n={};this.#r.length&&await Promise.all(this.#r.map(async s=>{try{let i=await s({messages:e,config:this.config});i&&typeof i=="object"&&Object.assign(n,i)}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",i)}}));let o=this.#k(e);return o&&Object.assign(n,o),Object.keys(n).length?n:null}#w(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n:void 0}#_(e,n){let o=n?.selectedModelId;return!o||!("model"in e)?e:this.config.composer?.models?.some(i=>i.id===o)?{...e,model:o}:e}async#he(e,n){let o=this.#x().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let s=Dd(th(e),p=>_d(p)&&(p.role==="user"||p.role==="assistant"||p.role==="system")&&(!p.variant||p.variant==="assistant")?nh(p):null),i=this.#w(n),l={agent:this.#_(this.config.agent??{agentId:o},i),messages:s,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};i&&(l.composerOptions=i);let c=[...Md(this.config),...await(await this.#d())?.snapshotForDispatch()??[]];c.length>0&&(l.clientTools=c);let u=await this.#A(e);return u&&(l.context=u),l}async#pe(e,n){let o=Dd(th(e),p=>_d(p)?nh(p):null),s=this.#x(),i={messages:o,...s.agentId?{agent:{agentId:s.agentId}}:s.flowId?{flowId:s.flowId}:{}};if(s.targetPayload)for(let[p,g]of Object.entries(s.targetPayload))p!=="messages"&&(i[p]=g);let l=[...Md(this.config),...await(await this.#d())?.snapshotForDispatch()??[]];l.length>0&&(i.clientTools=l);let c=await this.#A(e);c&&(i.context=c);let u=this.#w(n);if(u&&(i.composerOptions=u),this.#a)try{let p=await this.#a({payload:{...i},config:this.config});if(p&&typeof p=="object"){let g=p;return i.clientTools!==void 0&&!("clientTools"in g)&&(g.clientTools=i.clientTools),g}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",p)}return i}async#F(e,n,o,s){let{streamResponse:i}=Yf()??await Tr();return i({config:()=>this.config,createStreamParser:this.#s,parseSSEEvent:this.#i,onSSEEvent:(l,c)=>this.#v?.(l,c)},e,n,o,s)}};var{setLoader:yM,load:UC,provide:bM,getSync:qC}=je({fallbackImport:()=>import("./ui-extras-entry-WAYFKVNW.js")});var vl=UC;var Fd=qC;var{setLoader:wM,load:jC,provide:SM,getSync:KC}=je({fallbackImport:()=>import("./session-actions-ISSKSI66.js")});var Nd=jC;var oh=KC;var GC=t=>t.sourceLabel?`quoted-text source=${t.sourceLabel}`:"quoted-text";function YC(t){let e=t?.text?.trim()??"";return e?vf(GC(t),e):""}function rh(t){let e=YC(t.quote);return e?t.contentParts&&t.contentParts.length>0?{contentParts:[zo(e),...t.contentParts]}:{llmContent:[e,t.text].filter(Boolean).join(`
4
4
 
5
- `);c=O.pop()??"";for(let j of O){let X=j.split(`
6
- `),Y="message",ge="",xe=null;for(let $e of X)$e.startsWith("event:")?Y=$e.replace("event:","").trim():$e.startsWith("data:")?ge+=$e.replace("data:","").trim():$e.startsWith("id:")&&(xe=$e.slice(3).trim());let Se=()=>{xe!==null&&xe!==""&&n({type:"cursor",id:xe})};if(!ge){Se();continue}let dt;try{dt=JSON.parse(ge)}catch($e){n({type:"error",error:$e instanceof Error?$e:new Error("Failed to parse chat stream payload")});continue}let Wt=dt!==null&&typeof dt=="object"&&!Array.isArray(dt)?dt:null,Xe=Y!=="message"?Y:typeof Wt?.type=="string"?Wt.type:"message";if(this.onSSEEvent?.(Xe,dt),this.parseSSEEvent){E.current=C;let $e=await this.handleCustomSSEEvent(dt,n,E,b,u,H);if(E.current&&E.current!==C&&(C=E.current),$e){Se();continue}}Wt&&(Fe.push({...Wt,type:Xe}),bn()),Se()}}bn()}};var NM=t=>t.sourceLabel?`quoted-text source=${t.sourceLabel}`:"quoted-text";function FM(t){let e=t?.text?.trim()??"";return e?Gy(NM(t),e):""}function hv(t){let e=FM(t.quote);return e?t.contentParts&&t.contentParts.length>0?{contentParts:[Io(e),...t.contentParts]}:{llmContent:[e,t.text].filter(Boolean).join(`
7
-
8
- `)}:{}}function Jc(t,e=140){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}function yv(t,e){let n=t.findIndex(s=>s.id===e);if(n===-1||t[n].role!=="user")return null;let o=n+1;for(;o<t.length&&t[o].role!=="user";)o+=1;return{start:n,end:o}}function lg(t,e){let n=t.findIndex(o=>o.id===e);if(n<=0)return null;for(let o=n-1;o>=0;o-=1)if(t[o].role==="user")return t[o].id;return null}function bv(t){for(let e=t.length-1;e>=0;e-=1){let n=t[e];if(n.role==="user"||n.streaming)return null;if(!(n.role!=="assistant"||n.variant))return lg(t,n.id)?n.id:null}return null}function cg(t){return t.role!=="user"||t.variant||t.streaming||t.contentParts?.length||t.contextMentions?.length||t.contentSegments?.length||t.mentionContext&&Object.keys(t.mentionContext).length>0||t.rawContent!==void 0||t.llmContent!==void 0&&t.llmContent!==t.content||t.quote?!1:typeof t.content=="string"&&t.content.length>0}function dg(t){let e=["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 n of e){let o=t.find(s=>s.name===n);if(o)return o}return t.find(n=>n.lang.startsWith("en"))??t[0]}var Ua=class t{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(e,n){if(!t.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let s=new SpeechSynthesisUtterance(e.text),i=o.getVoices();if(e.voice){let l=i.find(c=>c.name===e.voice);l&&(s.voice=l)}else i.length>0&&(s.voice=this.options.pickVoice?this.options.pickVoice(i):dg(i));e.rate!==void 0&&(s.rate=e.rate),e.pitch!==void 0&&(s.pitch=e.pitch),s.onend=()=>n.onEnd?.(),s.onerror=l=>{let c=l.error;c==="canceled"||c==="interrupted"?n.onEnd?.():n.onError?.(new Error(c||"Speech synthesis failed"))},setTimeout(()=>{o.speak(s),n.onStart?.()},50)}pause(){t.isSupported()&&window.speechSynthesis.pause()}resume(){t.isSupported()&&window.speechSynthesis.resume()}stop(){t.isSupported()&&window.speechSynthesis.cancel()}};var Zc=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(e){return this.activeId===e?this.state:"idle"}activeMessageId(){return this.activeId}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggle(e,n){if(this.activeId===e){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,n)}async play(e,n){let o=++this.generation;this.engine?.stop(),this.set(e,"loading");try{if(!this.engine){let s=await this.resolveEngine();if(o!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(e,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(e,n){this.activeId=n==="idle"?null:e,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};var $a=class{constructor(){this.cancelled=!1}start(e){this.turnId=e,this.cancelled=!1}cancel(){this.cancelled=!0}accepts(e){return!this.cancelled&&(!e||!this.turnId||e===this.turnId)}};var{setLoader:zk,load:UM}=Ht({fallbackImport:()=>import("./voice-runtime-7DA7MJH4.js")});var pg=UM;function ug(t){if(!t)return"";let e=$M(t);return vv(e!==null?e:t)}function $M(t){let e=t.trim(),n=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(e=n[1].trim()),!e.startsWith("{"))return null;try{let o=JSON.parse(e);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function vv(t){if(!t)return"";let e=t;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
5
+ `)}:{}}function Cl(t,e=140){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}function sh(t,e){let n=t.findIndex(s=>s.id===e);if(n===-1||t[n].role!=="user")return null;let o=n+1;for(;o<t.length&&t[o].role!=="user";)o+=1;return{start:n,end:o}}function Vd(t,e){let n=t.findIndex(o=>o.id===e);if(n<=0)return null;for(let o=n-1;o>=0;o-=1)if(t[o].role==="user")return t[o].id;return null}function ih(t){for(let e=t.length-1;e>=0;e-=1){let n=t[e];if(n.role==="user"||n.streaming)return null;if(!(n.role!=="assistant"||n.variant))return Vd(t,n.id)?n.id:null}return null}function $d(t){return t.role!=="user"||t.variant||t.streaming||t.contentParts?.length||t.contextMentions?.length||t.contentSegments?.length||t.mentionContext&&Object.keys(t.mentionContext).length>0||t.rawContent!==void 0||t.llmContent!==void 0&&t.llmContent!==t.content||t.quote?!1:typeof t.content=="string"&&t.content.length>0}function zd(t){let e=["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 n of e){let o=t.find(s=>s.name===n);if(o)return o}return t.find(n=>n.lang.startsWith("en"))??t[0]}var Ci=class t{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(e,n){if(!t.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let s=new SpeechSynthesisUtterance(e.text),i=o.getVoices();if(e.voice){let l=i.find(c=>c.name===e.voice);l&&(s.voice=l)}else i.length>0&&(s.voice=this.options.pickVoice?this.options.pickVoice(i):zd(i));e.rate!==void 0&&(s.rate=e.rate),e.pitch!==void 0&&(s.pitch=e.pitch),s.onend=()=>n.onEnd?.(),s.onerror=l=>{let c=l.error;c==="canceled"||c==="interrupted"?n.onEnd?.():n.onError?.(new Error(c||"Speech synthesis failed"))},setTimeout(()=>{o.speak(s),n.onStart?.()},50)}pause(){t.isSupported()&&window.speechSynthesis.pause()}resume(){t.isSupported()&&window.speechSynthesis.resume()}stop(){t.isSupported()&&window.speechSynthesis.cancel()}};var wl=class{#e=null;#t=null;#s="idle";#r=new Set;#a=0;#f;constructor(e){this.#f=e}get supportsPause(){return this.#e?.supportsPause??!0}stateFor(e){return this.#t===e?this.#s:"idle"}activeMessageId(){return this.#t}onChange(e){return this.#r.add(e),()=>this.#r.delete(e)}toggle(e,n){if(this.#t===e){if(this.#s==="playing"){this.#e?.supportsPause?(this.#e.pause(),this.#i(e,"paused")):this.stop();return}if(this.#s==="paused"){this.#e?.resume(),this.#i(e,"playing");return}if(this.#s==="loading"){this.stop();return}}this.play(e,n)}async play(e,n){let o=++this.#a;this.#e?.stop(),this.#i(e,"loading");try{if(!this.#e){let s=await this.#f();if(o!==this.#a)return;if(!s){this.#i(null,"idle");return}this.#e=s}this.#e.speak(n,{onStart:()=>{o===this.#a&&this.#i(e,"playing")},onEnd:()=>{o===this.#a&&this.#i(null,"idle")},onError:()=>{o===this.#a&&this.#i(null,"idle")}})}catch{o===this.#a&&this.#i(null,"idle")}}stop(){this.#a++,this.#e?.stop(),this.#i(null,"idle")}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#r.clear()}#i(e,n){this.#t=n==="idle"?null:e,this.#s=n;for(let o of this.#r)o(this.#t,this.#s)}};var wi=class{#e;#t=!1;start(e){this.#e=e,this.#t=!1}cancel(){this.#t=!0}accepts(e){return!this.#t&&(!e||!this.#e||e===this.#e)}};var{setLoader:HM,load:QC,getSync:XC}=je({fallbackImport:()=>import("./voice-runtime-UOQOFAFY.js")});var Si=QC,ah=XC;function Ud(t){if(!t)return"";let e=JC(t);return lh(e!==null?e:t)}function JC(t){let e=t.trim(),n=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(e=n[1].trim()),!e.startsWith("{"))return null;try{let o=JSON.parse(e);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function lh(t){if(!t)return"";let e=t;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
9
6
  `),e=e.replace(/\n{2,}/g,`
10
- `),e.trim()}var Cv=null;var gg=()=>Cv?Cv():import("./runtype-tts-entry-UJAEF7NZ.js");var{setLoader:Yk,load:VM}=Ht({fallbackImport:()=>import("./session-reconnect-JKIJBHS5.js")});var wv=VM;var qM=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId","getIdentityProof","identityProvider","getStoredConversationId","setStoredConversationId","clearStoredConversationId","clearStoredSessionId"];function zM(t,e){return qM.some(n=>t[n]!==e[n])}var Ho=class extends Error{constructor(e,n){super(n),this.name="SessionHistoryError",this.code=e}};function fg(t,e){let n=t instanceof Error?t:new Error(String(t));if(typeof e=="string")return e;if(typeof e=="function")return e(n);let o="Sorry: 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}
7
+ `),e.trim()}var ch=null;var qd=()=>ch?ch():import("./runtype-tts-entry-NFBVWR7N.js");var{setLoader:OM,load:ZC}=je({fallbackImport:()=>import("./session-reconnect-JKIJBHS5.js")});var dh=ZC;var ew=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId","getIdentityProof","identityProvider","getStoredConversationId","setStoredConversationId","clearStoredConversationId","clearStoredSessionId"];function tw(t,e){return ew.some(n=>t[n]!==e[n])}var jn=class extends Error{constructor(e,n){super(n),this.name="SessionHistoryError",this.code=e}};function jd(t,e){let n=t instanceof Error?t:new Error(String(t));if(typeof e=="string")return e;if(typeof e=="function")return e(n);let o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
11
8
 
12
- _Details: ${n.message}_`:o}var mg=t=>({isError:!0,content:[{type:"text",text:t}]}),jM=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,xv=t=>yi(t)||t===Or,ed=class t{constructor(e={},n,o={}){this.config=e;this.callbacks=n;this.historyInternals=o;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=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.voiceSetupPromise=null;this.voiceSetupGeneration=0;this.voiceLevel=0;this.voiceActive=!1;this.voiceStatus="disconnected";this.activeConversationId=null;this.activeConversationRevision=null;this.historyNextMessageCursor=null;this.historyOpenEpoch=0;this.suppressWelcomeInjection=!1;this.historyRecovery=null;this.historySendBlocked=!1;this.historyGate=null;this.olderPageRequests=new Map;this.projectionFinalizationPromise=null;this.acknowledgedProjections=new Map;this.pendingProjections=null;this.bootConversationRevision=null;this.bootRevisionCaptured=!1;this.visitorStoreUnsubscribe=null;this.subscribedVisitorStore=null;this.credentialReinitPending=!1;this.credentialReinitPromise=null;this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.voiceTurns=new $a;this.voiceDisconnectPromise=Promise.resolve();this.ttsSpokenMessageIds=new Set;this.readAloud=new Zc(()=>this.createSpeechEngine());this.handleEvent=e=>{if(e.type==="message"){this.upsertMessage(e.message),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.activeAssistantMessageId=e.message.id);let n=e.message.toolCall,o=!!n?.name&&(yi(n.name)||n.name===Or&&Nr(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:e.message.agentMetadata.agentName??"",status:"running",currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.isAwaitPending()||this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null,this.invalidateConversationRevision(),this.scheduleProjectionFinalization());let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(e.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};this.historyInternals=this.composeHistoryInternals(o),this.messages=[...e.initialMessages??[]].map(s=>({...s,sequence:s.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Fa(e,this.historyInternals),this.syncVisitorStoreSubscription(),this.wireDefaultWebMcpConfirm();for(let s of e.initialArtifacts??[])this.artifacts.set(s.id,{...s,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts(),this.prefetchVoiceRuntime()}prefetchVoiceRuntime(){this.config.voiceRecognition?.provider&&pg().catch(()=>{})}prefetchRuntypeTts(){let e=this.config.textToSpeech;if(e?.provider!=="runtype"||e.createEngine)return;let n=e.host??this.config.apiUrl,o=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||gg().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return xb(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceLevel(){return this.voiceProvider?.onLevel?this.voiceLevel:null}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&(this.voiceTurns.cancel(),this.voiceProvider.stopPlayback())}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let n=Ua.isSupported()?new Ua({pickVoice:e?.pickVoice}):null;if(e?.provider==="runtype"){let o=e.host??this.config.apiUrl,s=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,i=this.config.clientToken,l=e.browserFallback!==!1;if(o&&s&&i)return gg().then(({RuntypeSpeechEngine:c,FallbackSpeechEngine:d})=>{let g=new c({host:o,agentId:s,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return l&&n?new d(g,n,{onFallback:u=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${u.message}`)}):g});if(l&&n)return i&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){try{let n=e||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.cleanupVoice();let o=this.voiceDisconnectPromise,s=++this.voiceSetupGeneration;this.voiceSetupPromise=pg().then(async i=>{await o,s===this.voiceSetupGeneration&&this.wireVoiceProvider(i.createVoiceProvider(n))}).catch(i=>{console.error("Failed to setup voice:",i)}).finally(()=>{s===this.voiceSetupGeneration&&(this.voiceSetupPromise=null)})}catch(n){console.error("Failed to setup voice:",n)}}wireVoiceProvider(e){try{this.voiceProvider=e;let n=this.voiceSetupGeneration,o=()=>this.voiceProvider===e&&n===this.voiceSetupGeneration,i=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(l=>{o()&&l.provider!=="runtype"&&l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((l,c,d,g)=>{if(o())if(l==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!d});else{let u=this.injectMessage({role:"user",content:c,streaming:!1,voiceProcessing:!d});this.pendingVoiceUserMessageId=u.id}if(d){this.voiceTurns.start(g?.turnId),this.pendingVoiceUserMessageId=null;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}}else{if(!this.voiceTurns.accepts(g?.turnId))return;if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c,createdAt:new Date().toISOString(),streaming:!d,voiceProcessing:!d});else{let u=this.injectMessage({role:"assistant",content:c,streaming:!d,voiceProcessing:!d});this.pendingVoiceAssistantMessageId=u.id}d&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onLevel&&this.voiceProvider.onLevel(l=>{o()&&(this.voiceLevel=Number.isFinite(l)?Math.max(0,Math.min(1,l)):0)}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(l=>{o()&&this.config.voiceRecognition?.onMetrics?.(l)}),this.voiceProvider.onError(l=>{o()&&(console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:i,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null))}),this.voiceProvider.onStatusChange(l=>{o()&&(this.voiceStatus=l,this.voiceActive=l==="listening",(l==="listening"||l==="idle"||l==="disconnected")&&this.settlePendingVoiceTurn(l!=="listening"),this.callbacks.onVoiceStatusChanged?.(l))}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider&&this.voiceSetupPromise&&await this.voiceSetupPromise,!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(e){console.error("Failed to start voice:",e)}}}prewarmVoice(){if(!gn(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let e=this.voiceSetupGeneration,n=()=>{let o=this.voiceProvider;!o?.prewarm||e!==this.voiceSetupGeneration||this.voiceActive||this.isBargeInActive()||Promise.resolve().then(()=>o.prewarm?.()).catch(()=>{})};if(!this.voiceProvider&&this.voiceSetupPromise){this.voiceSetupPromise.then(n,()=>{});return}n()}cleanupVoice(){let e=this.voiceProvider!==null;if(this.voiceSetupGeneration++,this.voiceSetupPromise=null,this.voiceProvider){let n=this.voiceProvider;this.voiceProvider=null,this.voiceDisconnectPromise=this.disconnectVoice(n)}this.voiceActive=!1,this.voiceStatus="disconnected",this.settlePendingVoiceTurn(!0),this.voiceTurns=new $a,e&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async disconnectVoice(e){try{await e.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}settlePendingVoiceTurn(e){let n=e?this.pendingVoiceUserMessageId:null,o=this.pendingVoiceAssistantMessageId;!n&&!o||(o&&this.voiceTurns.cancel(),e&&(this.pendingVoiceUserMessageId=null),this.pendingVoiceAssistantMessageId=null,o&&this.ttsSpokenMessageIds.add(o),this.messages=this.messages.flatMap(s=>s.id!==n&&s.id!==o?[s]:s.id===o&&!s.content.trim()?[]:[{...s,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),o&&this.setStreaming(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:e.runtype?.agentId??this.config.agentId??"",clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine,prewarmMode:e.runtype?.prewarmMode,attachIdleMs:e.runtype?.attachIdleMs}};case"browser":return{type:"browser",browser:{language:e.browser?.language||"en-US",continuous:e.browser?.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.bootConversationRevision=this.historyInternals.getStoredConversationRevision?.()??null,this.bootRevisionCaptured=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:new Error(String(e))),null}}warmClientSession(){let e=!this.messages.length;this.client.warmSession().then(n=>{n&&this.client.getClientSession()===n&&this.setClientSession(n,e)})}setClientSession(e,n){this.clientSession=e,this.injectWelcomeMessage(e,n)}injectWelcomeMessage(e,n=!this.messages.length){if(this.suppressWelcomeInjection||!e.config.welcomeMessage||!n)return;let o=this.messages[0],s={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:o?.createdAt??new Date().toISOString(),sequence:o?(o.sequence??0)-1:this.nextSequence()};this.appendMessage(s)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,n){return this.client.submitMessageFeedback(e,n)}async submitCSATFeedback(e,n){return this.client.submitCSATFeedback(e,n)}async submitNPSFeedback(e,n){return this.client.submitNPSFeedback(e,n)}setHistoryInternals(e){this.historyInternals=this.composeHistoryInternals(e),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.cleanupVoice(),this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(e){let n=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:o=>{this.handleHistoryContinuityChanged(o),n?.(o)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let e=this.historyProvider;if(!e)throw new Ho("history_unavailable","No conversation history provider is installed");return e}historyContext(e){let n=this.requireHistoryProvider(),o=e??this.config.features?.history?.scope,s=this.config.getIdentityProof?"verified-user":"browser",i=o??(n.capabilities.scopes.includes(s)?s:n.capabilities.scopes[0]??s);if(!n.capabilities.scopes.includes(i))throw new Ss("unsupported_scope","This history scope is not supported.");return{scope:i}}getHistoryState(){return{activeConversationId:this.activeConversationId,conversationRevision:this.activeConversationRevision,nextMessageCursor:this.historyNextMessageCursor,recovery:this.historyRecovery,sendBlocked:this.historySendBlocked}}getActiveConversationId(){return this.activeConversationId}emitHistoryState(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}notifyHistory(e,n){this.callbacks.onHistoryNotice?.({code:e,message:n})}async awaitHistorySettled(){let e=this.historyGate;e&&await e.catch(()=>{});let n=this.projectionFinalizationPromise;n&&await n.catch(()=>{})}assertHistoryIdle(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new Ho("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(e){return this.requireHistoryProvider().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId!==void 0?{targetId:e.targetId}:{},context:this.historyContext(e?.scope)})}async openConversation(e,n){let o=this.requireHistoryProvider();this.assertHistoryIdle();let s=this.historyContext(n?.scope);await this.awaitHistorySettled();let i=++this.historyOpenEpoch,l=await o.getPage(e,{context:s});if(i!==this.historyOpenEpoch)throw new Ho("superseded","A later selection won");let c=await o.prepareOpen(e,{context:s});if(i!==this.historyOpenEpoch)throw c.discard(),new Ho("superseded","A later selection won");this.suppressWelcomeInjection=!0;try{await this.commitActivation(c)}finally{this.suppressWelcomeInjection=!1}this.activeConversationId=c.conversationId||e,this.activeConversationRevision=c.conversationRevision||l.conversationRevision||null,this.historyNextMessageCursor=l.nextCursor,this.historyRecovery=null,this.historySendBlocked=!1,this.resetConversationScopedState();for(let d of l.messages)this.acknowledgedProjections.set(d.id,d.content);return this.persistConversationMetadata(),this.hydrateMessages(l.messages),this.emitHistoryState(),{summary:l.summary,nextMessageCursor:l.nextCursor}}loadOlderMessages(e,n,o){let s=this.requireHistoryProvider(),i=this.historyContext(o?.scope),l=n??this.historyNextMessageCursor;if(!l)return Promise.resolve({messages:[],nextMessageCursor:null});let c=`${e} ${l}`,d=this.olderPageRequests.get(c);if(d)return d;let g=this.fetchOlderPage(s,e,l,i).finally(()=>{this.olderPageRequests.delete(c)});return this.olderPageRequests.set(c,g),g}async fetchOlderPage(e,n,o,s){let i=this.messages[0]?.createdAt,l=await e.getPage(n,{cursor:o,...i?{beforeCreatedAt:i}:{},context:s});if(this.activeConversationId&&this.activeConversationId!==n)return{messages:[],nextMessageCursor:l.nextCursor};let c=Na(this.messages,l.messages);this.messages=this.sortMessages(c.map(d=>this.ensureSequence(d))),this.historyNextMessageCursor=l.nextCursor;for(let d of l.messages)this.acknowledgedProjections.set(d.id,d.content);return this.historyInternals.setStoredMessageCursor?.(l.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.emitHistoryState(),{messages:l.messages,nextMessageCursor:l.nextCursor}}async startNewConversation(e){let n=this.requireHistoryProvider(),o=this.historyContext(e?.scope);await this.awaitHistorySettled();let s=++this.historyOpenEpoch,i=await n.prepareStartNew({context:o});if(s!==this.historyOpenEpoch)throw i.discard(),new Ho("superseded","A later action won");await this.installFreshConversation(i)}async installFreshConversation(e){this.discardConversationState(),await this.commitActivation(e),this.activeConversationId=e.conversationId||null,this.activeConversationRevision=e.conversationRevision||null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.persistConversationMetadata(),this.emitHistoryState()}async deleteConversation(e,n){let o=this.requireHistoryProvider(),s=this.historyContext(n?.scope);await this.awaitHistorySettled(),await o.delete(e,{context:s}),e===this.activeConversationId&&await this.recoverFromDestroyedConversation(s)}async updateConversation(e,n,o){let s=this.requireHistoryProvider();if(!s.update)throw new Ho("history_unavailable","This history provider cannot update conversations");let i=this.historyContext(o?.scope);return await this.awaitHistorySettled(),s.update(e,n,{context:i})}canUpdateConversations(){return typeof this.historyProvider?.update=="function"}async clearConversationHistory(e){let n=this.requireHistoryProvider(),o=this.historyContext(e?.scope);await this.awaitHistorySettled();let s=await n.deleteAll({...e?.targetId!==void 0?{targetId:e.targetId}:{},context:o});return await this.recoverFromDestroyedConversation(o),s}async resetHistoryDevice(){let e=this.requireHistoryProvider();if(!e.resetDevice)throw new Ho("history_unavailable","This history provider cannot reset the device");this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null;try{return await e.resetDevice()}finally{this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.emitHistoryState()}}async recoverFromDestroyedConversation(e){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historySendBlocked=!0,this.historyRecovery=null,this.emitHistoryState(),await this.prepareReplacementConversation(e)}async prepareReplacementConversation(e){let n=this.historyProvider;if(!n){this.historySendBlocked=!1,this.emitHistoryState();return}try{let o=await n.prepareStartNew({context:e});await this.installFreshConversation(o)}catch{this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async retryRequiredConversation(){if(!(this.historyRecovery!=="new_conversation_required"||!this.historyProvider)&&(this.historyRecovery=null,await this.prepareReplacementConversation(this.historyContext()),this.historyRecovery==="new_conversation_required"))throw new Ho("new_conversation_required","A new conversation is required before sending")}async commitActivation(e){await e.commit();let n=this.client.getClientSession();n&&n.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(n)}bindActivatedSession(e){this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.activeConversationId=e.conversationId,this.activeConversationRevision=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.suppressWelcomeInjection||this.injectWelcomeMessage(e)}persistConversationMetadata(){this.activeConversationId?this.config.setStoredConversationId?.(this.activeConversationId):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.activeConversationRevision),this.historyInternals.setStoredMessageCursor?.(this.historyNextMessageCursor)}resetConversationScopedState(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.acknowledgedProjections.clear(),this.setPendingProjections(null)}discardConversationState(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.resetConversationScopedState(),this.olderPageRequests.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}handleHistoryContinuityChanged(e){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.historySendBlocked=!0,this.discardConversationState(),this.activeConversationId=e.conversationId,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),this.notifyHistory("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.historyGate=Promise.resolve().then(()=>{this.historySendBlocked=!1,this.historyGate=null,this.emitHistoryState()})}syncVisitorStoreSubscription(){let e=this.historyInternals.visitorStore??null;e!==this.subscribedVisitorStore&&(this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=e,e&&(this.visitorStoreUnsubscribe=e.subscribe(n=>this.handleExternalCredentialChange(n))))}handleExternalCredentialChange(e){if(e.source!=="external"||e.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.credentialReinitPending=!0,this.credentialReinitPromise=null;let n=this.messages.length>0;n||this.activeConversationId!==null||(this.config.getStoredConversationId?.()??null)!==null?this.discardConversationState():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.olderPageRequests.clear(),this.setPendingProjections(null)),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),n&&this.notifyHistory("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}completeCredentialReinit(){return this.credentialReinitPending?(this.credentialReinitPromise||(this.credentialReinitPromise=this.runCredentialReinit().finally(()=>{this.credentialReinitPromise=null})),this.credentialReinitPromise):Promise.resolve()}async runCredentialReinit(){if(!this.isClientTokenMode()){this.credentialReinitPending=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.credentialReinitPending=!1}catch{}}reconcileBootConversation(e){let n=this.historyProvider,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.activeConversationId;if(!n||!o)return Promise.resolve();let s=this.historyContext(e?.scope);this.historySendBlocked=!0,this.emitHistoryState();let i=this.runBootReconciliation(n,o,s).finally(()=>{this.historySendBlocked=this.historyRecovery!==null,this.historyGate===i&&(this.historyGate=null),this.emitHistoryState()});return this.historyGate=i,i}async runBootReconciliation(e,n,o){this.activeConversationId=n;let s=this.clientSession?.conversationRevision??this.activeConversationRevision??null,i=this.bootRevisionCaptured?this.bootConversationRevision:this.historyInternals.getStoredConversationRevision?.()??null;if(this.bootRevisionCaptured=!1,this.historyNextMessageCursor=this.historyInternals.getStoredMessageCursor?.()??this.historyNextMessageCursor,await this.replayPendingProjections(),s&&i&&s===i){this.activeConversationRevision=s;return}let l=await e.getPage(n,{context:o}),c=new Set(l.messages.map(m=>m.id)),d=this.messages.some(m=>c.has(m.id)),g=l.messages[0]?.createdAt,u;if(!d)u=l.messages.map(m=>this.ensureSequence(m));else{let m=this.resumable?this.activeAssistantMessageId:null,y=this.messages.filter(b=>c.has(b.id)||b.id===m?!0:g!==void 0&&b.createdAt<g);u=Na(y,l.messages).map(b=>this.ensureSequence(b))}this.historyNextMessageCursor=l.nextCursor,this.activeConversationRevision=l.conversationRevision||s||null,this.acknowledgedProjections.clear();for(let m of l.messages)this.acknowledgedProjections.set(m.id,m.content);this.persistConversationMetadata(),this.messages=this.sortMessages(u),this.callbacks.onMessagesChanged([...this.messages])}projectionFinalizationEnabled(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}setPendingProjections(e){this.pendingProjections=e,this.historyInternals.setPendingDisplayProjections?.(e)}readPendingProjections(){return this.historyInternals.getPendingDisplayProjections?.()??this.pendingProjections}recordDispatchedProjections(e){if(this.projectionFinalizationEnabled())for(let n of e){let o=Oa(n);o!==void 0&&this.acknowledgedProjections.set(n.id,o)}}scheduleProjectionFinalization(){if(!this.projectionFinalizationEnabled())return;let e=this.activeConversationId;if(!e)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let s=Oa(o);s!==void 0&&this.acknowledgedProjections.get(o.id)!==s&&n.push({id:o.id,displayContent:s})}n.length!==0&&(this.setPendingProjections({conversationId:e,messageIds:n.map(o=>o.id)}),this.enqueueProjectionFinalization(e,n))}enqueueProjectionFinalization(e,n){let s=(this.projectionFinalizationPromise??Promise.resolve()).catch(()=>{}).then(()=>this.finalizeProjections(e,n,!1)).finally(()=>{this.projectionFinalizationPromise===s&&(this.projectionFinalizationPromise=null)});this.projectionFinalizationPromise=s}async finalizeProjections(e,n,o){if(this.activeConversationId!==e)return;let s=n.filter(i=>this.acknowledgedProjections.get(i.id)!==i.displayContent);if(s.length===0){this.clearFinalizedMarker(e,n);return}try{let{conversationRevision:i}=await this.client.finalizeDisplayProjections(e,s);for(let l of s)this.acknowledgedProjections.set(l.id,l.displayContent);this.activeConversationId===e&&i&&(this.activeConversationRevision=i),this.clearFinalizedMarker(e,n)}catch(i){if(!o&&this.isTransientProjectionError(i)){await this.finalizeProjections(e,s,!0);return}if(i instanceof Oe&&(i.code==="not_found"||i.code==="conversation_deleted")){this.clearFinalizedMarker(e,n);return}this.notifyHistory("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}isTransientProjectionError(e){return e instanceof Oe?e.code==="request_failed":e instanceof Error}clearFinalizedMarker(e,n){let o=this.readPendingProjections();if(!o||o.conversationId!==e)return;let s=new Set(n.map(l=>l.id)),i=o.messageIds.filter(l=>!s.has(l));this.setPendingProjections(i.length?{conversationId:e,messageIds:i}:null)}async replayPendingProjections(){if(!this.projectionFinalizationEnabled())return;let e=this.readPendingProjections();if(!e)return;if(this.activeConversationId&&e.conversationId!==this.activeConversationId){this.setPendingProjections(null);return}let n=[];for(let o of e.messageIds){let s=this.messages.find(i=>i.id===o);!s||typeof s.content!="string"||n.push({id:o,displayContent:s.content})}if(n.length===0){this.setPendingProjections(null);return}this.enqueueProjectionFinalization(e.conversationId,n),await this.projectionFinalizationPromise?.catch(()=>{})}invalidateConversationRevision(){this.activeConversationId&&(this.activeConversationRevision=null,this.historyInternals.setStoredConversationRevision?.(null))}async awaitHistorySendable(){await this.awaitHistorySettled(),await this.completeCredentialReinit(),this.historyRecovery==="new_conversation_required"&&await this.retryRequiredConversation()}static isConversationDeleted(e){return e instanceof Oe&&e.code==="conversation_deleted"}async dispatchWithDeletedRecovery(e,n,o,s,i){this.recordDispatchedProjections(e);try{await this.client.dispatch({messages:e,signal:n.signal,assistantMessageId:o,composerOptions:i?.composerOptions,interrupt:i?.interrupt},this.handleEvent);return}catch(l){if(!t.isConversationDeleted(l))throw l;let c=await this.recoverFromDeletedConversation(s);if(!c)throw l;this.recordDispatchedProjections([c]),await this.client.dispatch({messages:[c],signal:n.signal,assistantMessageId:o,composerOptions:i?.composerOptions},this.handleEvent)}}async recoverFromDeletedConversation(e){let n=this.messages.find(s=>s.id===e);if(!n)return null;let o={...n};this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.suppressWelcomeInjection=!0;try{let s=this.historyProvider;if(s){let i=await s.prepareStartNew({context:this.historyContext()});await this.installFreshConversation(i)}else{this.client.clearClientSession();let i=await this.client.initSession();this.bindActivatedSession(i)}}catch{return this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.suppressWelcomeInjection=!1}return this.appendMessage(o),this.setStreaming(!0),this.notifyHistory("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(s=>s.id===o.id)??o}updateConfig(e){let n=this.config.features?.artifacts?.display,o={...this.config,...e},s=wb(this.config,o),i=zM(this.config,o);this.config=o,s&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&gn(o.voiceRecognition.provider)&&this.setupVoice());let l=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!i){this.client.updateConfig(o),l&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let c=this.client.getSSEEventCallback();this.client=new Fa(this.config,this.historyInternals),l&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),c&&this.client.setSSEEventCallback(c)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:o,llmContent:s,contentParts:i,id:l,createdAt:c,sequence:d,streaming:g=!1,voiceProcessing:u,rawContent:m}=e,b={id:l??(n==="user"?qc():n==="assistant"?xi():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:c??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:g,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...u!==void 0&&{voiceProcessing:u},...m!==void 0&&{rawContent:m}};return this.upsertMessage(b),b}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let n=[];for(let o of e){let{role:s,content:i,llmContent:l,contentParts:c,id:d,createdAt:g,sequence:u,streaming:m=!1,voiceProcessing:y,rawContent:b}=o,S={id:d??(s==="user"?qc():s==="assistant"?xi():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:s,content:i,createdAt:g??new Date().toISOString(),sequence:u??this.nextSequence(),streaming:m,...l!==void 0&&{llmContent:l},...c!==void 0&&{contentParts:c},...y!==void 0&&{voiceProcessing:y},...b!==void 0&&{rawContent:b}};n.push(S)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(e){let{component:n,props:o={},text:s="",llmContent:i,id:l,createdAt:c,sequence:d}=e,g={text:s,component:n,props:o};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(g),...i!==void 0&&{llmContent:i},...l!==void 0&&{id:l},...c!==void 0&&{createdAt:c},...d!==void 0&&{sequence:d}})}async applyMentionBundle(e,n,o){let s;try{s=await o()}catch{return}let i=s.blocks.join(`
9
+ _Details: ${n.message}_`:o}var ph=t=>Cd(t)||t===Ad,Sl=class t{constructor(e={},n,o={}){this.config=e;this.callbacks=n;this.historyInternals=o;this.status="idle";this.streaming=!1;this.abortController=null;this.#e=Date.now();this.clientSession=null;this.agentExecution=null;this.#t=null;this.#s=null;this.#r=!1;this.#a=null;this.#f=null;this.#i=null;this.artifacts=new Map;this.#u=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.#v=0;this.webMcpApprovalResolvers=new Map;this.#N=0;this.approvalTokens=new Map;this.webMcpAwaitBatches=new Map;this.#n=null;this.#l=null;this.#h=0;this.#D=0;this.#O=!1;this.#V="disconnected";this.#o=null;this.#c=null;this.#g=null;this.#C=0;this.#L=!1;this.#y=null;this.#d=!1;this.#x=null;this.#E=new Map;this.#b=null;this.#m=new Map;this.#re=null;this.#se=null;this.#K=!1;this.#I=null;this.#$=null;this.#S=!1;this.#z=null;this.#G=null;this.#Y=null;this.#H=new wi;this.#ne=Promise.resolve();this.#U=null;this.#R=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new wl(()=>this.#me());this.#Qe=null;this.#q=0;this.handleEvent=e=>{let n=this.#R;if(n&&(e.type==="error"||e.type==="status"&&e.status==="error"?n.failed=!0:e.type==="message"&&e.message.role==="assistant"&&(n.dropped||this.ttsSpokenMessageIds.add(e.message.id),n.ids.includes(e.message.id)||n.ids.push(e.message.id))),e.type==="message"){this.upsertMessage(e.message),e.message.variant==="approval"&&e.message.approval&&e.message.approval.status!=="pending"&&this.#Be(e.message.id),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.#s=e.message.id),(e.message.variant==="approval"||e.message.agentMetadata?.awaitingLocalTool===!0)&&Nd().catch(()=>{});let o=e.message.toolCall,s=!!o?.name&&(Cd(o.name)||o.name===Ad&&ds(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&s&&this.#Xe(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:e.message.agentMetadata.agentName??"",status:"running",currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type==="cursor")this.#nt(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.#ot()){this.#we();return}if(this.#P(e.status),e.status==="connecting")this.#p(!0);else if(e.status==="idle"||e.status==="error"){this.#We()||this.#ge(),this.webMcpResolveControllers.size===0&&(this.#p(!1),this.abortController=null,this.#Ue(),this.#$e());let o=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(e.status==="error"?this.agentExecution.status="error":o||(this.agentExecution.status="complete")),this.#Je()}}else e.type==="error"?(this.#P("error"),this.#ge(),this.webMcpResolveControllers.size===0&&(this.#p(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.#tt(e)};this.historyInternals=this.#de(o),this.messages=[...e.initialMessages??[]].map(s=>({...s,sequence:s.sequence??this.#M()})),this.messages=this.#j(this.messages),this.client=new vi(e,this.historyInternals),this.#Ee(),this.#He();for(let s of e.initialArtifacts??[])this.artifacts.set(s.id,{...s,status:"complete"});e.initialSelectedArtifactId!=null&&(this.#u=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#Z(),this.callbacks.onStatusChanged(this.status),this.#ie(),this.#te()}#e;#t;#s;#r;#a;#f;#i;#u;#v;#N;#n;#l;#h;#D;#O;#V;#o;#c;#g;#C;#L;#y;#d;#x;#E;#b;#m;#re;#se;#K;#I;#$;#S;#z;#te(){this.config.voiceRecognition?.provider&&Si().catch(()=>{})}#ie(){let e=this.config.textToSpeech;if(e?.provider!=="runtype"||e.createEngine)return;let n=e.host??this.config.apiUrl,o=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||qd().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return Nf(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#O}getVoiceStatus(){return this.#V}getVoiceDisclosure(){return this.#n?.getDisclosure?.()??null}getVoiceLevel(){return this.#n?.onLevel?this.#D:null}getVoiceInterruptionMode(){return this.#n?.getInterruptionMode?this.#n.getInterruptionMode():"none"}stopVoicePlayback(){this.#n?.stopPlayback&&(this.#H.cancel(),this.#U?.cancel(),this.#n.stopPlayback())}isBargeInActive(){return this.#n?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#n?.deactivateBargeIn&&await this.#n.deactivateBargeIn()}#G;#Y;#H;#ne;#U;#R;#me(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let n=Ci.isSupported()?new Ci({pickVoice:e?.pickVoice}):null;if(e?.provider==="runtype"){let o=e.host??this.config.apiUrl,s=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,i=this.config.clientToken,l=e.browserFallback!==!1;if(o&&s&&i)return qd().then(({RuntypeSpeechEngine:c,FallbackSpeechEngine:u})=>{let p=new c({host:o,agentId:s,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return l&&n?new u(p,n,{onFallback:g=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${g.message}`)}):p});if(l&&n)return i&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){try{let n=e||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.cleanupVoice();let o=this.#ne,s=++this.#h;this.#l=Si().then(async i=>{await o,s===this.#h&&this.#ae(i,i.createVoiceProvider(n))}).catch(i=>{console.error("Failed to setup voice:",i)}).finally(()=>{s===this.#h&&(this.#l=null)})}catch(n){console.error("Failed to setup voice:",n)}}#ae(e,n){this.#n=n;let o=this;e.wireSessionVoice({session:this,provider:()=>o.#n,generation:()=>o.#h,get keyed(){return o.#U},set keyed(s){o.#U=s},get pendingUser(){return o.#G},set pendingUser(s){o.#G=s},get pendingAssistant(){return o.#Y},set pendingAssistant(s){o.#Y=s},turns:()=>o.#H,busy:()=>o.#fe(),setStreaming:s=>o.#p(s),setDelegation:s=>{o.#R=s},setLevel:s=>{o.#D=s},setStatus:s=>{o.#V=s,o.#O=s==="listening"},settlePending:s=>o.#le(s)},n,e.KeyedVoiceTranscript,e.createVoiceSessionBridge)}async toggleVoice(){if(!this.#n&&this.#l&&await this.#l,!this.#n){console.error("Voice not configured");return}if(this.#O)await this.#n.stopListening();else{this.stopSpeaking();try{await this.#n.startListening()}catch(e){console.error("Failed to start voice:",e)}}}prewarmVoice(){if(!Nt(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let e=this.#h,n=()=>{let o=this.#n;!o?.prewarm||e!==this.#h||this.#O||this.isBargeInActive()||Promise.resolve().then(()=>o.prewarm?.()).catch(()=>{})};if(!this.#n&&this.#l){this.#l.then(n,()=>{});return}n()}#fe(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#r||this.status==="resuming"}cleanupVoice(){let e=this.#n!==null;if(this.#h++,this.#l=null,this.#n){let n=this.#n;this.#n=null,this.#ne=this.#T(n)}this.#O=!1,this.#V="disconnected",this.#le(!0),this.#U?.settle(),this.#U=null,this.#H=new wi,e&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async#T(e){try{await e.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}#le(e){let n=e?this.#G:null,o=this.#Y;!n&&!o||(o&&this.#H.cancel(),e&&(this.#G=null),this.#Y=null,o&&this.ttsSpokenMessageIds.add(o),this.messages=this.messages.flatMap(s=>s.id!==n&&s.id!==o?[s]:s.id===o&&!s.content.trim()?[]:[{...s,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),o&&this.#p(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:e.runtype?.agentId??this.config.agentId??"",clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine,prewarmMode:e.runtype?.prewarmMode,attachIdleMs:e.runtype?.attachIdleMs,clientDelegation:e.runtype?.clientDelegation,callContext:e.runtype?.callContext,approvalTimeoutMs:e.runtype?.approvalTimeoutMs,disclosureText:e.runtype?.disclosureText}};case"browser":return{type:"browser",browser:{language:e.browser?.language||"en-US",continuous:e.browser?.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.#se=this.historyInternals.getStoredConversationRevision?.()??null,this.#K=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:new Error(String(e))),null}}warmClientSession(){let e=!this.messages.length;this.client.warmSession().then(n=>{n&&this.client.getClientSession()===n&&this.setClientSession(n,e)})}setClientSession(e,n){this.clientSession=e,this.#ce(e,n)}#ce(e,n=!this.messages.length){if(this.#L||!e.config.welcomeMessage||!n)return;let o=this.messages[0],s={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:o?.createdAt??new Date().toISOString(),sequence:o?(o.sequence??0)-1:this.#M()};this.#B(s)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,n){return this.client.submitMessageFeedback(e,n)}async submitCSATFeedback(e,n){return this.client.submitCSATFeedback(e,n)}async submitNPSFeedback(e,n){return this.client.submitNPSFeedback(e,n)}setHistoryInternals(e){this.historyInternals=this.#de(e),this.client.setHistoryInternals(this.historyInternals),this.#Ee()}destroy(){this.cleanupVoice(),this.#I?.(),this.#I=null,this.#$=null}#de(e){let n=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:o=>{this.#Oe(o),n?.(o)}}}get#W(){return this.historyInternals.historyProvider??null}#k(){let e=this.#W;if(!e)throw new jn("history_unavailable","No conversation history provider is installed");return e}#A(e){let n=this.#k(),o=e??this.config.features?.history?.scope,s=this.config.getIdentityProof?"verified-user":"browser",i=o??(n.capabilities.scopes.includes(s)?s:n.capabilities.scopes[0]??s);if(!n.capabilities.scopes.includes(i))throw new el("unsupported_scope","This history scope is not supported.");return{scope:i}}getHistoryState(){return{activeConversationId:this.#o,conversationRevision:this.#c,nextMessageCursor:this.#g,recovery:this.#y,sendBlocked:this.#d}}getActiveConversationId(){return this.#o}#w(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#_(e,n){this.callbacks.onHistoryNotice?.({code:e,message:n})}async awaitHistorySettled(){let e=this.#x;e&&await e.catch(()=>{});let n=this.#b;n&&await n.catch(()=>{})}#he(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new jn("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(e){return this.#k().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId!==void 0?{targetId:e.targetId}:{},context:this.#A(e?.scope)})}async openConversation(e,n){let o=this.#k();this.#he();let s=this.#A(n?.scope);await this.awaitHistorySettled();let i=++this.#C,l=await o.getPage(e,{context:s});if(i!==this.#C)throw new jn("superseded","A later selection won");let c=await o.prepareOpen(e,{context:s});if(i!==this.#C)throw c.discard(),new jn("superseded","A later selection won");this.#L=!0;try{await this.#Ae(c)}finally{this.#L=!1}this.#o=c.conversationId||e,this.#c=c.conversationRevision||l.conversationRevision||null,this.#g=l.nextCursor,this.#y=null,this.#d=!1,this.#Me();for(let u of l.messages)this.#m.set(u.id,u.content);return this.#ye(),this.hydrateMessages(l.messages),this.#w(),{summary:l.summary,nextMessageCursor:l.nextCursor}}loadOlderMessages(e,n,o){let s=this.#k(),i=this.#A(o?.scope),l=n??this.#g;if(!l)return Promise.resolve({messages:[],nextMessageCursor:null});let c=`${e} ${l}`,u=this.#E.get(c);if(u)return u;let p=this.#pe(s,e,l,i).finally(()=>{this.#E.delete(c)});return this.#E.set(c,p),p}async#pe(e,n,o,s){let i=this.messages[0]?.createdAt,l=await e.getPage(n,{cursor:o,...i?{beforeCreatedAt:i}:{},context:s});if(this.#o&&this.#o!==n)return{messages:[],nextMessageCursor:l.nextCursor};let c=Td(this.messages,l.messages);this.messages=this.#j(c.map(u=>this.#oe(u))),this.#g=l.nextCursor;for(let u of l.messages)this.#m.set(u.id,u.content);return this.historyInternals.setStoredMessageCursor?.(l.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#w(),{messages:l.messages,nextMessageCursor:l.nextCursor}}async startNewConversation(e){let n=this.#k(),o=this.#A(e?.scope);await this.awaitHistorySettled();let s=++this.#C,i=await n.prepareStartNew({context:o});if(s!==this.#C)throw i.discard(),new jn("superseded","A later action won");await this.#F(i)}async#F(e){this.#Q(),await this.#Ae(e),this.#o=e.conversationId||null,this.#c=e.conversationRevision||null,this.#g=null,this.#y=null,this.#d=!1,this.#ye(),this.#w()}async deleteConversation(e,n){let o=this.#k(),s=this.#A(n?.scope);await this.awaitHistorySettled(),await o.delete(e,{context:s}),e===this.#o&&await this.#Se(s)}async updateConversation(e,n,o){let s=this.#k();if(!s.update)throw new jn("history_unavailable","This history provider cannot update conversations");let i=this.#A(o?.scope);return await this.awaitHistorySettled(),s.update(e,n,{context:i})}canUpdateConversations(){return typeof this.#W?.update=="function"}async clearConversationHistory(e){let n=this.#k(),o=this.#A(e?.scope);await this.awaitHistorySettled();let s=await n.deleteAll({...e?.targetId!==void 0?{targetId:e.targetId}:{},context:o});return await this.#Se(o),s}async resetHistoryDevice(){let e=this.#k();if(!e.resetDevice)throw new jn("history_unavailable","This history provider cannot reset the device");this.#C+=1,this.#b=null;try{return await e.resetDevice()}finally{this.#Q(),this.#o=null,this.#c=null,this.#g=null,this.#y=null,this.#d=!1,this.#w()}}async#Se(e){this.#C+=1,this.#b=null,this.#Q(),this.#o=null,this.#c=null,this.#g=null,this.#d=!0,this.#y=null,this.#w(),await this.#xe(e)}async#xe(e){let n=this.#W;if(!n){this.#d=!1,this.#w();return}try{let o=await n.prepareStartNew({context:e});await this.#F(o)}catch{this.#d=!0,this.#y="new_conversation_required",this.#w(),this.#_("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async#De(){if(!(this.#y!=="new_conversation_required"||!this.#W)&&(this.#y=null,await this.#xe(this.#A()),this.#y==="new_conversation_required"))throw new jn("new_conversation_required","A new conversation is required before sending")}async#Ae(e){await e.commit();let n=this.client.getClientSession();n&&n.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(n)}bindActivatedSession(e){this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.#o=e.conversationId,this.#c=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.#L||this.#ce(e)}#ye(){this.#o?this.config.setStoredConversationId?.(this.#o):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#c),this.historyInternals.setStoredMessageCursor?.(this.#g)}#Me(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#Ce(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#m.clear(),this.#X(null)}#Q(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#ee(),this.#J(),this.#q++,this.messages=[],this.#Me(),this.#E.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#p(!1),this.#P("idle"),this.callbacks.onMessagesChanged([...this.messages])}#Oe(e){this.#C+=1,this.#b=null,this.#d=!0,this.#Q(),this.#o=e.conversationId,this.#c=null,this.#g=null,this.#y=null,this.#w(),this.#_("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.#x=Promise.resolve().then(()=>{this.#d=!1,this.#x=null,this.#w()})}#Ee(){let e=this.historyInternals.visitorStore??null;e!==this.#$&&(this.#I?.(),this.#I=null,this.#$=e,e&&(this.#I=e.subscribe(n=>this.#_e(n))))}#_e(e){if(e.source!=="external"||e.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#C+=1,this.#b=null,this.#S=!0,this.#z=null;let n=this.messages.length>0;n||this.#o!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#Q():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#E.clear(),this.#X(null)),this.#o=null,this.#c=null,this.#g=null,this.#y=null,this.#w(),n&&this.#_("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}#Fe(){return this.#S?(this.#z||(this.#z=this.#Ne().finally(()=>{this.#z=null})),this.#z):Promise.resolve()}async#Ne(){if(!this.isClientTokenMode()){this.#S=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.#S=!1}catch{}}reconcileBootConversation(e){let n=this.#W,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#o;if(!n||!o)return Promise.resolve();let s=this.#A(e?.scope);this.#d=!0,this.#w();let i=this.#Ve(n,o,s).finally(()=>{this.#d=this.#y!==null,this.#x===i&&(this.#x=null),this.#w()});return this.#x=i,i}async#Ve(e,n,o){this.#o=n;let s=this.clientSession?.conversationRevision??this.#c??null,i=this.#K?this.#se:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#K=!1,this.#g=this.historyInternals.getStoredMessageCursor?.()??this.#g,await this.replayPendingProjections(),s&&i&&s===i){this.#c=s;return}let l=await e.getPage(n,{context:o}),c=new Set(l.messages.map(y=>y.id)),u=this.messages.some(y=>c.has(y.id)),p=l.messages[0]?.createdAt,g;if(!u)g=l.messages.map(y=>this.#oe(y));else{let y=this.#t?this.#s:null,h=this.messages.filter(C=>c.has(C.id)||C.id===y?!0:p!==void 0&&C.createdAt<p);g=Td(h,l.messages).map(C=>this.#oe(C))}this.#g=l.nextCursor,this.#c=l.conversationRevision||s||null,this.#m.clear();for(let y of l.messages)this.#m.set(y.id,y.content);this.#ye(),this.messages=this.#j(g),this.callbacks.onMessagesChanged([...this.messages])}#be(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#X(e){this.#re=e,this.historyInternals.setPendingDisplayProjections?.(e)}#Te(){return this.historyInternals.getPendingDisplayProjections?.()??this.#re}#ke(e){if(this.#be())for(let n of e){let o=gi(n);o!==void 0&&this.#m.set(n.id,o)}}#$e(){if(!this.#be())return;let e=this.#o;if(!e)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let s=gi(o);s!==void 0&&this.#m.get(o.id)!==s&&n.push({id:o.id,displayContent:s})}n.length!==0&&(this.#X({conversationId:e,messageIds:n.map(o=>o.id)}),this.#Pe(e,n))}#Pe(e,n){let s=(this.#b??Promise.resolve()).catch(()=>{}).then(()=>this.#Le(e,n,!1)).finally(()=>{this.#b===s&&(this.#b=null)});this.#b=s}async#Le(e,n,o){if(this.#o!==e)return;let s=n.filter(i=>this.#m.get(i.id)!==i.displayContent);if(s.length===0){this.#ve(e,n);return}try{let{conversationRevision:i}=await this.client.finalizeDisplayProjections(e,s);for(let l of s)this.#m.set(l.id,l.displayContent);this.#o===e&&i&&(this.#c=i),this.#ve(e,n)}catch(i){if(!o&&this.#ze(i)){await this.#Le(e,s,!0);return}if(i instanceof bt&&(i.code==="not_found"||i.code==="conversation_deleted")){this.#ve(e,n);return}this.#_("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}#ze(e){return e instanceof bt?e.code==="request_failed":e instanceof Error}#ve(e,n){let o=this.#Te();if(!o||o.conversationId!==e)return;let s=new Set(n.map(l=>l.id)),i=o.messageIds.filter(l=>!s.has(l));this.#X(i.length?{conversationId:e,messageIds:i}:null)}async replayPendingProjections(){if(!this.#be())return;let e=this.#Te();if(!e)return;if(this.#o&&e.conversationId!==this.#o){this.#X(null);return}let n=[];for(let o of e.messageIds){let s=this.messages.find(i=>i.id===o);!s||typeof s.content!="string"||n.push({id:o,displayContent:s.content})}if(n.length===0){this.#X(null);return}this.#Pe(e.conversationId,n),await this.#b?.catch(()=>{})}#Ue(){this.#o&&(this.#c=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Ie(){await this.awaitHistorySettled(),await this.#Fe(),this.#y==="new_conversation_required"&&await this.#De()}static#qe(e){return e instanceof bt&&e.code==="conversation_deleted"}async#je(e,n,o,s,i){this.#ke(e);try{await this.client.dispatch({messages:e,signal:n.signal,assistantMessageId:o,composerOptions:i?.composerOptions,interrupt:i?.interrupt},this.handleEvent);return}catch(l){if(!t.#qe(l))throw l;let c=await this.#Ke(s);if(!c)throw l;this.#ke([c]),await this.client.dispatch({messages:[c],signal:n.signal,assistantMessageId:o,composerOptions:i?.composerOptions},this.handleEvent)}}async#Ke(e){let n=this.messages.find(s=>s.id===e);if(!n)return null;let o={...n};this.#C+=1,this.#b=null,this.#Q(),this.#o=null,this.#c=null,this.#g=null,this.#L=!0;try{let s=this.#W;if(s){let i=await s.prepareStartNew({context:this.#A()});await this.#F(i)}else{this.client.clearClientSession();let i=await this.client.initSession();this.bindActivatedSession(i)}}catch{return this.#d=!0,this.#y="new_conversation_required",this.#w(),this.#_("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.#L=!1}return this.#B(o),this.#p(!0),this.#_("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(s=>s.id===o.id)??o}updateConfig(e){let n=this.config.features?.artifacts?.display,o={...this.config,...e},s=Ff(this.config,o),i=tw(this.config,o);this.config=o,s&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&Nt(o.voiceRecognition.provider)&&this.setupVoice());let l=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!i){this.client.updateConfig(o),l&&this.#Re();return}this.#J(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let c=this.client.getSSEEventCallback();this.client=new vi(this.config,this.historyInternals),l&&this.#Re(),this.#He(),c&&this.client.setSSEEventCallback(c)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:o,llmContent:s,contentParts:i,id:l,createdAt:c,sequence:u,streaming:p=!1,voiceProcessing:g,voiceCaption:y,rawContent:h}=e,E={id:l??(n==="user"?bl():n==="assistant"?hs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:c??new Date().toISOString(),sequence:u??this.#M(),streaming:p,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...y&&{voiceCaption:y},...h!==void 0&&{rawContent:h}};return this.upsertMessage(E),E}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let n=[];for(let o of e){let{role:s,content:i,llmContent:l,contentParts:c,id:u,createdAt:p,sequence:g,streaming:y=!1,voiceProcessing:h,rawContent:C}=o,A={id:u??(s==="user"?bl():s==="assistant"?hs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:s,content:i,createdAt:p??new Date().toISOString(),sequence:g??this.#M(),streaming:y,...l!==void 0&&{llmContent:l},...c!==void 0&&{contentParts:c},...h!==void 0&&{voiceProcessing:h},...C!==void 0&&{rawContent:C}};n.push(A)}return this.messages=this.#j([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(e){let{component:n,props:o={},text:s="",llmContent:i,id:l,createdAt:c,sequence:u}=e,p={text:s,component:n,props:o};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(p),...i!==void 0&&{llmContent:i},...l!==void 0&&{id:l},...c!==void 0&&{createdAt:c},...u!==void 0&&{sequence:u}})}async#Ge(e,n,o){let s;try{s=await o()}catch{return}let i=s.blocks.join(`
13
10
 
14
11
  `),l=[i,n].filter(Boolean).join(`
15
12
 
16
- `),c=Array.isArray(e.contentParts)&&e.contentParts.length>0,d=s.contentParts.length>0;if(c){let g=[];i&&g.push(Io(i)),g.push(...s.contentParts),g.push(...e.contentParts),e.contentParts=g}else if(d){let g=[];l&&g.push(Io(l)),g.push(...s.contentParts),e.contentParts=g}else i&&(e.llmContent=l);Object.keys(s.context).length>0&&(e.mentionContext=s.context)}async sendMessage(e,n){let o=e.trim(),s=!!n?.replayFields&&(n.replayFields.llmContent!==void 0||n.replayFields.rawContent!==void 0||(n.replayFields.contextMentions?.length??0)>0);if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0)&&!s)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let i=qc(),l=xi();this.activeAssistantMessageId=null;let c=n?.contentParts&&Qc(n.contentParts)?Ei:"",d={id:i,role:"user",content:o||c,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments},...n?.composerOptions&&{composerOptions:n.composerOptions},...n?.replayFields??{}};this.appendMessage(d),this.setStreaming(!0);let g=new AbortController;if(this.abortController=g,n?.mentions){let m=this.messages.find(y=>y.id===i)??d;if(await this.applyMentionBundle(m,o,n.mentions.finalize),g.signal.aborted||this.abortController!==g)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let m=this.messages.find(b=>b.id===i)??d,y=hv({quote:n.quote,text:m.llmContent??m.content,contentParts:m.contentParts});y.contentParts&&(m.contentParts=y.contentParts),y.llmContent!==void 0&&(m.llmContent=y.llmContent),(y.contentParts||y.llmContent!==void 0)&&(m.quote={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let u=[...this.messages];try{await this.dispatchWithDeletedRecovery(u,g,l,i,{composerOptions:n?.composerOptions,interrupt:n?.interrupt})}catch(m){if(this.status==="resuming"||this.reconnecting)return;let y=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));if(!y){let b=fg(m,this.config.errorMessage);if(b){let C={id:l,role:"assistant",createdAt:new Date().toISOString(),content:b,sequence:this.nextSequence()};this.appendMessage(C)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,y||(m instanceof Error?this.callbacks.onError?.(m):this.callbacks.onError?.(new Error(String(m))))}}resubmitFrom(e,n){let o=yv(this.messages,e);if(!o)return!1;let s=this.messages[o.start],i=n.replacement,l=i?i.text:s.content,c=i?i.contentParts:s.contentParts;if(!(!!l?.trim()||(c?.length??0)>0||!i&&(s.llmContent?.trim()?.length??0)>0))return!1;let g=i?void 0:{...s.llmContent!==void 0&&{llmContent:s.llmContent},...s.rawContent!==void 0&&{rawContent:s.rawContent},...s.mentionContext&&{mentionContext:s.mentionContext},...s.contextMentions&&{contextMentions:s.contextMentions},...s.quote&&{quote:s.quote}},u=i?this.toComposerOptionsPayload(i.options):s.composerOptions,m=i?i.contentSegments:s.contentSegments,y=i?i.options?.quote:void 0,b=i?i.viaVoice:s.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,o.start),this.sendMessage(l??"",{...c?.length?{contentParts:[...c]}:{},...m?.length?{contentSegments:[...m]}:{},...u?{composerOptions:u}:{},...y?{quote:y}:{},...g&&Object.keys(g).length>0?{replayFields:g}:{},viaVoice:b===!0}),!0}toComposerOptionsPayload(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n:void 0}async continueConversation(){if(this.streaming)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.abortController?.abort(),this.teardownReconnect();let e=xi();this.activeAssistantMessageId=null,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:e},this.handleEvent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;let i=s instanceof Error&&(s.name==="AbortError"||s.message.includes("aborted")||s.message.includes("abort"));if(!i){let l=fg(s,this.config.errorMessage);if(l){let c={id:e,role:"assistant",createdAt:new Date().toISOString(),content:l,sequence:this.nextSequence()};this.appendMessage(c)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,i||(s instanceof Error?this.callbacks.onError?.(s):this.callbacks.onError?.(new Error(String(s))))}}async connectStream(e,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,s=!1;for(let i of this.messages)i.streaming&&i.id!==o&&(i.streaming=!1,s=!0);s&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(i){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.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(s=>{this.webMcpApprovalResolvers.set(o,s)})}resolveWebMcpApproval(e,n){let o=this.webMcpApprovalResolvers.get(e);if(!o)return;this.webMcpApprovalResolvers.delete(e);let s=this.messages.find(i=>i.id===e);s?.approval&&this.upsertMessage({...s,approval:{...s.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(e,n,o){let s=`approval-${e.id}`,i={...e,status:n,resolvedAt:Date.now()},l=this.messages.find(u=>u.id===s),c={id:s,role:"assistant",content:"",createdAt:l?.createdAt??new Date().toISOString(),...l?.sequence!==void 0?{sequence:l.sequence}:{},streaming:!1,variant:"approval",approval:i};this.upsertMessage(c),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,g=d&&typeof d=="object"?d.onDecision:void 0;try{let u;if(g?u=await g({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},n,o):u=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},n),u){let m=null;if(u instanceof Response){if(!u.ok){let y=await u.json().catch(()=>null);throw new Error(y?.error??`Approval request failed: ${u.status}`)}m=u.body}else u instanceof ReadableStream&&(m=u);m?await this.connectStream(m,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${e.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(u){let m=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}persistAskUserQuestionProgress(e,n){let o=this.messages.find(s=>s.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(e,n){let o=this.messages.find(s=>s.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(e,n){if(this.messages.find(u=>u.id===e.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let s=e.agentMetadata?.executionId,i=e.toolCall?.name;if(!s||!i){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let l=typeof n=="string"?void 0:n;if(l===void 0&&typeof n=="string"){let u=e.toolCall?.args,m=Array.isArray(u?.questions)?u.questions:[];if(m.length===1){let y=typeof m[0]?.question=="string"?m[0].question:"";y&&(l={[y]:n})}}this.markAskUserQuestionResolved(e,l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let c=e.toolCall.id,d=e.toolCall?.args,g=Array.isArray(d?.questions)?d.questions:[];if(g.length===0){let u=typeof n=="string"?n:Object.entries(n).map(([m,y])=>`${m}: ${Array.isArray(y)?y.join(", "):y}`).join(" | ");this.appendMessage({id:`ask-user-answer-${c}`,role:"user",content:u,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let u=l??{};g.forEach((m,y)=>{let b=typeof m?.question=="string"?m.question:"";if(!b)return;let C=u[b],S=Array.isArray(C)?C.join(", "):typeof C=="string"?C:"";this.appendMessage({id:`ask-user-q-${c}-${y}`,role:"assistant",content:b,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${c}-${y}`,role:"user",content:S||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let u=await this.client.resumeFlow(s,{[i]:n},{after:this.resumable?.executionId===s?this.resumable.lastEventId:void 0});if(!u.ok){let m=await u.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${u.status}`)}u.body?await this.connectStream(u.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(u){let m=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}enqueueWebMcpAwait(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.id;if(!n||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let s=this.webMcpAwaitBatches.get(n);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,s)),!s.seen.has(o)&&(s.seen.add(o),s.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(e){let n=this.webMcpAwaitBatches.get(e);if(!n)return;this.webMcpAwaitBatches.delete(e);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(e,o)}resolveWebMcpToolStartedAt(e){let o=[this.messages.find(s=>s.id===e.id)?.toolCall?.startedAt,e.toolCall?.startedAt];for(let s of o)if(typeof s=="number"&&Number.isFinite(s))return s;return Date.now()}isSuggestRepliesAlreadyResolved(e){return e.toolCall?.name!==Or?!1:(this.messages.find(o=>o.id===e.id)??e).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(e){let n=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),n}markWebMcpToolComplete(e,n,o,s=Date.now(),i){this.messages.some(l=>l.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...i},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:n,startedAt:o,completedAt:s,duration:void 0,durationMs:Math.max(0,s-o)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,n){let o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let i=async d=>{let g=d.toolCall?.name,u=d.toolCall?.id;if(!g||!u)return null;let m=`${e}:${u}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m)||this.isSuggestRepliesAlreadyResolved(d))return null;this.webMcpInflightKeys.add(m),o.push(m);let y=this.markWebMcpToolRunning(d),b=d.agentMetadata?.webMcpToolCallId??g;if(g===Or)return{dedupeKey:m,resumeKey:b,output:Gb(),toolMessage:d,startedAt:y,completedAt:Date.now()};let C=this.client.executeWebMcpToolCall(g,d.toolCall?.args,s.signal),S;if(!C)S={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{S=await C}catch(E){let H=E instanceof Error&&(E.name==="AbortError"||E.message.includes("aborted")||E.message.includes("abort"));return H||this.callbacks.onError?.(E instanceof Error?E:new Error(String(E))),this.markWebMcpToolComplete(d,mg(H?"Aborted by cancel()":jM(E)),y),this.webMcpInflightKeys.delete(m),null}return s.signal.aborted?(this.markWebMcpToolComplete(d,mg("Aborted by cancel()"),y),this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:b,output:S,toolMessage:d,startedAt:y,completedAt:Date.now()}},l;if(this.config.webmcp?.execution==="sequential"){l=[];for(let d of n)l.push(await i(d))}else l=await Promise.all(n.map(i));let c=[];try{if(c=l.filter(m=>m!==null),c.length===0)return;let d={};for(let m of c)d[m.resumeKey]=m.output;let g=await this.client.resumeFlow(e,d,{signal:s.signal,after:this.resumable?.executionId===e?this.resumable.lastEventId:void 0});if(!g.ok){let m=await g.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${g.status}`)}let u=c[0].dedupeKey;for(let m of c){this.webMcpResolvedKeys.add(m.dedupeKey);let y=m.toolMessage.toolCall?.name,b=m.toolMessage.agentMetadata?.webMcpToolCallId;this.markWebMcpToolComplete(m.toolMessage,m.output,m.startedAt,m.completedAt,{...y===Or?{suggestRepliesResolved:!0}:{},...y&&b?{clientToolAnswer:{toolCallId:b,toolName:y,args:m.toolMessage.toolCall?.args,result:m.output,batch:u}}:{}})}g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(d){if(!(d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"))))this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)));else for(let u of c)this.markWebMcpToolComplete(u.toolMessage,mg("Aborted by cancel()"),u.startedAt)}finally{for(let d of o)this.webMcpInflightKeys.delete(d);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.name,s=e.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP await missing executionId: dispatch left paused."));return}if(!o)return;if(!s){let l=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(l)||this.webMcpResolvedKeys.has(l))return;this.webMcpInflightKeys.add(l);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(l)}catch(c){this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}finally{this.webMcpInflightKeys.delete(l)}return}let i=`${n}:${s}`;if(!(this.webMcpInflightKeys.has(i)||this.webMcpResolvedKeys.has(i)||this.isSuggestRepliesAlreadyResolved(e)))return this.resolveWebMcpToolCallBatch(n,[e])}async resumeWithToolOutput(e,n,o,s){let i=await this.client.resumeFlow(e,{[n]:o},{signal:s?.signal,after:this.resumable?.executionId===e?this.resumable.lastEventId:void 0});if(!i.ok){let l=await i.json().catch(()=>null);throw new Error(l?.error??`Resume failed: ${i.status}`)}s?.onHttpOk?.(),i.body?await this.connectStream(i.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),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(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){let n=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=e.artifactType==="markdown"?{id:n,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),e.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(e){let n=`artifact-ref-${e.id}`,o=Br(this.config.features?.artifacts,e),s=Wa(o,{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:"complete",...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}),i=this.messages.find(l=>l.id===n);if(i){i.rawContent=s,i.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:s})}refreshArtifactReferenceBlocks(){let e=!1;for(let n of this.artifacts.values()){let o=this.messages.find(l=>l.id===`artifact-ref-${n.id}`);if(!o)continue;let s=Br(this.config.features?.artifacts,n),i=Wa(s,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==i&&(o.rawContent=i,o.streaming=n.status==="streaming",e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:"",...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:e.component??"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let n=this.artifacts.get(e.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+e.artDelta);break}case"artifact_update":{let n=this.artifacts.get(e.id);n?.artifactType==="component"&&(n.props={...n.props,...e.props},e.component&&(n.component=e.component));break}case"artifact_complete":{let n=this.artifacts.get(e.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,n=null){this.artifacts.clear();for(let o of e)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(e){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:e,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant==="approval"&&e.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(e=>{this.reconnecting&&this.resumable&&e.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=wv().then(({createReconnectController:e})=>{let n=e(this.buildReconnectHost());return this.reconnectController=n,n}),this.reconnectControllerPromise.catch(()=>{this.reconnectControllerPromise=null})),this.reconnectControllerPromise)}buildReconnectHost(){let e=this;return{get config(){return e.config},getResumable:()=>e.resumable,clearResumable:()=>e.clearResumable(),getStatus:()=>e.status,setStatus:n=>e.setStatus(n),setStreaming:n=>e.setStreaming(n),setReconnecting:n=>{e.reconnecting=n},setAbortController:n=>{e.abortController=n},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(n,o,s)=>e.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:s}),appendMessage:n=>e.appendMessage(n),nextSequence:()=>e.nextSequence(),emitReconnect:n=>e.callbacks.onReconnect?.(n),buildErrorContent:n=>fg(new Error(n),e.config.errorMessage),onError:n=>e.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=xi(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:e.executionId,lastEventId:e.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let e=this.messages.length-1;e>=0;e--){let n=this.messages[e];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let e=this.resumable!==null;this.resumable=null,e&&this.config.onExecutionState?.(null)}notifyExecutionState(e){let n=this.config.onExecutionState;if(n){if(e){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let n=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),n&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!e?.enabled||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let o=[...this.messages].reverse().find(i=>i.role==="assistant"&&i.content&&!i.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let s=ug(o.content);s.trim()&&this.readAloud.play(o.id,{text:s,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return dg(e)}toggleReadAloud(e){let n=this.messages.find(i=>i.id===e);if(!n||n.role!=="assistant")return;let o=ug(n.content||"");if(!o.trim())return;let s=this.config.textToSpeech;this.readAloud.toggle(e,{text:o,voice:s?.voice,rate:s?.rate,pitch:s?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let n=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let n=this.ensureSequence(e),o=this.messages.findIndex(s=>s.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((s,i)=>{if(i!==o)return s;let l={...s,...n};s.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(l.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),s.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(l.agentMetadata={...l.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let c=s.agentMetadata?.clientToolAnswer;if(c&&l.agentMetadata&&!l.agentMetadata.clientToolAnswer&&(l.agentMetadata={...l.agentMetadata,clientToolAnswer:c}),s.approval&&n.approval&&s.approval.id===n.approval.id){let m=s.approval,y=n.approval;l.approval={...m,...y,executionId:y.executionId||m.executionId,toolName:y.toolName||m.toolName,description:y.description||m.description,toolType:y.toolType??m.toolType,reason:y.reason??m.reason,parameters:y.parameters??m.parameters}}let d=n.toolCall?.name,g=n.agentMetadata?.executionId,u=n.toolCall?.id;if(d&&xv(d)&&g&&u&&n.agentMetadata?.awaitingLocalTool===!0){let m=`${g}:${u}`,y=this.webMcpInflightKeys.has(m),b=this.webMcpResolvedKeys.has(m),C=s.toolCall?.name,S=s.agentMetadata?.executionId===g&&s.toolCall?.id===u&&C!==void 0&&xv(C)&&s.toolCall?.status==="complete";(y||b||S)&&(l.agentMetadata={...l.agentMetadata??{},awaitingLocalTool:!1},l.toolCall=s.toolCall,l.streaming=s.streaming)}return l}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((n,o)=>{let s=new Date(n.createdAt).getTime(),i=new Date(o.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(i)&&s!==i)return s-i;let l=n.sequence??0,c=o.sequence??0;return l!==c?l-c:n.id.localeCompare(o.id)})}};import{File as KM,FileCode as GM,FileSpreadsheet as QM,FileText as hg,X as YM}from"lucide";var XM={add:t=>tv(t)},JM=t=>Number.isFinite(t)?Math.min(1,Math.max(0,t)):0,td={allowedTypes:sr,maxFileSize:10*1024*1024,maxFiles:4};function ZM(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function eT(t){return t==="application/pdf"?hg:t.startsWith("text/")?hg:t.includes("word")?hg:t.includes("excel")||t.includes("spreadsheet")?QM:t==="application/json"?GM:KM}var Va=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:e.allowedTypes??td.allowedTypes,maxFileSize:e.maxFileSize??td.maxFileSize,maxFiles:e.maxFiles??td.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}hasCustomAdapter(){return typeof this.config.adapter?.add=="function"}adapter(){return this.hasCustomAdapter()?this.config.adapter:XM}setPreviewsContainer(e){this.previewsContainer=e}remountPreviews(e){if(this.previewsContainer=e,e){e.innerHTML="";for(let n of this.attachments)this.renderPreview(n)}this.updatePreviewsVisibility()}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:td.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange),e.adapter!==void 0&&(this.config.adapter=e.adapter)}isReady(){return this.attachments.every(e=>e.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart).filter(e=>e!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){if(!e.length||this.destroyed)return;let n=[];for(let o of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let s=nv(o,this.config.allowedTypes,this.config.maxFileSize);if(!s.valid){let l=s.error?.includes("type")?"type":"size";this.config.onFileRejected?.(o,l);continue}let i={id:ZM(),file:o,previewUrl:Yc(o)?URL.createObjectURL(o):null,contentPart:null,status:this.hasCustomAdapter()?"uploading":"processing",progress:this.hasCustomAdapter()?0:void 0};this.attachments.push(i),this.renderPreview(i),n.push(i)}this.updatePreviewsVisibility(),this.notify(),await Promise.all(n.map(o=>this.runAdd(o)))}async runAdd(e){let n=new AbortController;this.pendingAdds.set(e.id,n);let o=()=>this.destroyed||n.signal.aborted||this.pendingAdds.get(e.id)!==n||!this.attachments.includes(e);try{let s=await this.adapter().add(e.file,{signal:n.signal,onProgress:i=>{o()||e.status!=="uploading"||(e.progress=JM(i),this.updatePreview(e),this.notify())}});if(o())return;e.contentPart=s,e.status="ready",e.progress=void 0,e.error=void 0}catch(s){if(o())return;e.status="error",e.progress=void 0,e.error=s instanceof Error?s.message:String(s??"Upload failed")}finally{this.pendingAdds.get(e.id)===n&&this.pendingAdds.delete(e.id)}this.updatePreview(e),this.notify()}retryAttachment(e){let n=this.attachments.find(o=>o.id===e);!n||n.status!=="error"||this.destroyed||(n.status=this.hasCustomAdapter()?"uploading":"processing",n.progress=this.hasCustomAdapter()?0:void 0,n.error=void 0,this.updatePreview(n),this.notify(),this.runAdd(n))}abortAdd(e){let n=this.pendingAdds.get(e);n&&(this.pendingAdds.delete(e),n.abort())}removeAttachment(e){let n=this.attachments.findIndex(i=>i.id===e);if(n===-1)return;let o=this.attachments[n];this.abortAdd(e),o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let s=this.previewsContainer?.querySelector(`[data-attachment-id="${e}"]`);s&&s.remove(),o.status==="ready"&&o.contentPart&&this.releasePart(o.contentPart),this.updatePreviewsVisibility(),this.notify()}releasePart(e){let n=this.config.adapter?.remove;if(n)try{let o=n(e,{signal:new AbortController().signal});o&&typeof o.catch=="function"&&o.catch(s=>{console.error("[AttachmentManager] adapter.remove failed:",s)})}catch(o){console.error("[AttachmentManager] adapter.remove failed:",o)}}clearAttachments(){for(let e of this.attachments)this.abortAdd(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.pendingAdds.clear(),this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.notify()}destroy(){if(!this.destroyed){this.destroyed=!0;for(let e of this.pendingAdds.values())e.abort();this.pendingAdds.clear();for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.previewsContainer=null}}notify(){this.destroyed||this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let n=Yc(e.file),o=P("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",e.id),o.style.width="48px",o.style.height="48px",n&&e.previewUrl){let u=P("img");u.src=e.previewUrl,u.alt=e.file.name,u.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",u.style.width="48px",u.style.height="48px",u.style.objectFit="cover",u.style.borderRadius="8px",o.appendChild(u)}else{let u=P("div");u.style.width="48px",u.style.height="48px",u.style.borderRadius="8px",u.style.backgroundColor="var(--persona-container, #f3f4f6)",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.display="flex",u.style.flexDirection="column",u.style.alignItems="center",u.style.justifyContent="center",u.style.gap="2px",u.style.overflow="hidden";let m=eT(e.file.type),y=$t(m,20,"var(--persona-muted, #6b7280)",1.5);y&&u.appendChild(y);let b=P("span");b.textContent=ov(e.file.type,e.file.name),b.style.fontSize="8px",b.style.fontWeight="600",b.style.color="var(--persona-muted, #6b7280)",b.style.textTransform="uppercase",b.style.lineHeight="1",u.appendChild(b),o.appendChild(u)}let s=G("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),i=P("div","persona-attachment-progress");i.appendChild(P("div","persona-attachment-progress__bar"));let l=G("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),c=de("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);c?l.appendChild(c):l.textContent="\u21BB",l.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),this.retryAttachment(e.id)}),s.append(i,l),o.appendChild(s);let d=P("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");d.type="button",d.setAttribute("aria-label","Remove attachment"),d.style.position="absolute",d.style.top="-4px",d.style.insetInlineEnd="-4px",d.style.width="18px",d.style.height="18px",d.style.borderRadius="50%",d.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",d.style.border="none",d.style.cursor="pointer",d.style.display="flex",d.style.alignItems="center",d.style.justifyContent="center",d.style.padding="0";let g=$t(YM,10,"var(--persona-text-inverse, #ffffff)",2);g?d.appendChild(g):(d.textContent="\xD7",d.style.color="var(--persona-text-inverse, #ffffff)",d.style.fontSize="14px",d.style.lineHeight="1"),d.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(d),this.previewsContainer.appendChild(o),this.applyPreviewState(o,e)}updatePreview(e){let n=this.previewsContainer?.querySelector(`[data-attachment-id="${e.id}"]`);n&&this.applyPreviewState(n,e)}applyPreviewState(e,n){e.dataset.status=n.status;let o=n.status!=="ready"&&n.status!=="error";e.setAttribute("aria-busy",o?"true":"false"),e.title=n.status==="error"?`${n.file.name}: ${n.error??"Upload failed"}`:n.file.name;let s=e.querySelector(".persona-attachment-progress__bar");if(s){let i=n.progress;s.style.width=typeof i=="number"?`${Math.round(i*100)}%`:""}}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,n){return new t({allowedTypes:e?.allowedTypes,maxFileSize:e?.maxFileSize,maxFiles:e?.maxFiles,onFileRejected:e?.onFileRejected,onAttachmentsChange:n,adapter:e?.adapter})}};var Sv=(t,e)=>t.length===e.length&&t.every((n,o)=>n===e[o]),tT=(t,e)=>t.length===e.length&&t.every((n,o)=>{let s=e[o];return n.id===s.id&&n.name===s.name&&n.mimeType===s.mimeType&&n.size===s.size&&n.status===s.status&&n.progress===s.progress&&n.error===s.error});function Av(){let t={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},e=new Set,n=null,o=!1,s=!1,i=()=>t.preparing?"preparing":t.streaming?"streaming":"idle",l=()=>{let u=i();return Object.freeze({text:t.text,attachments:Object.freeze(t.attachments.map(m=>Object.freeze({...m}))),mentionRefs:Object.freeze([...t.mentionRefs]),selectedModelId:t.selectedModelId,activeModeIds:Object.freeze([...t.activeModeIds]),quote:t.quote?Object.freeze({...t.quote}):void 0,pendingSubmission:t.pendingSubmission,phase:u,inputDisabled:t.inputDisabled,sendDisabled:u!=="idle"||t.sendDisabled||t.inputDisabled})},c=()=>(n||(n=l()),n),d=()=>{if(o=!1,s||e.size===0)return;let u=c();for(let m of[...e])try{m(u)}catch(y){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",y)}},g=()=>{n=null,!(s||o)&&(o=!0,queueMicrotask(d))};return{getState:c,subscribe:u=>(e.add(u),()=>e.delete(u)),setText:u=>{t.text!==u&&(t.text=u,g())},setAttachments:u=>{tT(t.attachments,u)||(t.attachments=[...u],g())},setMentionRefs:u=>{Sv(t.mentionRefs,u)||(t.mentionRefs=[...u],g())},setSelectedModelId:u=>{t.selectedModelId!==u&&(t.selectedModelId=u,g())},setActiveModeIds:u=>{Sv(t.activeModeIds,u)||(t.activeModeIds=[...u],g())},setQuote:u=>{let m=t.quote;m?.text===u?.text&&m?.messageId===u?.messageId&&m?.sourceLabel===u?.sourceLabel||(t.quote=u?{...u}:void 0,g())},setPendingSubmission:u=>{t.pendingSubmission!==u&&(t.pendingSubmission=u,g())},setPreparing:u=>{t.preparing!==u&&(t.preparing=u,g())},setStreaming:u=>{t.streaming!==u&&(t.streaming=u,g())},setInputDisabled:u=>{t.inputDisabled!==u&&(t.inputDisabled=u,g())},setSendDisabled:u=>{t.sendDisabled!==u&&(t.sendDisabled=u,g())},flush:()=>{o&&d()},destroy:()=>{s=!0,o=!1,e.clear()}}}var Pn=(t,...e)=>{for(let n of e){let o=t.querySelector(n);if(o)return o}return null},Mv=(t,e)=>{let n=P("div",t);return n.setAttribute(e,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function Tv(t,e={}){let n=Pn(t,"[data-persona-composer-form]"),o=Pn(t,"[data-persona-composer-input]");if(!n||!o){let H=`[Persona] composer surface is missing required element(s): ${[!n&&"form",!o&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(e.debug&&(n||o))throw new Error(H);return typeof console<"u"&&console.warn(H),null}let s={header:Pn(t,"[data-persona-composer-header]"),body:Pn(t,"[data-persona-composer-body]"),actionsStart:Pn(t,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Pn(t,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Pn(t,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Pn(t,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Pn(t,"[data-persona-composer-status]")},i=new Set,l=s.header;l||(i.add("header"),l=Mv("persona-widget-composer__header","data-persona-composer-header"),n.parentNode?n.parentNode.insertBefore(l,n):t.appendChild(l));let c=s.body??o.parentElement??n,d=(E,H,I,N,x)=>{if(H)return H;i.add(E);let D=Mv(I,N);return x.appendChild(D),D},g=d("actionsStart",s.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),u=d("actionsEnd",s.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),m=d("suggestions",s.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",t),y=d("status",s.status,"persona-widget-composer__status","data-persona-composer-status",t),b=[],C=(E,H)=>E.target===H.target&&E.type===H.type&&E.handler===H.handler,S=Pn(t,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:t,form:n,input:o,header:l,body:c,actionsStart:g,actionsEnd:u,suggestions:m,status:y,attachmentInput:S,attachmentPreviews:Pn(t,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Pn(t,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Pn(t,"[data-persona-composer-submit]")??void 0,micButton:Pn(t,"[data-persona-composer-mic]")??void 0,synthesized:i,found:s,addListener:(E,H,I,N)=>{E.addEventListener(H,I,N),b.push({target:E,type:H,handler:I,options:N})},removeListener:(E,H,I,N)=>{E.removeEventListener(H,I,N),b=b.filter(x=>!C(x,{target:E,type:H,handler:I}))},destroy:()=>{for(let E of b)E.target.removeEventListener(E.type,E.handler,E.options);b=[]}}}var nT=8,oT=8,yg=10,Ev=200,Pv=300,kv=0,od=t=>Math.max(0,t);function Lv(t){t.delayMs!==void 0&&(Ev=od(t.delayMs)),t.skipDelayMs!==void 0&&(Pv=od(t.skipDelayMs))}var rT=()=>Date.now()<kv,sT=t=>{kv=t>0?Date.now()+t:0},nd=new WeakMap,vg="data-persona-tooltip-suppressed",iT=t=>typeof t.closest=="function"&&t.closest(`[${vg}]`)!==null;function Iv(t){nd.get(t)?.hide()}var Hv=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t,aT=t=>{let e=t.getRootNode?.();return Hv(e)?e:t.ownerDocument.body},bg=(t,e,n)=>Math.min(Math.max(t,e),Math.max(e,n)),lT=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(t=>`--persona-tooltip-${t}`),"--persona-font-family","--persona-radius-sm"];function tn(t){nd.get(t.anchor)?.destroy();let{anchor:e,trigger:n=e,text:o,hint:s,enabled:i=!0,gap:l=nT,viewportPadding:c=oT}=t,d=()=>e.ownerDocument,g=()=>d().defaultView??window,u=null,m=null,y=null,b=null,C,S=!1,E=!1,H=!1,I=()=>(typeof o=="function"?o():o).trim(),N=()=>(typeof s=="function"?s():s??"").trim(),x=()=>od(t.delayMs??Ev),D=()=>od(t.skipDelayMs??Pv),L=()=>{C!==void 0&&(g().clearTimeout(C),C=void 0)},$=()=>{L();let pe=u!==null;b?.(),b=null,u?.remove(),u=null,m=null,y=null,pe&&sT(D())},K=()=>{if(!u)return;let pe=d(),ve=g(),Ce=e.getBoundingClientRect(),me=u.getBoundingClientRect(),vt=pe.documentElement.clientWidth||ve.innerWidth,st=pe.documentElement.clientHeight||ve.innerHeight,he=vt-c-me.width,W=Ce.left+Ce.width/2-me.width/2,We=bg(W,c,he),Fe=Ce.top-c,bn=st-c-Ce.bottom,sn=me.height+l,Kt=Fe>=sn||Fe>=bn?"top":"bottom",kn=Kt==="top"?Ce.top-l-me.height:Ce.bottom+l,Be=st-c-me.height,Ge=bg(kn,c,Be),Pe=Ce.left+Ce.width/2,Bo=Math.max(yg,me.width-yg),V=bg(Pe-We,yg,Bo);u.dataset.placement=Kt,u.style.left=`${We}px`,u.style.top=`${Ge}px`,u.style.setProperty("--persona-tooltip-arrow-x",`${V}px`)},se=()=>{if(H||!i||u||!e.isConnected||iT(e))return;let pe=I(),ve=aT(e);if(!pe||!ve)return;let Ce=d(),me=g();u=Ce.createElement("div"),u.className="persona-control-tooltip",u.setAttribute("role","tooltip"),u.dataset.state="measuring",u.style.zIndex=String(Pc);let vt=me.getComputedStyle?.(e);if(vt){for(let sn of lT){let Kt=vt.getPropertyValue(sn).trim();Kt&&u.style.setProperty(sn,Kt)}vt.fontFamily&&(u.style.fontFamily=vt.fontFamily)}m=Ce.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=pe,u.appendChild(m);let st=N();st&&(y=Ce.createElement("span"),y.className="persona-control-tooltip__hint",y.textContent=st,u.appendChild(y));let he=Ce.createElement("span");he.className="persona-control-tooltip__arrow",u.appendChild(he),ve.appendChild(u),K(),u.dataset.state="open";let W=()=>{if(!e.isConnected){$();return}m&&(m.textContent=I()),y&&(y.textContent=N()),K()};me.addEventListener("scroll",W,!0),me.addEventListener("resize",W);let We=e.getRootNode(),Fe=Hv(We)?We:Ce.documentElement,bn=typeof MutationObserver>"u"?null:new MutationObserver(()=>{e.isConnected||$()});bn?.observe(Fe,{childList:!0,subtree:!0}),b=()=>{me.removeEventListener("scroll",W,!0),me.removeEventListener("resize",W),bn?.disconnect()}},ne=pe=>{if(!(H||u)){if(L(),pe||x()<=0||rT()){se();return}C=g().setTimeout(()=>{C=void 0,se()},x())}},M=()=>{S||E?ne(E):$()},T=()=>{let pe=g();(!pe.matchMedia||!pe.matchMedia("(hover: none)").matches)&&(S=!0,M())},_=()=>{S=!1,M()},k=()=>{try{E=e.matches(":focus-visible")}catch{E=!0}M()},Z=()=>{E=!1,M()},F=()=>{S=!1,E=!1,$()},ie=pe=>{pe.key==="Escape"&&F()};n.addEventListener("mouseenter",T),n.addEventListener("mouseleave",_),e.addEventListener("focus",k),e.addEventListener("blur",Z),e.addEventListener("keydown",ie),e.addEventListener("click",F);let le={get isOpen(){return u!==null},show:se,hide:$,reposition:K,destroy:()=>{H||(H=!0,$(),n.removeEventListener("mouseenter",T),n.removeEventListener("mouseleave",_),e.removeEventListener("focus",k),e.removeEventListener("blur",Z),e.removeEventListener("keydown",ie),e.removeEventListener("click",F),nd.delete(e))}};return nd.set(e,le),le}function Cg(t){let e=t.ownerDocument?.defaultView;if(!e?.getComputedStyle)return 20;let n=e.getComputedStyle(t).lineHeight;if(!n||!n.trim().endsWith("px"))return 20;let o=parseFloat(n);return Number.isFinite(o)&&o>0?o:20}function rd(t,e){return typeof t!="number"||!Number.isFinite(t)?e:t>0?t:e}function Rv(t,e){t.style.maxHeight=`${e*Cg(t)}px`,t.style.overflowY="auto"}function qa(t){let e=t?.ownerDocument?.defaultView??(typeof window<"u"?window:null);if(!e||typeof e.matchMedia!="function")return!1;try{return e.matchMedia("(pointer: coarse)").matches===!0}catch{return!1}}function Wv(t){return t.insertNewlineOnTouchEnter===!0&&t.coarsePointer===!0}function Bv(t,e){if(t.key!=="Enter"||t.shiftKey||t.isComposing)return!1;let n=t.metaKey===!0||t.ctrlKey===!0,o=e.submitKey??"enter";return o==="none"?!1:o==="mod-enter"?n:n||!Wv(e)}function cT(t){return(t.submitKey??"enter")!=="enter"||Wv(t)?"enter":"send"}function sd(t,e){t.setAttribute("enterkeyhint",cT(e))}function id(t,e){let n=e?.autocomplete;t.setAttribute("autocomplete",typeof n=="string"&&n?n:"off");let o=(s,i)=>{i===void 0?t.removeAttribute(s):t.setAttribute(s,i)};o("autocapitalize",typeof e?.autocapitalize=="string"?e.autocapitalize:void 0),o("spellcheck",typeof e?.spellcheck=="boolean"?String(e.spellcheck):void 0),o("inputmode",typeof e?.inputmode=="string"&&e.inputmode?e.inputmode:void 0),o("aria-label",typeof e?.ariaLabel=="string"&&e.ariaLabel?e.ariaLabel:void 0)}function wg(t){return t===!0?{disabled:!0}:!t||typeof t!="object"?{disabled:!1}:{disabled:!0,reason:typeof t.reason=="string"&&t.reason?t.reason:void 0}}var Fn="persona-composer-control",mo="persona-composer-control--glyph",Sg=40,fn=24,ad=(t,e,n)=>{let o=t.ownerDocument?.defaultView;if(!o)return;let s=o.getComputedStyle(t);for(let i of n){let l=s.getPropertyValue(i).trim();l?e.style.setProperty(i,l):e.style.removeProperty(i)}},ld=(t,e)=>{let n=P("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=t?.copy?.inputPlaceholder??ju,n.dir="auto",sd(n,{submitKey:t?.composer?.submitKey,insertNewlineOnTouchEnter:t?.composer?.insertNewlineOnTouchEnter,coarsePointer:qa(n)}),id(n,t?.composer?.inputAttributes),n.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea",n.rows=1,n.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',n.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let o=rd(t?.composer?.maxLines,e?.defaultMaxLines??3),s=`${o*20}px`;n.style.maxHeight=s,n.style.overflowY="auto";let i=()=>{let c=n.style.maxHeight;if(c!==s){let g=parseFloat(c);if(Number.isFinite(g)&&g>0)return g}let d=o*Cg(n);return s=`${d}px`,n.style.maxHeight=s,d},l=()=>{n.addEventListener("input",()=>{n.style.height="auto";let c=Math.min(n.scrollHeight,i());n.style.height=`${c}px`})};return n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.addEventListener("focus",()=>{n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.style.boxShadow="none"}),n.addEventListener("blur",()=>{n.style.border="none",n.style.outline="none"}),{textarea:n,attachAutoResize:l}},pT="[data-persona-glyph-stack]",Ag=(t,e,n="send")=>{let o=G("span",{className:"persona-composer-glyph-stack",attrs:{"data-mode":n,"data-persona-glyph-stack":""}});return t.setAttribute("data-glyph","send"),e.setAttribute("data-glyph","stop"),o.append(t,e),o},cd=t=>{let e=t?.sendButton??{},n=e.useIcon??!1,o=e.iconText??"\u2191",s=e.iconName,i=e.stopIconName??"square",l=e.tooltipText??"Send message",c=e.stopTooltipText??"Stop generating",d=t?.copy?.sendButtonLabel??"Send",g=t?.copy?.stopButtonLabel??"Stop",u=e.showTooltip??!1,m=e.size,y=parseFloat(m??"")||Sg,b=e.backgroundColor,C=e.textColor,S=P("div","persona-send-button-wrapper"),E=G("button",{className:Nn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${Fn}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!b&&"persona-bg-persona-primary",!n&&!C&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?m:void 0,height:n?m:void 0,minWidth:n?m:void 0,minHeight:n?m:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?C||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":C||void 0,backgroundColor:n&&b||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:n?"0":e.paddingX||void 0,paddingRight:n?"0":e.paddingX||void 0,paddingTop:n?"0":e.paddingY||void 0,paddingBottom:n?"0":e.paddingY||void 0}}),H=null,I=null,N=null;if(n){let L=parseFloat(e.iconSize??"")||Math.round(y*.5),$=e.iconStrokeWidth??2,K=C?.trim()||"currentColor";if(s&&(H=de(s,L,K,$)),I=de(i,L,K,$),!e.iconSize)for(let se of[H,I])se&&(se.style.width=`var(--persona-components-composer-sendIconSize, ${L}px)`,se.style.height=`var(--persona-components-composer-sendIconSize, ${L}px)`);H&&I?(N=Ag(H,I),E.appendChild(N)):H?E.appendChild(H):(E.textContent=o,I=null)}else E.textContent=d;E.setAttribute("aria-label",l),S.appendChild(E),tn({anchor:E,trigger:S,text:()=>E.getAttribute("aria-label")??"",enabled:u});let x="send";return{button:E,wrapper:S,setMode:L=>{if(L===x)return;x=L;let $=L==="stop"?c:l;E.setAttribute("aria-label",$),E.setAttribute("data-persona-send-mode",L),n?(E.querySelector(pT)??N)?.setAttribute("data-mode",L):E.textContent=L==="stop"?g:d},glyphStack:N}},Pi=t=>{let e=t?.voiceRecognition??{};if(!(e.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),s=e.provider?.type==="runtype",i=e.provider?.type==="custom";if(!(o||s||i))return null;let c=e.iconName??"mic",d=e.iconSize,g=parseFloat(d??"")||fn,u=e.backgroundColor??t?.sendButton?.backgroundColor,m=e.iconColor??t?.sendButton?.textColor,y=P("div","persona-send-button-wrapper"),b=G("button",{className:Nn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Fn,!d&&mo),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":e.tooltipText??"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:m||"var(--persona-text, #111827)",backgroundColor:u||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),S=de(c,g,m||"currentColor",1.5);S?b.appendChild(S):b.textContent="\u{1F3A4}",y.appendChild(b);let E=e.tooltipText??"Start voice recognition",H=e.showTooltip??!1;return tn({anchor:b,trigger:y,text:()=>b.getAttribute("aria-label")??E,enabled:H}),{button:b,wrapper:y}},dd=t=>{let e=t?.attachments??{};if(e.enabled!==!0)return null;let n=P("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");n.setAttribute("data-persona-composer-attachment-previews",""),n.style.display="none";let o=P("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(e.allowedTypes??sr).join(","),o.multiple=(e.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=e.buttonIconName??"paperclip",i=P("div","persona-send-button-wrapper"),l=G("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Fn} ${mo}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":e.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),c=de(s,fn,"currentColor",1.5);c?l.appendChild(c):l.textContent="\u{1F4CE}",l.addEventListener("click",g=>{g.preventDefault(),o.click()}),i.appendChild(l);let d=e.buttonTooltipText??"Attach file";return tn({anchor:l,trigger:i,text:()=>l.getAttribute("aria-label")??d}),{button:l,wrapper:i,input:o,previewsContainer:n}},pd=t=>{let e=t?.statusIndicator??{},n=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",o=P("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status",""),Ps(o,e,"idle");let s=e.idleText??"Online";if(e.idleLink){let i=P("a");i.href=e.idleLink,i.target="_blank",i.rel="noopener noreferrer",i.textContent=s,i.style.color="inherit",i.style.textDecoration="none",o.appendChild(i)}else o.textContent=s;return o},ud=()=>G("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var uT='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',gT=["--persona-components-composer-overflowMenu-background","--persona-components-composer-overflowMenu-borderColor","--persona-components-composer-overflowMenu-borderRadius","--persona-components-composer-overflowMenu-foreground","--persona-components-composer-overflowMenu-shadow"],Mg="data-persona-menu-focus",fT=new Set(["ArrowDown","ArrowUp","Home","End"]);function Dv(t){return t.getAttribute("role")==="menuitem"?t:t.querySelector(uT)??t}var mT=t=>t.disabled===!0||t.getAttribute("aria-disabled")==="true";function _v(t){let e=t.label,n=!1,o=P("div","persona-send-button-wrapper"),s=G("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Fn} ${mo}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(s);let i=G("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),l=()=>{let k=t.getButtonSize?.()??"";s.style.width=k,s.style.height=k,s.style.minWidth=k,s.style.minHeight=k,s.style.lineHeight="1",s.replaceChildren();let Z=de("plus",fn,"currentColor",1.5);Z?s.appendChild(Z):s.textContent="+"},c=()=>{s.setAttribute("aria-label",e),s.setAttribute("title",e),i.setAttribute("aria-label",e)};c(),l();let d=[],g=-1,u=!1,m=()=>{let Z=i.getRootNode().activeElement;return Z instanceof HTMLElement?Z:null},y=()=>{let k=m();for(let Z of d){let F=!!k&&Dv(Z)===k;Z.toggleAttribute(Mg,F&&u)}},b=()=>d.filter(k=>k.isConnected||i.contains(k)).map(Dv).filter(k=>!mT(k)),C=(k,Z)=>{k.forEach((F,ie)=>{F.setAttribute("tabindex",ie===Z?"0":"-1")})},S=k=>{let Z=b();if(Z.length===0)return;let F=(k%Z.length+Z.length)%Z.length;g=F,C(Z,F),Z[F].focus(),y()},E=()=>o.ownerDocument??document,H=null,I=null,N=null,x=()=>{H&&(E().removeEventListener("focusin",H,!0),H=null)},D=()=>{I&&(i.removeEventListener("focusin",I),I=null),N&&(i.removeEventListener("pointerdown",N,!0),N=null)},L=null,$=()=>(L||(L=kc({anchor:s,content:i,placement:"top-start",offset:6,onDismiss:()=>{s.setAttribute("aria-expanded","false"),x()}})),L),K=()=>L?.isOpen===!0,se=(k=!1)=>{if(K()){L?.close(),s.setAttribute("aria-expanded","false"),x(),D(),g=-1,u=!1;for(let Z of d)Z.removeAttribute(Mg);k&&s.focus()}},ne=(k=0,Z=!1)=>{if(n||K())return;u=Z,ad(s,i,gT),$().open(),s.setAttribute("aria-expanded","true");let F=b();C(F,-1),S(k<0?F.length-1:k),H=ie=>{let le=typeof ie.composedPath=="function"?ie.composedPath():[];le.includes(i)||le.includes(o)||se()},E().addEventListener("focusin",H,!0),I=()=>y(),i.addEventListener("focusin",I),N=()=>{u=!1},i.addEventListener("pointerdown",N,!0)},M=k=>{k.preventDefault(),k.stopPropagation(),K()?se(!0):ne(0)},T=k=>{if(k.key==="ArrowDown"||k.key==="Enter"||k.key===" "){k.preventDefault(),u=!0,K()?S(0):ne(0,!0);return}k.key==="ArrowUp"&&(k.preventDefault(),u=!0,K()?S(-1):ne(-1,!0))},_=k=>{switch(fT.has(k.key)&&(u=!0),k.key){case"ArrowDown":k.preventDefault(),S(g+1);return;case"ArrowUp":k.preventDefault(),S(g-1);return;case"Home":k.preventDefault(),S(0);return;case"End":k.preventDefault(),S(b().length-1);return;case"Escape":k.preventDefault(),k.stopPropagation(),se(!0);return;case"Tab":se(!0);return;default:}};return s.addEventListener("click",M),s.addEventListener("keydown",T),i.addEventListener("keydown",_),{trigger:o,triggerButton:s,panel:i,setItems:k=>{for(let F of d)k.includes(F)||F.removeAttribute(Mg);if(d=[...k],!K())return;let Z=b();C(Z,Math.min(g,Z.length-1)),y()},isOpen:K,open:()=>ne(0),close:se,setLabel:k=>{k!==e&&(e=k,c())},applyButtonSize:l,destroy:()=>{n=!0,x(),D(),s.removeEventListener("click",M),s.removeEventListener("keydown",T),i.removeEventListener("keydown",_),L?.destroy(),L=null,o.remove(),i.remove(),d=[]}}}var Ro={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},Ov="data-persona-composer-action",Tg="data-persona-composer-disable-when-streaming",hT="core:overflow",yT=t=>t==="core:attachment"?"attachments":t.startsWith("core:mention")?"mentions":null;function bT(t,e){if(t===void 0)return null;if(typeof t=="number")return Number.isFinite(t)?t:null;let n=Number.parseFloat(t);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(t)&&Number.isFinite(n))return n;let o=P("div");o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.height="0",o.style.width=t,e.appendChild(o);let s=o.getBoundingClientRect().width;return o.remove(),Number.isFinite(s)&&s>0?s:Number.isFinite(n)?n:null}function Eg(t){let e=t.clientWidth;if(!e)return 0;let n=t.ownerDocument?.defaultView;if(!n?.getComputedStyle)return e;let o=n.getComputedStyle(t),s=(Number.parseFloat(o.paddingLeft)||0)+(Number.parseFloat(o.paddingRight)||0);return Math.max(0,e-s)}var Nv=(t,e)=>{!t||typeof console>"u"||console.warn(e)},vT=(t,e)=>e.includes(":")?e:`${t}:${e}`;function CT(t){let{debug:e}=t,n=[],o=new Map,s=0,i=c=>{let d=o.get(c.id);if(d){Nv(e,`[Persona] composer action "${c.id}" is already contributed by ${Fv(d)}; the ${Fv(c)} copy is ignored.`);return}o.set(c.id,c),n.push(c)};for(let c of t.builtIns)i({id:c.id,placement:c.placement,presentation:"bar",order:c.order,sequence:s++,source:"core",builtIn:c});let l=(c,d,g)=>{let u=g?vT(g,c.id):c.id,m=c.order??Ro.custom;c.placement==="end"&&m>=Ro.send&&(Nv(e,`[Persona] composer action "${u}" ordered at ${m} would render after send; clamped to ${Ro.send-1}.`),m=Ro.send-1),i({id:u,placement:c.placement,presentation:c.presentation??"bar",order:m,sequence:s++,source:d,pluginId:g,action:c})};for(let c of t.configActions??[])l(c,"config");for(let c of t.plugins){if(!c.contributeComposerActions)continue;let d;try{d=c.contributeComposerActions(t.contributionContext)}catch(g){typeof console<"u"&&console.error(`[Persona] plugin "${c.id}" contributeComposerActions failed:`,g);continue}for(let g of d??[])l(g,"plugin",c.id)}return n.sort((c,d)=>c.order===d.order?c.sequence-d.sequence:c.order-d.order)}var Fv=t=>t.source==="plugin"?`plugin "${t.pluginId}"`:t.source==="config"?"composer.actions":"a core built-in",Uv=(t,e,n)=>t===void 0?n:typeof t=="function"?t(e)===!0:t===!0,wT=t=>t.phase==="streaming"||t.text.trim().length>0||t.attachments.length>0;function xT(t,e){if(!t||t==="always")return!0;let n=wT(e);return t==="when-text"?n:!n}var Fr=t=>t.kind==="custom",Pg=t=>t instanceof HTMLButtonElement?t:t.querySelector("button")??t,ST=t=>{let e=Pg(t);return e.getAttribute("aria-label")?.trim()||e.getAttribute("title")?.trim()||""},AT='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function MT(t){let e="",n=o=>{if(o.nodeType===Node.TEXT_NODE){e+=o.nodeValue??"";return}if(o.nodeType!==Node.ELEMENT_NODE)return;let s=o;typeof s.matches=="function"&&s.matches(AT)||o.childNodes.forEach(n)};return n(t),e.trim()}var TT=t=>MT(t).length===0;function $v(t){let e=new Map,n=[],o=!1,s=()=>t.getButtonSize?.(),i=(M,T)=>{let _=M.button;if(!_)return;_.setAttribute("role","menuitem"),_.setAttribute("tabindex","-1"),_.className="persona-composer-overflow-menu__item";for(let F of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])_.style[F]="";_.style.lineHeight="1",T.tooltipText?_.setAttribute("title",T.tooltipText):_.removeAttribute("title"),_.replaceChildren();let k=P("span","persona-composer-overflow-menu__icon");if(T.iconName){let F=de(T.iconName,16,"currentColor",1.5);F&&k.appendChild(F)}let Z=P("span","persona-composer-overflow-menu__label");Z.textContent=T.shortLabel??T.label,_.append(k,Z)},l=(M,T)=>{let _=M.button;if(!_)return;if(_.setAttribute("aria-label",T.label),T.pressed===void 0?_.removeAttribute("aria-pressed"):_.setAttribute("aria-pressed",T.pressed?"true":"false"),_.toggleAttribute(Tg,T.disableWhenStreaming===!0),M.mode==="menu"){M.tooltip?.destroy(),M.tooltip=void 0,i(M,T);return}_.removeAttribute("role"),_.removeAttribute("tabindex"),_.removeAttribute("title");let k=s(),Z=!!T.shortLabel;if(_.className=Nn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Fn,mo,Z&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),_.style.width=k&&!Z?k:"",_.style.height=k??"",_.style.minWidth=k&&!Z?k:"",_.style.minHeight=k??"",_.style.fontSize=Z?"":"18px",_.style.lineHeight="1",_.style.color=T.iconColor??"",_.style.backgroundColor=T.backgroundColor??"",_.replaceChildren(),T.iconName){let F=de(T.iconName,fn,"currentColor",1.5);F&&_.appendChild(F)}if(Z){let F=P("span","persona-composer-action-button__label");F.textContent=T.shortLabel,_.appendChild(F)}else _.firstChild||(_.textContent=T.label);M.tooltip?.destroy(),M.tooltip=tn({anchor:_,trigger:M.element,text:()=>T.tooltipText??T.label,enabled:!!T.tooltipText})},c=(M,T)=>{let _=M.action,k=G("button",{attrs:{type:"button"}}),Z=k;if(T==="bar"){let le=P("div","persona-send-button-wrapper");le.appendChild(k),Z=le}Z.setAttribute(Ov,M.id);let F={resolved:M,element:Z,button:k,owned:!0,managed:!0,busy:!1,visible:!0,mode:T},ie=le=>{if(le.preventDefault(),le.stopPropagation(),F.busy||k.disabled)return;let pe=F.resolved.action;F.mode==="menu"&&b?.close(!0);let ve;try{ve=pe.onSelect(t.actionContext,le)}catch(Ce){t.reportError(Ce,{actionId:F.resolved.id});return}!ve||typeof ve.then!="function"||(F.busy=!0,k.setAttribute("aria-busy","true"),ve.catch(Ce=>{t.reportError(Ce,{actionId:F.resolved.id})}).finally(()=>{F.busy=!1,k.removeAttribute("aria-busy")}))};return k.addEventListener("click",ie),F.detach=()=>k.removeEventListener("click",ie),l(F,_),F},d=M=>{let T=M.action,_;try{_=T.render({...t.actionContext,id:M.id,action:T})}catch(k){return t.reportError(k,{actionId:M.id}),null}return _?.element?(_.element.setAttribute(Ov,M.id),_.element.toggleAttribute(Tg,T.disableWhenStreaming===!0),{resolved:M,element:_.element,owned:!0,managed:!0,destroy:_.destroy,busy:!1,visible:!0,mode:"bar"}):null},g=(M,T)=>{if(M.builtIn){let k=M.builtIn.element;return k?{resolved:M,element:k,owned:!1,managed:M.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let _=M.action;return _?Fr(_)?d(M):c(M,T):null},u=M=>{if(M.detach?.(),M.tooltip?.destroy(),M.detachMenuSlot?.(),M.detachMenuSlot=void 0,M.menuLabel?.remove(),M.menuLabel=void 0,M.menuSlot?.remove(),M.menuSlot=void 0,M.owned){try{M.destroy?.()}catch(T){t.reportError(T,{actionId:M.resolved.id})}M.element.remove()}},m=(M,T)=>{for(let _=0;_<T.length;_++){let k=T[_];if(!k.managed)continue;let Z=null;for(let F=_+1;F<T.length;F++){let ie=T[F];if(!ie.managed&&ie.element.parentElement===M){Z=ie.element;break}}Z?(k.element.parentElement!==M||k.element.nextSibling!==Z)&&M.insertBefore(k.element,Z):M.lastChild!==k.element&&M.appendChild(k.element)}},y=(M,T)=>{if(M.button){M.button.disabled=T;return}if(!M.owned)return;let _=M.element;_.toggleAttribute("data-disabled",T),_.setAttribute("aria-disabled",T?"true":"false");let k=_ instanceof HTMLButtonElement||_ instanceof HTMLSelectElement||_ instanceof HTMLInputElement||_ instanceof HTMLTextAreaElement?_:_.querySelector("button, select, input, textarea");k&&(k.disabled=T)},b=null,C=null,S=null,E=0,H=()=>{let M=t.getOverflow?.();return M?.enabled===!0?M:void 0},I=()=>(b?b.setLabel(t.getOverflowLabel?.()??"More actions"):b=_v({label:t.getOverflowLabel?.()??"More actions",getButtonSize:s}),b),N=M=>{C!==M&&(S?.disconnect(),C=M,E=Eg(M),!(typeof ResizeObserver>"u")&&(S=new ResizeObserver(T=>{let k=T[T.length-1]?.contentRect?.width??Eg(M);k!==E&&(E=k,se())}),S.observe(M)))},x=(M,T)=>{let _=bT(M.collapseAutoActionsBelow,T);if(_===null)return!1;let k=E||Eg(T);return k>0&&k<_},D=(M,T,_)=>{if(!T)return"bar";if(M.resolved.builtIn){let Z=yT(M.resolved.id);return Z&&T.includeBuiltIns?.includes(Z)?"menu":"bar"}let k=M.resolved.presentation;return k==="overflow"||k==="auto"&&_?"menu":"bar"},L=M=>{let T=M.menuSlot;if(!T)return;if(!TT(M.element)){M.menuLabel?.remove(),M.menuLabel=void 0;return}let _=ST(M.element);if(!_){M.menuLabel?.remove(),M.menuLabel=void 0;return}M.menuLabel||(M.menuLabel=P("span","persona-composer-overflow-menu__label")),M.menuLabel.textContent!==_&&(M.menuLabel.textContent=_),M.menuLabel.parentElement!==T&&T.appendChild(M.menuLabel)},$=(M,T)=>{if(M.mode===T)return M;let _=M.resolved.action;if(_&&!Fr(_)){u(M),e.delete(M.resolved.id);let k=c(M.resolved,T);return e.set(M.resolved.id,k),k}if(T==="menu"){let k=G("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[vg]:""}});k.appendChild(M.element),Iv(Pg(M.element)),M.menuSlot=k;let Z=F=>{let ie=Pg(M.element);if(ie.disabled)return;let le=F.target===ie||ie.contains(F.target);b?.close(!0),le||ie.click()};k.addEventListener("click",Z,!0),M.detachMenuSlot=()=>k.removeEventListener("click",Z,!0),M.managed=!0,L(M)}else M.detachMenuSlot?.(),M.detachMenuSlot=void 0,M.menuLabel?.remove(),M.menuLabel=void 0,M.menuSlot?.remove(),M.menuSlot=void 0;return M.mode=T,M},K=(M,T)=>{let _=T.map(k=>k.menuSlot??k.element);for(_.forEach((k,Z)=>{let F=M.children[Z];F!==k&&(F?M.insertBefore(k,F):M.appendChild(k))});M.children.length>_.length;)M.lastElementChild?.remove()},se=()=>{if(o)return;let M=t.getBindings();if(!M)return;let T=t.getState(),_=T.phase==="streaming",k=H();k&&N(M.footer);let Z=k?x(k,M.footer):!1,F={start:[],end:[]},ie=[];for(let le of n){let pe=e.get(le.id);if(!pe)continue;let ve=le.action,Ce=ve?Uv(ve.visible,T,!0)&&xT(ve.visibility,T):!0;if(pe.visible!==Ce&&(pe.visible=Ce,!Ce&&pe.managed&&(pe.menuSlot??pe.element).remove()),!!Ce){if(pe=$(pe,D(pe,k,Z)),ve){let me=Uv(ve.disabled,T,!1)||ve.disableWhenStreaming===!0&&_;y(pe,me),!Fr(ve)&&ve.pressed!==void 0&&pe.button?.setAttribute("aria-pressed",ve.pressed?"true":"false")}pe.mode==="menu"?(L(pe),ie.push(pe)):F[le.placement].push(pe)}}if(ie.length>0){let le=I();K(le.panel,ie),le.setItems(ie.map(me=>me.menuSlot??me.element)),le.applyButtonSize();let pe=Number.isFinite(k?.order)?k?.order:Ro.overflow,ve=F.start.findIndex(me=>me.resolved.order>pe),Ce={resolved:{id:hT,placement:"start",presentation:"bar",order:pe,sequence:-1,source:"core"},element:le.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};F.start.splice(ve<0?F.start.length:ve,0,Ce)}else b&&(b.close(),b.trigger.remove(),b.setItems([]));m(M.actionsStart,F.start),m(M.actionsEnd,F.end)};return{resolve:()=>{if(o)return;let M=CT(t.collect()),T=new Set(M.map(_=>_.id));for(let[_,k]of e)T.has(_)||(u(k),e.delete(_));for(let _ of M){let k=e.get(_.id);if(!k){let le=g(_,"bar");le&&e.set(_.id,le);continue}let Z=k.resolved.action,F=_.action;if(!!Z!=!!F||Z&&F&&Fr(Z)!==Fr(F)||Z&&F&&Fr(Z)&&Fr(F)&&Z.render!==F.render){u(k),e.delete(_.id);let le=g(_,k.mode);le&&e.set(_.id,le);continue}k.resolved=_,_.builtIn?(k.managed=_.builtIn.managed===!0||k.mode==="menu",_.builtIn.element&&k.mode==="bar"&&(k.element=_.builtIn.element)):F&&!Fr(F)?l(k,F):F&&k.element.toggleAttribute(Tg,F.disableWhenStreaming===!0)}n=M,se()},sync:se,getResolved:()=>n,getOverflowMenu:()=>b,destroy:()=>{if(!o){o=!0,S?.disconnect(),S=null,C=null;for(let M of e.values())u(M);e.clear(),b?.destroy(),b=null,n=[]}}}}var ET="core:model",PT=700,Vv=16,kT=["--persona-components-composer-modelPicker-menuBackground","--persona-components-composer-modelPicker-menuBorderRadius","--persona-components-composer-modelPicker-rowHoverBackground","--persona-components-composer-modelPicker-labelColor","--persona-components-composer-modelPicker-descriptionColor"],qv=()=>{let t=G("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),e=G("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:t,chevron:e}};function zv(t){let e=t.label??"Model",n=t.presentation??"native",o=null,s=d=>{let g=t.getSelectedModelId();return d.find(u=>u.id===g)??d[0]},i=()=>{let d=G("select",{className:"persona-composer-model-picker",attrs:{"aria-label":e,"data-persona-composer-model-picker":""}}),g="",u=()=>{let S=t.getModels(),E=S.map(H=>`${H.id}:${H.label}`).join("|");E!==g&&(g=E,d.replaceChildren(...S.map(H=>{let I=G("option",{attrs:{value:H.id}});return I.textContent=H.label,I}))),d.value=s(S)?.id??""};u(),o=u;let m=()=>{d.value&&t.onSelect(d.value)};d.addEventListener("change",m);let y=S=>S.stopPropagation();d.addEventListener("click",y);let{wrapper:b,chevron:C}=qv();return b.append(d,C),{element:b,destroy:()=>{o===u&&(o=null),d.removeEventListener("change",m),d.removeEventListener("click",y)}}},l=()=>{let d=G("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),g=P("span","persona-composer-model-picker-label"),u=P("span","persona-composer-model-picker-suffix");d.append(g,u);let m=G("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":e,"data-persona-composer-model-menu":""}}),y=new Map,b="",C=null,S=()=>C?.isOpen===!0,E=(T=!1)=>{S()&&(C?.close(),d.setAttribute("aria-expanded","false"),T&&d.focus())},H=T=>{let _=[...y.values()];if(_.length===0)return;let k=(T%_.length+_.length)%_.length;_[k].focus()},I=T=>{if(S())return;C||(C=kc({anchor:d,content:m,placement:"top-start",offset:6,onDismiss:()=>d.setAttribute("aria-expanded","false")})),ad(d,m,kT),C.open(),d.setAttribute("aria-expanded","true");let k=[...y.keys()].indexOf(s(t.getModels())?.id??"");H(T??(k>=0?k:0))},N=T=>{E(!0),t.onSelect(T)},x=T=>{T.preventDefault(),T.stopPropagation();let _=T.currentTarget.getAttribute("data-persona-model-option");_&&N(_)},D=T=>{let _=G("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":T.id}});if(T.icon){let le=de(T.icon,Vv,"currentColor",1.5);if(le){let pe=P("span","persona-composer-model-option-icon");pe.appendChild(le),_.appendChild(pe)}}let k=P("span","persona-composer-model-option-body"),Z=P("span","persona-composer-model-option-label");if(Z.textContent=T.label,k.appendChild(Z),T.description){let le=P("span","persona-composer-model-option-description");le.textContent=T.description,k.appendChild(le)}_.appendChild(k);let F=P("span","persona-composer-model-option-check");F.setAttribute("aria-hidden","true");let ie=de("check",Vv,"currentColor",2);return ie&&F.appendChild(ie),_.appendChild(F),_.addEventListener("click",x),_},L=()=>{let T=t.getModels(),_=T.map(F=>`${F.id}:${F.label}:${F.icon??""}:${F.description??""}`).join("|");if(_!==b){b=_;for(let F of y.values())F.removeEventListener("click",x);y.clear(),m.replaceChildren(...T.map(F=>{let ie=D(F);return y.set(F.id,ie),ie}))}let k=s(T);for(let[F,ie]of y)ie.setAttribute("aria-selected",String(F===k?.id));g.textContent=k?.label??"";let Z=t.getSuffix?.()??"";u.textContent=Z,d.setAttribute("aria-label",[e,[k?.label,Z].filter(Boolean).join(" ")].filter(Boolean).join(": "))};L(),o=L;let $=T=>{T.preventDefault(),T.stopPropagation(),S()?E(!0):I()},K=T=>{if(T.key==="ArrowDown"){T.preventDefault(),S()?H(0):I(0);return}T.key==="ArrowUp"&&(T.preventDefault(),S()?H(-1):I(-1))},se=T=>{let _=[...y.values()],k=_.indexOf(T.target?.closest?.(".persona-composer-model-option"));switch(T.key){case"ArrowDown":T.preventDefault(),H(k+1);return;case"ArrowUp":T.preventDefault(),H(k-1);return;case"Home":T.preventDefault(),H(0);return;case"End":T.preventDefault(),H(_.length-1);return;case"Escape":T.preventDefault(),T.stopPropagation(),E(!0);return;case"Tab":E(!0);return;default:}};d.addEventListener("click",$),d.addEventListener("keydown",K),m.addEventListener("keydown",se);let{wrapper:ne,chevron:M}=qv();return ne.append(d,M),{element:ne,destroy:()=>{o===L&&(o=null),d.removeEventListener("click",$),d.removeEventListener("keydown",K),m.removeEventListener("keydown",se);for(let T of y.values())T.removeEventListener("click",x);y.clear(),C?.destroy(),C=null,m.remove()}}};return{action:{id:ET,kind:"custom",placement:"end",order:PT,presentation:n==="popover"?"bar":"auto",label:e,render:()=>n==="popover"?l():i()},repaint:()=>o?.()}}var LT=":scope > [data-persona-composer-mode]";function jv(t){let e=t.row,n="",o=!1,s=new Set(t.initialIds??[]),i=g=>{let u=G("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":g.id}});if(g.iconName){let C=P("span","persona-mention-chip-icon"),S=de(g.iconName,12,"currentColor",1.5);S&&C.appendChild(S),u.appendChild(C)}let m=P("span","persona-mention-chip-label");m.textContent=g.shortLabel??g.label,u.appendChild(m);let y=G("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${g.label}`}}),b=de("x",12,"currentColor",2);return b?y.appendChild(b):y.textContent="\xD7",y.addEventListener("click",C=>{C.preventDefault(),C.stopPropagation(),t.onRemove(g.id)}),u.appendChild(y),u},l=()=>Array.from(e.querySelectorAll(LT)),c=g=>{g.setAttribute("data-persona-chip-exit",""),g.setAttribute("aria-hidden","true"),g.style.pointerEvents="none";let u=()=>{g.remove(),Lc(e)},m=e.ownerDocument.defaultView,y=typeof m?.getComputedStyle=="function"?m.getComputedStyle(g).animationName:"";if(!y||y==="none"){u();return}g.addEventListener("animationend",u,{once:!0}),g.addEventListener("animationcancel",u,{once:!0})},d=()=>{for(let g of l())g.remove()};return{element:e,render:(g,u)=>{if(o)return;let m=u.filter(S=>g.includes(S.id)),y=m.map(S=>`${S.id}:${S.shortLabel??S.label}`).join("|");if(y===n)return;n=y;let b=new Map;for(let S of l()){let E=S.getAttribute("data-persona-composer-mode");E&&m.some(I=>I.id===E)&&!S.hasAttribute("data-persona-chip-exit")?b.set(E,S):S.hasAttribute("data-persona-chip-exit")||c(S)}let C=e.firstChild;for(let S of m){let E=b.get(S.id);E||(E=i(S),s.has(S.id)||(E.setAttribute("data-persona-chip-enter",""),E.addEventListener("animationend",()=>E?.removeAttribute("data-persona-chip-enter"),{once:!0}))),s.delete(S.id),E!==C&&e.insertBefore(E,C),C=E.nextSibling}Lc(e)},destroy:()=>{o=!0,d(),Lc(e)}}}var Kv=t=>`core:mode:${t}`;var kg=t=>Math.min(300+t,499),Gv=t=>`core:mode-group:${t}`;function gd(t,e){return t?e?.find(n=>n.id===t)?.presentation==="segmented":!1}function IT(t,e){return t?e?.find(n=>n.id===t)?.chipVisibility==="hidden":!1}function Qv(t,e){return t?.length?t.filter(n=>!gd(n.groupId,e)&&!IT(n.groupId,e)):[]}var HT=(t,e)=>t.groupId?e?.find(n=>n.id===t.groupId)?.selection??null:null;function Yv(t,e,n,o){let s=n.find(c=>c.id===e);if(!s)return[...t];let i=t.includes(e),l=new Set(t);if(i)l.delete(e);else{if(HT(s,o)==="single"){let c=n.filter(d=>d.groupId===s.groupId).map(d=>d.id);l=new Set([...l].filter(d=>!c.includes(d)))}l.add(e)}return n.filter(c=>l.has(c.id)).map(c=>c.id)}function fd(t,e){return e?.length?e.filter(n=>t.includes(n.id)).map(n=>n.id):[]}function Xv(t,e){return e?.length?e.filter(n=>t.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function Jv(t,e){if(!(!e?.length||t.length===0))return e.find(n=>t.includes(n.id)&&n.placeholder)?.placeholder}var RT=16;function Zv(t){let e=null;return{action:{id:Gv(t.groupId),kind:"custom",placement:"start",presentation:"bar",label:t.getGroup()?.label??t.groupId,render:()=>{let o=G("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":t.groupId}}),s=new Map,i="",l=g=>{g.preventDefault(),g.stopPropagation();let m=g.currentTarget.getAttribute("data-persona-composer-mode");!m||t.getActiveIds().includes(m)&&t.getGroup()?.selection==="single"||t.onSelect(m)},c=g=>{let u=G("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":g.id,"aria-label":g.label}});if(g.iconName){let y=de(g.iconName,RT,"currentColor",1.5);y&&u.appendChild(y)}let m=P("span","persona-composer-segmented-label");return m.textContent=g.shortLabel??g.label,u.appendChild(m),u.addEventListener("click",l),u},d=()=>{let g=t.getGroup();g?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",g.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let u=t.getModes(),m=u.map(b=>`${b.id}:${b.shortLabel??b.label}:${b.iconName??""}`).join("|");if(m!==i){i=m;for(let C of s.values())C.removeEventListener("click",l);s.clear();let b=u.map(C=>{let S=c(C);return s.set(C.id,S),S});o.replaceChildren(...b)}let y=t.getActiveIds();for(let[b,C]of s)C.setAttribute("aria-pressed",String(y.includes(b)))};return d(),e=d,{element:o,destroy:()=>{e===d&&(e=null);for(let g of s.values())g.removeEventListener("click",l);s.clear()}}}},repaint:()=>e?.()}}function eC(t){let e=G("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});e.style.display="none";let n="",o=!1,s=i=>{let l=P("span","persona-composer-quote-bar"),c=P("div","persona-composer-quote-content");if(i.sourceLabel){let m=P("div","persona-composer-quote-source");m.textContent=i.sourceLabel,c.appendChild(m)}let d=G("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});d.textContent=Jc(i.text),c.appendChild(d);let g=G("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":t.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),u=de("x",12,"currentColor",2);u?g.appendChild(u):g.textContent="\xD7",g.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),t.onDismiss()}),e.replaceChildren(l,c,g)};return{element:e,render:i=>{if(o)return;let l=i?`${i.sourceLabel??""}\0${i.text}`:"";if(l!==n){if(n=l,!i){e.replaceChildren(),e.style.display="none";return}s(i),e.style.display="flex"}},destroy:()=>{o=!0,e.replaceChildren(),e.remove()}}}function tC(t){let e=G("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});e.style.display="none";let n,o=!1,s=(l,c,d,g)=>{let u=G("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":c,[d]:""}}),m=de(l,12,"currentColor",2);return m?u.appendChild(m):u.textContent=c,u.addEventListener("click",y=>{y.preventDefault(),y.stopPropagation(),g()}),u},i=l=>{let c=Jc(l.text??"",90);if(c)return c;let d=l.contentParts?.length??0;return d>0?d===1?"1 attachment":`${d} attachments`:(l.mentionRefs?.length??0)>0?l.mentionRefs.map(u=>u.label).join(", "):"Queued message"};return{element:e,render:l=>{if(o||l===n)return;if(n=l,!l){e.replaceChildren(),e.style.display="none";return}let c=P("span","persona-composer-pending-badge");c.textContent=t.label??"Sends next";let d=G("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});d.textContent=i(l),e.replaceChildren(c,d,s("pencil",t.editLabel??"Edit queued message","data-persona-composer-pending-edit",t.onEdit),s("x",t.removeLabel??"Remove queued message","data-persona-composer-pending-remove",t.onRemove)),e.style.display="flex"},destroy:()=>{o=!0,e.replaceChildren(),e.remove()}}}function nC(t){let e=G("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":t.messageId,"data-preserve-runtime":""}}),n=G("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});n.value=t.initialText;let o=()=>{n.style.height="auto",n.style.height=`${n.scrollHeight}px`};n.addEventListener("input",o);let s=P("div","persona-message-edit-actions"),i=(c,d,g,u)=>{let m=G("button",{className:`persona-message-edit-button ${d}`,attrs:{type:"button",[g]:""},text:c});return m.addEventListener("click",y=>{y.preventDefault(),y.stopPropagation(),u()}),m},l=()=>{let c=n.value.trim();c&&t.onSave(c)};return s.append(i(t.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",t.onCancel),i(t.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",l)),n.addEventListener("keydown",c=>{if(c.key==="Escape"){c.preventDefault(),c.stopPropagation(),t.onCancel();return}c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),l())}),e.append(n,s),{element:e,getValue:()=>n.value,focus:()=>{n.focus();let c=n.value.length;n.setSelectionRange(c,c),o()},destroy:()=>{e.replaceChildren(),e.remove()}}}function oC(t){let e=t.text??"";if(e.trim().length>0||(t.mentionRefs?.length??0)>0||(t.activeModeIds?.length??0)>0||t.quote||t.selectedModelId)return{text:e,...t.mentionRefs?.length?{mentionRefs:[...t.mentionRefs]}:{},...t.contentSegments?.length?{contentSegments:[...t.contentSegments]}:{},...t.selectedModelId?{selectedModelId:t.selectedModelId}:{},...t.activeModeIds?.length?{activeModeIds:[...t.activeModeIds]}:{},...t.quote?{quote:{...t.quote}}:{}}}function rC(t,e){if(!t||typeof t.text!="string")return;let n=new Set(e.mentionSourceIds),o=(t.mentionRefs??[]).filter(d=>n.has(d.sourceId)),s=o.length===(t.mentionRefs?.length??0)&&o.length>0,i=new Set(e.modes.map(d=>d.id)),l=(t.activeModeIds??[]).filter(d=>i.has(d)),c=t.selectedModelId&&e.modelIds.includes(t.selectedModelId)?t.selectedModelId:void 0;return{text:t.text,...s?{mentionRefs:o}:{},...s&&t.contentSegments?.length?{contentSegments:t.contentSegments}:{},...c?{selectedModelId:c}:{},...l.length?{activeModeIds:l}:{},...t.quote?.text?{quote:t.quote}:{}}}function sC(t){let e=t.delay??500,n=null,o=!1,s=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{o||(s(),n=setTimeout(()=>{n=null,t.write()},e))},flush:()=>{o||n===null||(s(),t.write())},cancel:s,destroy:()=>{o=!0,s()}}}function iC(t){return t.wrapped||t.text.includes(`
17
- `)?!1:!(t.hasAttachments||t.hasChips||t.hasQuote||t.hasPendingSubmission)}function aC(){let t=!1;return{observe:(e,n)=>n?(e&&(t=!0),t):(t=!1,!1),release:()=>{t=!1}}}function lC(t){if(!t)return!1;let e=t.ownerDocument?.defaultView;if(!e?.getComputedStyle)return!1;let n=e.getComputedStyle(t),o=Number.parseFloat(n.lineHeight),s=Number.parseFloat(n.fontSize),i=Number.isFinite(o)&&o>0?o:Number.isFinite(s)&&s>0?s*1.4:0;if(!i)return!1;let l=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return t.scrollHeight-l>i*1.5}function Lg(t){return Object.freeze({text:t.text,contentParts:t.contentParts?Object.freeze([...t.contentParts]):void 0,mentionRefs:Object.freeze([...t.mentionRefs]),contentSegments:t.contentSegments?Object.freeze([...t.contentSegments]):void 0,options:Object.freeze({...t.options}),viaVoice:t.viaVoice})}function dC(t){return t.inputDisabled===!0||t.sendDisabled===!0||t.hasAttachments&&!t.attachmentsReady?!1:!!t.text||t.hasAttachments||t.hasMentions||t.hasServerMentions}var WT=t=>typeof t?.then=="function";function cC(t,e){return e===!1?{status:"canceled"}:!e||typeof e!="object"?{status:"proceed"}:(typeof e.text=="string"&&(t.text=e.text),e.options&&(t.options={...t.options,...e.options}),{status:"proceed"})}function pC(t,e,n){let o;try{o=t(Lg(e),{signal:n})}catch(s){return{status:"error",error:s}}return WT(o)?Promise.resolve(o).then(s=>n.aborted?{status:"aborted"}:cC(e,s),s=>n.aborted?{status:"aborted"}:{status:"error",error:s}):cC(e,o)}function uC(t){let{config:e,onOpen:n}=t,o=e.buttonIconName??"plus",s=e.buttonTooltipText??"Add context",i=P("div","persona-send-button-wrapper"),l=G("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${Fn} ${mo}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":s,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),c=de(o,fn,"currentColor",1.5);return c?l.appendChild(c):l.textContent="+",l.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),n()}),i.appendChild(l),tn({anchor:l,trigger:i,text:()=>l.getAttribute("aria-label")??s}),{button:l,wrapper:i}}var{setLoader:PI,load:BT}=Ht({fallbackImport:()=>import("./context-mentions-45MODWOY.js")});var Ig=BT;var{setLoader:II,load:DT}=Ht({fallbackImport:()=>import("./context-mentions-inline-I2RDEBAK.js"),resetOnSetLoader:!0});var gC=DT;function za(t,e={}){if(e.render)return e.render({ref:t,readonly:!!e.readonly});let n=G("span",{className:Nn("persona-mention-token",e.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":t.sourceId,title:t.label,role:"img","aria-label":`${t.label} mention`}});t.color&&n.style.setProperty("--persona-mention-token-accent",t.color);let o=de(t.iconName??"at-sign",13,"currentColor",2);if(o){let s=P("span","persona-mention-token-icon");s.appendChild(o),n.appendChild(s)}return n.appendChild(G("span",{className:"persona-mention-token-label",text:`@${t.label}`})),n}function fC(t){let e=t.config.contextMentions;if(!e?.enabled)return null;let n=Zy(e).filter(x=>x.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(x=>x.sources.some(D=>typeof D.matchCommand=="function")),s=x=>o.some(D=>D.trigger?D.position==="line-start"?x.split(`
18
- `).some($=>$.startsWith(D.trigger)):(D.position==="anywhere"?x:x.split(`
19
- `)[0]).startsWith(D.trigger):!1),i=(x,D)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${x}`,{detail:D}))}catch{}},l=!t.chipRow,c=t.chipRow??G("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),d=null,g=null,u=t.textarea,m=null,y=null,b=null,C=null,S=()=>{if(d)return Promise.resolve(d);if(g)return g;let x=Ig().then(D=>(D.setMentionIconRenderer(de),d=D.mountContextMentions({mentionConfig:e,textarea:t.textarea,composerInput:m??void 0,anchor:t.anchor,contextRow:c,getMessages:t.getMessages,getConfig:()=>t.config,liveRegionHost:t.liveRegionHost,popoverContainer:t.popoverContainer,onPickerOpenChange:N,emit:i}),d)).catch(D=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",D),g===x&&(g=null),null));return g=x,x},E=()=>{gC().then(x=>{let D=x.mountInlineComposer({textarea:t.textarea,renderToken:$=>za($,{render:e.renderMentionToken}),onMentionRemoved:$=>d?.untrackMention($)});m=D.input,y=D.destroy;let L=u;L.replaceWith(D.element),u=D.element,C={next:D.element,prev:L},b?.(D.element,L),d?d.rebindComposer(D.input):g&&g.then($=>$?.rebindComposer(D.input))}).catch(x=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",x)})};e.display==="inline"&&E();let H=[],I=new Map;for(let x of n){if(!x.showButton)continue;let D=uC({config:{...e,buttonIconName:x.buttonIconName,buttonTooltipText:x.buttonTooltipText},onOpen:()=>{S().then(L=>L?.openMenu(x.trigger))}});H.push(D),I.set(x.trigger,D.button)}let N=(x,D,L)=>{let $=I.get(D);$&&($.setAttribute("aria-expanded",x?"true":"false"),x?$.setAttribute("aria-controls",L):$.removeAttribute("aria-controls"))};return{affordanceButtons:H.map(x=>x.wrapper),contextRow:c,handleInput:x=>{if(d){d.handleInput();return}if(!Jy(x))return;let D=u,L=D.selectionStart??0;Xy(D.value,L,n)&&S().then($=>$?.handleInput())},handleKeydown:x=>{if(d?.isMenuOpen())return d.handleKeydown(x);if(x.key==="Backspace"&&d?.hasMentions()&&!C){let D=u,L=D.selectionStart===0&&D.selectionEnd===0;if((D.value.length===0||L)&&d.removeLastChip())return x.preventDefault(),!0}return!1},isMenuOpen:()=>d?.isMenuOpen()??!1,hasMentions:()=>d?.hasMentions()??!1,getMentionRefs:()=>d?.getMentionRefs()??[],collectForSubmit:()=>d?.collectForSubmit()??null,takeInlineCommand:async x=>s(x)?(d??await S())?.dispatchInlineCommand(x)??null:null,clear:()=>d?.clear(),prefetch:()=>{Ig().catch(()=>{})},onComposerSwap:x=>{b=x,C&&x(C.next,C.prev)},destroy:()=>{d?.destroy(),y?.();for(let x of H)x.wrapper.remove();l&&c.remove()}}}var md=t=>t?.launcher?.variant??(t?.future?.v5Defaults===!0?"circle":"pill"),hd={background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",border:"transparent",size:"48px",iconSize:"24px",borderRadius:"palette.radius.full",shadow:"0 8px 24px rgba(0,0,0,.16)",offset:"20px"};var bd="16px",vd="transparent",_T=(()=>{let t={};for(let e of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])t[e]=e===0?"0px":`${e/4}rem`;return t})(),ja={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"},purple:{50:"#faf5ff",100:"#f3e8ff",200:"#e9d5ff",300:"#d8b4fe",400:"#c084fc",500:"#a855f7",600:"#9333ea",700:"#7e22ce",800:"#6b21a8",900:"#581c87",950:"#3b0764"},teal:{50:"#f0fdfa",100:"#ccfbf1",200:"#99f6e4",300:"#5eead4",400:"#2dd4bf",500:"#14b8a6",600:"#0d9488",700:"#0f766e",800:"#115e59",900:"#134e4a",950:"#042f2e"}},spacing:_T,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"}},yd={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"}},Un={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",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"semantic.colors.surface",foreground:"semantic.colors.primary",border:"semantic.colors.border",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:zu,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:bd,canvasBackground:vd,modes:{floating:{border:"1px solid var(--persona-border)",shadow:"palette.shadows.xl",borderRadius:"palette.radius.xl"},inline:{border:"1px solid var(--persona-border)",shadow:"none",borderRadius:"palette.radius.xl"},docked:{border:"none",shadow:"none",borderRadius:"palette.radius.xl"},sidebar:{border:"none",borderRadius:"0"},mobile:{border:"none",shadow:"none",borderRadius:"0"}}},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"20px 24px",minimalPadding:"16px 24px",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{gap:"12px",user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},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",borderRadius:"palette.radius.md"},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:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},eventStream:{badge:{flow:{background:"palette.colors.success.100",foreground:"palette.colors.success.700"},step:{background:"palette.colors.primary.100",foreground:"palette.colors.primary.700"},reasoning:{background:"palette.colors.warning.100",foreground:"palette.colors.warning.700"},tool:{background:"palette.colors.purple.100",foreground:"palette.colors.purple.800"},agent:{background:"palette.colors.teal.100",foreground:"palette.colors.teal.800"},error:{background:"palette.colors.error.100",foreground:"palette.colors.error.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.600"}}},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"}}},OT=ja.colors.gray,NT={50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"},FT={...ja,colors:{...ja.colors,gray:OT}},UT={...ja,colors:{...ja.colors,gray:NT},radius:{none:"0px",sm:"4px",md:"8px",lg:"12px",xl:"16px","2xl":"24px",full:"9999px"}};var $T=yd,VT={...yd,colors:{...yd.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...yd.typography,fontSize:"14px",lineHeight:"1.5"}};var Rg=Un,qT={...Un,launcher:hd,activity:{rowHeight:"32px",labelSize:"13px",iconSize:"16px",indent:"0px",groupIndent:"0px",groupGap:"0px",groupPadding:"0px",transcriptGap:"0px",responseGap:"12px",bodyPadding:"4px 0",bodySize:"13px",bodyLineHeight:"1.5",bodyFontWeight:"400",sectionGap:"8px",bodySurface:"transparent"},toolBubble:{shadow:"none"},reasoningBubble:{shadow:"none"},input:{...Un.input,borderRadius:"palette.radius.full"},introCard:{...Un.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...Un.suggestion.chip,fontWeight:"400"},card:{...Un.suggestion.card,fontWeight:"400"},list:{...Un.suggestion.list,fontWeight:"400"}},panel:{...Un.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...Un.header,background:"semantic.colors.container",foreground:"semantic.colors.text",padding:"8px 8px 8px 16px",minimalPadding:"8px 8px 8px 16px",minHeight:"48px",borderBottom:"none",iconBackground:"transparent",iconForeground:"semantic.colors.text",iconScale:"1",controlSize:"28px",controlIconSize:"18px",controlStrokeWidth:"1.5",actionIconForeground:"semantic.colors.textMuted",controlBorderRadius:"8px",controlHoverBackground:"color-mix(in srgb, var(--persona-text) 8%, transparent)",controlHoverForeground:"semantic.colors.text",controlFocusOutline:"2px solid color-mix(in srgb, var(--persona-text) 50%, transparent)",title:{fontSize:"14px",fontWeight:"500",lineHeight:"1.5"}},message:{...Un.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...Un.message.user,background:"palette.colors.gray.100",text:"semantic.colors.text",borderRadius:"palette.radius.xl",shadow:"none",padding:"8px 14px",fontSize:"14px",lineHeight:"1.5"},assistant:{...Un.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...Un.composer,padding:"8px",fontSize:"15px",lineHeight:"1.5",controlSize:"32px",controlIconSize:"20px",sendIconSize:"18px",sendButtonRadius:"9999px",footerBorder:"none",overlayBand:"linear-gradient(to bottom, transparent, var(--persona-container) 24px)",focusBorderColor:"color-mix(in srgb, var(--persona-text) 28%, var(--persona-border))",focusRing:"1px solid color-mix(in srgb, var(--persona-text) 12%, transparent)"}};var zT=t=>Rr({future:t}),Wg=t=>zT(t)==="v5"?{palette:UT,semantic:VT,components:qT}:{palette:FT,semantic:$T,components:Rg};function on(t,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let n=e.split("."),o=t;for(let s of n){if(o==null)return;o=o[s]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?on(t,o):o}function hC(t){let e={};function n(o,s){for(let[i,l]of Object.entries(o)){let c=`${s}.${i}`;if(typeof l=="string"){let d=on(t,l);d!==void 0&&(e[c]={path:c,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof l=="object"&&l!==null&&n(l,c)}}return n(t.palette,"palette"),n(t.semantic,"semantic"),n(t.components,"components"),e}function jT(t){let e=[],n=[];return t.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),t.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),t.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:n}}function yC(t,e){let n={...t};for(let[o,s]of Object.entries(e)){let i=n[o];i&&typeof i=="object"&&!Array.isArray(i)&&s&&typeof s=="object"&&!Array.isArray(s)?n[o]=yC(i,s):n[o]=s}return n}function KT(t,e){return e?yC(t,e):t}function ki(t,e={}){let n=Wg(e.future),o={palette:n.palette,semantic:n.semantic,components:n.components},s={palette:{...o.palette,...t?.palette,colors:{...o.palette.colors,...t?.palette?.colors},spacing:{...o.palette.spacing,...t?.palette?.spacing},typography:{...o.palette.typography,...t?.palette?.typography},shadows:{...o.palette.shadows,...t?.palette?.shadows},borders:{...o.palette.borders,...t?.palette?.borders},radius:{...o.palette.radius,...t?.palette?.radius}},semantic:{...o.semantic,...t?.semantic,colors:{...o.semantic.colors,...t?.semantic?.colors,interactive:{...o.semantic.colors.interactive,...t?.semantic?.colors?.interactive},feedback:{...o.semantic.colors.feedback,...t?.semantic?.colors?.feedback}},spacing:{...o.semantic.spacing,...t?.semantic?.spacing},typography:{...o.semantic.typography,...t?.semantic?.typography}},components:KT(o.components,t?.components)},i=t?.components?.activity;for(let g of["toolBubble","reasoningBubble"])for(let u of["rowHeight","labelSize","iconSize","indent","bodySurface"])i?.[u]!==void 0&&(s.components[g][u]=i[u]);let l=t?.components?.collapsibleWidget?.surface;l!==void 0&&i?.bodySurface===void 0&&(s.components.activity={...s.components.activity,bodySurface:l});let c=t?.components?.header;c?.padding!==void 0&&c.minimalPadding===void 0&&(s.components.header.minimalPadding=s.components.header.padding);let d=t?.components?.message;if(d?.gap!==void 0&&d.fullscreenGap===void 0&&(s.components.message.fullscreenGap=s.components.message.gap),e.validate!==!1){let g=jT(s);if(!g.valid)throw new Error(`Theme validation failed: ${g.errors.map(u=>u.message).join(", ")}`)}if(e.plugins)for(let g of e.plugins)s=g.transform(s);return s}var Hg=t=>t.trim()==="0"?"0px":t,mC="--persona-",GT=t=>{if(!t)return;let e=t.trim().toLowerCase(),n;if(e.charCodeAt(0)===35){let l=e.slice(1);if(!/^[0-9a-f]+$/.test(l))return;l.length===3||l.length===4?n=[0,1,2].map(c=>parseInt(l[c]+l[c],16)):(l.length===6||l.length===8)&&(n=[0,2,4].map(c=>parseInt(l.slice(c,c+2),16)))}else{let l=e.match(/^rgba?\(([^)]+)\)$/);if(l){let c=l[1].split(/[,/\s]+/).filter(Boolean);c.length>=3&&(n=c.slice(0,3).map(d=>{let g=d.endsWith("%"),u=parseFloat(g?d.slice(0,-1):d);return g?u/100*255:u}))}}if(!n||n.some(l=>!Number.isFinite(l)))return;let[o,s,i]=n.map(l=>{let c=Math.max(0,Math.min(255,l))/255;return c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4)});return .2126*o+.7152*s+.0722*i},QT=.179,nn=(t,e)=>{for(let[n,...o]of e){let s;for(let i of o)if(s=i.charCodeAt(0)===61?i.slice(1):t[mC+i],s!==void 0)break;s!==void 0&&(t[mC+n]=s)}};function bC(t){let e=hC(t),n={};for(let[W,We]of Object.entries(e)){let Fe=W.replace(/\./g,"-");n[`--persona-${Fe}`]=We.value}nn(n,[["primary","semantic-colors-primary","palette-colors-primary-500"],["secondary","semantic-colors-secondary","palette-colors-secondary-500"],["accent","semantic-colors-accent","palette-colors-accent-500"],["surface","semantic-colors-surface","palette-colors-gray-50"],["background","semantic-colors-background","palette-colors-gray-50"],["container","semantic-colors-container","palette-colors-gray-100"],["text","semantic-colors-text","palette-colors-gray-900"],["text-muted","semantic-colors-text-muted","palette-colors-gray-500"],["text-inverse","semantic-colors-text-inverse","palette-colors-gray-50"],["border","semantic-colors-border","palette-colors-gray-200"],["divider","semantic-colors-divider","palette-colors-gray-200"],["muted","text-muted"],["voice-recording-indicator","components-voice-recording-indicator","palette-colors-error-500"],["voice-recording-bg","components-voice-recording-background","palette-colors-error-50"],["voice-processing-icon","components-voice-processing-icon","palette-colors-primary-500"],["voice-speaking-icon","components-voice-speaking-icon","palette-colors-success-500"],["approval-bg","components-approval-requested-background","surface"],["approval-border","components-approval-requested-border","border"],["approval-text","components-approval-requested-text","palette-colors-gray-900"],["approval-shadow","components-approval-requested-shadow","=0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"],["approval-approve-bg","components-approval-approve-background","button-primary-bg"],["approval-deny-bg","components-approval-deny-background","container"],["attachment-image-bg","components-attachment-image-background","palette-colors-gray-100"],["attachment-image-border","components-attachment-image-border","palette-colors-gray-200"],["font-family","semantic-typography-fontFamily","palette-typography-fontFamily-sans"],["font-size","semantic-typography-fontSize","palette-typography-fontSize-base"],["font-weight","semantic-typography-fontWeight","palette-typography-fontWeight-normal"],["line-height","semantic-typography-lineHeight","palette-typography-lineHeight-normal"],["input-font-family","font-family"],["input-font-weight","font-weight"],["radius-sm","palette-radius-sm","=0.125rem"],["radius-md","palette-radius-md","=0.375rem"],["radius-lg","palette-radius-lg","=0.5rem"],["radius-xl","palette-radius-xl","=0.75rem"],["radius-full","palette-radius-full","=9999px"],["launcher-radius","components-launcher-borderRadius","palette-radius-full","=9999px"],["launcher-bg","components-launcher-background","surface"],["launcher-fg","components-launcher-foreground","primary"]]);let o=n["--persona-components-launcher-foreground"];n["--persona-launcher-fg-muted"]=o&&o!==n["--persona-primary"]?`color-mix(in srgb, ${o} 70%, transparent)`:n["--persona-muted"],nn(n,[["launcher-border","components-launcher-border","border"],["button-primary-bg","components-button-primary-background","primary"],["button-primary-fg","components-button-primary-foreground","text-inverse"],["button-radius","components-button-primary-borderRadius","palette-radius-full","=9999px"],["button-stop-bg","components-button-stop-background"],["button-stop-fg","components-button-stop-foreground"]]),nn(n,[["button-ghost-bg","components-button-ghost-background","=transparent"],["button-ghost-fg","components-button-ghost-foreground","text"],["button-ghost-radius","components-button-ghost-borderRadius","radius-md","=0.375rem"],["button-ghost-hover-bg","components-button-ghost-hoverBackground","=rgba(0, 0, 0, 0.05)"],["panel-radius","components-panel-borderRadius","radius-xl","=0.75rem"]]),n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,nn(n,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??bd,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??vd,nn(n,[["launcher-shadow","components-launcher-shadow","=0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"],["input-radius","components-input-borderRadius","radius-lg","=0.5rem"],["message-user-radius","components-message-user-borderRadius","radius-lg","=0.5rem"],["message-assistant-radius","components-message-assistant-borderRadius","radius-lg","=0.5rem"]]),nn(n,[["header-bg","components-header-background","surface"]]);let s=n["--persona-header-bg"],i=n["--persona-components-header-foreground"],l=i?`color-mix(in srgb, ${i} 72%, ${s})`:void 0;n["--persona-header-border"]=n["--persona-components-header-border"]??(i?`color-mix(in srgb, ${i} 14%, ${s})`:void 0)??n["--persona-divider"],nn(n,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),n["--persona-header-title-fg"]=n["--persona-components-header-title-color"]??n["--persona-components-header-titleForeground"]??i??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??l??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??l??n["--persona-muted"],nn(n,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let c=t.components?.header;c?.shadow&&(n["--persona-header-shadow"]=c.shadow),c?.borderBottom&&(n["--persona-header-border-bottom"]=c.borderBottom),c?.minHeight&&(n["--persona-header-min-height"]=c.minHeight);let d=n["--persona-components-history-railHeader-background"];d&&(n["--persona-history-rail-header-bg"]=d);let g=n["--persona-components-history-railHeader-border"];g&&(n["--persona-history-rail-header-border"]=g);let u=n["--persona-components-history-railHeader-minHeight"];u&&(n["--persona-history-rail-header-min-height"]=u);for(let[W,We]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let Fe=n[`--persona-components-history-overlay-${W}`];Fe&&(n[`--persona-history-overlay-${We}`]=Fe)}for(let[W,We]of[["background","bg"],["borderRadius","radius"]]){let Fe=n[`--persona-components-history-menu-${W}`];Fe&&(n[`--persona-history-menu-${We}`]=Fe)}let m=t.components?.history?.motion;if(m){let W=bn=>{if(bn===void 0)return;let sn=String(bn).trim();return/^\d+(\.\d+)?$/.test(sn)?`${sn}ms`:sn},We=W(m.enterDurationMs);We!==void 0&&(n["--persona-history-enter-ms"]=We);let Fe=W(m.exitDurationMs);Fe!==void 0&&(n["--persona-history-exit-ms"]=Fe),m.enterEasing&&(n["--persona-history-enter-easing"]=m.enterEasing),m.exitEasing&&(n["--persona-history-exit-easing"]=m.exitEasing)}let y=n["--persona-components-history-dangerForeground"];y&&(n["--persona-history-danger-fg"]=y),n["--persona-danger"]=n["--persona-components-history-confirm-dangerBackground"]??n["--persona-palette-colors-error-700"]??"#b42318",n["--persona-danger-fg"]=n["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let W of["scrim","shadow"]){let We=n[`--persona-components-history-confirm-${W}`];We&&(n[`--persona-history-confirm-${W}`]=We)}for(let[W,We]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let Fe=n[`--persona-components-tooltip-${W}`];Fe&&(n[`--persona-tooltip-${We}`]=Fe)}t.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[W,We]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let Fe=n[`--persona-components-messageActions-${W}`];Fe&&(n[`--persona-message-action-${We}`]=Fe)}nn(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let b=n["--persona-components-introCard-background"],C=n["--persona-components-introCard-shadow"],S=(!b||b==="transparent"||b==="none")&&(!C||C==="none"),E=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=S&&E==="1.5rem"?"1.5rem 0":E,nn(n,[["intro-card-shadow","components-introCard-shadow","=none"],["intro-card-border","components-introCard-border","=none"],["input-background","components-input-background","surface"],["input-placeholder","components-input-placeholder","text-muted"],["input-backdrop-filter","components-input-backdropFilter","=none"],["message-user-bg","components-message-user-background","accent"],["message-user-text","components-message-user-text","text-inverse"],["message-user-shadow","components-message-user-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["message-assistant-bg","components-message-assistant-background","surface"],["message-assistant-text","components-message-assistant-text","text"],["message-assistant-border","components-message-assistant-border","border"],["message-assistant-shadow","components-message-assistant-shadow","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-bg","components-scrollToBottom-background","button-primary-bg","accent"],["scroll-to-bottom-fg","components-scrollToBottom-foreground","button-primary-fg","text-inverse"],["scroll-to-bottom-border","components-scrollToBottom-border","primary"],["scroll-to-bottom-size","components-scrollToBottom-size","=40px"],["scroll-to-bottom-radius","components-scrollToBottom-borderRadius","button-radius","radius-full","=9999px"],["scroll-to-bottom-shadow","components-scrollToBottom-shadow","palette-shadows-sm","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-padding","components-scrollToBottom-padding","=0.5rem 0.875rem"],["scroll-to-bottom-gap","components-scrollToBottom-gap","=0.5rem"],["scroll-to-bottom-font-size","components-scrollToBottom-fontSize","palette-typography-fontSize-sm","=0.875rem"],["scroll-to-bottom-icon-size","components-scrollToBottom-iconSize","=14px"],["event-badge-flow-bg","components-eventStream-badge-flow-background","=#dcfce7"],["event-badge-flow-fg","components-eventStream-badge-flow-foreground","=#15803d"],["event-badge-step-bg","components-eventStream-badge-step-background","=#f5f5f5"],["event-badge-step-fg","components-eventStream-badge-step-foreground","=#0a0a0a"],["event-badge-reasoning-bg","components-eventStream-badge-reasoning-background","=#fef9c3"],["event-badge-reasoning-fg","components-eventStream-badge-reasoning-foreground","=#a16207"],["event-badge-tool-bg","components-eventStream-badge-tool-background","=#f3e8ff"],["event-badge-tool-fg","components-eventStream-badge-tool-foreground","=#6b21a8"],["event-badge-agent-bg","components-eventStream-badge-agent-background","=#ccfbf1"],["event-badge-agent-fg","components-eventStream-badge-agent-foreground","=#115e59"],["event-badge-error-bg","components-eventStream-badge-error-background","=#fee2e2"],["event-badge-error-fg","components-eventStream-badge-error-foreground","=#b91c1c"],["event-badge-default-bg","components-eventStream-badge-default-background","=#f3f4f6"],["event-badge-default-fg","components-eventStream-badge-default-foreground","=#4b5563"],["tool-bubble-shadow","components-toolBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["reasoning-bubble-shadow","components-reasoningBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["composer-shadow","components-composer-shadow","=none"]]),nn(n,[["composer-padding","components-composer-padding","=0.75rem 1rem"],["composer-gap","components-composer-gap","=0.5rem"],["composer-font-size","components-composer-fontSize","=0.875rem"],["composer-line-height","components-composer-lineHeight","=1.25rem"],["composer-control-size","components-composer-controlSize","=40px"],["composer-control-icon-size","components-composer-controlIconSize","=24px"],["motion-duration-fast","components-motion-durationFast","=120ms"],["motion-duration-base","components-motion-durationBase","=200ms"],["motion-easing","components-motion-easing","=cubic-bezier(0.2, 0, 0, 1)"],["composer-border-color","components-composer-borderColor","border","=#e5e7eb"],["composer-overlay-band","components-composer-overlayBand","=transparent"],["scrollbar-thumb","components-scrollbar-thumb","border","=#e5e7eb"],["scrollbar-track","components-scrollbar-track","=transparent"],["md-inline-code-bg","components-markdown-inlineCode-background","container"],["md-inline-code-color","components-markdown-inlineCode-foreground","text"],["md-link-color","components-markdown-link-foreground","accent","=#0f0f0f"]]);let H=n["--persona-components-markdown-heading-h1-fontSize"];H&&(n["--persona-md-h1-size"]=H);let I=n["--persona-components-markdown-heading-h1-fontWeight"];I&&(n["--persona-md-h1-weight"]=I);let N=n["--persona-components-markdown-heading-h2-fontSize"];N&&(n["--persona-md-h2-size"]=N);let x=n["--persona-components-markdown-heading-h2-fontWeight"];x&&(n["--persona-md-h2-weight"]=x);let D=n["--persona-components-markdown-prose-fontFamily"];D&&D!=="inherit"&&(n["--persona-md-prose-font-family"]=D),nn(n,[["md-code-block-bg","components-markdown-codeBlock-background","container"],["md-code-block-border-color","components-markdown-codeBlock-borderColor","border"],["md-code-block-text-color","components-markdown-codeBlock-textColor","=inherit"]]),nn(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),nn(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),nn(n,[["md-hr-color","components-markdown-hr-color","divider"]]),nn(n,[["md-blockquote-border-color","components-markdown-blockquote-borderColor","palette-colors-gray-900"],["md-blockquote-bg","components-markdown-blockquote-background","=transparent"],["md-blockquote-text-color","components-markdown-blockquote-textColor","palette-colors-gray-500"]]);let L=[["container","surface"],["surface","surface"],["border","border"]];for(let[W,We]of L){let Fe=n[`--persona-components-collapsibleWidget-${W}`]??n[`--persona-${We}`];Fe!==void 0&&(n[`--persona-cw-${W}`]=Fe,n[`--cw-${W}`]=Fe)}nn(n,[["message-border","components-message-border","border"]]),nn(n,[["message-user-padding","components-message-user-padding"],["message-user-max-width","components-message-user-maxWidth"],["message-user-font-size","components-message-user-fontSize"],["message-user-font-family","components-message-user-fontFamily"],["message-user-line-height","components-message-user-lineHeight"],["message-assistant-padding","components-message-assistant-padding"],["message-assistant-border-width","components-message-assistant-borderWidth"],["message-assistant-max-width","components-message-assistant-maxWidth"],["message-assistant-font-size","components-message-assistant-fontSize"],["message-assistant-font-family","components-message-assistant-fontFamily"],["message-assistant-line-height","components-message-assistant-lineHeight"]]);let $=t.components,K=$?.iconButton;K&&(K.background&&(n["--persona-icon-btn-bg"]=K.background),K.border&&(n["--persona-icon-btn-border"]=K.border),K.color&&(n["--persona-icon-btn-color"]=K.color),K.padding&&(n["--persona-icon-btn-padding"]=K.padding),K.borderRadius&&(n["--persona-icon-btn-radius"]=K.borderRadius),K.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=K.hoverBackground),K.hoverColor&&(n["--persona-icon-btn-hover-color"]=K.hoverColor),K.activeBackground&&(n["--persona-icon-btn-active-bg"]=K.activeBackground),K.activeBorder&&(n["--persona-icon-btn-active-border"]=K.activeBorder));let se=$?.labelButton;se&&(se.background&&(n["--persona-label-btn-bg"]=se.background),se.border&&(n["--persona-label-btn-border"]=se.border),se.color&&(n["--persona-label-btn-color"]=se.color),se.padding&&(n["--persona-label-btn-padding"]=se.padding),se.borderRadius&&(n["--persona-label-btn-radius"]=se.borderRadius),se.hoverBackground&&(n["--persona-label-btn-hover-bg"]=se.hoverBackground),se.fontSize&&(n["--persona-label-btn-font-size"]=se.fontSize),se.gap&&(n["--persona-label-btn-gap"]=se.gap));let ne=$?.toggleGroup;ne&&(ne.gap&&(n["--persona-toggle-group-gap"]=ne.gap),ne.borderRadius&&(n["--persona-toggle-group-radius"]=ne.borderRadius));let M=$?.artifact;if(M?.toolbar){let W=M.toolbar;W.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=W.iconHoverColor),W.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=W.iconHoverBackground),W.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=W.iconPadding),W.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=W.iconBorderRadius),W.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=W.iconBorder),W.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Hg(W.toggleGroupGap)),W.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=W.toggleBorderRadius),W.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=Hg(W.toggleGroupPadding)),W.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=W.toggleGroupBorder),W.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=W.toggleGroupBorderRadius),W.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=on(t,W.toggleGroupBackground)??W.toggleGroupBackground),W.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=W.copyBackground),W.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=W.copyBorder),W.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=W.copyColor),W.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Hg(W.copyBorderRadius)),W.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=W.copyPadding),W.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=W.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??W.copyMenuBackground),W.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=W.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??W.copyMenuBorder),W.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=W.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??W.copyMenuShadow),W.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=W.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??W.copyMenuBorderRadius),W.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=W.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??W.copyMenuItemHoverBackground),W.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=W.iconBackground),W.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=W.toolbarBorder)}if(M?.tab){let W=M.tab;W.background&&(n["--persona-artifact-tab-bg"]=W.background),W.activeBackground&&(n["--persona-artifact-tab-active-bg"]=W.activeBackground),W.activeBorder&&(n["--persona-artifact-tab-active-border"]=W.activeBorder),W.borderRadius&&(n["--persona-artifact-tab-radius"]=W.borderRadius),W.textColor&&(n["--persona-artifact-tab-color"]=W.textColor),W.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=W.hoverBackground),W.listBackground&&(n["--persona-artifact-tab-list-bg"]=W.listBackground),W.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=W.listBorderColor),W.listPadding&&(n["--persona-artifact-tab-list-padding"]=W.listPadding)}if(M?.pane){let W=M.pane;if(W.toolbarBackground){let We=on(t,W.toolbarBackground)??W.toolbarBackground;n["--persona-artifact-toolbar-bg"]=We}}if(M?.card){let W=M.card;W.background&&(n["--persona-artifact-card-bg"]=W.background),W.border&&(n["--persona-artifact-card-border"]=W.border),W.borderRadius&&(n["--persona-artifact-card-radius"]=W.borderRadius),W.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=W.hoverBackground),W.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=W.hoverBorderColor)}if(M?.inline){let W=M.inline;W.background&&(n["--persona-artifact-inline-bg"]=on(t,W.background)??W.background),W.border&&(n["--persona-artifact-inline-border"]=W.border),W.borderRadius&&(n["--persona-artifact-inline-radius"]=W.borderRadius),W.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=on(t,W.chromeBackground)??W.chromeBackground),W.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=on(t,W.chromeBorder)??W.chromeBorder),W.titleColor&&(n["--persona-artifact-inline-title-color"]=on(t,W.titleColor)??W.titleColor),W.mutedColor&&(n["--persona-artifact-inline-muted-color"]=on(t,W.mutedColor)??W.mutedColor),W.frameHeight&&(n["--persona-artifact-inline-frame-height"]=W.frameHeight)}let T=$?.code;T&&(T.keywordColor&&(n["--persona-code-keyword-color"]=T.keywordColor),T.stringColor&&(n["--persona-code-string-color"]=T.stringColor),T.commentColor&&(n["--persona-code-comment-color"]=T.commentColor),T.numberColor&&(n["--persona-code-number-color"]=T.numberColor),T.tagColor&&(n["--persona-code-tag-color"]=T.tagColor),T.attrColor&&(n["--persona-code-attr-color"]=T.attrColor),T.propertyColor&&(n["--persona-code-property-color"]=T.propertyColor),T.lineNumberColor&&(n["--persona-code-line-number-color"]=T.lineNumberColor),T.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=T.gutterBorderColor),T.background&&(n["--persona-code-bg"]=on(t,T.background)??T.background));let _=n["--persona-surface"],k=n["--persona-container"],Z=n["--persona-palette-colors-gray-100"]??"#f3f4f6",F=n["--persona-palette-colors-gray-200"]??"#e5e7eb",ie=n["--persona-palette-colors-gray-300"]??"#d1d5db",le=!k||k===_,pe=GT(_??n["--persona-background"]),ve=le&&pe!==void 0&&pe<QT,Ce=ve?"rgba(255, 255, 255, 0.08)":Z,me=ve?"rgba(255, 255, 255, 0.12)":F,vt=ve?"rgba(255, 255, 255, 0.16)":ie,st=le?Ce:k,he=le?me:k;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??st,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??he,le&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??vt),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??st,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??st,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??st,n}var YT=t=>!!t&&"launcher"in t&&(t.launcher?.sidebarMode===!0||t.launcher?.mountMode==="docked"),vC=(t,e)=>{if(!e||!YT(e))return t;let n=e.theme?.components?.panel?.width,o=e.darkTheme?.components?.panel?.width;return(Ga(e)==="dark"?o??n:n)!=null?t:{...t,components:{...t.components,panel:{...t.components.panel,width:Rr(e)==="v5"?"400px":"420px"}}}},XT={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"}}},Ka={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},eventStream:{badge:{flow:{background:"palette.colors.success.900",foreground:"palette.colors.success.300"},step:{background:"palette.colors.primary.800",foreground:"palette.colors.primary.200"},reasoning:{background:"palette.colors.warning.900",foreground:"palette.colors.warning.300"},tool:{background:"palette.colors.purple.900",foreground:"palette.colors.purple.300"},agent:{background:"palette.colors.teal.900",foreground:"palette.colors.teal.300"},error:{background:"palette.colors.error.900",foreground:"palette.colors.error.300"},default:{background:"palette.colors.gray.800",foreground:"palette.colors.gray.300"}}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},Bg=XT,JT={...Bg,colors:{...Bg.colors,primary:{50:"#0f0f10",100:"#27272a",200:"#3f3f46",300:"#52525b",400:"#71717a",500:"#f4f4f5",600:"#e4e4e7",700:"#d4d4d8",800:"#a1a1aa",900:"#fafafa",950:"#ffffff"},gray:{50:"#1a1a1b",100:"#27272a",200:"#2a2a2d",300:"#52525b",400:"#71717a",500:"#a1a1aa",600:"#b4b4bd",700:"#d4d4d8",800:"#e4e4e7",900:"#f4f4f5",950:"#fafafa"}}},ZT=Ka,eE={semantic:{colors:{primary:"palette.colors.primary.500",accent:"palette.colors.primary.600",background:"#0f0f10",surface:"palette.colors.gray.50",container:"#1c1c20",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"#0f0f10",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"}}},components:{...Ka.components,button:{...Ka.components?.button,primary:{background:"semantic.colors.primary",foreground:"palette.colors.primary.50"}},markdown:{inlineCode:{background:"palette.colors.gray.100",foreground:"semantic.colors.text"},link:{foreground:"semantic.colors.accent"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"semantic.colors.text"},table:{headerBackground:"palette.colors.gray.100",borderColor:"semantic.colors.border"},blockquote:{background:"semantic.colors.container",borderColor:"palette.colors.gray.300",textColor:"semantic.colors.textMuted"}},eventStream:{...Ka.components?.eventStream,badge:{...Ka.components?.eventStream?.badge,step:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"}}}}},tE=t=>Rr({future:t})==="v5"?{palette:JT,components:eE}:{palette:Bg,components:ZT},CC=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Dg=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",nE=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":Dg()},Ga=t=>nE(t),oE=(t,e={})=>ki(t,e),rE=(t,e={})=>{let n=tE(e.future),o=fo(n.components,t??{})??{};return ki({...o,palette:{...o.palette,colors:Rr(e)==="v5"?fo(n.palette.colors,o.palette?.colors):{...n.palette.colors,...o.palette?.colors}}},{validate:!1,future:e.future})},ir=t=>{let e=Ga(t),n=CC(t?.theme),o=md(t)==="circle"?hd:{...Rg.launcher,...t?.future?.v5Defaults?{offset:"1.5rem"}:{}},s=fo({components:{launcher:o}},n),i=CC(t?.darkTheme);return vC(e==="dark"?rE(fo(s??{},i??{}),{future:t?.future}):oE(s,{future:t?.future}),t)},sE=t=>bC(t),Qa=(t,e)=>{let n=ir(e),o=sE(n);for(let[s,i]of Object.entries(o))t.style.setProperty(s,i);t.setAttribute("data-persona-color-scheme",Ga(e)),t.setAttribute("data-persona-defaults",Rr(e))},Cd=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(Dg())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>t(Dg());n.addEventListener?(n.addEventListener("change",o),e.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),e.push(()=>n.removeListener(o)))}return()=>{e.forEach(n=>n())}};import{Activity as Vw,Check as qw,Copy as zw}from"lucide";var Ur=(t,e)=>t?.layout?.contentMaxWidth??(e?t?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var wd="24px",_g=(t,e)=>e||t?.composer?.placement!=="overlay"?"block":"overlay",Ya=t=>{if(typeof t!="string")return null;let e=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(t);if(!e)return null;let n=Number(e[1])/100;return n>0&&n<1?n:null},wC=t=>Math.max(0,Math.round(t.columnHeight*(1-t.fraction))-t.footerHeight);var xC=null;var Og=()=>{if(xC!==null)return xC;if(typeof navigator>"u")return!1;let e=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(e)},iE="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",xd=(t,e)=>{console.warn(`[persona] ${t} shortcut: ${e}`)},Sd=t=>{let e=t.toLowerCase().split("+").map(s=>s.trim()),n=e.pop(),o={key:n,mod:!1,shift:!1,alt:!1};for(let s of e)if(s==="mod"||s==="cmd"||s==="ctrl")o.mod=!0;else if(s==="shift")o.shift=!0;else if(s==="alt"||s==="option")o.alt=!0;else return xd("unknown modifier in",t),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(xd("unsupported",t),null):(n==="space"&&(o.key=" "),o)},aE=t=>iE.split(" ").find(e=>e.toLowerCase()===t)??(t===" "?"Space":t.length===1?t.toUpperCase():t[0].toUpperCase()+t.slice(1)),SC=(t,e)=>{let n=Sd(t);if(!n)return"";let o=Og(),s=aE(n.key);if(!e&&o)return`${n.alt?"\u2325":""}${n.shift?"\u21E7":""}\u2318${s}`;let i=[e?o?"Meta":"Control":"Ctrl"];return n.alt&&i.push("Alt"),n.shift&&i.push("Shift"),i.push(s),i.join("+")},Ad=t=>SC(t,!1),Xa=t=>SC(t,!0),lE=(t,e)=>e.key?.toLowerCase()===t.key&&(Og()?e.metaKey:e.ctrlKey)===t.mod&&!(Og()?e.ctrlKey:e.metaKey)&&e.shiftKey===t.shift&&e.altKey===t.alt,cE=t=>{if(!(t instanceof HTMLElement))return!1;let e=t.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"||t.isContentEditable},AC=t=>{let e=new Map,n=t?.ownerDocument??(typeof document<"u"?document:null),o=(i,l)=>{if((i.scope??"widget")==="page")return!0;if(!t)return!1;let c=l.composedPath?.();return c?.length?c.includes(t):t.contains(l.target)},s=i=>{if(i.isComposing||!e.size)return;let l=i.composedPath?.()[0]??i.target;for(let c of e.values())if(lE(c.parsed,i)&&c.when?.()!==!1&&o(c,i)&&!(!c.allowInInput&&cE(l))){i.preventDefault();try{c.run(i)}catch(d){xd(`${c.id} threw on`,c.combo),console.warn(d)}return}};return n?.addEventListener("keydown",s),{register(i){let l=Sd(i.combo);if(!l)return()=>{};let c=`${l.mod?"m":""}${l.shift?"s":""}${l.alt?"a":""}${l.key}`,d=e.get(c);return d?(xd(`${d.id} already owns`,i.combo),()=>{}):(e.set(c,{...i,parsed:l}),i.element?.setAttribute("aria-keyshortcuts",Xa(i.combo)),()=>{e.get(c)?.id===i.id&&e.delete(c),i.element?.removeAttribute("aria-keyshortcuts")})},destroy(){e.clear(),n?.removeEventListener("keydown",s)}}};import{Idiomorph as dE}from"idiomorph";var Md=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;dE.morph(t,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,i){if(s instanceof HTMLElement&&o){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-tool-elapsed"))return i instanceof HTMLElement&&i.getAttribute("data-tool-elapsed")===s.getAttribute("data-tool-elapsed")?!1:void 0;if(s.hasAttribute("data-preserve-animation")){if(i instanceof HTMLElement&&!i.hasAttribute("data-preserve-animation"))return;if(i instanceof HTMLElement&&i.hasAttribute("data-preserve-animation")){let l=s.textContent??"",c=i.textContent??"";if(l!==c)return}return!1}}}}})};var MC=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var Ng={index:-1,draft:""};function TC(t){let{direction:e,history:n,currentValue:o,atStart:s,state:i}=t,l=i.index!==-1;if(n.length===0)return{handled:!1,state:i};if(e==="up"){if(!l&&!s)return{handled:!1,state:i};if(!l){let c=n.length-1;return{handled:!0,value:n[c],state:{index:c,draft:o}}}if(i.index>0){let c=i.index-1;return{handled:!0,value:n[c],state:{index:c,draft:i.draft}}}return{handled:!0,state:i}}if(!l)return{handled:!1,state:i};if(i.index<n.length-1){let c=i.index+1;return{handled:!0,value:n[c],state:{index:c,draft:i.draft}}}return{handled:!0,value:i.draft,state:{index:-1,draft:i.draft}}}function EC(t,e){return[t.id,t.role,t.content?.length??0,t.content?.slice(-32)??"",t.streaming?"1":"0",t.voiceProcessing?"1":"0",t.variant??"",t.rawContent?.length??0,t.llmContent?.length??0,t.approval?.status??"",t.toolCall?.status??"",t.toolCall?.name??"",t.toolCall?.chunks?.length??0,t.toolCall?.chunks?.[t.toolCall.chunks.length-1]?.slice(-32)??"",typeof t.toolCall?.args=="string"?t.toolCall.args.length:t.toolCall?.args?JSON.stringify(t.toolCall.args).length:0,t.reasoning?.chunks?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.slice(-32)??"",t.contentParts?.length??0,t.stopReason??"",e].join("\0")}function PC(){return new Map}function kC(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function LC(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function IC(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}var{setLoader:cH,load:pE}=Ht({fallbackImport:()=>import("./animations-extra-SNTZ6Z6B.js")});var HC=pE;function Fg(t,e=ln){let n=t.style.position,o=t.style.zIndex,s=t.style.isolation,i=getComputedStyle(t),l=i.position==="static"||i.position==="";return l&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{l&&(t.style.position=n),t.style.zIndex=o,t.style.isolation=s}}var Ja=0,$r=null;function Ug(t=document){if(Ja++,Ja===1){let n=t.body,s=(t.defaultView??window).scrollY||t.documentElement.scrollTop;$r={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:s},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${s}px`,n.style.width="100%"}let e=!1;return()=>{if(!e&&(e=!0,Ja=Math.max(0,Ja-1),Ja===0&&$r)){let n=t.body,o=t.defaultView??window;n.style.overflow=$r.originalOverflow,n.style.position=$r.originalPosition,n.style.top=$r.originalTop,n.style.width=$r.originalWidth,o.scrollTo(0,$r.scrollY),$r=null}}}var Za={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},xt=t=>(t?.launcher?.mountMode??"floating")==="docked",el=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",oo=t=>{let e=t?.launcher?.dock,n=nr(t).dockWidth?e?.width:on(ir(t),"components.panel.width");return{side:e?.side??Za.side,width:n??Za.width,animate:e?.animate??Za.animate,reveal:e?.reveal??Za.reveal,maxHeight:e?.maxHeight??Za.maxHeight}};import{ArrowRight as uE}from"lucide";var $g=t=>t==="followUp"?"follow-up":t,Vg=(t,e=0)=>{if(typeof t=="string"){let s=t.trim();return s?{id:s,label:s,prompt:s,emphasis:"default"}:null}let n=t.label.trim();if(!n)return null;let o=t.prompt?.trim()||n;return{id:t.id?.trim()||o||`suggestion-${e}`,label:n,prompt:o,description:t.description?.trim()||void 0,icon:t.icon,iconColor:t.iconColor?.trim()||void 0,behavior:t.behavior,emphasis:t.emphasis??"default"}},RC=new WeakSet,gE=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,fE=t=>{gE()||t.forEach((e,n)=>{typeof e.animate=="function"&&e.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},qg=t=>{var N,x,D;let{item:e,index:n,surface:o,source:s,variant:i,streaming:l,config:c,plugins:d,chipsConfig:g,session:u,getTextarea:m,eventTarget:y,submitPrompt:b}=t,C=o==="followUp",S=e.behavior,E=()=>{if(u.isStreaming())return;let L={suggestion:{...e},surface:o,source:s,behavior:S},$=y.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:L,bubbles:!0,composed:!0,cancelable:!0}));if(C&&y.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:e.prompt},bubbles:!0,composed:!0})),!$)return;for(let se of d)if(se.onSuggestionSelect?.({suggestion:{...e},surface:o,source:s,variant:i,config:c})===!1)return;let K=m();if(S==="fill"){K.value=e.prompt,K.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),K.focus();return}if(b){b(e.prompt);return}K.value="",u.sendMessage(e.prompt)},H=()=>{let L=P("button",`persona-suggestion persona-suggestion--${i}`);if(L.type="button",L.disabled=l,L.dataset.suggestionId=e.id,L.dataset.emphasis=e.emphasis,L.dataset.behavior=S,i==="chip"&&(g?.fontWeight&&(L.style.fontWeight=g.fontWeight),g?.paddingX&&(L.style.paddingLeft=g.paddingX,L.style.paddingRight=g.paddingX),g?.paddingY&&(L.style.paddingTop=g.paddingY,L.style.paddingBottom=g.paddingY)),e.icon){let K=de(e.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);K&&(K.classList.add("persona-suggestion__icon"),e.iconColor&&(K.style.color=e.iconColor),L.appendChild(K))}let $=P("span","persona-suggestion__copy");if($.appendChild(G("span",{className:"persona-suggestion__label",text:e.label})),e.description&&i!=="chip"&&$.appendChild(G("span",{className:"persona-suggestion__description",text:e.description})),L.appendChild($),i!=="chip"){let K=$t(uE,16,"currentColor",1.8);K&&(K.classList.add("persona-suggestion__arrow"),L.appendChild(K))}return L.addEventListener("click",E),L},I=null;for(let L of d)if(L.renderSuggestion&&(I=L.renderSuggestion({suggestion:{...e},index:n,surface:o,source:s,variant:i,streaming:l,config:c,defaultRenderer:H,select:E}),I))break;return I??(I=H()),(N=I.dataset).suggestionId||(N.suggestionId=e.id),(x=I.dataset).behavior||(x.behavior=S),(D=I.dataset).emphasis||(D.emphasis=e.emphasis),I instanceof HTMLButtonElement||I.setAttribute("aria-disabled",l?"true":"false"),I},tl=t=>{let e=[],n=[],o=null,s=null,i=()=>{t.removeAttribute("data-scroll-left"),t.removeAttribute("data-scroll-right")},l=()=>{if(s=null,t.hidden||t.dataset.variant!=="chip"||t.dataset.overflow!=="scroll"){i();return}let u=Math.max(0,t.scrollWidth-t.clientWidth);if(u<=1){i();return}let m=getComputedStyle(t).direction==="rtl",y=Math.min(u,Math.max(0,Math.abs(t.scrollLeft))),b=4,C=y<=b,S=y>=u-b,E=m?!S:!C,H=m?!C:!S;t.toggleAttribute("data-scroll-left",E),t.toggleAttribute("data-scroll-right",H)},c=()=>{if(s!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&l();return}s=requestAnimationFrame(l)};t.addEventListener("scroll",c,{passive:!0});let d=typeof ResizeObserver=="function"?new ResizeObserver(c):null;return d?.observe(t),{buttons:e,elements:n,destroy:()=>{t.removeEventListener("scroll",c),d?.disconnect(),s!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(s),s=null},render:(u,m,y,b,C,S)=>{t.replaceChildren(),e.length=0,n.length=0;let E=S?.source??"config",H=S?.surface??(E==="config"?"starter":"followUp"),I=H==="followUp",N=S?.variant??"chip",x=S?.behavior??"send",D=S?.overflow??"wrap",L=S?.config??{},$=S?.plugins??[],K=typeof S?.maxItems=="number"?Math.max(0,Math.floor(S.maxItems)):void 0,se=I?"followUps":"starters";!RC.has(L)&&L.debug===!0&&N!=="chip"&&L.suggestions?.[se]?.overflow!==void 0&&(RC.add(L),console.info(`[persona] suggestions.${se}.overflow applies to the "chip" variant only; the "${N}" variant manages its own stacking.`));let ne=F=>F.map(Vg).filter(ie=>ie!==null).map(ie=>({...ie,behavior:ie.behavior??x})),M=ne(u??[]);$.forEach(F=>{F.transformSuggestions&&(M=ne(F.transformSuggestions({suggestions:M.map(ie=>({...ie})),surface:H,source:E,config:L})))});let T=K===void 0?M:M.slice(0,K);if(!T.length){t.hidden=!0,o=null,i();return}if(!I&&(b??m.getMessages()).some(ie=>ie.role==="user")){t.hidden=!0,o=null;return}t.hidden=!1,t.classList.add("persona-suggestions"),t.dataset.personaSuggestionSurface=$g(H),t.dataset.variant=N,t.dataset.overflow=D;let _=document.createDocumentFragment(),k=m.isStreaming();T.forEach((F,ie)=>{let le=qg({item:F,index:ie,surface:H,source:E,variant:N,streaming:k,config:L,plugins:$,chipsConfig:C,session:m,getTextarea:()=>y,eventTarget:t,submitPrompt:S?.submitPrompt});_.appendChild(le),n.push(le),[...le instanceof HTMLButtonElement?[le]:[],...Array.from(le.querySelectorAll("button"))].forEach(ve=>{e.includes(ve)||(ve.disabled=k,e.push(ve))})}),t.appendChild(_),l(),c();let Z=JSON.stringify({normalized:T,surface:H,variant:N,source:E});Z!==o&&(o=Z,fE(n),t.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:T.map(F=>({...F})),surface:H,source:E,variant:N},bubbles:!0,composed:!0})),I&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:T.map(F=>F.prompt)},bubbles:!0,composed:!0})))}}};var $n={"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 mE="persona-header-control",hE="persona-header-control--glyph",yE="persona-header-control--sparse",bE=20,vE={x:[1.4,1.05]},WC="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",CE="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Td=(t,e,n={})=>{let{iconSize:o,iconText:s}=n,[i,l]=vE[e]??[1,1.5],c=!o;t.classList.toggle(hE,c),t.classList.toggle(yE,c&&i!==1);let d=parseFloat(o??"")||bE,g=de(e,`${Math.round(d*i)}px`,"currentColor",l);g?(g.style.display="block",c||(g.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((l/1.5).toFixed(4))})`),t.replaceChildren(g)):s&&(t.textContent=s)},Hs=t=>{let{ariaLabel:e,tooltip:n=!0,tooltipHint:o,iconName:s,iconText:i,wrapperClassName:l=WC,size:c,iconSize:d,color:g,backgroundColor:u,borderWidth:m,borderColor:y,borderRadius:b,paddingX:C,paddingY:S,hidden:E,extraClassName:H,attrs:I}=t,N=P("div",l),x=!!(m||y),D=G("button",{className:Nn(mE,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"persona-bg-transparent hover:persona-bg-gray-100",!x&&"persona-border-none",!b&&"persona-rounded-full",H),attrs:{type:"button","aria-label":e,...I},style:{width:c,height:c,minWidth:c,minHeight:c,display:E?"none":void 0,color:g||mn.actionIconColor,backgroundColor:u,border:x?`${m||"0px"} solid ${y||"transparent"}`:void 0,borderRadius:b,paddingLeft:C,paddingRight:C,paddingTop:S,paddingBottom:S}});return s?Td(D,s,{iconSize:d,iconText:i}):i&&(D.textContent=i),N.appendChild(D),tn({anchor:D,trigger:N,text:()=>D.getAttribute("aria-label")??e,hint:o,enabled:n}),{button:D,wrapper:N}},Li=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=WC,buttonSize:s,iconSize:i}=e,l=t?.launcher??{},c=l.closeButtonTooltipText??"Close chat",d=l.closeButtonShowTooltip??!0,{button:g,wrapper:u}=Hs({ariaLabel:c,tooltip:d,iconName:l.closeButtonIconName??"x",iconText:l.closeButtonIconText??"\xD7",wrapperClassName:o,size:s??l.closeButtonSize,iconSize:i,color:l.closeButtonColor,backgroundColor:l.closeButtonBackgroundColor,borderWidth:l.closeButtonBorderWidth,borderColor:l.closeButtonBorderColor,borderRadius:l.closeButtonBorderRadius,paddingX:l.closeButtonPaddingX,paddingY:l.closeButtonPaddingY,hidden:!n});return{button:g,wrapper:u}},Ii=(t,e={})=>{let{wrapperClassName:n=CE,buttonSize:o,iconSize:s}=e,l=(t?.launcher??{}).clearChat??{},c=l.tooltipText??"Clear chat",d=l.showTooltip??!0,{button:g,wrapper:u}=Hs({ariaLabel:c,tooltip:d,iconName:l.iconName??"refresh-cw",wrapperClassName:n,size:o??l.size,iconSize:s,color:l.iconColor,backgroundColor:l.backgroundColor,borderWidth:l.borderWidth,borderColor:l.borderColor,borderRadius:l.borderRadius,paddingX:l.paddingX,paddingY:l.paddingY});return{button:g,wrapper:u}};var mn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-control-state-fg, var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af)))",minHeight:"var(--persona-header-min-height, auto)"},zg={fontFamily:"var(--persona-components-header-title-fontFamily, inherit)",fontSize:"var(--persona-components-header-title-fontSize, 1rem)",fontWeight:"var(--persona-components-header-title-fontWeight, 600)",lineHeight:"var(--persona-components-header-title-lineHeight, 1.5rem)",letterSpacing:"var(--persona-components-header-title-letterSpacing, normal)"},wE={fontFamily:"var(--persona-components-header-subtitle-fontFamily, inherit)",fontSize:"var(--persona-components-header-subtitle-fontSize, 0.75rem)",fontWeight:"var(--persona-components-header-subtitle-fontWeight, inherit)",lineHeight:"var(--persona-components-header-subtitle-lineHeight, 1rem)",letterSpacing:"var(--persona-components-header-subtitle-letterSpacing, normal)"},Rs=t=>{let{config:e,showClose:n=!0}=t,o=G("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3",attrs:{"data-persona-theme-zone":"header"},style:{padding:"var(--persona-components-header-padding, 20px 24px)",minHeight:mn.minHeight,backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),s=e?.launcher??{},i=s.headerIconSize??Ha,l=s.closeButtonPlacement??"inline",c=s.headerIconHidden??!1,d=s.headerIconName,g=G("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:i,width:i,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!c)if(d){let D=parseFloat(i)||24,L=de(d,D*.6,"currentColor",1);L?(L.style.width=`calc(${D}px * var(--persona-components-header-iconScale, 0.6))`,L.style.height=`calc(${D}px * var(--persona-components-header-iconScale, 0.6))`,g.replaceChildren(L)):g.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let D=P("img");D.src=e.launcher.iconUrl,D.alt="",D.className="persona-rounded-xl persona-object-cover",D.style.height=i,D.style.width=i,g.replaceChildren(D)}else g.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let u=P("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=G("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:mn.titleColor,...zg}}),y=G("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:mn.subtitleColor,...wE}});u.append(m,y),c?o.append(u):o.append(g,u);let b=s.clearChat??{},C=b.enabled??!0,S=b.placement??"inline",E=null,H=null;if(C){let L=Ii(e,{wrapperClassName:S==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=L.button,H=L.wrapper,S==="top-right"&&(H.style.right="48px"),S==="inline"&&o.appendChild(H)}let I=l==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":C&&S==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:N,wrapper:x}=Li(e,{showClose:n,wrapperClassName:I});return l!=="top-right"&&o.appendChild(x),{header:o,iconHolder:g,headerTitle:m,headerSubtitle:y,closeButton:N,closeButtonWrapper:x,clearChatButton:E,clearChatButtonWrapper:H}},nl=(t,e,n)=>{let o=n?.launcher??{},s=o.closeButtonPlacement??"inline",i=o.clearChat?.placement??"inline";t.appendChild(e.header),s==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&i==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};var xE=t=>{let e=Rs({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),n=t.layoutHeaderConfig?.onTitleClick;if(n){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return e};function SE(t,e,n){if(e?.length)for(let o of e){let{button:s,wrapper:i}=Hs({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?Ad(o.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(s.setAttribute("data-persona-header-action",o.id),o.shortcut){let l=Xa(o.shortcut);l&&s.setAttribute("aria-keyshortcuts",l)}if(o.menuItems?.length){let l=lb({items:o.menuItems,onSelect:c=>n?.(c),anchor:i,position:"bottom-right"});i.appendChild(l.element),s.addEventListener("click",c=>{c.stopPropagation(),l.toggle()})}else s.addEventListener("click",()=>n?.(o.id));t.appendChild(i)}}var AE=t=>{let{config:e,showClose:n=!0,onClose:o,layoutHeaderConfig:s,onHeaderAction:i}=t,l=e?.launcher??{},c=P("div","persona-flex persona-items-center persona-justify-between");c.setAttribute("data-persona-theme-zone","header"),c.style.minHeight=mn.minHeight,c.style.padding="var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))",c.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",c.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",c.style.boxShadow="var(--persona-header-shadow, none)",c.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=s?.titleMenu,g,u;if(d){let x=db({label:l.title??"Chat Assistant",menuItems:d.menuItems,onSelect:D=>{let L=K=>{K===!1&&x.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:D}}))},$=d.onSelect(D);$ instanceof Promise?$.then(L,()=>{}):L($)},hover:d.hover,className:""});g=x.element,g.style.color=mn.titleColor,u=g.querySelector(".persona-combo-btn-label")??g}else{if(g=P("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=P("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=mn.titleColor,Object.assign(u.style,zg),u.textContent=l.title??"Chat Assistant",g.appendChild(u),s?.onTitleClick){g.style.cursor="pointer",g.setAttribute("role","button"),g.setAttribute("tabindex","0");let D=s.onTitleClick;g.addEventListener("click",L=>{L.target.closest("button")||D()}),g.addEventListener("keydown",L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),D())})}let x=s?.titleRowHover;x&&(g.style.borderRadius=x.borderRadius??"10px",g.style.padding=x.padding??"6px 4px 6px 12px",g.style.margin="-6px 0 -6px -12px",g.style.border="1px solid transparent",g.style.transition="background-color 0.15s ease, border-color 0.15s ease",g.style.width="fit-content",g.style.flex="none",g.addEventListener("mouseenter",()=>{g.style.backgroundColor=x.background??"",g.style.borderColor=x.border??""}),g.addEventListener("mouseleave",()=>{g.style.backgroundColor="",g.style.borderColor="transparent"}))}c.appendChild(g);let m="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:y,wrapper:b}=Li(e,{showClose:n,wrapperClassName:m});o&&y.addEventListener("click",o);let C=P("div","persona-flex persona-items-center persona-gap-1");d||SE(C,s?.trailingActions,s?.onAction??i);let S=l.clearChat??{},E=null,H=null;if(S.enabled??!0){let x=S.placement??"inline",D=Ii(e,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});E=D.button,H=D.wrapper,x==="top-right"?H.style.right="48px":C.appendChild(H)}C.appendChild(b),c.appendChild(C);let I=P("div");I.style.display="none";let N=P("span");return N.style.display="none",{header:c,iconHolder:I,headerTitle:u,headerSubtitle:N,closeButton:y,closeButtonWrapper:b,clearChatButton:E,clearChatButtonWrapper:H}},BC={default:xE,minimal:AE},ME=t=>BC[t]??BC.default,Ed=(t,e,n)=>{if(e?.render){let l=e.render({config:t,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),c=P("div");c.style.display="none";let d=P("span"),g=P("span"),u=P("button");u.style.display="none";let m=P("div");return m.style.display="none",{header:l,iconHolder:c,headerTitle:d,headerSubtitle:g,closeButton:u,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",i=ME(o)({config:t,showClose:e?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:e,onHeaderAction:e?.onAction});return e&&(e.showIcon===!1&&(i.iconHolder.style.display="none"),e.showTitle===!1&&(i.headerTitle.style.display="none"),e.showSubtitle===!1&&(i.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(i.closeButton.style.display="none"),e.showClearChat===!1&&i.clearChatButtonWrapper&&(i.clearChatButtonWrapper.style.display="none")),i};var ol=t=>{let{config:e}=t,n=G("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=ud(),s=G("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""}}),{textarea:i,attachAutoResize:l}=ld(e);l();let c=cd(e),d=Pi(e),g=dd(e),u=pd(e),m=G("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});s.append(m),g&&(g.previewsContainer.style.gap="8px",m.append(g.previewsContainer),s.append(g.input)),s.append(i);let y=G("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),b=G("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),C=G("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return g&&b.append(g.wrapper),d&&C.append(d.wrapper),C.append(c.wrapper),y.append(b,C),s.append(y),s.addEventListener("click",S=>{S.target!==c.button&&S.target!==c.wrapper&&S.target!==d?.button&&S.target!==d?.wrapper&&S.target!==g?.button&&S.target!==g?.wrapper&&i.focus()}),e?.statusIndicator?.mode==="transient"?n.append(o,u,s):n.append(o,s,u),{footer:n,suggestions:o,composerForm:s,header:m,textarea:i,sendButton:c.button,sendButtonWrapper:c.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:u,attachmentButton:g?.button??null,attachmentButtonWrapper:g?.wrapper??null,attachmentInput:g?.input??null,attachmentPreviewsContainer:g?.previewsContainer??null,actionsRow:y,leftActions:b,rightActions:C,setSendButtonMode:c.setMode}};import{ChevronUp as TE,MessageSquare as EE}from"lucide";var DC=()=>{let t=G("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=P("span","persona-pill-peek__icon"),n=$t(EE,16,"currentColor",1.5);n&&e.appendChild(n);let o=P("span","persona-pill-peek__text"),s=P("span","persona-pill-peek__caret"),i=$t(TE,16,"currentColor",1.5);return i&&s.appendChild(i),t.append(e,o,s),{root:t,textNode:o}},Pd=t=>{let{config:e}=t,n=G("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=ud(),s=pd(e);s.style.display="none";let{textarea:i,attachAutoResize:l}=ld(e,{defaultMaxLines:5});l();let c=cd(e),d=Pi(e),g=dd(e);g&&g.previewsContainer.classList.add("persona-pill-composer__previews");let u=G("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),m=G("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});g&&m.append(g.wrapper);let y=G("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});d&&y.append(d.wrapper),y.append(c.wrapper),u.addEventListener("click",S=>{S.target!==c.button&&S.target!==c.wrapper&&S.target!==d?.button&&S.target!==d?.wrapper&&S.target!==g?.button&&S.target!==g?.wrapper&&i.focus()}),g&&u.append(g.input),u.append(m,i,y);let b=G("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(b),g&&b.append(g.previewsContainer),n.append(o,u,s);let C=u;return{footer:n,suggestions:o,composerForm:u,header:b,textarea:i,sendButton:c.button,sendButtonWrapper:c.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:s,attachmentButton:g?.button??null,attachmentButtonWrapper:g?.wrapper??null,attachmentInput:g?.input??null,attachmentPreviewsContainer:g?.previewsContainer??null,actionsRow:C,leftActions:m,rightActions:y,setSendButtonMode:c.setMode}};var PE=t=>{switch(t){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}},kE=(t,e)=>{if(!t)return null;let n=PE(t);if(n===null)return null;let o=e?.[t],s=o!==void 0?o:n;return s||null},LE=(t,e)=>{let n=P("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",t),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=e,n},IE=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},Kg=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},Gg=320,UC=320,HE=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),RE=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),WE=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),BE=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),DE=t=>{if(!t||t.length===0)return null;let e=G("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=G("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),s=P("span","persona-mention-chip-icon"),i=de(n.iconName??"at-sign",13,"currentColor",2);i&&s.appendChild(i),o.appendChild(s),o.appendChild(G("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},_E=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(za(o.ref,{readonly:!0,render:e}))}return n},_C="\uE000",OC="\uE001",OE=(t,e,n,o)=>{let s=Math.random().toString(36).slice(2,8),i=y=>`${_C}${s}:${y}${OC}`,l=e.map((y,b)=>y.kind==="text"?y.text:i(b)).join(""),c=n(l);if(!e.every((y,b)=>y.kind==="text"||c.includes(i(b)))){t.replaceChildren(_E(e,o));return}t.innerHTML=c;let g=new RegExp(`${_C}${s}:(\\d+)${OC}`),u=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),m=[];for(let y=u.nextNode();y;y=u.nextNode())m.push(y);for(let y of m){let b=y;for(let C=g.exec(b.data);C;C=g.exec(b.data)){let S=e[Number(C[1])],E=b.splitText(C.index);E.data=E.data.slice(C[0].length),S?.kind==="mention"&&E.parentNode?.insertBefore(za(S.ref,{readonly:!0,render:o}),E),b=E}}},NE=(t,e,n)=>{if(t.length===0)return null;try{let o=P("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),e&&(o.style.marginBottom="8px");let s=0,i=!1,l=()=>{i||(i=!0,o.remove(),n?.())};return t.forEach((c,d)=>{let g=P("img");g.alt=c.alt?.trim()||`Attached image ${d+1}`,g.loading="lazy",g.decoding="async",g.referrerPolicy="no-referrer",g.style.display="block",g.style.width="100%",g.style.maxWidth=`${Gg}px`,g.style.maxHeight=`${UC}px`,g.style.height="auto",g.style.objectFit="contain",g.style.borderRadius="10px",g.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",g.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;s+=1,g.addEventListener("error",()=>{u||(u=!0,s=Math.max(0,s-1),g.remove(),s===0&&l())}),g.addEventListener("load",()=>{u=!0}),IE(c.image)?(g.src=c.image,o.appendChild(g)):(u=!0,s=Math.max(0,s-1),g.remove())}),s===0?(l(),null):o}catch{return n?.(),null}},FE=t=>{if(t.length===0)return null;try{let e=P("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(o=>{if(!Kg(o.audio))return;let s=P("audio");s.controls=!0,s.preload="metadata",s.src=o.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${Gg}px`,e.appendChild(s),n+=1}),n===0?(e.remove(),null):e}catch{return null}},UE=t=>{if(t.length===0)return null;try{let e=P("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(o=>{if(!Kg(o.video))return;let s=P("video");s.controls=!0,s.preload="metadata",s.src=o.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${Gg}px`,s.style.maxHeight=`${UC}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(s),n+=1}),n===0?(e.remove(),null):e}catch{return null}},$E=t=>{if(t.length===0)return null;try{let e=P("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(o=>{if(!Kg(o.data))return;let s=P("a");s.href=o.data,s.download=o.filename,s.target="_blank",s.rel="noopener noreferrer",s.textContent=o.filename,s.className="persona-message-file-attachment",s.style.display="inline-flex",s.style.alignItems="center",s.style.gap="6px",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.fontSize="0.875rem",s.style.textDecoration="underline",s.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",s.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",s.style.color="inherit",e.appendChild(s),n+=1}),n===0?(e.remove(),null):e}catch{return null}},rl=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.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 s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",t.appendChild(e),t.appendChild(n),t.appendChild(o),t.appendChild(s),t},VE=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:rl};if(e){let s=e(o);if(s!==null)return s}return rl()},qE=(t,e)=>{let n=P("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=e==="user"?t.userAvatar:t.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let s=P("img");s.src=o,s.alt=e==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(s)}else n.textContent=o,n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=e==="user"?"U":"A",n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},NC=(t,e,n="div")=>{let o=P(n,"persona-text-xs persona-text-persona-muted"),s=new Date(t.createdAt);return e.format?o.textContent=e.format(s):o.textContent=s.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},sl=(t,e="bubble")=>{let n=["persona-message-bubble"];switch(e){case"flat":t==="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-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),t==="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-container","persona-text-persona-text","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"),t==="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-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},FC={bubble:{padding:"0.75rem 1.25rem",fontSize:"0.875rem",lineHeight:"1.75"},minimal:{padding:"0.5rem 0.75rem",fontSize:"0.875rem",lineHeight:"1.75"},flat:{padding:"0.5rem 0",fontSize:"inherit",lineHeight:"inherit"}},zE=(t,e,n="bubble",o)=>{if(!o)return;let s=e==="user"?"user":"assistant",i=FC[n??"bubble"]??FC.bubble;o.padding&&(t.style.padding=`var(--persona-message-${s}-padding, ${i.padding})`),o.fontSize&&(t.style.fontSize=`var(--persona-message-${s}-font-size, ${i.fontSize})`),o.lineHeight&&(t.style.lineHeight=`var(--persona-message-${s}-line-height, ${i.lineHeight})`),o.fontFamily&&(t.style.fontFamily=`var(--persona-message-${s}-font-family, inherit)`)},kd="custom:",jE=t=>`${kd}${t}`,$C=(t,e)=>e!=="user"&&e!=="assistant"?[]:(t?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(e)),KE=(t,e,n,o)=>{let s=e.showCopy??!0,i=e.showUpvote??!1,l=e.showDownvote??!1,c=e.showReadAloud??!1,d=(e.showRegenerate??!1)&&o?.canRegenerate===!0,g=(e.showEdit??!1)&&o?.canEdit===!0,u=(e.showQuote??!1)&&o?.canQuote!==!1,m=$C(e,t.role);if(!s&&!i&&!l&&!c&&!d&&!g&&!u&&m.length===0){let N=P("div");return N.style.display="none",N.id=`actions-${t.id}`,N.setAttribute("data-actions-for",t.id),N}let y=e.visibility??"hover",b=e.align??"right",C=e.layout??"pill-inside",S={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[b],E={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[C],H=P("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${S} ${E} ${y==="hover"?"persona-message-actions-hover":""}`);H.id=`actions-${t.id}`,H.setAttribute("data-actions-for",t.id);let I=(N,x,D)=>{let L=cb({icon:N,label:x,size:14,className:"persona-message-action-btn",chromeless:!0});return L.setAttribute("data-action",D),L};s&&H.appendChild(I("copy","Copy message","copy")),c&&H.appendChild(I("volume-2","Read aloud","read-aloud")),i&&H.appendChild(I("thumbs-up","Upvote","upvote")),l&&H.appendChild(I("thumbs-down","Downvote","downvote")),d&&H.appendChild(I("refresh-cw","Regenerate response","regenerate")),g&&H.appendChild(I("pencil","Edit message","edit")),u&&H.appendChild(I("quote","Quote message","quote"));for(let N of m)H.appendChild(I(N.iconName??"ellipsis",N.label,jE(N.id)));return H},Qg=(t,e,n,o,s,i)=>{let l=n??{},c=l.layout??"bubble",d=l.avatar,g=l.timestamp,u=d?.show??!1,m=g?.show??!1,y=d?.position??"left",b=g?.position??"below",C=sl(t.role,c),S=P("div",C.join(" "));S.id=`bubble-${t.id}`,S.setAttribute("data-message-id",t.id),S.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message");let E=Wg(i?.widgetConfig?.future).components.message,H=i?.widgetConfig?.theme?.components?.message;zE(S,t.role,c,t.role==="user"?{...E.user,...H?.user,...i?.widgetConfig?.darkTheme?.components?.message?.user}:{...E.assistant,...H?.assistant,...i?.widgetConfig?.darkTheme?.components?.message?.assistant}),c==="flat"?(S.style.backgroundColor="transparent",S.style.color=t.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):t.role==="user"?(S.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",S.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(S.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",S.style.color="var(--persona-message-assistant-text, var(--persona-text))");let I=HE(t),N=t.content?.trim()??"",D=I.length>0&&N===Ei,L=Ic(i?.widgetConfig?.features?.streamAnimation),$=i?.widgetConfig?.features?.streamAnimation?.plugins,K=t.role==="assistant"&&L.type!=="none"?Ta(L.type,$):null,se=t.role==="assistant"&&K?.isAnimating?.(t)===!0,ne=t.role==="assistant"&&K!==null&&(!!t.streaming||se);ne&&K?.bubbleClass&&S.classList.add(K.bubbleClass);let M=document.createElement("div");M.classList.add("persona-message-content"),t.streaming&&M.classList.add("persona-content-streaming"),ne&&K&&(K.containerClass&&M.classList.add(K.containerClass),M.style.setProperty("--persona-stream-step",`${L.speed}ms`),M.style.setProperty("--persona-stream-duration",`${L.duration}ms`));let T=ne?Hc(t.content??"",L.buffer,K,t,!!t.streaming):t.content??"",_=()=>{let he=e({text:T,message:t,streaming:!!t.streaming,raw:t.rawContent});return ne&&K?.wrap==="char"?Ea(he,"char",t.id,{skipTags:K.skipTags}):ne&&K?.wrap==="word"?Ea(he,"word",t.id,{skipTags:K.skipTags}):he},k=null;if(D?(k=document.createElement("div"),k.innerHTML=_(),k.style.display="none",M.appendChild(k)):t.contentSegments?.length?OE(M,t.contentSegments,he=>e({text:he,message:t,streaming:!!t.streaming,raw:t.rawContent}),i?.widgetConfig?.contextMentions?.renderMentionToken):M.innerHTML=_(),ne&&K?.useCaret&&!D&&N){let he=Rc(),W=M.querySelectorAll(".persona-stream-char, .persona-stream-word"),We=W[W.length-1];if(We?.parentNode)We.parentNode.insertBefore(he,We.nextSibling);else{let Fe=M.lastElementChild;Fe?Fe.appendChild(he):M.appendChild(he)}}if(m&&b==="inline"&&t.createdAt){let he=NC(t,g,"span");he.classList.add("persona-timestamp-inline");let W=M.lastElementChild;W?W.appendChild(he):M.appendChild(he)}if(I.length>0){let he=NE(I,!D&&!!N,()=>{D&&k&&(k.style.display="")});he?S.appendChild(he):D&&k&&(k.style.display="")}let Z=RE(t);if(Z.length>0){let he=FE(Z);he&&S.appendChild(he)}let F=WE(t);if(F.length>0){let he=UE(F);he&&S.appendChild(he)}let ie=BE(t);if(ie.length>0){let he=$E(ie);he&&S.appendChild(he)}let le=t.contentSegments?.length?null:DE(t.contextMentions);if(le&&S.appendChild(le),S.appendChild(M),m&&b==="below"&&t.createdAt){let he=NC(t,g);he.classList.add("persona-mt-1"),S.appendChild(he)}let pe=t.role==="assistant"?kE(t.stopReason,i?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let he=!!(T&&T.trim()),W=L.placeholder==="skeleton",We=W&&L.buffer==="line"&&he;if(he)We&&S.appendChild(Pa());else if(W)S.appendChild(Pa());else{let Fe=VE("inline",i?.loadingIndicatorRenderer,i?.widgetConfig);Fe&&S.appendChild(Fe)}}pe&&t.stopReason&&!t.streaming&&(N||(M.style.display="none"),S.appendChild(LE(t.stopReason,pe)));let ve=t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1,Ce=i?.actionEligibility,me=t.role==="user"&&!t.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&Ce?.canEdit===!0||o?.showQuote===!0&&Ce?.canQuote===!0||$C(o,"user").length>0);if((ve||me)&&o){let he=KE(t,me?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,s,Ce);S.appendChild(he)}if(!u||t.role==="system")return S;let vt=P("div",`persona-message-with-avatar persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),st=qE(d,t.role);return y==="right"||y==="left"&&t.role==="user"?vt.append(S,st):vt.append(st,S),vt};var GE=40,QE=(t,e)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}if(typeof e=="function"){let n=null;try{n=e()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){t.hidden=!0;return}t.appendChild(n),t.hidden=!1;return}if(e.type==="lucide"){let n=de(e.name,GE);if(!n){t.hidden=!0;return}t.appendChild(n)}else e.type==="image"?t.appendChild(G("img",{className:"persona-welcome-icon-image",attrs:{src:e.url,alt:e.alt}})):t.appendChild(G("span",{className:"persona-welcome-icon-text",text:e.text}));t.hidden=!1},VC=(t,e,n={})=>{let o=G("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let s=P("p","persona-welcome-kicker");s.hidden=!0;let i=P("h2","persona-welcome-title"),l=P("p","persona-welcome-subtitle"),c=G("div",{className:"persona-welcome-head-text"},s,i),d=G("div",{className:"persona-welcome-title-row"},o,c);return{host:G("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},d,l,e),iconHolder:o,kicker:s,title:i,subtitle:l,starterSuggestions:e}},Hi=(t,e,n)=>{e.hidden=!n,e.style.display=n?"":"none",t.classList.toggle("persona-gap-6",n),t.classList.toggle("persona-gap-3",!n)},Id=(t,e)=>{t.title.textContent=e.title,t.kicker.textContent=e.kicker??"",t.kicker.hidden=!e.kicker,t.subtitle.textContent=e.subtitle,t.subtitle.hidden=e.subtitle==="",QE(t.iconHolder,e.icon),t.host.setAttribute("data-persona-welcome-variant",e.variant),t.host.setAttribute("data-persona-welcome-dismiss",e.dismiss),t.host.setAttribute("data-persona-welcome-layout",e.layout??"top"),t.host.setAttribute("data-persona-welcome-anchor",e.anchor??"bottom"),e.iconPlacement==="inline"?t.host.setAttribute("data-persona-welcome-icon-placement","inline"):t.host.removeAttribute("data-persona-welcome-icon-placement"),e.align?t.host.setAttribute("data-persona-welcome-align",e.align):t.host.removeAttribute("data-persona-welcome-align")},YE="data-persona-welcome-plugin",qC="data-persona-welcome-overlay",Ld="persona-welcome-overlay-active",Yg=new WeakMap,Xg=(t,e,n)=>{n.setAttribute(YE,""),e.appendChild(n),e.setAttribute("data-persona-welcome-content","plugin"),e.setAttribute(qC,""),t.classList.contains(Ld)||(Yg.set(t,t.scrollTop),t.classList.add(Ld),t.scrollTop=0)},Jg=(t,e,n)=>{n&&n!==e&&n.remove(),e.removeAttribute("data-persona-welcome-content"),e.removeAttribute(qC),t.classList.contains(Ld)&&(t.classList.remove(Ld),t.scrollTop=Yg.get(t)??t.scrollTop,Yg.delete(t))},zC=()=>{let t=G("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return t.hidden=!0,t},Hd=(t,e,n)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",s=G("div",{className:sl("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:e,style:o==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});t.appendChild(G("div",{className:"persona-flex"},s)),t.hidden=!1},jC=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,KC=(t,e)=>{if(jC()||typeof t.animate!="function"||!t.isConnected)return e(null),null;let n=t.getBoundingClientRect(),o=t.parentElement,s=0,i=0,l=0;if(o){let C=getComputedStyle(o);s=parseFloat(C.rowGap)||0;let S=t.previousElementSibling,E=t.nextElementSibling,I=o.getBoundingClientRect().top+(parseFloat(C.borderTopWidth)||0)+(parseFloat(C.paddingTop)||0)-o.scrollTop;i=Math.max(0,S?n.top-S.getBoundingClientRect().bottom-s:n.top-I),l=Math.max(0,E?E.getBoundingClientRect().top-n.bottom-s:0)}let c=t.style.overflow;t.style.overflow="hidden";let d=getComputedStyle(t),g=parseFloat(d.paddingTop)||0,u=parseFloat(d.paddingBottom)||0,m=t.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${g}px`,paddingBottom:`${u}px`,marginTop:`${i}px`,marginBottom:`${l}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-s}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),y=!1,b=()=>{y||(y=!0,t.style.overflow=c,e(m))};return m.finished.then(b).catch(b),m},GC=(t,e,n,o=260)=>{if(e<=1||jC()||typeof t.animate!="function"||!t.isConnected)return null;let s=n==="drop"?-e:e;return t.animate([{transform:`translateY(${s}px)`},{transform:"none"}],{duration:o,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var XE="Hello \u{1F44B}",JE="I can answer questions and help you get things done here.",QC=new WeakSet,hn=(t,e)=>!!t&&t[e]!==void 0,ZE=(t,e)=>{!t||t.debug!==!0||!e.length||QC.has(t)||(QC.add(t),e.forEach(n=>console.warn(`[persona] ${n}`)))},Rd=(t,e=t?.launcher?.fullHeight===!0&&!t.launcher.sidebarMode&&t.launcher.mountMode!=="docked")=>{let n=t?.welcome,o=t?.copy,s=t?.future?.v5Defaults===!0,i=n?.layout??(s?"centered":"top"),l=hn(n,"variant")?n.variant:o?.showWelcomeCard===!1?"none":"card",c=l==="hero"&&!s&&n?.layout===void 0?"on-first-message":hn(n,"dismiss")?n.dismiss:s||l==="hero"?"on-first-message":"never",d=[];hn(n,"title")&&hn(o,"welcomeTitle")&&d.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),hn(n,"subtitle")&&hn(o,"welcomeSubtitle")&&d.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),hn(n,"variant")&&hn(o,"showWelcomeCard")&&d.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),l==="hero"&&hn(n,"message")&&d.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!s&&n?.layout===void 0&&l==="hero"&&hn(n,"dismiss")&&n.dismiss!=="on-first-message"&&d.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let g=n?.anchor??(i==="centered"&&e?"center":"bottom"),u=Ya(n?.anchorComposerTop)!==null;return hn(n,"anchorComposerTop")&&!u&&d.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),g!=="center"&&(hn(n,"anchorComposerTop")||hn(n,"composerGap"))&&d.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),ZE(t,d),{title:hn(n,"title")?n.title:o?.welcomeTitle??(s?"What can I help with?":XE),kicker:n?.kicker??"",subtitle:hn(n,"subtitle")?n.subtitle:o?.welcomeSubtitle??(s?"":JE),icon:n?.icon,align:n?.align==="start"||n?.align==="center"?n.align:i==="centered"?"center":void 0,iconPlacement:n?.icon&&typeof n.icon!="function"&&n.icon.placement==="inline"?"inline":"above",variant:l,dismiss:c,message:l==="hero"?void 0:n?.message,layout:i,anchor:g,anchorComposerTop:u?n.anchorComposerTop:"44%",composerGap:n?.composerGap?.trim()||wd}},YC=t=>(t??[]).some(e=>e.role==="user")?"active":"empty",Ri=(t,e)=>t.variant==="none"?!1:t.dismiss==="never"?!0:!(e??[]).some(n=>n.role==="user");var e0="var(--persona-components-panel-maxWidth)",XC="var(--persona-components-panel-height)",t0="var(--persona-components-panel-maxHeight)",Ws=t=>{let e=nr(t),n=e.launcherWidth?t?.launcher?.width:e.legacyLauncherWidth?t?.launcherWidth:void 0,o=t?.launcher?.heightOffset??0,s=o===0?`max(200px, ${XC})`:`max(200px, calc(${XC} - ${o}px))`;return{width:n??hb,maxWidth:n??e0,height:s,maxHeight:t0}},JC="16px",ef="10px",tf="14px",ZC=t=>{let e=t?.launcher?.enabled??!0,n=xt(t);if(el(t)){let g=t?.launcher?.composerBar??{},u=P("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=g.expandedSize??"anchored",u.style.zIndex=String(t?.launcher?.zIndex??ln);let m=P("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");m.style.width="100%",u.appendChild(m);let y=P("div","persona-widget-pill-root");return y.setAttribute("data-persona-composer-bar",""),y.dataset.state="collapsed",y.dataset.expandedSize=g.expandedSize??"anchored",y.style.zIndex=String(t?.launcher?.zIndex??ln),{wrapper:u,panel:m,pillRoot:y}}if(n){let g=P("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=P("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return g.appendChild(u),{wrapper:g,panel:u}}if(!e){let g=P("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=P("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),m=nr(t),b=m.launcherWidth||m.legacyLauncherWidth||t?.theme?.components?.panel?.width!==void 0?Ws(t).width:"100%";return g.style.width=b,u.style.width="100%",g.appendChild(u),{wrapper:g,panel:u}}let s=t?.launcher??{},i=s.position&&$n[s.position]?$n[s.position]:$n["bottom-right"],l=P("div",`persona-widget-wrapper persona-fixed ${i} persona-transition`);l.style.zIndex=String(t?.launcher?.zIndex??ln);let c=P("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=Ws(t);return c.style.width=d.width,c.style.maxWidth=d.maxWidth,l.appendChild(c),{wrapper:l,panel:c}},nf=t=>{let e=G("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":$g(t)}});return e.hidden=!0,e},ew=(t,e)=>{let n=nf("starter"),o=VC(t,n,{flatShadow:xt(t)}),s=Rd(t);Id(o,s),Hi(e,o.host,Ri(s,t?.initialMessages));let i=zC();return Hd(i,s.message,t),{welcome:o,greetingHost:i}},n0=(t,e)=>{let n=P("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:s}=Li(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:JC,iconSize:ef});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let i=t?.launcher?.clearChat?.enabled??!0,l=null,c=null;if(i){let $=Ii(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:JC,iconSize:tf});l=$.button,c=$.wrapper,c.style.position="absolute",c.style.top="8px",c.style.right="32px",c.style.zIndex="10"}let d=G("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),g=G("div",{className:"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",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});g.style.setProperty("scrollbar-gutter","stable");let{welcome:u,greetingHost:m}=ew(t,g),{host:y,title:b,subtitle:C}=u,S=u.starterSuggestions,E=P("div","persona-widget-messages persona-flex persona-flex-col");E.style.gap="var(--persona-components-message-gap, 12px)";let H=nf("followUp"),I=Ur(t,!0);I&&(E.style.maxWidth=I,E.style.marginLeft="auto",E.style.marginRight="auto",E.style.width="100%"),g.append(y,m,E,H);let N=G("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),x=Pd({config:t}),{root:D,textNode:L}=DC();return n.append(d,s,g,N),c&&n.appendChild(c),{container:n,body:g,messagesWrapper:E,starterSuggestions:S,transcriptSuggestions:H,composerOverlay:N,suggestions:x.suggestions,textarea:x.textarea,sendButton:x.sendButton,sendButtonWrapper:x.sendButtonWrapper,micButton:x.micButton,micButtonWrapper:x.micButtonWrapper,composerForm:x.composerForm,statusText:x.statusText,welcomeHost:y,welcomeIconHolder:u.iconHolder,greetingHost:m,introKicker:u.kicker,introTitle:b,introSubtitle:C,closeButton:o,closeButtonWrapper:s,clearChatButton:l,clearChatButtonWrapper:c,iconHolder:P("span"),headerTitle:P("span"),headerSubtitle:P("span"),header:d,footer:x.footer,attachmentButton:x.attachmentButton,attachmentButtonWrapper:x.attachmentButtonWrapper,attachmentInput:x.attachmentInput,attachmentPreviewsContainer:x.attachmentPreviewsContainer,actionsRow:x.actionsRow,leftActions:x.leftActions,rightActions:x.rightActions,setSendButtonMode:x.setSendButtonMode,peekBanner:D,peekTextNode:L}},tw=(t,e=!0)=>{if(el(t))return n0(t,e);let n=G("div",{className:"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",attrs:{"data-persona-theme-zone":"container"}}),o=t?.layout?.header,s=t?.layout?.showHeader!==!1,i=o?Ed(t,o,{showClose:e}):Rs({config:t,showClose:e}),l=G("div",{className:"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",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});l.style.setProperty("scrollbar-gutter","stable");let{welcome:c,greetingHost:d}=ew(t,l),{host:g,title:u,subtitle:m}=c,y=c.starterSuggestions,b=P("div","persona-widget-messages persona-flex persona-flex-col");b.style.gap="var(--persona-components-message-gap, 12px)";let C=nf("followUp"),S=Ur(t,!1);S&&(b.style.maxWidth=S,b.style.marginLeft="auto",b.style.marginRight="auto",b.style.width="100%"),l.append(g,d,b,C);let E=ol({config:t}),H=t?.layout?.showFooter!==!1;s?nl(n,i,t):(i.header.style.display="none",nl(n,i,t)),n.append(l);let I=G("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}});return H||(E.footer.style.display="none"),n.append(E.footer),n.append(I),{container:n,body:l,messagesWrapper:b,starterSuggestions:y,transcriptSuggestions:C,composerOverlay:I,suggestions:E.suggestions,textarea:E.textarea,sendButton:E.sendButton,sendButtonWrapper:E.sendButtonWrapper,micButton:E.micButton,micButtonWrapper:E.micButtonWrapper,composerForm:E.composerForm,statusText:E.statusText,welcomeHost:g,welcomeIconHolder:c.iconHolder,greetingHost:d,introKicker:c.kicker,introTitle:u,introSubtitle:m,closeButton:i.closeButton,closeButtonWrapper:i.closeButtonWrapper,clearChatButton:i.clearChatButton,clearChatButtonWrapper:i.clearChatButtonWrapper,iconHolder:i.iconHolder,headerTitle:i.headerTitle,headerSubtitle:i.headerSubtitle,header:i.header,footer:E.footer,attachmentButton:E.attachmentButton,attachmentButtonWrapper:E.attachmentButtonWrapper,attachmentInput:E.attachmentInput,attachmentPreviewsContainer:E.attachmentPreviewsContainer,actionsRow:E.actionsRow,leftActions:E.leftActions,rightActions:E.rightActions,setSendButtonMode:E.setSendButtonMode}};var of=(t,e)=>{let n=P("button");n.type="button",n.innerHTML=`
13
+ `),c=Array.isArray(e.contentParts)&&e.contentParts.length>0,u=s.contentParts.length>0;if(c){let p=[];i&&p.push(zo(i)),p.push(...s.contentParts),p.push(...e.contentParts),e.contentParts=p}else if(u){let p=[];l&&p.push(zo(l)),p.push(...s.contentParts),e.contentParts=p}else i&&(e.llmContent=l);Object.keys(s.context).length>0&&(e.mentionContext=s.context)}async sendMessage(e,n){let o=e.trim(),s=!!n?.replayFields&&(n.replayFields.llmContent!==void 0||n.replayFields.rawContent!==void 0||(n.replayFields.contextMentions?.length??0)>0);if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0)&&!s)return;this.#R&&!n?.voiceTurn&&(this.#R.failed=!0,this.#R=null),(this.#x||this.#b||this.#d||this.#S)&&await this.#Ie(),this.stopSpeaking(),this.abortController?.abort(),this.#J(),this.#q++,this.#ee();let i=n?.voiceTurn?.userMessageId,l=i?this.messages.find(C=>C.id===i&&C.role==="user"):void 0,c=l?.id??bl(),u=hs();this.#s=null;let p=n?.contentParts&&nf(n.contentParts)?Za:"",g={id:c,role:"user",content:o||p,createdAt:new Date().toISOString(),sequence:this.#M(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments},...n?.composerOptions&&{composerOptions:n.composerOptions},...n?.replayFields??{}};l?(l.viaVoice=!0,delete l.voiceCaption,l.content.trim()!==o&&(l.llmContent=o),this.callbacks.onMessagesChanged([...this.messages])):this.#B(g),this.#p(!0);let y=new AbortController;if(this.abortController=y,n?.mentions){let C=this.messages.find(E=>E.id===c)??g;if(await this.#Ge(C,o,n.mentions.finalize),y.signal.aborted||this.abortController!==y)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let C=this.messages.find(A=>A.id===c)??g,E=rh({quote:n.quote,text:C.llmContent??C.content,contentParts:C.contentParts});E.contentParts&&(C.contentParts=E.contentParts),E.llmContent!==void 0&&(C.llmContent=E.llmContent),(E.contentParts||E.llmContent!==void 0)&&(C.quote={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let h=l?[...this.messages.filter(C=>C!==l),{...l,createdAt:new Date().toISOString()}]:[...this.messages];try{await this.#je(h,y,u,c,{composerOptions:n?.composerOptions,interrupt:n?.interrupt})}catch(C){if(this.status==="resuming"||this.#r)return;this.#R&&(this.#R.failed=!0);let E=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!E){let A=jd(C,this.config.errorMessage);if(A){let I={id:u,role:"assistant",createdAt:new Date().toISOString(),content:A,sequence:this.#M()};this.#B(I)}}this.#P("idle"),this.#p(!1),this.abortController=null,E||(C instanceof Error?this.callbacks.onError?.(C):this.callbacks.onError?.(new Error(String(C))))}}resubmitFrom(e,n){let o=sh(this.messages,e);if(!o)return!1;let s=this.messages[o.start],i=n.replacement,l=i?i.text:s.content,c=i?i.contentParts:s.contentParts;if(!(!!l?.trim()||(c?.length??0)>0||!i&&(s.llmContent?.trim()?.length??0)>0))return!1;let p=i?void 0:{...s.llmContent!==void 0&&{llmContent:s.llmContent},...s.rawContent!==void 0&&{rawContent:s.rawContent},...s.mentionContext&&{mentionContext:s.mentionContext},...s.contextMentions&&{contextMentions:s.contextMentions},...s.quote&&{quote:s.quote}},g=i?this.#Ye(i.options):s.composerOptions,y=i?i.contentSegments:s.contentSegments,h=i?i.options?.quote:void 0,C=i?i.viaVoice:s.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,o.start),this.sendMessage(l??"",{...c?.length?{contentParts:[...c]}:{},...y?.length?{contentSegments:[...y]}:{},...g?{composerOptions:g}:{},...h?{quote:h}:{},...p&&Object.keys(p).length>0?{replayFields:p}:{},viaVoice:C===!0}),!0}#Ye(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n:void 0}async continueConversation(){if(this.streaming)return;(this.#x||this.#b||this.#d||this.#S)&&await this.#Ie(),this.abortController?.abort(),this.#ee();let e=hs();this.#s=null,this.#p(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:e},this.handleEvent)}catch(s){if(this.status==="resuming"||this.#r)return;let i=s instanceof Error&&(s.name==="AbortError"||s.message.includes("aborted")||s.message.includes("abort"));if(!i){let l=jd(s,this.config.errorMessage);if(l){let c={id:e,role:"assistant",createdAt:new Date().toISOString(),content:l,sequence:this.#M()};this.#B(c)}}this.#P("idle"),this.#p(!1),this.abortController=null,i||(s instanceof Error?this.callbacks.onError?.(s):this.callbacks.onError?.(new Error(String(s))))}}async connectStream(e,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.#s=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,s=!1;for(let i of this.messages)i.streaming&&i.id!==o&&(i.streaming=!1,s=!0);s&&this.callbacks.onMessagesChanged([...this.messages]),this.#p(!0);try{await this.client.processStream(e,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(i){if(this.status==="resuming"||this.#r)return;this.#P("error"),this.webMcpResolveControllers.size===0&&(this.#p(!1),this.abortController=null),this.callbacks.onError?.(i instanceof Error?i:new Error(String(i)))}}#He(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.#N}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.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(s=>{this.webMcpApprovalResolvers.set(o,s)})}resolveWebMcpApproval(e,n){let o=this.webMcpApprovalResolvers.get(e);if(!o)return;this.webMcpApprovalResolvers.delete(e);let s=this.messages.find(i=>i.id===e);s?.approval&&this.upsertMessage({...s,approval:{...s.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}#Qe;#q;#ue(e){let n=this.#Qe??={s:this,setStreaming:i=>this.#p(i),appendMessage:i=>this.#B(i),nextSequence:()=>this.#M(),settleApprovalPausedToolCall:i=>this.#Be(i),resumeAfter:i=>this.#t?.executionId===i?this.#t.lastEventId:void 0},o=oh();if(o)return e(o,n);let s=this.#q;return Nd().then(i=>s===this.#q?e(i,n):void 0,i=>{this.callbacks.onError?.(i instanceof Error?i:new Error(String(i)))})}resolveApproval(e,n,o){return this.#ue((s,i)=>s.resolveApproval(i,e,n,o))}resolveAskUserQuestion(e,n){return this.#ue((o,s)=>o.resolveAskUserQuestion(s,e,n))}resolveWebMcpToolCall(e){return this.#ue((n,o)=>n.resolveWebMcpToolCall(o,e))}persistAskUserQuestionProgress(e,n){let o=this.messages.find(s=>s.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(e,n){let o=this.messages.find(s=>s.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}#Xe(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.id;if(!n||!o){let i=this.#v;queueMicrotask(()=>{i===this.#v&&this.resolveWebMcpToolCall(e)});return}let s=this.webMcpAwaitBatches.get(n);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,s)),!s.seen.has(o)&&(s.seen.add(o),s.snapshots.push(e))}#Je(){if(this.webMcpAwaitBatches.size===0)return;let e=this.#v;queueMicrotask(()=>{if(e===this.#v)for(let n of[...this.webMcpAwaitBatches.keys()])this.#Ze(n)})}#Ze(e){let n=this.webMcpAwaitBatches.get(e);if(!n)return;this.webMcpAwaitBatches.delete(e);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.#ue((s,i)=>s.resolveWebMcpToolCallBatch(i,e,o))}#J(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.#v++}cancel(){this.abortController?.abort(),this.abortController=null,this.#ee(),this.#J(),this.#q++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#p(!1),this.#P("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#ee(),this.#J(),this.#q++,this.messages=[],this.agentExecution=null,this.#Ce(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#p(!1),this.#P("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.#u}selectArtifact(e){this.#u=e,this.#Z()}clearArtifacts(){this.#Ce()}upsertArtifact(e){let n=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=e.artifactType==="markdown"?{id:n,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(n,o),this.#u=n,this.#Z(),e.transcript!==!1&&this.#et(o),o}#et(e){let n=`artifact-ref-${e.id}`,o=as(this.config.features?.artifacts,e),s=wd(o,{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:"complete",...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}),i=this.messages.find(l=>l.id===n);if(i){i.rawContent=s,i.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:s})}#Re(){let e=!1;for(let n of this.artifacts.values()){let o=this.messages.find(l=>l.id===`artifact-ref-${n.id}`);if(!o)continue;let s=as(this.config.features?.artifacts,n),i=wd(s,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==i&&(o.rawContent=i,o.streaming=n.status==="streaming",e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}#Ce(){this.artifacts.size===0&&this.#u===null||(this.artifacts.clear(),this.#u=null,this.#Z())}#Z(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#u})}#tt(e){switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:"",...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:e.component??"",props:{}}),this.#u=e.id;break}case"artifact_delta":{let n=this.artifacts.get(e.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+e.artDelta);break}case"artifact_update":{let n=this.artifacts.get(e.id);n?.artifactType==="component"&&(n.props={...n.props,...e.props},e.component&&(n.component=e.component));break}case"artifact_complete":{let n=this.artifacts.get(e.id);n&&(n.status="complete");break}default:return}this.#Z()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.#ee(),this.#J(),this.#q++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#j(e.map(n=>({...n,streaming:!1,sequence:n.sequence??this.#M()}))),this.#p(!1),this.#P("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,n=null){this.artifacts.clear();for(let o of e)this.artifacts.set(o.id,{...o,status:"complete"});this.#u=n,this.#Z()}#nt(e){let n=this.agentExecution?.executionId;if(!n||!this.#s||this.agentExecution?.status!=="running")return;let o=this.#t===null;this.#t={executionId:n,lastEventId:e,assistantMessageId:this.#s,status:"running"},this.#at(o)}#ot(){return this.#t!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.#We()}#We(){return this.messages.some(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant==="approval"&&e.approval?.status==="pending")}#we(){this.#r||!this.#t||typeof this.config.reconnectStream!="function"||(this.#r=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.#t}),this.#p(!0),this.#P("resuming"),this.#rt().then(e=>{this.#r&&this.#t&&e.begin()}))}#rt(){return this.#a?Promise.resolve(this.#a):(this.#f||(this.#f=dh().then(({createReconnectController:e})=>{let n=e(this.#st());return this.#a=n,n}),this.#f.catch(()=>{this.#f=null})),this.#f)}#st(){let e=this;return{get config(){return e.config},getResumable:()=>e.#t,clearResumable:()=>e.#ge(),getStatus:()=>e.status,setStatus:n=>e.#P(n),setStreaming:n=>e.#p(n),setReconnecting:n=>{e.#r=n},setAbortController:n=>{e.abortController=n},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(n,o,s)=>e.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:s}),appendMessage:n=>e.#B(n),nextSequence:()=>e.#M(),emitReconnect:n=>e.callbacks.onReconnect?.(n),buildErrorContent:n=>jd(new Error(n),e.config.errorMessage),onError:n=>e.callbacks.onError?.(n)}}reconnectNow(){if(this.#r){this.#a?.wake();return}this.#we()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.#r)return;let n=this.#it();n||(n=hs(),this.#B({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.#M()})),this.#s=n,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.#t={executionId:e.executionId,lastEventId:e.after,assistantMessageId:n,status:"running"},this.#we()}#it(){for(let e=this.messages.length-1;e>=0;e--){let n=this.messages[e];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}#ee(){this.#r=!1,this.#a?.teardown(),this.#ge()}#ge(){this.#i&&(clearTimeout(this.#i),this.#i=null);let e=this.#t!==null;this.#t=null,e&&this.config.onExecutionState?.(null)}#at(e){let n=this.config.onExecutionState;if(n){if(e){this.#i&&(clearTimeout(this.#i),this.#i=null),n(this.#t);return}this.#i||(this.#i=setTimeout(()=>{this.#i=null,this.config.onExecutionState?.(this.#t)},500))}}getResumableHandle(){return this.#t}#P(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}#p(e){if(this.streaming===e)return;let n=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),n&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(e){let n=this.config.textToSpeech;if(!n?.enabled||!(!n.provider||n.provider==="browser"||n.provider==="runtype"&&n.browserFallback))return;let s=[...this.messages].reverse().find(l=>l.role==="assistant"&&l.content&&!l.voiceProcessing);if(!s||e&&!e.includes(s.id))return;if(this.ttsSpokenMessageIds.has(s.id)){this.ttsSpokenMessageIds.delete(s.id);return}let i=Ud(s.content);i.trim()&&this.readAloud.play(s.id,{text:i,voice:n.voice,rate:n.rate,pitch:n.pitch})}static pickBestVoice(e){return zd(e)}toggleReadAloud(e){let n=this.messages.find(i=>i.id===e);if(!n||n.role!=="assistant")return;let o=Ud(n.content||"");if(!o.trim())return;let s=this.config.textToSpeech;this.readAloud.toggle(e,{text:o,voice:s?.voice,rate:s?.rate,pitch:s?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}#Be(e){let n=this.messages.find(c=>c.id===e)?.approval,o=n?.toolCallId,s=o&&this.messages.find(c=>c.toolCall?.id===o),i=s&&s.toolCall;if(!i||i.status==="complete"||n.status==="pending")return;let l={...i,status:"complete",approvalStatus:n.status,completedAt:Date.now(),...n.status==="approved"?{superseded:!0}:{success:!1,error:n.status==="denied"?"Denied":"Approval timed out"}};this.upsertMessage({...s,streaming:!1,toolCall:l})}#B(e){let n=this.#oe(e);this.messages=this.#j([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let n=this.#oe(e),o=this.messages.findIndex(s=>s.id===n.id);if(o===-1){this.#B(n);return}this.messages=this.messages.map((s,i)=>{if(i!==o)return s;let l={...s,...n};s.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(l.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),s.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(l.agentMetadata={...l.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let c=s.agentMetadata?.clientToolAnswer;if(c&&l.agentMetadata&&!l.agentMetadata.clientToolAnswer&&(l.agentMetadata={...l.agentMetadata,clientToolAnswer:c}),s.approval&&n.approval&&s.approval.id===n.approval.id){let y=s.approval,h=n.approval;l.approval={...y,...h,executionId:h.executionId||y.executionId,toolName:h.toolName||y.toolName,description:h.description||y.description,toolType:h.toolType??y.toolType,reason:h.reason??y.reason,parameters:h.parameters??y.parameters,toolCallId:h.toolCallId??y.toolCallId}}let u=n.toolCall?.name,p=n.agentMetadata?.executionId,g=n.toolCall?.id;if(u&&ph(u)&&p&&g&&n.agentMetadata?.awaitingLocalTool===!0){let y=`${p}:${g}`,h=this.webMcpInflightKeys.has(y),C=this.webMcpResolvedKeys.has(y),E=s.toolCall?.name,A=s.agentMetadata?.executionId===p&&s.toolCall?.id===g&&E!==void 0&&ph(E)&&s.toolCall?.status==="complete";(h||C||A)&&(l.agentMetadata={...l.agentMetadata??{},awaitingLocalTool:!1},l.toolCall=s.toolCall,l.streaming=s.streaming)}return l}),this.messages=this.#j(this.messages),this.callbacks.onMessagesChanged([...this.messages])}#oe(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.#M()}}#M(){return this.#e++}#j(e){return[...e].sort((n,o)=>{let s=new Date(n.createdAt).getTime(),i=new Date(o.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(i)&&s!==i)return s-i;let l=n.sequence??0,c=o.sequence??0;return l!==c?l-c:n.id.localeCompare(o.id)})}};import{File as nw,FileCode as ow,FileSpreadsheet as rw,FileText as Kd,X as sw}from"lucide";var iw={add:t=>of(t)},aw=t=>Number.isFinite(t)?Math.min(1,Math.max(0,t)):0,xl={allowedTypes:us,maxFileSize:10*1024*1024,maxFiles:4};function lw(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function cw(t){return t==="application/pdf"?Kd:t.startsWith("text/")?Kd:t.includes("word")?Kd:t.includes("excel")||t.includes("spreadsheet")?rw:t==="application/json"?ow:nw}var xi=class t{constructor(e={}){this.attachments=[];this.#e=null;this.#t=new Map;this.#s=!1;this.config={allowedTypes:e.allowedTypes??xl.allowedTypes,maxFileSize:e.maxFileSize??xl.maxFileSize,maxFiles:e.maxFiles??xl.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}#e;#t;#s;#r(){return typeof this.config.adapter?.add=="function"}#a(){return this.#r()?this.config.adapter:iw}setPreviewsContainer(e){this.#e=e}remountPreviews(e){if(this.#e=e,e){e.innerHTML="";for(let n of this.attachments)this.#N(n)}this.#h()}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:xl.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange),e.adapter!==void 0&&(this.config.adapter=e.adapter)}isReady(){return this.attachments.every(e=>e.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart).filter(e=>e!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){if(!e.length||this.#s)return;let n=[];for(let o of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let s=rf(o,this.config.allowedTypes,this.config.maxFileSize);if(!s.valid){let l=s.error?.includes("type")?"type":"size";this.config.onFileRejected?.(o,l);continue}let i={id:lw(),file:o,previewUrl:Ed(o)?URL.createObjectURL(o):null,contentPart:null,status:this.#r()?"uploading":"processing",progress:this.#r()?0:void 0};this.attachments.push(i),this.#N(i),n.push(i)}this.#h(),this.#v(),await Promise.all(n.map(o=>this.#f(o)))}async#f(e){let n=new AbortController;this.#t.set(e.id,n);let o=()=>this.#s||n.signal.aborted||this.#t.get(e.id)!==n||!this.attachments.includes(e);try{let s=await this.#a().add(e.file,{signal:n.signal,onProgress:i=>{o()||e.status!=="uploading"||(e.progress=aw(i),this.#n(e),this.#v())}});if(o())return;e.contentPart=s,e.status="ready",e.progress=void 0,e.error=void 0}catch(s){if(o())return;e.status="error",e.progress=void 0,e.error=s instanceof Error?s.message:String(s??"Upload failed")}finally{this.#t.get(e.id)===n&&this.#t.delete(e.id)}this.#n(e),this.#v()}retryAttachment(e){let n=this.attachments.find(o=>o.id===e);!n||n.status!=="error"||this.#s||(n.status=this.#r()?"uploading":"processing",n.progress=this.#r()?0:void 0,n.error=void 0,this.#n(n),this.#v(),this.#f(n))}#i(e){let n=this.#t.get(e);n&&(this.#t.delete(e),n.abort())}removeAttachment(e){let n=this.attachments.findIndex(i=>i.id===e);if(n===-1)return;let o=this.attachments[n];this.#i(e),o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let s=this.#e?.querySelector(`[data-attachment-id="${e}"]`);s&&s.remove(),o.status==="ready"&&o.contentPart&&this.#u(o.contentPart),this.#h(),this.#v()}#u(e){let n=this.config.adapter?.remove;if(n)try{let o=n(e,{signal:new AbortController().signal});o&&typeof o.catch=="function"&&o.catch(s=>{console.error("[AttachmentManager] adapter.remove failed:",s)})}catch(o){console.error("[AttachmentManager] adapter.remove failed:",o)}}clearAttachments(){for(let e of this.attachments)this.#i(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#t.clear(),this.#e&&(this.#e.innerHTML=""),this.#h(),this.#v()}destroy(){if(!this.#s){this.#s=!0;for(let e of this.#t.values())e.abort();this.#t.clear();for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#e=null}}#v(){this.#s||this.config.onAttachmentsChange?.(this.getAttachments())}#N(e){if(!this.#e)return;let n=Ed(e.file),o=P("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",e.id),o.style.width="48px",o.style.height="48px",n&&e.previewUrl){let g=P("img");g.src=e.previewUrl,g.alt=e.file.name,g.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",g.style.width="48px",g.style.height="48px",g.style.objectFit="cover",g.style.borderRadius="8px",o.appendChild(g)}else{let g=P("div");g.style.width="48px",g.style.height="48px",g.style.borderRadius="8px",g.style.backgroundColor="var(--persona-container, #f3f4f6)",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.display="flex",g.style.flexDirection="column",g.style.alignItems="center",g.style.justifyContent="center",g.style.gap="2px",g.style.overflow="hidden";let y=cw(e.file.type),h=yt(y,20,"var(--persona-muted, #6b7280)",1.5);h&&g.appendChild(h);let C=P("span");C.textContent=sf(e.file.type,e.file.name),C.style.fontSize="8px",C.style.fontWeight="600",C.style.color="var(--persona-muted, #6b7280)",C.style.textTransform="uppercase",C.style.lineHeight="1",g.appendChild(C),o.appendChild(g)}let s=Y("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),i=P("div","persona-attachment-progress");i.appendChild(P("div","persona-attachment-progress__bar"));let l=Y("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),c=se("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);c?l.appendChild(c):l.textContent="\u21BB",l.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),this.retryAttachment(e.id)}),s.append(i,l),o.appendChild(s);let u=P("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");u.type="button",u.setAttribute("aria-label","Remove attachment"),u.style.position="absolute",u.style.top="-4px",u.style.insetInlineEnd="-4px",u.style.width="18px",u.style.height="18px",u.style.borderRadius="50%",u.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",u.style.border="none",u.style.cursor="pointer",u.style.display="flex",u.style.alignItems="center",u.style.justifyContent="center",u.style.padding="0";let p=yt(sw,10,"var(--persona-text-inverse, #ffffff)",2);p?u.appendChild(p):(u.textContent="\xD7",u.style.color="var(--persona-text-inverse, #ffffff)",u.style.fontSize="14px",u.style.lineHeight="1"),u.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(u),this.#e.appendChild(o),this.#l(o,e)}#n(e){let n=this.#e?.querySelector(`[data-attachment-id="${e.id}"]`);n&&this.#l(n,e)}#l(e,n){e.dataset.status=n.status;let o=n.status!=="ready"&&n.status!=="error";e.setAttribute("aria-busy",o?"true":"false"),e.title=n.status==="error"?`${n.file.name}: ${n.error??"Upload failed"}`:n.file.name;let s=e.querySelector(".persona-attachment-progress__bar");if(s){let i=n.progress;s.style.width=typeof i=="number"?`${Math.round(i*100)}%`:""}}#h(){this.#e&&(this.#e.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,n){return new t({allowedTypes:e?.allowedTypes,maxFileSize:e?.maxFileSize,maxFiles:e?.maxFiles,onFileRejected:e?.onFileRejected,onAttachmentsChange:n,adapter:e?.adapter})}};var uh=(t,e)=>t.length===e.length&&t.every((n,o)=>n===e[o]),dw=(t,e)=>t.length===e.length&&t.every((n,o)=>{let s=e[o];return n.id===s.id&&n.name===s.name&&n.mimeType===s.mimeType&&n.size===s.size&&n.status===s.status&&n.progress===s.progress&&n.error===s.error});function gh(){let t={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},e=new Set,n=null,o=!1,s=!1,i=()=>t.preparing?"preparing":t.streaming?"streaming":"idle",l=()=>{let g=i();return Object.freeze({text:t.text,attachments:Object.freeze(t.attachments.map(y=>Object.freeze({...y}))),mentionRefs:Object.freeze([...t.mentionRefs]),selectedModelId:t.selectedModelId,activeModeIds:Object.freeze([...t.activeModeIds]),quote:t.quote?Object.freeze({...t.quote}):void 0,pendingSubmission:t.pendingSubmission,phase:g,inputDisabled:t.inputDisabled,sendDisabled:g!=="idle"||t.sendDisabled||t.inputDisabled})},c=()=>(n||(n=l()),n),u=()=>{if(o=!1,s||e.size===0)return;let g=c();for(let y of[...e])try{y(g)}catch(h){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",h)}},p=()=>{n=null,!(s||o)&&(o=!0,queueMicrotask(u))};return{getState:c,subscribe:g=>(e.add(g),()=>e.delete(g)),setText:g=>{t.text!==g&&(t.text=g,p())},setAttachments:g=>{dw(t.attachments,g)||(t.attachments=[...g],p())},setMentionRefs:g=>{uh(t.mentionRefs,g)||(t.mentionRefs=[...g],p())},setSelectedModelId:g=>{t.selectedModelId!==g&&(t.selectedModelId=g,p())},setActiveModeIds:g=>{uh(t.activeModeIds,g)||(t.activeModeIds=[...g],p())},setQuote:g=>{let y=t.quote;y?.text===g?.text&&y?.messageId===g?.messageId&&y?.sourceLabel===g?.sourceLabel||(t.quote=g?{...g}:void 0,p())},setPendingSubmission:g=>{t.pendingSubmission!==g&&(t.pendingSubmission=g,p())},setPreparing:g=>{t.preparing!==g&&(t.preparing=g,p())},setStreaming:g=>{t.streaming!==g&&(t.streaming=g,p())},setInputDisabled:g=>{t.inputDisabled!==g&&(t.inputDisabled=g,p())},setSendDisabled:g=>{t.sendDisabled!==g&&(t.sendDisabled=g,p())},flush:()=>{o&&u()},destroy:()=>{s=!0,o=!1,e.clear()}}}var Qt=(t,...e)=>{for(let n of e){let o=t.querySelector(n);if(o)return o}return null},mh=(t,e)=>{let n=P("div",t);return n.setAttribute(e,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function fh(t,e={}){let n=Qt(t,"[data-persona-composer-form]"),o=Qt(t,"[data-persona-composer-input]");if(!n||!o){let L=`[Persona] composer surface is missing required element(s): ${[!n&&"form",!o&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(e.debug&&(n||o))throw new Error(L);return typeof console<"u"&&console.warn(L),null}let s={header:Qt(t,"[data-persona-composer-header]"),body:Qt(t,"[data-persona-composer-body]"),actionsStart:Qt(t,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Qt(t,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Qt(t,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Qt(t,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Qt(t,"[data-persona-composer-status]")},i=new Set,l=s.header;l||(i.add("header"),l=mh("persona-widget-composer__header","data-persona-composer-header"),n.parentNode?n.parentNode.insertBefore(l,n):t.appendChild(l));let c=s.body??o.parentElement??n,u=(I,L,k,R,B)=>{if(L)return L;i.add(I);let O=mh(k,R);return B.appendChild(O),O},p=u("actionsStart",s.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),g=u("actionsEnd",s.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),y=u("suggestions",s.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",t),h=u("status",s.status,"persona-widget-composer__status","data-persona-composer-status",t),C=[],E=(I,L)=>I.target===L.target&&I.type===L.type&&I.handler===L.handler,A=Qt(t,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:t,form:n,input:o,header:l,body:c,actionsStart:p,actionsEnd:g,suggestions:y,status:h,attachmentInput:A,attachmentPreviews:Qt(t,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Qt(t,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Qt(t,"[data-persona-composer-submit]")??void 0,micButton:Qt(t,"[data-persona-composer-mic]")??void 0,synthesized:i,found:s,addListener:(I,L,k,R)=>{I.addEventListener(L,k,R),C.push({target:I,type:L,handler:k,options:R})},removeListener:(I,L,k,R)=>{I.removeEventListener(L,k,R),C=C.filter(B=>!E(B,{target:I,type:L,handler:k}))},destroy:()=>{for(let I of C)I.target.removeEventListener(I.type,I.handler,I.options);C=[]}}}var pw='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',uw=["--persona-components-composer-overflowMenu-background","--persona-components-composer-overflowMenu-borderColor","--persona-components-composer-overflowMenu-borderRadius","--persona-components-composer-overflowMenu-foreground","--persona-components-composer-overflowMenu-shadow"],Gd="data-persona-menu-focus",gw=new Set(["ArrowDown","ArrowUp","Home","End"]);function hh(t){return t.getAttribute("role")==="menuitem"?t:t.querySelector(pw)??t}var mw=t=>t.disabled===!0||t.getAttribute("aria-disabled")==="true";function yh(t){let e=t.label,n=!1,o=P("div","persona-send-button-wrapper"),s=Y("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Uo} ${Mr}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(s);let i=Y("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),l=()=>{let x=t.getButtonSize?.()??"";s.style.width=x,s.style.height=x,s.style.minWidth=x,s.style.minHeight=x,s.style.lineHeight="1",s.replaceChildren();let z=se("plus",qn,"currentColor",1.5);z?s.appendChild(z):s.textContent="+"},c=()=>{s.setAttribute("aria-label",e),s.setAttribute("title",e),i.setAttribute("aria-label",e)};c(),l();let u=[],p=-1,g=!1,y=()=>{let z=i.getRootNode().activeElement;return z instanceof HTMLElement?z:null},h=()=>{let x=y();for(let z of u){let W=!!x&&hh(z)===x;z.toggleAttribute(Gd,W&&g)}},C=()=>u.filter(x=>x.isConnected||i.contains(x)).map(hh).filter(x=>!mw(x)),E=(x,z)=>{x.forEach((W,ee)=>{W.setAttribute("tabindex",ee===z?"0":"-1")})},A=x=>{let z=C();if(z.length===0)return;let W=(x%z.length+z.length)%z.length;p=W,E(z,W),z[W].focus(),h()},I=()=>o.ownerDocument??document,L=null,k=null,R=null,B=()=>{L&&(I().removeEventListener("focusin",L,!0),L=null)},O=()=>{k&&(i.removeEventListener("focusin",k),k=null),R&&(i.removeEventListener("pointerdown",R,!0),R=null)},V=null,J=()=>(V||(V=ll({anchor:s,content:i,placement:"top-start",offset:6,onDismiss:()=>{s.setAttribute("aria-expanded","false"),B()}})),V),_=()=>V?.isOpen===!0,Q=(x=!1)=>{if(_()){V?.close(),s.setAttribute("aria-expanded","false"),B(),O(),p=-1,g=!1;for(let z of u)z.removeAttribute(Gd);x&&s.focus()}},G=(x=0,z=!1)=>{if(n||_())return;g=z,tl(s,i,uw),J().open(),s.setAttribute("aria-expanded","true");let W=C();E(W,-1),A(x<0?W.length-1:x),L=ee=>{let ne=typeof ee.composedPath=="function"?ee.composedPath():[];ne.includes(i)||ne.includes(o)||Q()},I().addEventListener("focusin",L,!0),k=()=>h(),i.addEventListener("focusin",k),R=()=>{g=!1},i.addEventListener("pointerdown",R,!0)},w=x=>{x.preventDefault(),x.stopPropagation(),_()?Q(!0):G(0)},v=x=>{if(x.key==="ArrowDown"||x.key==="Enter"||x.key===" "){x.preventDefault(),g=!0,_()?A(0):G(0,!0);return}x.key==="ArrowUp"&&(x.preventDefault(),g=!0,_()?A(-1):G(-1,!0))},T=x=>{switch(gw.has(x.key)&&(g=!0),x.key){case"ArrowDown":x.preventDefault(),A(p+1);return;case"ArrowUp":x.preventDefault(),A(p-1);return;case"Home":x.preventDefault(),A(0);return;case"End":x.preventDefault(),A(C().length-1);return;case"Escape":x.preventDefault(),x.stopPropagation(),Q(!0);return;case"Tab":Q(!0);return;default:}};return s.addEventListener("click",w),s.addEventListener("keydown",v),i.addEventListener("keydown",T),{trigger:o,triggerButton:s,panel:i,setItems:x=>{for(let W of u)x.includes(W)||W.removeAttribute(Gd);if(u=[...x],!_())return;let z=C();E(z,Math.min(p,z.length-1)),h()},isOpen:_,open:()=>G(0),close:Q,setLabel:x=>{x!==e&&(e=x,c())},applyButtonSize:l,destroy:()=>{n=!0,B(),O(),s.removeEventListener("click",w),s.removeEventListener("keydown",v),i.removeEventListener("keydown",T),V?.destroy(),V=null,o.remove(),i.remove(),u=[]}}}var Kn={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},bh="data-persona-composer-action",Yd="data-persona-composer-disable-when-streaming",fw="core:overflow",hw=t=>t==="core:attachment"?"attachments":t.startsWith("core:mention")?"mentions":null;function yw(t,e){if(t===void 0)return null;if(typeof t=="number")return Number.isFinite(t)?t:null;let n=Number.parseFloat(t);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(t)&&Number.isFinite(n))return n;let o=P("div");o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.height="0",o.style.width=t,e.appendChild(o);let s=o.getBoundingClientRect().width;return o.remove(),Number.isFinite(s)&&s>0?s:Number.isFinite(n)?n:null}function Qd(t){let e=t.clientWidth;if(!e)return 0;let n=t.ownerDocument?.defaultView;if(!n?.getComputedStyle)return e;let o=n.getComputedStyle(t),s=(Number.parseFloat(o.paddingLeft)||0)+(Number.parseFloat(o.paddingRight)||0);return Math.max(0,e-s)}var vh=(t,e)=>{!t||typeof console>"u"||console.warn(e)},bw=(t,e)=>e.includes(":")?e:`${t}:${e}`;function vw(t){let{debug:e}=t,n=[],o=new Map,s=0,i=c=>{let u=o.get(c.id);if(u){vh(e,`[Persona] composer action "${c.id}" is already contributed by ${Ch(u)}; the ${Ch(c)} copy is ignored.`);return}o.set(c.id,c),n.push(c)};for(let c of t.builtIns)i({id:c.id,placement:c.placement,presentation:"bar",order:c.order,sequence:s++,source:"core",builtIn:c});let l=(c,u,p)=>{let g=p?bw(p,c.id):c.id,y=c.order??Kn.custom;c.placement==="end"&&y>=Kn.send&&(vh(e,`[Persona] composer action "${g}" ordered at ${y} would render after send; clamped to ${Kn.send-1}.`),y=Kn.send-1),i({id:g,placement:c.placement,presentation:c.presentation??"bar",order:y,sequence:s++,source:u,pluginId:p,action:c})};for(let c of t.configActions??[])l(c,"config");for(let c of t.plugins){if(!c.contributeComposerActions)continue;let u;try{u=c.contributeComposerActions(t.contributionContext)}catch(p){typeof console<"u"&&console.error(`[Persona] plugin "${c.id}" contributeComposerActions failed:`,p);continue}for(let p of u??[])l(p,"plugin",c.id)}return n.sort((c,u)=>c.order===u.order?c.sequence-u.sequence:c.order-u.order)}var Ch=t=>t.source==="plugin"?`plugin "${t.pluginId}"`:t.source==="config"?"composer.actions":"a core built-in",wh=(t,e,n)=>t===void 0?n:typeof t=="function"?t(e)===!0:t===!0,Cw=t=>t.phase==="streaming"||t.text.trim().length>0||t.attachments.length>0;function ww(t,e){if(!t||t==="always")return!0;let n=Cw(e);return t==="when-text"?n:!n}var jo=t=>t.kind==="custom",Xd=t=>t instanceof HTMLButtonElement?t:t.querySelector("button")??t,Sw=t=>{let e=Xd(t);return e.getAttribute("aria-label")?.trim()||e.getAttribute("title")?.trim()||""},xw='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function Aw(t){let e="",n=o=>{if(o.nodeType===Node.TEXT_NODE){e+=o.nodeValue??"";return}if(o.nodeType!==Node.ELEMENT_NODE)return;let s=o;typeof s.matches=="function"&&s.matches(xw)||o.childNodes.forEach(n)};return n(t),e.trim()}var Mw=t=>Aw(t).length===0;function Sh(t){let e=new Map,n=[],o=!1,s=()=>t.getButtonSize?.(),i=(w,v)=>{let T=w.button;if(!T)return;T.setAttribute("role","menuitem"),T.setAttribute("tabindex","-1"),T.className="persona-composer-overflow-menu__item";for(let W of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])T.style[W]="";T.style.lineHeight="1",v.tooltipText?T.setAttribute("title",v.tooltipText):T.removeAttribute("title"),T.replaceChildren();let x=P("span","persona-composer-overflow-menu__icon");if(v.iconName){let W=se(v.iconName,16,"currentColor",1.5);W&&x.appendChild(W)}let z=P("span","persona-composer-overflow-menu__label");z.textContent=v.shortLabel??v.label,T.append(x,z)},l=(w,v)=>{let T=w.button;if(!T)return;if(T.setAttribute("aria-label",v.label),v.pressed===void 0?T.removeAttribute("aria-pressed"):T.setAttribute("aria-pressed",v.pressed?"true":"false"),T.toggleAttribute(Yd,v.disableWhenStreaming===!0),w.mode==="menu"){w.tooltip?.destroy(),w.tooltip=void 0,i(w,v);return}T.removeAttribute("role"),T.removeAttribute("tabindex"),T.removeAttribute("title");let x=s(),z=!!v.shortLabel;if(T.className=ss("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Uo,Mr,z&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),T.style.width=x&&!z?x:"",T.style.height=x??"",T.style.minWidth=x&&!z?x:"",T.style.minHeight=x??"",T.style.fontSize=z?"":"18px",T.style.lineHeight="1",T.style.color=v.iconColor??"",T.style.backgroundColor=v.backgroundColor??"",T.replaceChildren(),v.iconName){let W=se(v.iconName,qn,"currentColor",1.5);W&&T.appendChild(W)}if(z){let W=P("span","persona-composer-action-button__label");W.textContent=v.shortLabel,T.appendChild(W)}else T.firstChild||(T.textContent=v.label);w.tooltip?.destroy(),w.tooltip=vn({anchor:T,trigger:w.element,text:()=>v.tooltipText??v.label,enabled:!!v.tooltipText})},c=(w,v)=>{let T=w.action,x=Y("button",{attrs:{type:"button"}}),z=x;if(v==="bar"){let ne=P("div","persona-send-button-wrapper");ne.appendChild(x),z=ne}z.setAttribute(bh,w.id);let W={resolved:w,element:z,button:x,owned:!0,managed:!0,busy:!1,visible:!0,mode:v},ee=ne=>{if(ne.preventDefault(),ne.stopPropagation(),W.busy||x.disabled)return;let he=W.resolved.action;W.mode==="menu"&&C?.close(!0);let ve;try{ve=he.onSelect(t.actionContext,ne)}catch(Xe){t.reportError(Xe,{actionId:W.resolved.id});return}!ve||typeof ve.then!="function"||(W.busy=!0,x.setAttribute("aria-busy","true"),ve.catch(Xe=>{t.reportError(Xe,{actionId:W.resolved.id})}).finally(()=>{W.busy=!1,x.removeAttribute("aria-busy")}))};return x.addEventListener("click",ee),W.detach=()=>x.removeEventListener("click",ee),l(W,T),W},u=w=>{let v=w.action,T;try{T=v.render({...t.actionContext,id:w.id,action:v})}catch(x){return t.reportError(x,{actionId:w.id}),null}return T?.element?(T.element.setAttribute(bh,w.id),T.element.toggleAttribute(Yd,v.disableWhenStreaming===!0),{resolved:w,element:T.element,owned:!0,managed:!0,destroy:T.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(w,v)=>{if(w.builtIn){let x=w.builtIn.element;return x?{resolved:w,element:x,owned:!1,managed:w.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let T=w.action;return T?jo(T)?u(w):c(w,v):null},g=w=>{if(w.detach?.(),w.tooltip?.destroy(),w.detachMenuSlot?.(),w.detachMenuSlot=void 0,w.menuLabel?.remove(),w.menuLabel=void 0,w.menuSlot?.remove(),w.menuSlot=void 0,w.owned){try{w.destroy?.()}catch(v){t.reportError(v,{actionId:w.resolved.id})}w.element.remove()}},y=(w,v)=>{for(let T=0;T<v.length;T++){let x=v[T];if(!x.managed)continue;let z=null;for(let W=T+1;W<v.length;W++){let ee=v[W];if(!ee.managed&&ee.element.parentElement===w){z=ee.element;break}}z?(x.element.parentElement!==w||x.element.nextSibling!==z)&&w.insertBefore(x.element,z):w.lastChild!==x.element&&w.appendChild(x.element)}},h=(w,v)=>{if(w.button){w.button.disabled=v;return}if(!w.owned)return;let T=w.element;T.toggleAttribute("data-disabled",v),T.setAttribute("aria-disabled",v?"true":"false");let x=T instanceof HTMLButtonElement||T instanceof HTMLSelectElement||T instanceof HTMLInputElement||T instanceof HTMLTextAreaElement?T:T.querySelector("button, select, input, textarea");x&&(x.disabled=v)},C=null,E=null,A=null,I=0,L=()=>{let w=t.getOverflow?.();return w?.enabled===!0?w:void 0},k=()=>(C?C.setLabel(t.getOverflowLabel?.()??"More actions"):C=yh({label:t.getOverflowLabel?.()??"More actions",getButtonSize:s}),C),R=w=>{E!==w&&(A?.disconnect(),E=w,I=Qd(w),!(typeof ResizeObserver>"u")&&(A=new ResizeObserver(v=>{let x=v[v.length-1]?.contentRect?.width??Qd(w);x!==I&&(I=x,Q())}),A.observe(w)))},B=(w,v)=>{let T=yw(w.collapseAutoActionsBelow,v);if(T===null)return!1;let x=I||Qd(v);return x>0&&x<T},O=(w,v,T)=>{if(!v)return"bar";if(w.resolved.builtIn){let z=hw(w.resolved.id);return z&&v.includeBuiltIns?.includes(z)?"menu":"bar"}let x=w.resolved.presentation;return x==="overflow"||x==="auto"&&T?"menu":"bar"},V=w=>{let v=w.menuSlot;if(!v)return;if(!Mw(w.element)){w.menuLabel?.remove(),w.menuLabel=void 0;return}let T=Sw(w.element);if(!T){w.menuLabel?.remove(),w.menuLabel=void 0;return}w.menuLabel||(w.menuLabel=P("span","persona-composer-overflow-menu__label")),w.menuLabel.textContent!==T&&(w.menuLabel.textContent=T),w.menuLabel.parentElement!==v&&v.appendChild(w.menuLabel)},J=(w,v)=>{if(w.mode===v)return w;let T=w.resolved.action;if(T&&!jo(T)){g(w),e.delete(w.resolved.id);let x=c(w.resolved,v);return e.set(w.resolved.id,x),x}if(v==="menu"){let x=Y("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[lf]:""}});x.appendChild(w.element),cf(Xd(w.element)),w.menuSlot=x;let z=W=>{let ee=Xd(w.element);if(ee.disabled)return;let ne=W.target===ee||ee.contains(W.target);C?.close(!0),ne||ee.click()};x.addEventListener("click",z,!0),w.detachMenuSlot=()=>x.removeEventListener("click",z,!0),w.managed=!0,V(w)}else w.detachMenuSlot?.(),w.detachMenuSlot=void 0,w.menuLabel?.remove(),w.menuLabel=void 0,w.menuSlot?.remove(),w.menuSlot=void 0;return w.mode=v,w},_=(w,v)=>{let T=v.map(x=>x.menuSlot??x.element);for(T.forEach((x,z)=>{let W=w.children[z];W!==x&&(W?w.insertBefore(x,W):w.appendChild(x))});w.children.length>T.length;)w.lastElementChild?.remove()},Q=()=>{if(o)return;let w=t.getBindings();if(!w)return;let v=t.getState(),T=v.phase==="streaming",x=L();x&&R(w.footer);let z=x?B(x,w.footer):!1,W={start:[],end:[]},ee=[];for(let ne of n){let he=e.get(ne.id);if(!he)continue;let ve=ne.action,Xe=ve?wh(ve.visible,v,!0)&&ww(ve.visibility,v):!0;if(he.visible!==Xe&&(he.visible=Xe,!Xe&&he.managed&&(he.menuSlot??he.element).remove()),!!Xe){if(he=J(he,O(he,x,z)),ve){let Je=wh(ve.disabled,v,!1)||ve.disableWhenStreaming===!0&&T;h(he,Je),!jo(ve)&&ve.pressed!==void 0&&he.button?.setAttribute("aria-pressed",ve.pressed?"true":"false")}he.mode==="menu"?(V(he),ee.push(he)):W[ne.placement].push(he)}}if(ee.length>0){let ne=k();_(ne.panel,ee),ne.setItems(ee.map(Je=>Je.menuSlot??Je.element)),ne.applyButtonSize();let he=Number.isFinite(x?.order)?x?.order:Kn.overflow,ve=W.start.findIndex(Je=>Je.resolved.order>he),Xe={resolved:{id:fw,placement:"start",presentation:"bar",order:he,sequence:-1,source:"core"},element:ne.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};W.start.splice(ve<0?W.start.length:ve,0,Xe)}else C&&(C.close(),C.trigger.remove(),C.setItems([]));y(w.actionsStart,W.start),y(w.actionsEnd,W.end)};return{resolve:()=>{if(o)return;let w=vw(t.collect()),v=new Set(w.map(T=>T.id));for(let[T,x]of e)v.has(T)||(g(x),e.delete(T));for(let T of w){let x=e.get(T.id);if(!x){let ne=p(T,"bar");ne&&e.set(T.id,ne);continue}let z=x.resolved.action,W=T.action;if(!!z!=!!W||z&&W&&jo(z)!==jo(W)||z&&W&&jo(z)&&jo(W)&&z.render!==W.render){g(x),e.delete(T.id);let ne=p(T,x.mode);ne&&e.set(T.id,ne);continue}x.resolved=T,T.builtIn?(x.managed=T.builtIn.managed===!0||x.mode==="menu",T.builtIn.element&&x.mode==="bar"&&(x.element=T.builtIn.element)):W&&!jo(W)?l(x,W):W&&x.element.toggleAttribute(Yd,W.disableWhenStreaming===!0)}n=w,Q()},sync:Q,getResolved:()=>n,getOverflowMenu:()=>C,destroy:()=>{if(!o){o=!0,A?.disconnect(),A=null,E=null;for(let w of e.values())g(w);e.clear(),C?.destroy(),C=null,n=[]}}}}var Ew="core:model",Tw=700,xh=16,kw=["--persona-components-composer-modelPicker-menuBackground","--persona-components-composer-modelPicker-menuBorderRadius","--persona-components-composer-modelPicker-rowHoverBackground","--persona-components-composer-modelPicker-labelColor","--persona-components-composer-modelPicker-descriptionColor"],Ah=()=>{let t=Y("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),e=Y("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:t,chevron:e}};function Mh(t){let e=t.label??"Model",n=t.presentation??"native",o=null,s=u=>{let p=t.getSelectedModelId();return u.find(g=>g.id===p)??u[0]},i=()=>{let u=Y("select",{className:"persona-composer-model-picker",attrs:{"aria-label":e,"data-persona-composer-model-picker":""}}),p="",g=()=>{let A=t.getModels(),I=A.map(L=>`${L.id}:${L.label}`).join("|");I!==p&&(p=I,u.replaceChildren(...A.map(L=>{let k=Y("option",{attrs:{value:L.id}});return k.textContent=L.label,k}))),u.value=s(A)?.id??""};g(),o=g;let y=()=>{u.value&&t.onSelect(u.value)};u.addEventListener("change",y);let h=A=>A.stopPropagation();u.addEventListener("click",h);let{wrapper:C,chevron:E}=Ah();return C.append(u,E),{element:C,destroy:()=>{o===g&&(o=null),u.removeEventListener("change",y),u.removeEventListener("click",h)}}},l=()=>{let u=Y("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),p=P("span","persona-composer-model-picker-label"),g=P("span","persona-composer-model-picker-suffix");u.append(p,g);let y=Y("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":e,"data-persona-composer-model-menu":""}}),h=new Map,C="",E=null,A=()=>E?.isOpen===!0,I=(v=!1)=>{A()&&(E?.close(),u.setAttribute("aria-expanded","false"),v&&u.focus())},L=v=>{let T=[...h.values()];if(T.length===0)return;let x=(v%T.length+T.length)%T.length;T[x].focus()},k=v=>{if(A())return;E||(E=ll({anchor:u,content:y,placement:"top-start",offset:6,onDismiss:()=>u.setAttribute("aria-expanded","false")})),tl(u,y,kw),E.open(),u.setAttribute("aria-expanded","true");let x=[...h.keys()].indexOf(s(t.getModels())?.id??"");L(v??(x>=0?x:0))},R=v=>{I(!0),t.onSelect(v)},B=v=>{v.preventDefault(),v.stopPropagation();let T=v.currentTarget.getAttribute("data-persona-model-option");T&&R(T)},O=v=>{let T=Y("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":v.id}});if(v.icon){let ne=se(v.icon,xh,"currentColor",1.5);if(ne){let he=P("span","persona-composer-model-option-icon");he.appendChild(ne),T.appendChild(he)}}let x=P("span","persona-composer-model-option-body"),z=P("span","persona-composer-model-option-label");if(z.textContent=v.label,x.appendChild(z),v.description){let ne=P("span","persona-composer-model-option-description");ne.textContent=v.description,x.appendChild(ne)}T.appendChild(x);let W=P("span","persona-composer-model-option-check");W.setAttribute("aria-hidden","true");let ee=se("check",xh,"currentColor",2);return ee&&W.appendChild(ee),T.appendChild(W),T.addEventListener("click",B),T},V=()=>{let v=t.getModels(),T=v.map(W=>`${W.id}:${W.label}:${W.icon??""}:${W.description??""}`).join("|");if(T!==C){C=T;for(let W of h.values())W.removeEventListener("click",B);h.clear(),y.replaceChildren(...v.map(W=>{let ee=O(W);return h.set(W.id,ee),ee}))}let x=s(v);for(let[W,ee]of h)ee.setAttribute("aria-selected",String(W===x?.id));p.textContent=x?.label??"";let z=t.getSuffix?.()??"";g.textContent=z,u.setAttribute("aria-label",[e,[x?.label,z].filter(Boolean).join(" ")].filter(Boolean).join(": "))};V(),o=V;let J=v=>{v.preventDefault(),v.stopPropagation(),A()?I(!0):k()},_=v=>{if(v.key==="ArrowDown"){v.preventDefault(),A()?L(0):k(0);return}v.key==="ArrowUp"&&(v.preventDefault(),A()?L(-1):k(-1))},Q=v=>{let T=[...h.values()],x=T.indexOf(v.target?.closest?.(".persona-composer-model-option"));switch(v.key){case"ArrowDown":v.preventDefault(),L(x+1);return;case"ArrowUp":v.preventDefault(),L(x-1);return;case"Home":v.preventDefault(),L(0);return;case"End":v.preventDefault(),L(T.length-1);return;case"Escape":v.preventDefault(),v.stopPropagation(),I(!0);return;case"Tab":I(!0);return;default:}};u.addEventListener("click",J),u.addEventListener("keydown",_),y.addEventListener("keydown",Q);let{wrapper:G,chevron:w}=Ah();return G.append(u,w),{element:G,destroy:()=>{o===V&&(o=null),u.removeEventListener("click",J),u.removeEventListener("keydown",_),y.removeEventListener("keydown",Q);for(let v of h.values())v.removeEventListener("click",B);h.clear(),E?.destroy(),E=null,y.remove()}}};return{action:{id:Ew,kind:"custom",placement:"end",order:Tw,presentation:n==="popover"?"bar":"auto",label:e,render:()=>n==="popover"?l():i()},repaint:()=>o?.()}}var Pw=":scope > [data-persona-composer-mode]";function Eh(t){let e=t.row,n="",o=!1,s=new Set(t.initialIds??[]),i=p=>{let g=Y("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":p.id}});if(p.iconName){let E=P("span","persona-mention-chip-icon"),A=se(p.iconName,12,"currentColor",1.5);A&&E.appendChild(A),g.appendChild(E)}let y=P("span","persona-mention-chip-label");y.textContent=p.shortLabel??p.label,g.appendChild(y);let h=Y("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),C=se("x",12,"currentColor",2);return C?h.appendChild(C):h.textContent="\xD7",h.addEventListener("click",E=>{E.preventDefault(),E.stopPropagation(),t.onRemove(p.id)}),g.appendChild(h),g},l=()=>Array.from(e.querySelectorAll(Pw)),c=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let g=()=>{p.remove(),al(e)},y=e.ownerDocument.defaultView,h=typeof y?.getComputedStyle=="function"?y.getComputedStyle(p).animationName:"";if(!h||h==="none"){g();return}p.addEventListener("animationend",g,{once:!0}),p.addEventListener("animationcancel",g,{once:!0})},u=()=>{for(let p of l())p.remove()};return{element:e,render:(p,g)=>{if(o)return;let y=g.filter(A=>p.includes(A.id)),h=y.map(A=>`${A.id}:${A.shortLabel??A.label}`).join("|");if(h===n)return;n=h;let C=new Map;for(let A of l()){let I=A.getAttribute("data-persona-composer-mode");I&&y.some(k=>k.id===I)&&!A.hasAttribute("data-persona-chip-exit")?C.set(I,A):A.hasAttribute("data-persona-chip-exit")||c(A)}let E=e.firstChild;for(let A of y){let I=C.get(A.id);I||(I=i(A),s.has(A.id)||(I.setAttribute("data-persona-chip-enter",""),I.addEventListener("animationend",()=>I?.removeAttribute("data-persona-chip-enter"),{once:!0}))),s.delete(A.id),I!==E&&e.insertBefore(I,E),E=I.nextSibling}al(e)},destroy:()=>{o=!0,u(),al(e)}}}var Th=t=>`core:mode:${t}`;var Jd=t=>Math.min(300+t,499),kh=t=>`core:mode-group:${t}`;function Al(t,e){return t?e?.find(n=>n.id===t)?.presentation==="segmented":!1}function Lw(t,e){return t?e?.find(n=>n.id===t)?.chipVisibility==="hidden":!1}function Ph(t,e){return t?.length?t.filter(n=>!Al(n.groupId,e)&&!Lw(n.groupId,e)):[]}var Iw=(t,e)=>t.groupId?e?.find(n=>n.id===t.groupId)?.selection??null:null;function Lh(t,e,n,o){let s=n.find(c=>c.id===e);if(!s)return[...t];let i=t.includes(e),l=new Set(t);if(i)l.delete(e);else{if(Iw(s,o)==="single"){let c=n.filter(u=>u.groupId===s.groupId).map(u=>u.id);l=new Set([...l].filter(u=>!c.includes(u)))}l.add(e)}return n.filter(c=>l.has(c.id)).map(c=>c.id)}function Ml(t,e){return e?.length?e.filter(n=>t.includes(n.id)).map(n=>n.id):[]}function Ih(t,e){return e?.length?e.filter(n=>t.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function Hh(t,e){if(!(!e?.length||t.length===0))return e.find(n=>t.includes(n.id)&&n.placeholder)?.placeholder}var Hw=16;function Rh(t){let e=null;return{action:{id:kh(t.groupId),kind:"custom",placement:"start",presentation:"bar",label:t.getGroup()?.label??t.groupId,render:()=>{let o=Y("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":t.groupId}}),s=new Map,i="",l=p=>{p.preventDefault(),p.stopPropagation();let y=p.currentTarget.getAttribute("data-persona-composer-mode");!y||t.getActiveIds().includes(y)&&t.getGroup()?.selection==="single"||t.onSelect(y)},c=p=>{let g=Y("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let h=se(p.iconName,Hw,"currentColor",1.5);h&&g.appendChild(h)}let y=P("span","persona-composer-segmented-label");return y.textContent=p.shortLabel??p.label,g.appendChild(y),g.addEventListener("click",l),g},u=()=>{let p=t.getGroup();p?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",p.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let g=t.getModes(),y=g.map(C=>`${C.id}:${C.shortLabel??C.label}:${C.iconName??""}`).join("|");if(y!==i){i=y;for(let E of s.values())E.removeEventListener("click",l);s.clear();let C=g.map(E=>{let A=c(E);return s.set(E.id,A),A});o.replaceChildren(...C)}let h=t.getActiveIds();for(let[C,E]of s)E.setAttribute("aria-pressed",String(h.includes(C)))};return u(),e=u,{element:o,destroy:()=>{e===u&&(e=null);for(let p of s.values())p.removeEventListener("click",l);s.clear()}}}},repaint:()=>e?.()}}function Wh(t){let e=Y("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});e.style.display="none";let n="",o=!1,s=i=>{let l=P("span","persona-composer-quote-bar"),c=P("div","persona-composer-quote-content");if(i.sourceLabel){let y=P("div","persona-composer-quote-source");y.textContent=i.sourceLabel,c.appendChild(y)}let u=Y("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});u.textContent=Cl(i.text),c.appendChild(u);let p=Y("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":t.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),g=se("x",12,"currentColor",2);g?p.appendChild(g):p.textContent="\xD7",p.addEventListener("click",y=>{y.preventDefault(),y.stopPropagation(),t.onDismiss()}),e.replaceChildren(l,c,p)};return{element:e,render:i=>{if(o)return;let l=i?`${i.sourceLabel??""}\0${i.text}`:"";if(l!==n){if(n=l,!i){e.replaceChildren(),e.style.display="none";return}s(i),e.style.display="flex"}},destroy:()=>{o=!0,e.replaceChildren(),e.remove()}}}function Bh(t){let e=Y("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});e.style.display="none";let n,o=!1,s=(l,c,u,p)=>{let g=Y("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":c,[u]:""}}),y=se(l,12,"currentColor",2);return y?g.appendChild(y):g.textContent=c,g.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),p()}),g},i=l=>{let c=Cl(l.text??"",90);if(c)return c;let u=l.contentParts?.length??0;return u>0?u===1?"1 attachment":`${u} attachments`:(l.mentionRefs?.length??0)>0?l.mentionRefs.map(g=>g.label).join(", "):"Queued message"};return{element:e,render:l=>{if(o||l===n)return;if(n=l,!l){e.replaceChildren(),e.style.display="none";return}let c=P("span","persona-composer-pending-badge");c.textContent=t.label??"Sends next";let u=Y("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});u.textContent=i(l),e.replaceChildren(c,u,s("pencil",t.editLabel??"Edit queued message","data-persona-composer-pending-edit",t.onEdit),s("x",t.removeLabel??"Remove queued message","data-persona-composer-pending-remove",t.onRemove)),e.style.display="flex"},destroy:()=>{o=!0,e.replaceChildren(),e.remove()}}}function Dh(t){let e=Y("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":t.messageId,"data-preserve-runtime":""}}),n=Y("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});n.value=t.initialText;let o=()=>{n.style.height="auto",n.style.height=`${n.scrollHeight}px`};n.addEventListener("input",o);let s=P("div","persona-message-edit-actions"),i=(c,u,p,g)=>{let y=Y("button",{className:`persona-message-edit-button ${u}`,attrs:{type:"button",[p]:""},text:c});return y.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),g()}),y},l=()=>{let c=n.value.trim();c&&t.onSave(c)};return s.append(i(t.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",t.onCancel),i(t.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",l)),n.addEventListener("keydown",c=>{if(c.key==="Escape"){c.preventDefault(),c.stopPropagation(),t.onCancel();return}c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),l())}),e.append(n,s),{element:e,getValue:()=>n.value,focus:()=>{n.focus();let c=n.value.length;n.setSelectionRange(c,c),o()},destroy:()=>{e.replaceChildren(),e.remove()}}}function Oh(t){let e=t.text??"";if(e.trim().length>0||(t.mentionRefs?.length??0)>0||(t.activeModeIds?.length??0)>0||t.quote||t.selectedModelId)return{text:e,...t.mentionRefs?.length?{mentionRefs:[...t.mentionRefs]}:{},...t.contentSegments?.length?{contentSegments:[...t.contentSegments]}:{},...t.selectedModelId?{selectedModelId:t.selectedModelId}:{},...t.activeModeIds?.length?{activeModeIds:[...t.activeModeIds]}:{},...t.quote?{quote:{...t.quote}}:{}}}function _h(t,e){if(!t||typeof t.text!="string")return;let n=new Set(e.mentionSourceIds),o=(t.mentionRefs??[]).filter(u=>n.has(u.sourceId)),s=o.length===(t.mentionRefs?.length??0)&&o.length>0,i=new Set(e.modes.map(u=>u.id)),l=(t.activeModeIds??[]).filter(u=>i.has(u)),c=t.selectedModelId&&e.modelIds.includes(t.selectedModelId)?t.selectedModelId:void 0;return{text:t.text,...s?{mentionRefs:o}:{},...s&&t.contentSegments?.length?{contentSegments:t.contentSegments}:{},...c?{selectedModelId:c}:{},...l.length?{activeModeIds:l}:{},...t.quote?.text?{quote:t.quote}:{}}}function Fh(t){let e=t.delay??500,n=null,o=!1,s=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{o||(s(),n=setTimeout(()=>{n=null,t.write()},e))},flush:()=>{o||n===null||(s(),t.write())},cancel:s,destroy:()=>{o=!0,s()}}}function Nh(t){return t.wrapped||t.text.includes(`
14
+ `)?!1:!(t.hasAttachments||t.hasChips||t.hasQuote||t.hasPendingSubmission)}function Vh(){let t=!1;return{observe:(e,n)=>n?(e&&(t=!0),t):(t=!1,!1),release:()=>{t=!1}}}function $h(t){if(!t)return!1;let e=t.ownerDocument?.defaultView;if(!e?.getComputedStyle)return!1;let n=e.getComputedStyle(t),o=Number.parseFloat(n.lineHeight),s=Number.parseFloat(n.fontSize),i=Number.isFinite(o)&&o>0?o:Number.isFinite(s)&&s>0?s*1.4:0;if(!i)return!1;let l=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return t.scrollHeight-l>i*1.5}function Zd(t){return Object.freeze({text:t.text,contentParts:t.contentParts?Object.freeze([...t.contentParts]):void 0,mentionRefs:Object.freeze([...t.mentionRefs]),contentSegments:t.contentSegments?Object.freeze([...t.contentSegments]):void 0,options:Object.freeze({...t.options}),viaVoice:t.viaVoice})}function Uh(t){return t.inputDisabled===!0||t.sendDisabled===!0||t.hasAttachments&&!t.attachmentsReady?!1:!!t.text||t.hasAttachments||t.hasMentions||t.hasServerMentions}var Rw=t=>typeof t?.then=="function";function zh(t,e){return e===!1?{status:"canceled"}:!e||typeof e!="object"?{status:"proceed"}:(typeof e.text=="string"&&(t.text=e.text),e.options&&(t.options={...t.options,...e.options}),{status:"proceed"})}function qh(t,e,n){let o;try{o=t(Zd(e),{signal:n})}catch(s){return{status:"error",error:s}}return Rw(o)?Promise.resolve(o).then(s=>n.aborted?{status:"aborted"}:zh(e,s),s=>n.aborted?{status:"aborted"}:{status:"error",error:s}):zh(e,o)}var El=t=>t?.launcher?.variant??(t?.future?.v5Defaults===!0?"circle":"pill"),Tl={background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",border:"transparent",size:"48px",iconSize:"24px",borderRadius:"palette.radius.full",shadow:"0 8px 24px rgba(0,0,0,.16)",offset:"20px"};var Pl="16px",Ll="transparent",Ww=(()=>{let t={};for(let e of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])t[e]=e===0?"0px":`${e/4}rem`;return t})(),Ai={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"},purple:{50:"#faf5ff",100:"#f3e8ff",200:"#e9d5ff",300:"#d8b4fe",400:"#c084fc",500:"#a855f7",600:"#9333ea",700:"#7e22ce",800:"#6b21a8",900:"#581c87",950:"#3b0764"},teal:{50:"#f0fdfa",100:"#ccfbf1",200:"#99f6e4",300:"#5eead4",400:"#2dd4bf",500:"#14b8a6",600:"#0d9488",700:"#0f766e",800:"#115e59",900:"#134e4a",950:"#042f2e"}},spacing:Ww,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"}},kl={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"}},an={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",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"semantic.colors.surface",foreground:"semantic.colors.primary",border:"semantic.colors.border",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:Rm,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Pl,canvasBackground:Ll,modes:{floating:{border:"1px solid var(--persona-border)",shadow:"palette.shadows.xl",borderRadius:"palette.radius.xl"},inline:{border:"1px solid var(--persona-border)",shadow:"none",borderRadius:"palette.radius.xl"},docked:{border:"none",shadow:"none",borderRadius:"palette.radius.xl"},sidebar:{border:"none",borderRadius:"0"},mobile:{border:"none",shadow:"none",borderRadius:"0"}}},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"20px 24px",minimalPadding:"16px 24px",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{gap:"12px",user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},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",borderRadius:"palette.radius.md"},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:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},eventStream:{badge:{flow:{background:"palette.colors.success.100",foreground:"palette.colors.success.700"},step:{background:"palette.colors.primary.100",foreground:"palette.colors.primary.700"},reasoning:{background:"palette.colors.warning.100",foreground:"palette.colors.warning.700"},tool:{background:"palette.colors.purple.100",foreground:"palette.colors.purple.800"},agent:{background:"palette.colors.teal.100",foreground:"palette.colors.teal.800"},error:{background:"palette.colors.error.100",foreground:"palette.colors.error.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.600"}}},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"}}},Bw=Ai.colors.gray,Dw={50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"},Ow={...Ai,colors:{...Ai.colors,gray:Bw}},_w={...Ai,colors:{...Ai.colors,gray:Dw},radius:{none:"0px",sm:"4px",md:"8px",lg:"12px",xl:"16px","2xl":"24px",full:"9999px"}};var Fw=kl,Nw={...kl,colors:{...kl.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...kl.typography,fontSize:"14px",lineHeight:"1.5"}};var tp=an,Vw={...an,launcher:Tl,activity:{rowHeight:"32px",labelSize:"13px",iconSize:"16px",indent:"0px",groupIndent:"0px",groupGap:"0px",groupPadding:"0px",transcriptGap:"0px",responseGap:"12px",bodyPadding:"4px 0",bodySize:"13px",bodyLineHeight:"1.5",bodyFontWeight:"400",sectionGap:"8px",bodySurface:"transparent"},toolBubble:{shadow:"none"},reasoningBubble:{shadow:"none"},input:{...an.input,borderRadius:"palette.radius.full"},introCard:{...an.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...an.suggestion.chip,fontWeight:"400"},card:{...an.suggestion.card,fontWeight:"400"},list:{...an.suggestion.list,fontWeight:"400"}},panel:{...an.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...an.header,background:"semantic.colors.container",foreground:"semantic.colors.text",padding:"8px 8px 8px 16px",minimalPadding:"8px 8px 8px 16px",minHeight:"48px",borderBottom:"none",iconBackground:"transparent",iconForeground:"semantic.colors.text",iconScale:"1",controlSize:"28px",controlIconSize:"18px",controlStrokeWidth:"1.5",actionIconForeground:"semantic.colors.textMuted",controlBorderRadius:"8px",controlHoverBackground:"color-mix(in srgb, var(--persona-text) 8%, transparent)",controlHoverForeground:"semantic.colors.text",controlFocusOutline:"2px solid color-mix(in srgb, var(--persona-text) 50%, transparent)",title:{fontSize:"14px",fontWeight:"500",lineHeight:"1.5"}},message:{...an.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...an.message.user,background:"palette.colors.gray.100",text:"semantic.colors.text",borderRadius:"palette.radius.xl",shadow:"none",padding:"8px 14px",fontSize:"14px",lineHeight:"1.5"},assistant:{...an.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...an.composer,padding:"8px",fontSize:"15px",lineHeight:"1.5",controlSize:"32px",controlIconSize:"20px",sendIconSize:"18px",sendButtonRadius:"9999px",footerBorder:"none",overlayBand:"linear-gradient(to bottom, transparent, var(--persona-container) 24px)",focusBorderColor:"color-mix(in srgb, var(--persona-text) 28%, var(--persona-border))",focusRing:"1px solid color-mix(in srgb, var(--persona-text) 12%, transparent)"}};var $w=t=>Ar({future:t}),np=t=>$w(t)==="v5"?{palette:_w,semantic:Nw,components:Vw}:{palette:Ow,semantic:Fw,components:tp};function Pt(t,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let n=e.split("."),o=t;for(let s of n){if(o==null)return;o=o[s]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Pt(t,o):o}function Kh(t){let e={};function n(o,s){for(let[i,l]of Object.entries(o)){let c=`${s}.${i}`;if(typeof l=="string"){let u=Pt(t,l);u!==void 0&&(e[c]={path:c,value:u,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof l=="object"&&l!==null&&n(l,c)}}return n(t.palette,"palette"),n(t.semantic,"semantic"),n(t.components,"components"),e}function zw(t){let e=[],n=[];return t.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),t.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),t.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:n}}function Gh(t,e){let n={...t};for(let[o,s]of Object.entries(e)){let i=n[o];i&&typeof i=="object"&&!Array.isArray(i)&&s&&typeof s=="object"&&!Array.isArray(s)?n[o]=Gh(i,s):n[o]=s}return n}function Uw(t,e){return e?Gh(t,e):t}function ys(t,e={}){let n=np(e.future),o={palette:n.palette,semantic:n.semantic,components:n.components},s={palette:{...o.palette,...t?.palette,colors:{...o.palette.colors,...t?.palette?.colors},spacing:{...o.palette.spacing,...t?.palette?.spacing},typography:{...o.palette.typography,...t?.palette?.typography},shadows:{...o.palette.shadows,...t?.palette?.shadows},borders:{...o.palette.borders,...t?.palette?.borders},radius:{...o.palette.radius,...t?.palette?.radius}},semantic:{...o.semantic,...t?.semantic,colors:{...o.semantic.colors,...t?.semantic?.colors,interactive:{...o.semantic.colors.interactive,...t?.semantic?.colors?.interactive},feedback:{...o.semantic.colors.feedback,...t?.semantic?.colors?.feedback}},spacing:{...o.semantic.spacing,...t?.semantic?.spacing},typography:{...o.semantic.typography,...t?.semantic?.typography}},components:Uw(o.components,t?.components)},i=t?.components?.activity;for(let p of["toolBubble","reasoningBubble"])for(let g of["rowHeight","labelSize","iconSize","indent","bodySurface"])i?.[g]!==void 0&&(s.components[p][g]=i[g]);let l=t?.components?.collapsibleWidget?.surface;l!==void 0&&i?.bodySurface===void 0&&(s.components.activity={...s.components.activity,bodySurface:l});let c=t?.components?.header;c?.padding!==void 0&&c.minimalPadding===void 0&&(s.components.header.minimalPadding=s.components.header.padding);let u=t?.components?.message;if(u?.gap!==void 0&&u.fullscreenGap===void 0&&(s.components.message.fullscreenGap=s.components.message.gap),e.validate!==!1){let p=zw(s);if(!p.valid)throw new Error(`Theme validation failed: ${p.errors.map(g=>g.message).join(", ")}`)}if(e.plugins)for(let p of e.plugins)s=p.transform(s);return s}var ep=t=>t.trim()==="0"?"0px":t,jh="--persona-",qw=t=>{if(!t)return;let e=t.trim().toLowerCase(),n;if(e.charCodeAt(0)===35){let l=e.slice(1);if(!/^[0-9a-f]+$/.test(l))return;l.length===3||l.length===4?n=[0,1,2].map(c=>parseInt(l[c]+l[c],16)):(l.length===6||l.length===8)&&(n=[0,2,4].map(c=>parseInt(l.slice(c,c+2),16)))}else{let l=e.match(/^rgba?\(([^)]+)\)$/);if(l){let c=l[1].split(/[,/\s]+/).filter(Boolean);c.length>=3&&(n=c.slice(0,3).map(u=>{let p=u.endsWith("%"),g=parseFloat(p?u.slice(0,-1):u);return p?g/100*255:g}))}}if(!n||n.some(l=>!Number.isFinite(l)))return;let[o,s,i]=n.map(l=>{let c=Math.max(0,Math.min(255,l))/255;return c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4)});return .2126*o+.7152*s+.0722*i},jw=.179,kt=(t,e)=>{for(let[n,...o]of e){let s;for(let i of o)if(s=i.charCodeAt(0)===61?i.slice(1):t[jh+i],s!==void 0)break;s!==void 0&&(t[jh+n]=s)}};function Yh(t){let e=Kh(t),n={};for(let[H,Me]of Object.entries(e)){let de=H.replace(/\./g,"-");n[`--persona-${de}`]=Me.value}kt(n,[["primary","semantic-colors-primary","palette-colors-primary-500"],["secondary","semantic-colors-secondary","palette-colors-secondary-500"],["accent","semantic-colors-accent","palette-colors-accent-500"],["surface","semantic-colors-surface","palette-colors-gray-50"],["background","semantic-colors-background","palette-colors-gray-50"],["container","semantic-colors-container","palette-colors-gray-100"],["text","semantic-colors-text","palette-colors-gray-900"],["text-muted","semantic-colors-text-muted","palette-colors-gray-500"],["text-inverse","semantic-colors-text-inverse","palette-colors-gray-50"],["border","semantic-colors-border","palette-colors-gray-200"],["divider","semantic-colors-divider","palette-colors-gray-200"],["muted","text-muted"],["voice-recording-indicator","components-voice-recording-indicator","palette-colors-error-500"],["voice-recording-bg","components-voice-recording-background","palette-colors-error-50"],["voice-processing-icon","components-voice-processing-icon","palette-colors-primary-500"],["voice-speaking-icon","components-voice-speaking-icon","palette-colors-success-500"],["approval-bg","components-approval-requested-background","surface"],["approval-border","components-approval-requested-border","border"],["approval-text","components-approval-requested-text","palette-colors-gray-900"],["approval-shadow","components-approval-requested-shadow","=0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"],["approval-approve-bg","components-approval-approve-background","button-primary-bg"],["approval-deny-bg","components-approval-deny-background","container"],["attachment-image-bg","components-attachment-image-background","palette-colors-gray-100"],["attachment-image-border","components-attachment-image-border","palette-colors-gray-200"],["font-family","semantic-typography-fontFamily","palette-typography-fontFamily-sans"],["font-size","semantic-typography-fontSize","palette-typography-fontSize-base"],["font-weight","semantic-typography-fontWeight","palette-typography-fontWeight-normal"],["line-height","semantic-typography-lineHeight","palette-typography-lineHeight-normal"],["input-font-family","font-family"],["input-font-weight","font-weight"],["radius-sm","palette-radius-sm","=0.125rem"],["radius-md","palette-radius-md","=0.375rem"],["radius-lg","palette-radius-lg","=0.5rem"],["radius-xl","palette-radius-xl","=0.75rem"],["radius-full","palette-radius-full","=9999px"],["launcher-radius","components-launcher-borderRadius","palette-radius-full","=9999px"],["launcher-bg","components-launcher-background","surface"],["launcher-fg","components-launcher-foreground","primary"]]);let o=n["--persona-components-launcher-foreground"];n["--persona-launcher-fg-muted"]=o&&o!==n["--persona-primary"]?`color-mix(in srgb, ${o} 70%, transparent)`:n["--persona-muted"],kt(n,[["launcher-border","components-launcher-border","border"],["button-primary-bg","components-button-primary-background","primary"],["button-primary-fg","components-button-primary-foreground","text-inverse"],["button-radius","components-button-primary-borderRadius","palette-radius-full","=9999px"],["button-stop-bg","components-button-stop-background"],["button-stop-fg","components-button-stop-foreground"]]),kt(n,[["button-ghost-bg","components-button-ghost-background","=transparent"],["button-ghost-fg","components-button-ghost-foreground","text"],["button-ghost-radius","components-button-ghost-borderRadius","radius-md","=0.375rem"],["button-ghost-hover-bg","components-button-ghost-hoverBackground","=rgba(0, 0, 0, 0.05)"],["panel-radius","components-panel-borderRadius","radius-xl","=0.75rem"]]),n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,kt(n,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??Pl,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Ll,kt(n,[["launcher-shadow","components-launcher-shadow","=0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"],["input-radius","components-input-borderRadius","radius-lg","=0.5rem"],["message-user-radius","components-message-user-borderRadius","radius-lg","=0.5rem"],["message-assistant-radius","components-message-assistant-borderRadius","radius-lg","=0.5rem"]]),kt(n,[["header-bg","components-header-background","surface"]]);let s=n["--persona-header-bg"],i=n["--persona-components-header-foreground"],l=i?`color-mix(in srgb, ${i} 72%, ${s})`:void 0;n["--persona-header-border"]=n["--persona-components-header-border"]??(i?`color-mix(in srgb, ${i} 14%, ${s})`:void 0)??n["--persona-divider"],kt(n,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),n["--persona-header-title-fg"]=n["--persona-components-header-title-color"]??n["--persona-components-header-titleForeground"]??i??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??l??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??l??n["--persona-muted"],kt(n,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let c=t.components?.header;c?.shadow&&(n["--persona-header-shadow"]=c.shadow),c?.borderBottom&&(n["--persona-header-border-bottom"]=c.borderBottom),c?.minHeight&&(n["--persona-header-min-height"]=c.minHeight);let u=n["--persona-components-history-railHeader-background"];u&&(n["--persona-history-rail-header-bg"]=u);let p=n["--persona-components-history-railHeader-border"];p&&(n["--persona-history-rail-header-border"]=p);let g=n["--persona-components-history-railHeader-minHeight"];g&&(n["--persona-history-rail-header-min-height"]=g);for(let[H,Me]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let de=n[`--persona-components-history-overlay-${H}`];de&&(n[`--persona-history-overlay-${Me}`]=de)}for(let[H,Me]of[["background","bg"],["borderRadius","radius"]]){let de=n[`--persona-components-history-menu-${H}`];de&&(n[`--persona-history-menu-${Me}`]=de)}let y=t.components?.history?.motion;if(y){let H=In=>{if(In===void 0)return;let Ps=String(In).trim();return/^\d+(\.\d+)?$/.test(Ps)?`${Ps}ms`:Ps},Me=H(y.enterDurationMs);Me!==void 0&&(n["--persona-history-enter-ms"]=Me);let de=H(y.exitDurationMs);de!==void 0&&(n["--persona-history-exit-ms"]=de),y.enterEasing&&(n["--persona-history-enter-easing"]=y.enterEasing),y.exitEasing&&(n["--persona-history-exit-easing"]=y.exitEasing)}let h=n["--persona-components-history-dangerForeground"];h&&(n["--persona-history-danger-fg"]=h),n["--persona-danger"]=n["--persona-components-history-confirm-dangerBackground"]??n["--persona-palette-colors-error-700"]??"#b42318",n["--persona-danger-fg"]=n["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let H of["scrim","shadow"]){let Me=n[`--persona-components-history-confirm-${H}`];Me&&(n[`--persona-history-confirm-${H}`]=Me)}for(let[H,Me]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let de=n[`--persona-components-tooltip-${H}`];de&&(n[`--persona-tooltip-${Me}`]=de)}t.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[H,Me]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let de=n[`--persona-components-messageActions-${H}`];de&&(n[`--persona-message-action-${Me}`]=de)}kt(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let C=n["--persona-components-introCard-background"],E=n["--persona-components-introCard-shadow"],A=(!C||C==="transparent"||C==="none")&&(!E||E==="none"),I=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=A&&I==="1.5rem"?"1.5rem 0":I,kt(n,[["intro-card-shadow","components-introCard-shadow","=none"],["intro-card-border","components-introCard-border","=none"],["input-background","components-input-background","surface"],["input-placeholder","components-input-placeholder","text-muted"],["input-backdrop-filter","components-input-backdropFilter","=none"],["message-user-bg","components-message-user-background","accent"],["message-user-text","components-message-user-text","text-inverse"],["message-user-shadow","components-message-user-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["message-assistant-bg","components-message-assistant-background","surface"],["message-assistant-text","components-message-assistant-text","text"],["message-assistant-border","components-message-assistant-border","border"],["message-assistant-shadow","components-message-assistant-shadow","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-bg","components-scrollToBottom-background","button-primary-bg","accent"],["scroll-to-bottom-fg","components-scrollToBottom-foreground","button-primary-fg","text-inverse"],["scroll-to-bottom-border","components-scrollToBottom-border","primary"],["scroll-to-bottom-size","components-scrollToBottom-size","=40px"],["scroll-to-bottom-radius","components-scrollToBottom-borderRadius","button-radius","radius-full","=9999px"],["scroll-to-bottom-shadow","components-scrollToBottom-shadow","palette-shadows-sm","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-padding","components-scrollToBottom-padding","=0.5rem 0.875rem"],["scroll-to-bottom-gap","components-scrollToBottom-gap","=0.5rem"],["scroll-to-bottom-font-size","components-scrollToBottom-fontSize","palette-typography-fontSize-sm","=0.875rem"],["scroll-to-bottom-icon-size","components-scrollToBottom-iconSize","=14px"],["event-badge-flow-bg","components-eventStream-badge-flow-background","=#dcfce7"],["event-badge-flow-fg","components-eventStream-badge-flow-foreground","=#15803d"],["event-badge-step-bg","components-eventStream-badge-step-background","=#f5f5f5"],["event-badge-step-fg","components-eventStream-badge-step-foreground","=#0a0a0a"],["event-badge-reasoning-bg","components-eventStream-badge-reasoning-background","=#fef9c3"],["event-badge-reasoning-fg","components-eventStream-badge-reasoning-foreground","=#a16207"],["event-badge-tool-bg","components-eventStream-badge-tool-background","=#f3e8ff"],["event-badge-tool-fg","components-eventStream-badge-tool-foreground","=#6b21a8"],["event-badge-agent-bg","components-eventStream-badge-agent-background","=#ccfbf1"],["event-badge-agent-fg","components-eventStream-badge-agent-foreground","=#115e59"],["event-badge-error-bg","components-eventStream-badge-error-background","=#fee2e2"],["event-badge-error-fg","components-eventStream-badge-error-foreground","=#b91c1c"],["event-badge-default-bg","components-eventStream-badge-default-background","=#f3f4f6"],["event-badge-default-fg","components-eventStream-badge-default-foreground","=#4b5563"],["tool-bubble-shadow","components-toolBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["reasoning-bubble-shadow","components-reasoningBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["composer-shadow","components-composer-shadow","=none"]]),kt(n,[["composer-padding","components-composer-padding","=0.75rem 1rem"],["composer-gap","components-composer-gap","=0.5rem"],["composer-font-size","components-composer-fontSize","=0.875rem"],["composer-line-height","components-composer-lineHeight","=1.25rem"],["composer-control-size","components-composer-controlSize","=40px"],["composer-control-icon-size","components-composer-controlIconSize","=24px"],["motion-duration-fast","components-motion-durationFast","=120ms"],["motion-duration-base","components-motion-durationBase","=200ms"],["motion-easing","components-motion-easing","=cubic-bezier(0.2, 0, 0, 1)"],["composer-border-color","components-composer-borderColor","border","=#e5e7eb"],["composer-overlay-band","components-composer-overlayBand","=transparent"],["scrollbar-thumb","components-scrollbar-thumb","border","=#e5e7eb"],["scrollbar-track","components-scrollbar-track","=transparent"],["md-inline-code-bg","components-markdown-inlineCode-background","container"],["md-inline-code-color","components-markdown-inlineCode-foreground","text"],["md-link-color","components-markdown-link-foreground","accent","=#0f0f0f"]]);let L=n["--persona-components-markdown-heading-h1-fontSize"];L&&(n["--persona-md-h1-size"]=L);let k=n["--persona-components-markdown-heading-h1-fontWeight"];k&&(n["--persona-md-h1-weight"]=k);let R=n["--persona-components-markdown-heading-h2-fontSize"];R&&(n["--persona-md-h2-size"]=R);let B=n["--persona-components-markdown-heading-h2-fontWeight"];B&&(n["--persona-md-h2-weight"]=B);let O=n["--persona-components-markdown-prose-fontFamily"];O&&O!=="inherit"&&(n["--persona-md-prose-font-family"]=O),kt(n,[["md-code-block-bg","components-markdown-codeBlock-background","container"],["md-code-block-border-color","components-markdown-codeBlock-borderColor","border"],["md-code-block-text-color","components-markdown-codeBlock-textColor","=inherit"]]),kt(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),kt(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),kt(n,[["md-hr-color","components-markdown-hr-color","divider"]]),kt(n,[["md-blockquote-border-color","components-markdown-blockquote-borderColor","palette-colors-gray-900"],["md-blockquote-bg","components-markdown-blockquote-background","=transparent"],["md-blockquote-text-color","components-markdown-blockquote-textColor","palette-colors-gray-500"]]);let V=[["container","surface"],["surface","surface"],["border","border"]];for(let[H,Me]of V){let de=n[`--persona-components-collapsibleWidget-${H}`]??n[`--persona-${Me}`];de!==void 0&&(n[`--persona-cw-${H}`]=de,n[`--cw-${H}`]=de)}kt(n,[["message-border","components-message-border","border"]]),kt(n,[["message-user-padding","components-message-user-padding"],["message-user-max-width","components-message-user-maxWidth"],["message-user-font-size","components-message-user-fontSize"],["message-user-font-family","components-message-user-fontFamily"],["message-user-line-height","components-message-user-lineHeight"],["message-assistant-padding","components-message-assistant-padding"],["message-assistant-border-width","components-message-assistant-borderWidth"],["message-assistant-max-width","components-message-assistant-maxWidth"],["message-assistant-font-size","components-message-assistant-fontSize"],["message-assistant-font-family","components-message-assistant-fontFamily"],["message-assistant-line-height","components-message-assistant-lineHeight"]]);let J=t.components,_=J?.iconButton;_&&(_.background&&(n["--persona-icon-btn-bg"]=_.background),_.border&&(n["--persona-icon-btn-border"]=_.border),_.color&&(n["--persona-icon-btn-color"]=_.color),_.padding&&(n["--persona-icon-btn-padding"]=_.padding),_.borderRadius&&(n["--persona-icon-btn-radius"]=_.borderRadius),_.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=_.hoverBackground),_.hoverColor&&(n["--persona-icon-btn-hover-color"]=_.hoverColor),_.activeBackground&&(n["--persona-icon-btn-active-bg"]=_.activeBackground),_.activeBorder&&(n["--persona-icon-btn-active-border"]=_.activeBorder));let Q=J?.labelButton;Q&&(Q.background&&(n["--persona-label-btn-bg"]=Q.background),Q.border&&(n["--persona-label-btn-border"]=Q.border),Q.color&&(n["--persona-label-btn-color"]=Q.color),Q.padding&&(n["--persona-label-btn-padding"]=Q.padding),Q.borderRadius&&(n["--persona-label-btn-radius"]=Q.borderRadius),Q.hoverBackground&&(n["--persona-label-btn-hover-bg"]=Q.hoverBackground),Q.fontSize&&(n["--persona-label-btn-font-size"]=Q.fontSize),Q.gap&&(n["--persona-label-btn-gap"]=Q.gap));let G=J?.toggleGroup;G&&(G.gap&&(n["--persona-toggle-group-gap"]=G.gap),G.borderRadius&&(n["--persona-toggle-group-radius"]=G.borderRadius));let w=J?.artifact;if(w?.toolbar){let H=w.toolbar;H.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=H.iconHoverColor),H.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=H.iconHoverBackground),H.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=H.iconPadding),H.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=H.iconBorderRadius),H.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=H.iconBorder),H.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=ep(H.toggleGroupGap)),H.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=H.toggleBorderRadius),H.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=ep(H.toggleGroupPadding)),H.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=H.toggleGroupBorder),H.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=H.toggleGroupBorderRadius),H.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Pt(t,H.toggleGroupBackground)??H.toggleGroupBackground),H.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=H.copyBackground),H.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=H.copyBorder),H.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=H.copyColor),H.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=ep(H.copyBorderRadius)),H.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=H.copyPadding),H.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=H.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??H.copyMenuBackground),H.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=H.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??H.copyMenuBorder),H.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=H.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??H.copyMenuShadow),H.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=H.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??H.copyMenuBorderRadius),H.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=H.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??H.copyMenuItemHoverBackground),H.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=H.iconBackground),H.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=H.toolbarBorder)}if(w?.tab){let H=w.tab;H.background&&(n["--persona-artifact-tab-bg"]=H.background),H.activeBackground&&(n["--persona-artifact-tab-active-bg"]=H.activeBackground),H.activeBorder&&(n["--persona-artifact-tab-active-border"]=H.activeBorder),H.borderRadius&&(n["--persona-artifact-tab-radius"]=H.borderRadius),H.textColor&&(n["--persona-artifact-tab-color"]=H.textColor),H.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=H.hoverBackground),H.listBackground&&(n["--persona-artifact-tab-list-bg"]=H.listBackground),H.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=H.listBorderColor),H.listPadding&&(n["--persona-artifact-tab-list-padding"]=H.listPadding)}if(w?.pane){let H=w.pane;if(H.toolbarBackground){let Me=Pt(t,H.toolbarBackground)??H.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Me}}if(w?.card){let H=w.card;H.background&&(n["--persona-artifact-card-bg"]=H.background),H.border&&(n["--persona-artifact-card-border"]=H.border),H.borderRadius&&(n["--persona-artifact-card-radius"]=H.borderRadius),H.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=H.hoverBackground),H.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=H.hoverBorderColor)}if(w?.inline){let H=w.inline;H.background&&(n["--persona-artifact-inline-bg"]=Pt(t,H.background)??H.background),H.border&&(n["--persona-artifact-inline-border"]=H.border),H.borderRadius&&(n["--persona-artifact-inline-radius"]=H.borderRadius),H.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Pt(t,H.chromeBackground)??H.chromeBackground),H.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Pt(t,H.chromeBorder)??H.chromeBorder),H.titleColor&&(n["--persona-artifact-inline-title-color"]=Pt(t,H.titleColor)??H.titleColor),H.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Pt(t,H.mutedColor)??H.mutedColor),H.frameHeight&&(n["--persona-artifact-inline-frame-height"]=H.frameHeight)}let v=J?.code;v&&(v.keywordColor&&(n["--persona-code-keyword-color"]=v.keywordColor),v.stringColor&&(n["--persona-code-string-color"]=v.stringColor),v.commentColor&&(n["--persona-code-comment-color"]=v.commentColor),v.numberColor&&(n["--persona-code-number-color"]=v.numberColor),v.tagColor&&(n["--persona-code-tag-color"]=v.tagColor),v.attrColor&&(n["--persona-code-attr-color"]=v.attrColor),v.propertyColor&&(n["--persona-code-property-color"]=v.propertyColor),v.lineNumberColor&&(n["--persona-code-line-number-color"]=v.lineNumberColor),v.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=v.gutterBorderColor),v.background&&(n["--persona-code-bg"]=Pt(t,v.background)??v.background));let T=n["--persona-surface"],x=n["--persona-container"],z=n["--persona-palette-colors-gray-100"]??"#f3f4f6",W=n["--persona-palette-colors-gray-200"]??"#e5e7eb",ee=n["--persona-palette-colors-gray-300"]??"#d1d5db",ne=!x||x===T,he=qw(T??n["--persona-background"]),ve=ne&&he!==void 0&&he<jw,Xe=ve?"rgba(255, 255, 255, 0.08)":z,Je=ve?"rgba(255, 255, 255, 0.12)":W,Wt=ve?"rgba(255, 255, 255, 0.16)":ee,$e=ne?Xe:x,Ce=ne?Je:x;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??$e,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??Ce,ne&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??Wt),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??$e,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??$e,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??$e,n}var Kw=t=>!!t&&"launcher"in t&&(t.launcher?.sidebarMode===!0||t.launcher?.mountMode==="docked"),Qh=(t,e)=>{if(!e||!Kw(e))return t;let n=e.theme?.components?.panel?.width,o=e.darkTheme?.components?.panel?.width;return(Ei(e)==="dark"?o??n:n)!=null?t:{...t,components:{...t.components,panel:{...t.components.panel,width:Ar(e)==="v5"?"400px":"420px"}}}},Gw={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"}}},Mi={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},eventStream:{badge:{flow:{background:"palette.colors.success.900",foreground:"palette.colors.success.300"},step:{background:"palette.colors.primary.800",foreground:"palette.colors.primary.200"},reasoning:{background:"palette.colors.warning.900",foreground:"palette.colors.warning.300"},tool:{background:"palette.colors.purple.900",foreground:"palette.colors.purple.300"},agent:{background:"palette.colors.teal.900",foreground:"palette.colors.teal.300"},error:{background:"palette.colors.error.900",foreground:"palette.colors.error.300"},default:{background:"palette.colors.gray.800",foreground:"palette.colors.gray.300"}}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},op=Gw,Yw={...op,colors:{...op.colors,primary:{50:"#0f0f10",100:"#27272a",200:"#3f3f46",300:"#52525b",400:"#71717a",500:"#f4f4f5",600:"#e4e4e7",700:"#d4d4d8",800:"#a1a1aa",900:"#fafafa",950:"#ffffff"},gray:{50:"#1a1a1b",100:"#27272a",200:"#2a2a2d",300:"#52525b",400:"#71717a",500:"#a1a1aa",600:"#b4b4bd",700:"#d4d4d8",800:"#e4e4e7",900:"#f4f4f5",950:"#fafafa"}}},Qw=Mi,Xw={semantic:{colors:{primary:"palette.colors.primary.500",accent:"palette.colors.primary.600",background:"#0f0f10",surface:"palette.colors.gray.50",container:"#1c1c20",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"#0f0f10",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"}}},components:{...Mi.components,button:{...Mi.components?.button,primary:{background:"semantic.colors.primary",foreground:"palette.colors.primary.50"}},markdown:{inlineCode:{background:"palette.colors.gray.100",foreground:"semantic.colors.text"},link:{foreground:"semantic.colors.accent"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"semantic.colors.text"},table:{headerBackground:"palette.colors.gray.100",borderColor:"semantic.colors.border"},blockquote:{background:"semantic.colors.container",borderColor:"palette.colors.gray.300",textColor:"semantic.colors.textMuted"}},eventStream:{...Mi.components?.eventStream,badge:{...Mi.components?.eventStream?.badge,step:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"}}}}},Jw=t=>Ar({future:t})==="v5"?{palette:Yw,components:Xw}:{palette:op,components:Qw},Xh=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},rp=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",Zw=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":rp()},Ei=t=>Zw(t),eS=(t,e={})=>ys(t,e),tS=(t,e={})=>{let n=Jw(e.future),o=Sr(n.components,t??{})??{};return ys({...o,palette:{...o.palette,colors:Ar(e)==="v5"?Sr(n.palette.colors,o.palette?.colors):{...n.palette.colors,...o.palette?.colors}}},{validate:!1,future:e.future})},ho=t=>{let e=Ei(t),n=Xh(t?.theme),o=El(t)==="circle"?Tl:{...tp.launcher,...t?.future?.v5Defaults?{offset:"1.5rem"}:{}},s=Sr({components:{launcher:o}},n),i=Xh(t?.darkTheme);return Qh(e==="dark"?tS(Sr(s??{},i??{}),{future:t?.future}):eS(s,{future:t?.future}),t)},nS=t=>Yh(t),Ti=(t,e)=>{let n=ho(e),o=nS(n);for(let[s,i]of Object.entries(o))t.style.setProperty(s,i);t.setAttribute("data-persona-color-scheme",Ei(e)),t.setAttribute("data-persona-defaults",Ar(e))},Il=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(rp())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>t(rp());n.addEventListener?(n.addEventListener("change",o),e.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),e.push(()=>n.removeListener(o)))}return()=>{e.forEach(n=>n())}};import{Activity as fb,Check as hb,Copy as yb}from"lucide";var Ko=(t,e)=>t?.layout?.contentMaxWidth??(e?t?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Hl="24px",sp=(t,e)=>e||t?.composer?.placement!=="overlay"?"block":"overlay",ki=t=>{if(typeof t!="string")return null;let e=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(t);if(!e)return null;let n=Number(e[1])/100;return n>0&&n<1?n:null},Jh=t=>Math.max(0,Math.round(t.columnHeight*(1-t.fraction))-t.footerHeight);import{Idiomorph as oS}from"idiomorph";var Rl=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;oS.morph(t,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,i){if(s instanceof HTMLElement&&o){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-tool-elapsed"))return i instanceof HTMLElement&&i.getAttribute("data-tool-elapsed")===s.getAttribute("data-tool-elapsed")?!1:void 0;if(s.hasAttribute("data-preserve-animation")){if(i instanceof HTMLElement&&!i.hasAttribute("data-preserve-animation"))return;if(i instanceof HTMLElement&&i.hasAttribute("data-preserve-animation")){let l=s.textContent??"",c=i.textContent??"";if(l!==c)return}return!1}}}}})};var Zh=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var ip={index:-1,draft:""};function ey(t){let{direction:e,history:n,currentValue:o,atStart:s,state:i}=t,l=i.index!==-1;if(n.length===0)return{handled:!1,state:i};if(e==="up"){if(!l&&!s)return{handled:!1,state:i};if(!l){let c=n.length-1;return{handled:!0,value:n[c],state:{index:c,draft:o}}}if(i.index>0){let c=i.index-1;return{handled:!0,value:n[c],state:{index:c,draft:i.draft}}}return{handled:!0,state:i}}if(!l)return{handled:!1,state:i};if(i.index<n.length-1){let c=i.index+1;return{handled:!0,value:n[c],state:{index:c,draft:i.draft}}}return{handled:!0,value:i.draft,state:{index:-1,draft:i.draft}}}function ty(t,e){return[t.id,t.role,t.content?.length??0,t.content?.slice(-32)??"",t.streaming?"1":"0",t.voiceProcessing?"1":"0",t.variant??"",t.rawContent?.length??0,t.llmContent?.length??0,t.approval?.status??"",t.toolCall?.status??"",t.toolCall?.name??"",t.toolCall?.chunks?.length??0,t.toolCall?.chunks?.[t.toolCall.chunks.length-1]?.slice(-32)??"",typeof t.toolCall?.args=="string"?t.toolCall.args.length:t.toolCall?.args?JSON.stringify(t.toolCall.args).length:0,t.reasoning?.chunks?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.slice(-32)??"",t.contentParts?.length??0,t.stopReason??"",e].join("\0")}function ny(){return new Map}function oy(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function ry(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function sy(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}var{setLoader:fT,load:rS}=je({fallbackImport:()=>import("./animations-extra-SNTZ6Z6B.js")});var iy=rS;function ap(t,e=Dt){let n=t.style.position,o=t.style.zIndex,s=t.style.isolation,i=getComputedStyle(t),l=i.position==="static"||i.position==="";return l&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{l&&(t.style.position=n),t.style.zIndex=o,t.style.isolation=s}}var Pi=0,Go=null;function lp(t=document){if(Pi++,Pi===1){let n=t.body,s=(t.defaultView??window).scrollY||t.documentElement.scrollTop;Go={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:s},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${s}px`,n.style.width="100%"}let e=!1;return()=>{if(!e&&(e=!0,Pi=Math.max(0,Pi-1),Pi===0&&Go)){let n=t.body,o=t.defaultView??window;n.style.overflow=Go.originalOverflow,n.style.position=Go.originalPosition,n.style.top=Go.originalTop,n.style.width=Go.originalWidth,o.scrollTo(0,Go.scrollY),Go=null}}}var Li={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},rt=t=>(t?.launcher?.mountMode??"floating")==="docked",Ii=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",Cn=t=>{let e=t?.launcher?.dock,n=xr(t).dockWidth?e?.width:Pt(ho(t),"components.panel.width");return{side:e?.side??Li.side,width:n??Li.width,animate:e?.animate??Li.animate,reveal:e?.reveal??Li.reveal,maxHeight:e?.maxHeight??Li.maxHeight}};import{ArrowRight as sS}from"lucide";var cp=t=>t==="followUp"?"follow-up":t,dp=(t,e=0)=>{if(typeof t=="string"){let s=t.trim();return s?{id:s,label:s,prompt:s,emphasis:"default"}:null}let n=t.label.trim();if(!n)return null;let o=t.prompt?.trim()||n;return{id:t.id?.trim()||o||`suggestion-${e}`,label:n,prompt:o,description:t.description?.trim()||void 0,icon:t.icon,iconColor:t.iconColor?.trim()||void 0,behavior:t.behavior,emphasis:t.emphasis??"default"}},ay=new WeakSet,iS=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,aS=t=>{iS()||t.forEach((e,n)=>{typeof e.animate=="function"&&e.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},pp=t=>{let{item:e,index:n,surface:o,source:s,variant:i,streaming:l,config:c,plugins:u,chipsConfig:p,session:g,getTextarea:y,eventTarget:h,submitPrompt:C}=t,E=o==="followUp",A=e.behavior,I=()=>{if(g.isStreaming())return;let R={suggestion:{...e},surface:o,source:s,behavior:A},B=h.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:R,bubbles:!0,composed:!0,cancelable:!0}));if(E&&h.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:e.prompt},bubbles:!0,composed:!0})),!B)return;for(let V of u)if(V.onSuggestionSelect?.({suggestion:{...e},surface:o,source:s,variant:i,config:c})===!1)return;let O=y();if(A==="fill"){O.value=e.prompt,O.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),O.focus();return}if(C){C(e.prompt);return}O.value="",g.sendMessage(e.prompt)},L=()=>{let R=P("button",`persona-suggestion persona-suggestion--${i}`);if(R.type="button",R.disabled=l,R.dataset.suggestionId=e.id,R.dataset.emphasis=e.emphasis,R.dataset.behavior=A,i==="chip"&&(p?.fontWeight&&(R.style.fontWeight=p.fontWeight),p?.paddingX&&(R.style.paddingLeft=p.paddingX,R.style.paddingRight=p.paddingX),p?.paddingY&&(R.style.paddingTop=p.paddingY,R.style.paddingBottom=p.paddingY)),e.icon){let O=se(e.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);O&&(O.classList.add("persona-suggestion__icon"),e.iconColor&&(O.style.color=e.iconColor),R.appendChild(O))}let B=P("span","persona-suggestion__copy");if(B.appendChild(Y("span",{className:"persona-suggestion__label",text:e.label})),e.description&&i!=="chip"&&B.appendChild(Y("span",{className:"persona-suggestion__description",text:e.description})),R.appendChild(B),i!=="chip"){let O=yt(sS,16,"currentColor",1.8);O&&(O.classList.add("persona-suggestion__arrow"),R.appendChild(O))}return R.addEventListener("click",I),R},k=null;for(let R of u)if(R.renderSuggestion&&(k=R.renderSuggestion({suggestion:{...e},index:n,surface:o,source:s,variant:i,streaming:l,config:c,defaultRenderer:L,select:I}),k))break;return k??=L(),k.dataset.suggestionId||=e.id,k.dataset.behavior||=A,k.dataset.emphasis||=e.emphasis,k instanceof HTMLButtonElement||k.setAttribute("aria-disabled",l?"true":"false"),k},Hi=t=>{let e=[],n=[],o=null,s=null,i=()=>{t.removeAttribute("data-scroll-left"),t.removeAttribute("data-scroll-right")},l=()=>{if(s=null,t.hidden||t.dataset.variant!=="chip"||t.dataset.overflow!=="scroll"){i();return}let g=Math.max(0,t.scrollWidth-t.clientWidth);if(g<=1){i();return}let y=getComputedStyle(t).direction==="rtl",h=Math.min(g,Math.max(0,Math.abs(t.scrollLeft))),C=4,E=h<=C,A=h>=g-C,I=y?!A:!E,L=y?!E:!A;t.toggleAttribute("data-scroll-left",I),t.toggleAttribute("data-scroll-right",L)},c=()=>{if(s!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&l();return}s=requestAnimationFrame(l)};t.addEventListener("scroll",c,{passive:!0});let u=typeof ResizeObserver=="function"?new ResizeObserver(c):null;return u?.observe(t),{buttons:e,elements:n,destroy:()=>{t.removeEventListener("scroll",c),u?.disconnect(),s!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(s),s=null},render:(g,y,h,C,E,A)=>{t.replaceChildren(),e.length=0,n.length=0;let I=A?.source??"config",L=A?.surface??(I==="config"?"starter":"followUp"),k=L==="followUp",R=A?.variant??"chip",B=A?.behavior??"send",O=A?.overflow??"wrap",V=A?.config??{},J=A?.plugins??[],_=typeof A?.maxItems=="number"?Math.max(0,Math.floor(A.maxItems)):void 0,Q=k?"followUps":"starters";!ay.has(V)&&V.debug===!0&&R!=="chip"&&V.suggestions?.[Q]?.overflow!==void 0&&(ay.add(V),console.info(`[persona] suggestions.${Q}.overflow applies to the "chip" variant only; the "${R}" variant manages its own stacking.`));let G=W=>W.map(dp).filter(ee=>ee!==null).map(ee=>({...ee,behavior:ee.behavior??B})),w=G(g??[]);J.forEach(W=>{W.transformSuggestions&&(w=G(W.transformSuggestions({suggestions:w.map(ee=>({...ee})),surface:L,source:I,config:V})))});let v=_===void 0?w:w.slice(0,_);if(!v.length){t.hidden=!0,o=null,i();return}if(!k&&(C??y.getMessages()).some(ee=>ee.role==="user")){t.hidden=!0,o=null;return}t.hidden=!1,t.classList.add("persona-suggestions"),t.dataset.personaSuggestionSurface=cp(L),t.dataset.variant=R,t.dataset.overflow=O;let T=document.createDocumentFragment(),x=y.isStreaming();v.forEach((W,ee)=>{let ne=pp({item:W,index:ee,surface:L,source:I,variant:R,streaming:x,config:V,plugins:J,chipsConfig:E,session:y,getTextarea:()=>h,eventTarget:t,submitPrompt:A?.submitPrompt});T.appendChild(ne),n.push(ne),[...ne instanceof HTMLButtonElement?[ne]:[],...Array.from(ne.querySelectorAll("button"))].forEach(ve=>{e.includes(ve)||(ve.disabled=x,e.push(ve))})}),t.appendChild(T),l(),c();let z=JSON.stringify({normalized:v,surface:L,variant:R,source:I});z!==o&&(o=z,aS(n),t.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:v.map(W=>({...W})),surface:L,source:I,variant:R},bubbles:!0,composed:!0})),k&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:v.map(W=>W.prompt)},bubbles:!0,composed:!0})))}}};var ln={"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 lS="persona-header-control",cS="persona-header-control--glyph",dS="persona-header-control--sparse",pS=20,uS={x:[1.4,1.05]},ly="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",gS="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Wl=(t,e,n={})=>{let{iconSize:o,iconText:s}=n,[i,l]=uS[e]??[1,1.5],c=!o;t.classList.toggle(cS,c),t.classList.toggle(dS,c&&i!==1);let u=parseFloat(o??"")||pS,p=se(e,`${Math.round(u*i)}px`,"currentColor",l);p?(p.style.display="block",c||(p.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((l/1.5).toFixed(4))})`),t.replaceChildren(p)):s&&(t.textContent=s)},bs=t=>{let{ariaLabel:e,tooltip:n=!0,tooltipHint:o,iconName:s,iconText:i,wrapperClassName:l=ly,size:c,iconSize:u,color:p,backgroundColor:g,borderWidth:y,borderColor:h,borderRadius:C,paddingX:E,paddingY:A,hidden:I,extraClassName:L,attrs:k}=t,R=P("div",l),B=!!(y||h),O=Y("button",{className:ss(lS,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!g&&"persona-bg-transparent hover:persona-bg-gray-100",!B&&"persona-border-none",!C&&"persona-rounded-full",L),attrs:{type:"button","aria-label":e,...k},style:{width:c,height:c,minWidth:c,minHeight:c,display:I?"none":void 0,color:p||Vt.actionIconColor,backgroundColor:g,border:B?`${y||"0px"} solid ${h||"transparent"}`:void 0,borderRadius:C,paddingLeft:E,paddingRight:E,paddingTop:A,paddingBottom:A}});return s?Wl(O,s,{iconSize:u,iconText:i}):i&&(O.textContent=i),R.appendChild(O),vn({anchor:O,trigger:R,text:()=>O.getAttribute("aria-label")??e,hint:o,enabled:n}),{button:O,wrapper:R}},vs=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=ly,buttonSize:s,iconSize:i}=e,l=t?.launcher??{},c=l.closeButtonTooltipText??"Close chat",u=l.closeButtonShowTooltip??!0,{button:p,wrapper:g}=bs({ariaLabel:c,tooltip:u,iconName:l.closeButtonIconName??"x",iconText:l.closeButtonIconText??"\xD7",wrapperClassName:o,size:s??l.closeButtonSize,iconSize:i,color:l.closeButtonColor,backgroundColor:l.closeButtonBackgroundColor,borderWidth:l.closeButtonBorderWidth,borderColor:l.closeButtonBorderColor,borderRadius:l.closeButtonBorderRadius,paddingX:l.closeButtonPaddingX,paddingY:l.closeButtonPaddingY,hidden:!n});return{button:p,wrapper:g}},Cs=(t,e={})=>{let{wrapperClassName:n=gS,buttonSize:o,iconSize:s}=e,l=(t?.launcher??{}).clearChat??{},c=l.tooltipText??"Clear chat",u=l.showTooltip??!0,{button:p,wrapper:g}=bs({ariaLabel:c,tooltip:u,iconName:l.iconName??"refresh-cw",wrapperClassName:n,size:o??l.size,iconSize:s,color:l.iconColor,backgroundColor:l.backgroundColor,borderWidth:l.borderWidth,borderColor:l.borderColor,borderRadius:l.borderRadius,paddingX:l.paddingX,paddingY:l.paddingY});return{button:p,wrapper:g}};var Vt={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-control-state-fg, var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af)))",minHeight:"var(--persona-header-min-height, auto)"},up={fontFamily:"var(--persona-components-header-title-fontFamily, inherit)",fontSize:"var(--persona-components-header-title-fontSize, 1rem)",fontWeight:"var(--persona-components-header-title-fontWeight, 600)",lineHeight:"var(--persona-components-header-title-lineHeight, 1.5rem)",letterSpacing:"var(--persona-components-header-title-letterSpacing, normal)"},mS={fontFamily:"var(--persona-components-header-subtitle-fontFamily, inherit)",fontSize:"var(--persona-components-header-subtitle-fontSize, 0.75rem)",fontWeight:"var(--persona-components-header-subtitle-fontWeight, inherit)",lineHeight:"var(--persona-components-header-subtitle-lineHeight, 1rem)",letterSpacing:"var(--persona-components-header-subtitle-letterSpacing, normal)"},kr=t=>{let{config:e,showClose:n=!0}=t,o=Y("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3",attrs:{"data-persona-theme-zone":"header"},style:{padding:"var(--persona-components-header-padding, 20px 24px)",minHeight:Vt.minHeight,backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),s=e?.launcher??{},i=s.headerIconSize??$a,l=s.closeButtonPlacement??"inline",c=s.headerIconHidden??!1,u=s.headerIconName,p=Y("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:i,width:i,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!c)if(u){let O=parseFloat(i)||24,V=se(u,O*.6,"currentColor",1);V?(V.style.width=`calc(${O}px * var(--persona-components-header-iconScale, 0.6))`,V.style.height=`calc(${O}px * var(--persona-components-header-iconScale, 0.6))`,p.replaceChildren(V)):p.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let O=P("img");O.src=e.launcher.iconUrl,O.alt="",O.className="persona-rounded-xl persona-object-cover",O.style.height=i,O.style.width=i,p.replaceChildren(O)}else p.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let g=P("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),y=Y("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:Vt.titleColor,...up}}),h=Y("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Vt.subtitleColor,...mS}});g.append(y,h),c?o.append(g):o.append(p,g);let C=s.clearChat??{},E=C.enabled??!0,A=C.placement??"inline",I=null,L=null;if(E){let V=Cs(e,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});I=V.button,L=V.wrapper,A==="top-right"&&(L.style.right="48px"),A==="inline"&&o.appendChild(L)}let k=l==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":E&&A==="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:R,wrapper:B}=vs(e,{showClose:n,wrapperClassName:k});return l!=="top-right"&&o.appendChild(B),{header:o,iconHolder:p,headerTitle:y,headerSubtitle:h,closeButton:R,closeButtonWrapper:B,clearChatButton:I,clearChatButtonWrapper:L}},Ri=(t,e,n)=>{let o=n?.launcher??{},s=o.closeButtonPlacement??"inline",i=o.clearChat?.placement??"inline";t.appendChild(e.header),s==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&i==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};var fS=t=>{let e=kr({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),n=t.layoutHeaderConfig?.onTitleClick;if(n){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return e};function hS(t,e,n){if(e?.length)for(let o of e){let{button:s,wrapper:i}=bs({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?xf(o.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(s.setAttribute("data-persona-header-action",o.id),o.shortcut){let l=Af(o.shortcut);l&&s.setAttribute("aria-keyshortcuts",l)}if(o.menuItems?.length){let l=Wf({items:o.menuItems,onSelect:c=>n?.(c),anchor:i,position:"bottom-right"});i.appendChild(l.element),s.addEventListener("click",c=>{c.stopPropagation(),l.toggle()})}else s.addEventListener("click",()=>n?.(o.id));t.appendChild(i)}}var yS=t=>{let{config:e,showClose:n=!0,onClose:o,layoutHeaderConfig:s,onHeaderAction:i}=t,l=e?.launcher??{},c=P("div","persona-flex persona-items-center persona-justify-between");c.setAttribute("data-persona-theme-zone","header"),c.style.minHeight=Vt.minHeight,c.style.padding="var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))",c.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",c.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",c.style.boxShadow="var(--persona-header-shadow, none)",c.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let u=s?.titleMenu,p,g;if(u){let B=Df({label:l.title??"Chat Assistant",menuItems:u.menuItems,onSelect:O=>{let V=_=>{_===!1&&B.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:O}}))},J=u.onSelect(O);J instanceof Promise?J.then(V,()=>{}):V(J)},hover:u.hover,className:""});p=B.element,p.style.color=Vt.titleColor,g=p.querySelector(".persona-combo-btn-label")??p}else{if(p=P("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),g=P("span","persona-text-base persona-font-semibold persona-truncate"),g.style.color=Vt.titleColor,Object.assign(g.style,up),g.textContent=l.title??"Chat Assistant",p.appendChild(g),s?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let O=s.onTitleClick;p.addEventListener("click",V=>{V.target.closest("button")||O()}),p.addEventListener("keydown",V=>{(V.key==="Enter"||V.key===" ")&&(V.preventDefault(),O())})}let B=s?.titleRowHover;B&&(p.style.borderRadius=B.borderRadius??"10px",p.style.padding=B.padding??"6px 4px 6px 12px",p.style.margin="-6px 0 -6px -12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.style.width="fit-content",p.style.flex="none",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=B.background??"",p.style.borderColor=B.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}))}c.appendChild(p);let y="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:h,wrapper:C}=vs(e,{showClose:n,wrapperClassName:y});o&&h.addEventListener("click",o);let E=P("div","persona-flex persona-items-center persona-gap-1");u||hS(E,s?.trailingActions,s?.onAction??i);let A=l.clearChat??{},I=null,L=null;if(A.enabled??!0){let B=A.placement??"inline",O=Cs(e,{wrapperClassName:B==="top-right"?"persona-absolute persona-top-4 persona-z-50":y});I=O.button,L=O.wrapper,B==="top-right"?L.style.right="48px":E.appendChild(L)}E.appendChild(C),c.appendChild(E);let k=P("div");k.style.display="none";let R=P("span");return R.style.display="none",{header:c,iconHolder:k,headerTitle:g,headerSubtitle:R,closeButton:h,closeButtonWrapper:C,clearChatButton:I,clearChatButtonWrapper:L}},cy={default:fS,minimal:yS},bS=t=>cy[t]??cy.default,Bl=(t,e,n)=>{if(e?.render){let l=e.render({config:t,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),c=P("div");c.style.display="none";let u=P("span"),p=P("span"),g=P("button");g.style.display="none";let y=P("div");return y.style.display="none",{header:l,iconHolder:c,headerTitle:u,headerSubtitle:p,closeButton:g,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",i=bS(o)({config:t,showClose:e?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:e,onHeaderAction:e?.onAction});return e&&(e.showIcon===!1&&(i.iconHolder.style.display="none"),e.showTitle===!1&&(i.headerTitle.style.display="none"),e.showSubtitle===!1&&(i.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(i.closeButton.style.display="none"),e.showClearChat===!1&&i.clearChatButtonWrapper&&(i.clearChatButtonWrapper.style.display="none")),i};var Wi=t=>{let{config:e}=t,n=Y("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=il(),s=Y("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""}}),{textarea:i,attachAutoResize:l}=nl(e);l();let c=ol(e),u=gs(e),p=rl(e),g=sl(e),y=Y("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});s.append(y),p&&(p.previewsContainer.style.gap="8px",y.append(p.previewsContainer),s.append(p.input)),s.append(i);let h=Y("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),C=Y("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),E=Y("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return p&&C.append(p.wrapper),u&&E.append(u.wrapper),E.append(c.wrapper),h.append(C,E),s.append(h),s.addEventListener("click",A=>{A.target!==c.button&&A.target!==c.wrapper&&A.target!==u?.button&&A.target!==u?.wrapper&&A.target!==p?.button&&A.target!==p?.wrapper&&i.focus()}),e?.statusIndicator?.mode==="transient"?n.append(o,g,s):n.append(o,s,g),{footer:n,suggestions:o,composerForm:s,header:y,textarea:i,sendButton:c.button,sendButtonWrapper:c.wrapper,micButton:u?.button??null,micButtonWrapper:u?.wrapper??null,statusText:g,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:h,leftActions:C,rightActions:E,setSendButtonMode:c.setMode}};import{ChevronUp as vS,MessageSquare as CS}from"lucide";var dy=()=>{let t=Y("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=P("span","persona-pill-peek__icon"),n=yt(CS,16,"currentColor",1.5);n&&e.appendChild(n);let o=P("span","persona-pill-peek__text"),s=P("span","persona-pill-peek__caret"),i=yt(vS,16,"currentColor",1.5);return i&&s.appendChild(i),t.append(e,o,s),{root:t,textNode:o}},Dl=t=>{let{config:e}=t,n=Y("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=il(),s=sl(e);s.style.display="none";let{textarea:i,attachAutoResize:l}=nl(e,{defaultMaxLines:5});l();let c=ol(e),u=gs(e),p=rl(e);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let g=Y("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),y=Y("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});p&&y.append(p.wrapper);let h=Y("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});u&&h.append(u.wrapper),h.append(c.wrapper),g.addEventListener("click",A=>{A.target!==c.button&&A.target!==c.wrapper&&A.target!==u?.button&&A.target!==u?.wrapper&&A.target!==p?.button&&A.target!==p?.wrapper&&i.focus()}),p&&g.append(p.input),g.append(y,i,h);let C=Y("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(C),p&&C.append(p.previewsContainer),n.append(o,g,s);let E=g;return{footer:n,suggestions:o,composerForm:g,header:C,textarea:i,sendButton:c.button,sendButtonWrapper:c.wrapper,micButton:u?.button??null,micButtonWrapper:u?.wrapper??null,statusText:s,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:E,leftActions:y,rightActions:h,setSendButtonMode:c.setMode}};var wS=t=>{switch(t){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}},SS=(t,e)=>{if(!t)return null;let n=wS(t);if(n===null)return null;let o=e?.[t],s=o!==void 0?o:n;return s||null},xS=(t,e)=>{let n=P("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",t),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=e,n},AS=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},mp=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},fp=320,fy=320,MS=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),ES=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),TS=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),kS=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),PS=t=>{if(!t||t.length===0)return null;let e=Y("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=Y("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),s=P("span","persona-mention-chip-icon"),i=se(n.iconName??"at-sign",13,"currentColor",2);i&&s.appendChild(i),o.appendChild(s),o.appendChild(Y("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},LS=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Id(o.ref,{readonly:!0,render:e}))}return n},py="\uE000",uy="\uE001",IS=(t,e,n,o)=>{let s=Math.random().toString(36).slice(2,8),i=h=>`${py}${s}:${h}${uy}`,l=e.map((h,C)=>h.kind==="text"?h.text:i(C)).join(""),c=n(l);if(!e.every((h,C)=>h.kind==="text"||c.includes(i(C)))){t.replaceChildren(LS(e,o));return}t.innerHTML=c;let p=new RegExp(`${py}${s}:(\\d+)${uy}`),g=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),y=[];for(let h=g.nextNode();h;h=g.nextNode())y.push(h);for(let h of y){let C=h;for(let E=p.exec(C.data);E;E=p.exec(C.data)){let A=e[Number(E[1])],I=C.splitText(E.index);I.data=I.data.slice(E[0].length),A?.kind==="mention"&&I.parentNode?.insertBefore(Id(A.ref,{readonly:!0,render:o}),I),C=I}}},HS=(t,e,n)=>{if(t.length===0)return null;try{let o=P("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),e&&(o.style.marginBottom="8px");let s=0,i=!1,l=()=>{i||(i=!0,o.remove(),n?.())};return t.forEach((c,u)=>{let p=P("img");p.alt=c.alt?.trim()||`Attached image ${u+1}`,p.loading="lazy",p.decoding="async",p.referrerPolicy="no-referrer",p.style.display="block",p.style.width="100%",p.style.maxWidth=`${fp}px`,p.style.maxHeight=`${fy}px`,p.style.height="auto",p.style.objectFit="contain",p.style.borderRadius="10px",p.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",p.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let g=!1;s+=1,p.addEventListener("error",()=>{g||(g=!0,s=Math.max(0,s-1),p.remove(),s===0&&l())}),p.addEventListener("load",()=>{g=!0}),AS(c.image)?(p.src=c.image,o.appendChild(p)):(g=!0,s=Math.max(0,s-1),p.remove())}),s===0?(l(),null):o}catch{return n?.(),null}},RS=t=>{if(t.length===0)return null;try{let e=P("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(o=>{if(!mp(o.audio))return;let s=P("audio");s.controls=!0,s.preload="metadata",s.src=o.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${fp}px`,e.appendChild(s),n+=1}),n===0?(e.remove(),null):e}catch{return null}},WS=t=>{if(t.length===0)return null;try{let e=P("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(o=>{if(!mp(o.video))return;let s=P("video");s.controls=!0,s.preload="metadata",s.src=o.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${fp}px`,s.style.maxHeight=`${fy}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(s),n+=1}),n===0?(e.remove(),null):e}catch{return null}},BS=t=>{if(t.length===0)return null;try{let e=P("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(o=>{if(!mp(o.data))return;let s=P("a");s.href=o.data,s.download=o.filename,s.target="_blank",s.rel="noopener noreferrer",s.textContent=o.filename,s.className="persona-message-file-attachment",s.style.display="inline-flex",s.style.alignItems="center",s.style.gap="6px",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.fontSize="0.875rem",s.style.textDecoration="underline",s.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",s.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",s.style.color="inherit",e.appendChild(s),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Bi=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.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 s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",t.appendChild(e),t.appendChild(n),t.appendChild(o),t.appendChild(s),t},DS=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:Bi};if(e){let s=e(o);if(s!==null)return s}return Bi()},OS=(t,e)=>{let n=P("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=e==="user"?t.userAvatar:t.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let s=P("img");s.src=o,s.alt=e==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(s)}else n.textContent=o,n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=e==="user"?"U":"A",n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},gy=(t,e,n="div")=>{let o=P(n,"persona-text-xs persona-text-persona-muted"),s=new Date(t.createdAt);return e.format?o.textContent=e.format(s):o.textContent=s.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Di=(t,e="bubble")=>{let n=["persona-message-bubble"];switch(e){case"flat":t==="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-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),t==="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-container","persona-text-persona-text","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"),t==="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-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},my={bubble:{padding:"0.75rem 1.25rem",fontSize:"0.875rem",lineHeight:"1.75"},minimal:{padding:"0.5rem 0.75rem",fontSize:"0.875rem",lineHeight:"1.75"},flat:{padding:"0.5rem 0",fontSize:"inherit",lineHeight:"inherit"}},_S=(t,e,n="bubble",o)=>{if(!o)return;let s=e==="user"?"user":"assistant",i=my[n??"bubble"]??my.bubble;o.padding&&(t.style.padding=`var(--persona-message-${s}-padding, ${i.padding})`),o.fontSize&&(t.style.fontSize=`var(--persona-message-${s}-font-size, ${i.fontSize})`),o.lineHeight&&(t.style.lineHeight=`var(--persona-message-${s}-line-height, ${i.lineHeight})`),o.fontFamily&&(t.style.fontFamily=`var(--persona-message-${s}-font-family, inherit)`)},Ol="custom:",FS=t=>`${Ol}${t}`,hy=(t,e)=>e!=="user"&&e!=="assistant"?[]:(t?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(e)),NS=(t,e,n,o)=>{let s=e.showCopy??!0,i=e.showUpvote??!1,l=e.showDownvote??!1,c=e.showReadAloud??!1,u=(e.showRegenerate??!1)&&o?.canRegenerate===!0,p=(e.showEdit??!1)&&o?.canEdit===!0,g=(e.showQuote??!1)&&o?.canQuote!==!1,y=hy(e,t.role);if(!s&&!i&&!l&&!c&&!u&&!p&&!g&&y.length===0){let R=P("div");return R.style.display="none",R.id=`actions-${t.id}`,R.setAttribute("data-actions-for",t.id),R}let h=e.visibility??"hover",C=e.align??"right",E=e.layout??"pill-inside",A={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[C],I={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[E],L=P("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${A} ${I} ${h==="hover"?"persona-message-actions-hover":""}`);L.id=`actions-${t.id}`,L.setAttribute("data-actions-for",t.id);let k=(R,B,O)=>{let V=Bf({icon:R,label:B,size:14,className:"persona-message-action-btn",chromeless:!0});return V.setAttribute("data-action",O),V};s&&L.appendChild(k("copy","Copy message","copy")),c&&L.appendChild(k("volume-2","Read aloud","read-aloud")),i&&L.appendChild(k("thumbs-up","Upvote","upvote")),l&&L.appendChild(k("thumbs-down","Downvote","downvote")),u&&L.appendChild(k("refresh-cw","Regenerate response","regenerate")),p&&L.appendChild(k("pencil","Edit message","edit")),g&&L.appendChild(k("quote","Quote message","quote"));for(let R of y)L.appendChild(k(R.iconName??"ellipsis",R.label,FS(R.id)));return L},hp=(t,e,n,o,s,i)=>{let l=n??{},c=l.layout??"bubble",u=l.avatar,p=l.timestamp,g=u?.show??!1,y=p?.show??!1,h=u?.position??"left",C=p?.position??"below",E=Di(t.role,c),A=P("div",E.join(" "));A.id=`bubble-${t.id}`,A.setAttribute("data-message-id",t.id),A.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message");let I=np(i?.widgetConfig?.future).components.message,L=i?.widgetConfig?.theme?.components?.message;_S(A,t.role,c,t.role==="user"?{...I.user,...L?.user,...i?.widgetConfig?.darkTheme?.components?.message?.user}:{...I.assistant,...L?.assistant,...i?.widgetConfig?.darkTheme?.components?.message?.assistant}),c==="flat"?(A.style.backgroundColor="transparent",A.style.color=t.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):t.role==="user"?(A.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",A.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(A.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",A.style.color="var(--persona-message-assistant-text, var(--persona-text))");let k=MS(t),R=t.content?.trim()??"",O=k.length>0&&R===Za,V=cl(i?.widgetConfig?.features?.streamAnimation),J=i?.widgetConfig?.features?.streamAnimation?.plugins,_=t.role==="assistant"&&V.type!=="none"?mi(V.type,J):null,Q=t.role==="assistant"&&_?.isAnimating?.(t)===!0,G=t.role==="assistant"&&_!==null&&(!!t.streaming||Q);G&&_?.bubbleClass&&A.classList.add(_.bubbleClass);let w=document.createElement("div");w.classList.add("persona-message-content"),t.streaming&&w.classList.add("persona-content-streaming"),G&&_&&(_.containerClass&&w.classList.add(_.containerClass),w.style.setProperty("--persona-stream-step",`${V.speed}ms`),w.style.setProperty("--persona-stream-duration",`${V.duration}ms`));let v=G?dl(t.content??"",V.buffer,_,t,!!t.streaming):t.content??"",T=()=>{let Ce=e({text:v,message:t,streaming:!!t.streaming,raw:t.rawContent});return G&&_?.wrap==="char"?fi(Ce,"char",t.id,{skipTags:_.skipTags}):G&&_?.wrap==="word"?fi(Ce,"word",t.id,{skipTags:_.skipTags}):Ce},x=null;if(O?(x=document.createElement("div"),x.innerHTML=T(),x.style.display="none",w.appendChild(x)):t.contentSegments?.length?IS(w,t.contentSegments,Ce=>e({text:Ce,message:t,streaming:!!t.streaming,raw:t.rawContent}),i?.widgetConfig?.contextMentions?.renderMentionToken):w.innerHTML=T(),G&&_?.useCaret&&!O&&R){let Ce=pl(),H=w.querySelectorAll(".persona-stream-char, .persona-stream-word"),Me=H[H.length-1];if(Me?.parentNode)Me.parentNode.insertBefore(Ce,Me.nextSibling);else{let de=w.lastElementChild;de?de.appendChild(Ce):w.appendChild(Ce)}}if(y&&C==="inline"&&t.createdAt){let Ce=gy(t,p,"span");Ce.classList.add("persona-timestamp-inline");let H=w.lastElementChild;H?H.appendChild(Ce):w.appendChild(Ce)}if(k.length>0){let Ce=HS(k,!O&&!!R,()=>{O&&x&&(x.style.display="")});Ce?A.appendChild(Ce):O&&x&&(x.style.display="")}let z=ES(t);if(z.length>0){let Ce=RS(z);Ce&&A.appendChild(Ce)}let W=TS(t);if(W.length>0){let Ce=WS(W);Ce&&A.appendChild(Ce)}let ee=kS(t);if(ee.length>0){let Ce=BS(ee);Ce&&A.appendChild(Ce)}let ne=t.contentSegments?.length?null:PS(t.contextMentions);if(ne&&A.appendChild(ne),A.appendChild(w),y&&C==="below"&&t.createdAt){let Ce=gy(t,p);Ce.classList.add("persona-mt-1"),A.appendChild(Ce)}let he=t.role==="assistant"?SS(t.stopReason,i?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let Ce=!!(v&&v.trim()),H=V.placeholder==="skeleton",Me=H&&V.buffer==="line"&&Ce;if(Ce)Me&&A.appendChild(hi());else if(H)A.appendChild(hi());else{let de=DS("inline",i?.loadingIndicatorRenderer,i?.widgetConfig);de&&A.appendChild(de)}}he&&t.stopReason&&!t.streaming&&(R||(w.style.display="none"),A.appendChild(xS(t.stopReason,he)));let ve=t.role==="assistant"&&!t.streaming&&!t.voiceCaption&&t.content&&t.content.trim()&&o?.enabled!==!1,Xe=i?.actionEligibility,Je=t.role==="user"&&!t.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&Xe?.canEdit===!0||o?.showQuote===!0&&Xe?.canQuote===!0||hy(o,"user").length>0);if((ve||Je)&&o){let Ce=NS(t,Je?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,s,Xe);A.appendChild(Ce)}if(!g||t.role==="system")return A;let Wt=P("div",`persona-message-with-avatar persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),$e=OS(u,t.role);return h==="right"||h==="left"&&t.role==="user"?Wt.append(A,$e):Wt.append($e,A),Wt};var VS=40,$S=(t,e)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}if(typeof e=="function"){let n=null;try{n=e()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){t.hidden=!0;return}t.appendChild(n),t.hidden=!1;return}if(e.type==="lucide"){let n=se(e.name,VS);if(!n){t.hidden=!0;return}t.appendChild(n)}else e.type==="image"?t.appendChild(Y("img",{className:"persona-welcome-icon-image",attrs:{src:e.url,alt:e.alt}})):t.appendChild(Y("span",{className:"persona-welcome-icon-text",text:e.text}));t.hidden=!1},yy=(t,e,n={})=>{let o=Y("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let s=P("p","persona-welcome-kicker");s.hidden=!0;let i=P("h2","persona-welcome-title"),l=P("p","persona-welcome-subtitle"),c=Y("div",{className:"persona-welcome-head-text"},s,i),u=Y("div",{className:"persona-welcome-title-row"},o,c);return{host:Y("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},u,l,e),iconHolder:o,kicker:s,title:i,subtitle:l,starterSuggestions:e}},ws=(t,e,n)=>{e.hidden=!n,e.style.display=n?"":"none",t.classList.toggle("persona-gap-6",n),t.classList.toggle("persona-gap-3",!n)},Fl=(t,e)=>{t.title.textContent=e.title,t.kicker.textContent=e.kicker??"",t.kicker.hidden=!e.kicker,t.subtitle.textContent=e.subtitle,t.subtitle.hidden=e.subtitle==="",$S(t.iconHolder,e.icon),t.host.setAttribute("data-persona-welcome-variant",e.variant),t.host.setAttribute("data-persona-welcome-dismiss",e.dismiss),t.host.setAttribute("data-persona-welcome-layout",e.layout??"top"),t.host.setAttribute("data-persona-welcome-anchor",e.anchor??"bottom"),e.iconPlacement==="inline"?t.host.setAttribute("data-persona-welcome-icon-placement","inline"):t.host.removeAttribute("data-persona-welcome-icon-placement"),e.align?t.host.setAttribute("data-persona-welcome-align",e.align):t.host.removeAttribute("data-persona-welcome-align")},zS="data-persona-welcome-plugin",by="data-persona-welcome-overlay",_l="persona-welcome-overlay-active",yp=new WeakMap,bp=(t,e,n)=>{n.setAttribute(zS,""),e.appendChild(n),e.setAttribute("data-persona-welcome-content","plugin"),e.setAttribute(by,""),t.classList.contains(_l)||(yp.set(t,t.scrollTop),t.classList.add(_l),t.scrollTop=0)},vp=(t,e,n)=>{n&&n!==e&&n.remove(),e.removeAttribute("data-persona-welcome-content"),e.removeAttribute(by),t.classList.contains(_l)&&(t.classList.remove(_l),t.scrollTop=yp.get(t)??t.scrollTop,yp.delete(t))},vy=()=>{let t=Y("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return t.hidden=!0,t},Nl=(t,e,n)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",s=Y("div",{className:Di("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:e,style:o==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});t.appendChild(Y("div",{className:"persona-flex"},s)),t.hidden=!1},Cy=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,wy=(t,e)=>{if(Cy()||typeof t.animate!="function"||!t.isConnected)return e(null),null;let n=t.getBoundingClientRect(),o=t.parentElement,s=0,i=0,l=0;if(o){let E=getComputedStyle(o);s=parseFloat(E.rowGap)||0;let A=t.previousElementSibling,I=t.nextElementSibling,k=o.getBoundingClientRect().top+(parseFloat(E.borderTopWidth)||0)+(parseFloat(E.paddingTop)||0)-o.scrollTop;i=Math.max(0,A?n.top-A.getBoundingClientRect().bottom-s:n.top-k),l=Math.max(0,I?I.getBoundingClientRect().top-n.bottom-s:0)}let c=t.style.overflow;t.style.overflow="hidden";let u=getComputedStyle(t),p=parseFloat(u.paddingTop)||0,g=parseFloat(u.paddingBottom)||0,y=t.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${p}px`,paddingBottom:`${g}px`,marginTop:`${i}px`,marginBottom:`${l}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-s}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),h=!1,C=()=>{h||(h=!0,t.style.overflow=c,e(y))};return y.finished.then(C).catch(C),y},Sy=(t,e,n,o=260)=>{if(e<=1||Cy()||typeof t.animate!="function"||!t.isConnected)return null;let s=n==="drop"?-e:e;return t.animate([{transform:`translateY(${s}px)`},{transform:"none"}],{duration:o,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var US="Hello \u{1F44B}",qS="I can answer questions and help you get things done here.",xy=new WeakSet,$t=(t,e)=>!!t&&t[e]!==void 0,jS=(t,e)=>{!t||t.debug!==!0||!e.length||xy.has(t)||(xy.add(t),e.forEach(n=>console.warn(`[persona] ${n}`)))},Vl=(t,e=t?.launcher?.fullHeight===!0&&!t.launcher.sidebarMode&&t.launcher.mountMode!=="docked")=>{let n=t?.welcome,o=t?.copy,s=t?.future?.v5Defaults===!0,i=n?.layout??(s?"centered":"top"),l=$t(n,"variant")?n.variant:o?.showWelcomeCard===!1?"none":"card",c=l==="hero"&&!s&&n?.layout===void 0?"on-first-message":$t(n,"dismiss")?n.dismiss:s||l==="hero"?"on-first-message":"never",u=[];$t(n,"title")&&$t(o,"welcomeTitle")&&u.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),$t(n,"subtitle")&&$t(o,"welcomeSubtitle")&&u.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),$t(n,"variant")&&$t(o,"showWelcomeCard")&&u.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),l==="hero"&&$t(n,"message")&&u.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!s&&n?.layout===void 0&&l==="hero"&&$t(n,"dismiss")&&n.dismiss!=="on-first-message"&&u.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let p=n?.anchor??(i==="centered"&&e?"center":"bottom"),g=ki(n?.anchorComposerTop)!==null;return $t(n,"anchorComposerTop")&&!g&&u.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),p!=="center"&&($t(n,"anchorComposerTop")||$t(n,"composerGap"))&&u.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),jS(t,u),{title:$t(n,"title")?n.title:o?.welcomeTitle??(s?"What can I help with?":US),kicker:n?.kicker??"",subtitle:$t(n,"subtitle")?n.subtitle:o?.welcomeSubtitle??(s?"":qS),icon:n?.icon,align:n?.align==="start"||n?.align==="center"?n.align:i==="centered"?"center":void 0,iconPlacement:n?.icon&&typeof n.icon!="function"&&n.icon.placement==="inline"?"inline":"above",variant:l,dismiss:c,message:l==="hero"?void 0:n?.message,layout:i,anchor:p,anchorComposerTop:g?n.anchorComposerTop:"44%",composerGap:n?.composerGap?.trim()||Hl}},Ay=t=>(t??[]).some(e=>e.role==="user")?"active":"empty",Ss=(t,e)=>t.variant==="none"?!1:t.dismiss==="never"?!0:!(e??[]).some(n=>n.role==="user");var KS="var(--persona-components-panel-maxWidth)",My="var(--persona-components-panel-height)",GS="var(--persona-components-panel-maxHeight)",Pr=t=>{let e=xr(t),n=e.launcherWidth?t?.launcher?.width:e.legacyLauncherWidth?t?.launcherWidth:void 0,o=t?.launcher?.heightOffset??0,s=o===0?`max(200px, ${My})`:`max(200px, calc(${My} - ${o}px))`;return{width:n??Lm,maxWidth:n??KS,height:s,maxHeight:GS}},Ey="16px",wp="10px",Sp="14px",Ty=t=>{let e=t?.launcher?.enabled??!0,n=rt(t);if(Ii(t)){let p=t?.launcher?.composerBar??{},g=P("div","persona-widget-wrapper persona-fixed persona-transition");g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=p.expandedSize??"anchored",g.style.zIndex=String(t?.launcher?.zIndex??Dt);let y=P("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");y.style.width="100%",g.appendChild(y);let h=P("div","persona-widget-pill-root");return h.setAttribute("data-persona-composer-bar",""),h.dataset.state="collapsed",h.dataset.expandedSize=p.expandedSize??"anchored",h.style.zIndex=String(t?.launcher?.zIndex??Dt),{wrapper:g,panel:y,pillRoot:h}}if(n){let p=P("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),g=P("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return p.appendChild(g),{wrapper:p,panel:g}}if(!e){let p=P("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),g=P("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),y=xr(t),C=y.launcherWidth||y.legacyLauncherWidth||t?.theme?.components?.panel?.width!==void 0?Pr(t).width:"100%";return p.style.width=C,g.style.width="100%",p.appendChild(g),{wrapper:p,panel:g}}let s=t?.launcher??{},i=s.position&&ln[s.position]?ln[s.position]:ln["bottom-right"],l=P("div",`persona-widget-wrapper persona-fixed ${i} persona-transition`);l.style.zIndex=String(t?.launcher?.zIndex??Dt);let c=P("div","persona-widget-panel persona-relative persona-min-h-[320px]"),u=Pr(t);return c.style.width=u.width,c.style.maxWidth=u.maxWidth,l.appendChild(c),{wrapper:l,panel:c}},xp=t=>{let e=Y("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":cp(t)}});return e.hidden=!0,e},ky=(t,e)=>{let n=xp("starter"),o=yy(t,n,{flatShadow:rt(t)}),s=Vl(t);Fl(o,s),ws(e,o.host,Ss(s,t?.initialMessages));let i=vy();return Nl(i,s.message,t),{welcome:o,greetingHost:i}},YS=(t,e)=>{let n=P("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:s}=vs(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:Ey,iconSize:wp});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let i=t?.launcher?.clearChat?.enabled??!0,l=null,c=null;if(i){let J=Cs(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:Ey,iconSize:Sp});l=J.button,c=J.wrapper,c.style.position="absolute",c.style.top="8px",c.style.right="32px",c.style.zIndex="10"}let u=Y("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=Y("div",{className:"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",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});p.style.setProperty("scrollbar-gutter","stable");let{welcome:g,greetingHost:y}=ky(t,p),{host:h,title:C,subtitle:E}=g,A=g.starterSuggestions,I=P("div","persona-widget-messages persona-flex persona-flex-col");I.style.gap="var(--persona-components-message-gap, 12px)";let L=xp("followUp"),k=Ko(t,!0);k&&(I.style.maxWidth=k,I.style.marginLeft="auto",I.style.marginRight="auto",I.style.width="100%"),p.append(h,y,I,L);let R=Y("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),B=Dl({config:t}),{root:O,textNode:V}=dy();return n.append(u,s,p,R),c&&n.appendChild(c),{container:n,body:p,messagesWrapper:I,starterSuggestions:A,transcriptSuggestions:L,composerOverlay:R,suggestions:B.suggestions,textarea:B.textarea,sendButton:B.sendButton,sendButtonWrapper:B.sendButtonWrapper,micButton:B.micButton,micButtonWrapper:B.micButtonWrapper,composerForm:B.composerForm,statusText:B.statusText,welcomeHost:h,welcomeIconHolder:g.iconHolder,greetingHost:y,introKicker:g.kicker,introTitle:C,introSubtitle:E,closeButton:o,closeButtonWrapper:s,clearChatButton:l,clearChatButtonWrapper:c,iconHolder:P("span"),headerTitle:P("span"),headerSubtitle:P("span"),header:u,footer:B.footer,attachmentButton:B.attachmentButton,attachmentButtonWrapper:B.attachmentButtonWrapper,attachmentInput:B.attachmentInput,attachmentPreviewsContainer:B.attachmentPreviewsContainer,actionsRow:B.actionsRow,leftActions:B.leftActions,rightActions:B.rightActions,setSendButtonMode:B.setSendButtonMode,peekBanner:O,peekTextNode:V}},Py=(t,e=!0)=>{if(Ii(t))return YS(t,e);let n=Y("div",{className:"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",attrs:{"data-persona-theme-zone":"container"}}),o=t?.layout?.header,s=t?.layout?.showHeader!==!1,i=o?Bl(t,o,{showClose:e}):kr({config:t,showClose:e}),l=Y("div",{className:"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",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});l.style.setProperty("scrollbar-gutter","stable");let{welcome:c,greetingHost:u}=ky(t,l),{host:p,title:g,subtitle:y}=c,h=c.starterSuggestions,C=P("div","persona-widget-messages persona-flex persona-flex-col");C.style.gap="var(--persona-components-message-gap, 12px)";let E=xp("followUp"),A=Ko(t,!1);A&&(C.style.maxWidth=A,C.style.marginLeft="auto",C.style.marginRight="auto",C.style.width="100%"),l.append(p,u,C,E);let I=Wi({config:t}),L=t?.layout?.showFooter!==!1;s?Ri(n,i,t):(i.header.style.display="none",Ri(n,i,t)),n.append(l);let k=Y("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}});return L||(I.footer.style.display="none"),n.append(I.footer),n.append(k),{container:n,body:l,messagesWrapper:C,starterSuggestions:h,transcriptSuggestions:E,composerOverlay:k,suggestions:I.suggestions,textarea:I.textarea,sendButton:I.sendButton,sendButtonWrapper:I.sendButtonWrapper,micButton:I.micButton,micButtonWrapper:I.micButtonWrapper,composerForm:I.composerForm,statusText:I.statusText,welcomeHost:p,welcomeIconHolder:c.iconHolder,greetingHost:u,introKicker:c.kicker,introTitle:g,introSubtitle:y,closeButton:i.closeButton,closeButtonWrapper:i.closeButtonWrapper,clearChatButton:i.clearChatButton,clearChatButtonWrapper:i.clearChatButtonWrapper,iconHolder:i.iconHolder,headerTitle:i.headerTitle,headerSubtitle:i.headerSubtitle,header:i.header,footer:I.footer,attachmentButton:I.attachmentButton,attachmentButtonWrapper:I.attachmentButtonWrapper,attachmentInput:I.attachmentInput,attachmentPreviewsContainer:I.attachmentPreviewsContainer,actionsRow:I.actionsRow,leftActions:I.leftActions,rightActions:I.rightActions,setSendButtonMode:I.setSendButtonMode}};var Ap=(t,e)=>{let n=P("button");n.type="button",n.innerHTML=`
20
15
  <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>
21
16
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
22
17
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -24,15 +19,15 @@ _Details: ${n.message}_`:o}var mg=t=>({isError:!0,content:[{type:"text",text:t}]
24
19
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>
25
20
  </span>
26
21
  <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>
27
- `,n.addEventListener("click",e);let o=i=>{let l=i.launcher??{},c=xt(i),d=md(i)==="circle";d?(n.dataset.personaLauncherVariant="circle",n.setAttribute("aria-label",l.title??"Open chat")):(n.removeAttribute("data-persona-launcher-variant"),n.removeAttribute("aria-label"));let g=n.querySelector("[data-role='launcher-title']");if(g){let x=l.title??"Chat Assistant";g.textContent=x,g.setAttribute("title",x)}let u=n.querySelector("[data-role='launcher-subtitle']");if(u){let x=l.subtitle??"Here to help you get answers fast";u.textContent=x,u.setAttribute("title",x)}let m=n.querySelector(".persona-flex-col");m&&(l.textHidden||c||d?m.style.display="none":m.style.display="");let y=n.querySelector("[data-role='launcher-icon']");if(y)if(l.agentIconHidden)y.style.display="none";else{let x=l.agentIconSize??"40px";if(y.style.height=x,y.style.width=x,l.agentIconBackgroundColor?(y.style.backgroundColor=l.agentIconBackgroundColor,y.classList.remove("persona-bg-persona-primary")):(y.style.backgroundColor="",y.classList.add("persona-bg-persona-primary")),y.innerHTML="",l.agentIconName){let D=parseFloat(x)||24,L=de(l.agentIconName,D*.6,"var(--persona-text-inverse, #ffffff)",1.5);L?(y.appendChild(L),y.style.display=""):(y.textContent=l.agentIconText??"\u{1F4AC}",y.style.display="")}else l.iconUrl?y.style.display="none":(y.textContent=l.agentIconText??"\u{1F4AC}",y.style.display="")}let b=n.querySelector("[data-role='launcher-image']");if(b){let x=l.agentIconSize??"40px";b.style.height=x,b.style.width=x,l.iconUrl&&!l.agentIconName&&!l.agentIconHidden?(b.src=l.iconUrl,b.style.display="block"):b.style.display="none"}let C=n.querySelector("[data-role='launcher-call-to-action-icon']");if(C){let x=l.callToActionIconSize??"32px";C.style.height=x,C.style.width=x,l.callToActionIconBackgroundColor?(C.style.backgroundColor=l.callToActionIconBackgroundColor,C.classList.remove("persona-bg-persona-primary")):(C.style.backgroundColor="",C.classList.add("persona-bg-persona-primary")),l.callToActionIconColor?(C.style.color=l.callToActionIconColor,C.classList.remove("persona-text-persona-call-to-action")):(C.style.color="",C.classList.add("persona-text-persona-call-to-action"));let D=0;if(l.callToActionIconPadding?(C.style.boxSizing="border-box",C.style.padding=l.callToActionIconPadding,D=(parseFloat(l.callToActionIconPadding)||0)*2):(C.style.boxSizing="",C.style.padding=""),l.callToActionIconHidden||d)C.style.display="none";else if(C.style.display=c?"none":"",C.innerHTML="",l.callToActionIconName){let L=parseFloat(x)||24,$=Math.max(L-D,8),K=de(l.callToActionIconName,$,"currentColor",1.5);K?C.appendChild(K):C.textContent=l.callToActionIconText??"\u2197"}else C.textContent=l.callToActionIconText??"\u2197"}let S=l.position&&$n[l.position]?$n[l.position]:$n["bottom-right"],E="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-launcher persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",H="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-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=c?H:`${E} ${S}`,c||(n.style.zIndex=String(l.zIndex??ln));let I="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",N="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=l.border??I,n.style.boxShadow=l.shadow!==void 0?l.shadow.trim()===""?"none":l.shadow:N,c?(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=l.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},s=()=>{n.removeEventListener("click",e),n.remove()};return t&&o(t),{element:n,update:o,destroy:s}},o0="teaser-dismissed",ow=new Set,nw=t=>{let e=t?.persistState;return`${(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"}${o0}`},r0=(t,e)=>{if(ow.has(t))return!0;if(!e)return!1;try{return window.localStorage.getItem(t)==="1"}catch{return!1}},s0=(t,e)=>{if(ow.add(t),!!e)try{window.localStorage.setItem(t,"1")}catch{}},i0=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,a0=t=>{let e=t?.launcher?.teaser;return!e||!e.text||t?.launcher?.enabled===!1||xt(t??{})?null:e},rw=(t,e)=>{let n=P("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=t??{},s=null,i=null,l=null,c=null,d=null,g=!1,u=!1,m=!1,y=!1,b=()=>(s?.frequency??"once")==="once"&&o.persistState!==!1,C=()=>{d!==null&&(clearTimeout(d),d=null)},S=()=>{!i||!g||(g=!1,i.hidden=!0)},E=Z=>{C(),m=!0,S(),s0(nw(o),Z&&b())},H=Z=>{!s||m||E(Z==="user"&&g)},I=()=>{d=null,!(!i||m||y)&&(u=!0,g=!0,i.hidden=!1,!(i0()||typeof i.animate!="function")&&i.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},N=()=>{!s||!i||m||u||y||r0(nw(o),b())||(C(),d=setTimeout(I,Math.max(0,s.delayMs??0)))},x=()=>{E(b()),e()},D=Z=>{Z.stopPropagation(),E(b())},$=of(t,()=>{H("user"),e()}),K=()=>{C(),c?.removeEventListener("click",x),l?.removeEventListener("click",D),i?.remove(),i=null,c=null,l=null,g=!1},se=()=>{c=G("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),c.addEventListener("click",x),l=G("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),l.addEventListener("click",D),i=G("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},c,l),n.insertBefore(i,$.element)},ne=()=>{let Z=o.launcher?.position??"bottom-right",F=$n[Z]??$n["bottom-right"];if(!i){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",$.element.style.position="";return}n.className=Nn("persona-launcher-surface",F),n.setAttribute("data-teaser",Z),n.style.zIndex=String(o.launcher?.zIndex??ln),$.element.style.position="static"},M=Z=>{let F=a0(Z);if(s=F,!F){K();return}i||se(),c.textContent=F.text,l.hidden=F.dismissible===!1,l.setAttribute("aria-label",F.dismissLabel??"Dismiss message"),N()},T=Z=>{o=Z,$.update(Z),M(Z),ne()},_=(Z,F="user")=>{y=Z,Z&&H(F)},k=()=>{K(),$.destroy(),n.remove()};return n.appendChild($.element),t&&(M(t),ne()),{element:n,launcher:$,get teaser(){return i?{element:i,show:I,dismiss:E}:null},setPanelOpen:_,update:T,destroy:k}};var sw=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:s}=ZC(t),i=tw(t,e),l={wrapper:n,panel:o,pillRoot:s},c={container:i.container,body:i.body,messagesWrapper:i.messagesWrapper,starterSuggestions:i.starterSuggestions,transcriptSuggestions:i.transcriptSuggestions,composerOverlay:i.composerOverlay,welcomeHost:i.welcomeHost,welcomeIconHolder:i.welcomeIconHolder,greetingHost:i.greetingHost,introTitle:i.introTitle,introSubtitle:i.introSubtitle},d={element:i.header,iconHolder:i.iconHolder,headerTitle:i.headerTitle,headerSubtitle:i.headerSubtitle,closeButton:i.closeButton,closeButtonWrapper:i.closeButtonWrapper,clearChatButton:i.clearChatButton,clearChatButtonWrapper:i.clearChatButtonWrapper},g={footer:i.footer,form:i.composerForm,textarea:i.textarea,sendButton:i.sendButton,sendButtonWrapper:i.sendButtonWrapper,micButton:i.micButton,micButtonWrapper:i.micButtonWrapper,statusText:i.statusText,suggestions:i.suggestions,attachmentButton:i.attachmentButton,attachmentButtonWrapper:i.attachmentButtonWrapper,attachmentInput:i.attachmentInput,attachmentPreviewsContainer:i.attachmentPreviewsContainer,actionsRow:i.actionsRow,leftActions:i.leftActions,rightActions:i.rightActions,setSendButtonMode:i.setSendButtonMode,peekBanner:i.peekBanner,peekTextNode:i.peekTextNode};return{shell:l,panelElements:i,transcript:c,header:d,composer:g,replaceHeader:y=>(d.element.replaceWith(y.header),d.element=y.header,d.iconHolder=y.iconHolder,d.headerTitle=y.headerTitle,d.headerSubtitle=y.headerSubtitle,d.closeButton=y.closeButton,d.closeButtonWrapper=y.closeButtonWrapper,d.clearChatButton=y.clearChatButton,d.clearChatButtonWrapper=y.clearChatButtonWrapper,y),replaceComposer:y=>{g.footer.replaceWith(y),g.footer=y}}},rf=({config:t,plugins:e,onToggle:n})=>{let o=e.find(i=>i.renderLauncher);if(o?.renderLauncher){let i=o.renderLauncher({config:t,defaultRenderer:()=>of(t,n).element,onToggle:n});if(i)return{instance:null,element:i}}let s=rw(t,n);return{instance:s,element:s.element}};var l0=t=>{let e=t?.persistState;return(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"},c0=(t,e,n)=>`${l0(t)}plugin:${e}:${n}`,iw=t=>{let e=new Map,n=!1,o=()=>{if(n||t()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return s=>{let i=l=>c0(t(),s,l);return{get:l=>{let c=i(l),d=o();if(d)try{return d.getItem(c)}catch{n=!0}return e.get(c)??null},set:(l,c)=>{let d=i(l),g=o();if(g)try{g.setItem(d,c);return}catch{n=!0}e.set(d,c)},remove:l=>{let c=i(l);e.delete(c);let d=o();if(d)try{d.removeItem(c)}catch{n=!0}}}}};var d0=(t,e)=>{let n=t.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,e).join(`
28
- `):""},sf=(t,e,n)=>{$c(t,e,{stateSet:n,previewKind:"reasoning",iconColor:"currentColor"})},af=(t,e,n=new Set)=>{e=Vc(e,"reasoning");let o=t.reasoning,s=Oc("persona-reasoning-bubble",t.id);if(!o)return rr(s,t,e,"reasoning");let i=e?.features?.reasoningDisplay??{},l=i.expandable??Es.expandable,c=l&&n.has(t.id),d=o.status!=="complete",g=d0(t,i.previewMaxLines??Es.previewMaxLines),u=Nc({expandable:l,expanded:c,bubbleType:"reasoning"}),m=P("div","persona-flex persona-flex-col persona-text-left"),y=P("span","persona-text-xs persona-text-persona-primary"),b=Wr(e,"reasoning")==="row",C=b&&!d?`Thought for ${Ra(o.durationMs??(o.completedAt!==void 0&&o.startedAt!==void 0?o.completedAt-o.startedAt:void 0))}`:"Thinking...",S=e?.reasoning??{},E=String(o.startedAt??Date.now()),H=()=>{let F=P("span","");return F.setAttribute("data-tool-elapsed",E),F.textContent=Tc(o),F},I=S.renderCollapsedSummary?.({message:t,reasoning:o,defaultSummary:C,previewText:g,isActive:d,config:e??{},elapsed:Tc(o),createElapsedElement:H});typeof I=="string"&&I.trim()?(y.textContent=I,m.appendChild(y)):I instanceof HTMLElement?m.appendChild(I):(y.textContent=C,m.appendChild(y));let N=P("span","persona-text-xs persona-text-persona-primary");N.textContent=Fy(o),b||m.appendChild(N);let x=i.loadingAnimation??Es.loadingAnimation,D=S.activeTextTemplate,L=S.completeTextTemplate,$=d?D:L,K=I instanceof HTMLElement,se=(F,ie)=>{y.textContent="";let le=Ec(F,""),pe=0;for(let ve of le){let Ce=ve.styles.length>0?(()=>{let me=P("span",ve.styles.map(vt=>`persona-tool-text-${vt}`).join(" "));return y.appendChild(me),me})():y;if(ve.isDuration&&d)Ce.appendChild(H());else{let me=ve.isDuration?Tc(o):ve.text;ie?pe=vi(Ce,me,pe):Ce.appendChild(document.createTextNode(me))}}};if(!K&&$)if(N.style.display="none",y.style.display="",d&&x!=="none"){let F=S.loadingAnimationDuration??2e3;y.setAttribute("data-preserve-animation","true"),x==="pulse"?(y.classList.add("persona-tool-loading-pulse"),y.style.setProperty("--persona-tool-anim-duration",`${F}ms`),se($,!1)):(y.classList.add(`persona-tool-loading-${x}`),y.style.setProperty("--persona-tool-anim-duration",`${F}ms`),x==="shimmer-color"&&(S.loadingAnimationColor&&y.style.setProperty("--persona-tool-anim-color",S.loadingAnimationColor),S.loadingAnimationSecondaryColor&&y.style.setProperty("--persona-tool-anim-secondary-color",S.loadingAnimationSecondaryColor)),se($,!0))}else se($,!1);else if(!K&&d&&x!=="none"){y.style.display="";let F=S.loadingAnimationDuration??2e3;if(y.setAttribute("data-preserve-animation","true"),x==="pulse")y.classList.add("persona-tool-loading-pulse"),y.style.setProperty("--persona-tool-anim-duration",`${F}ms`);else{y.classList.add(`persona-tool-loading-${x}`),y.style.setProperty("--persona-tool-anim-duration",`${F}ms`),x==="shimmer-color"&&(S.loadingAnimationColor&&y.style.setProperty("--persona-tool-anim-color",S.loadingAnimationColor),S.loadingAnimationSecondaryColor&&y.style.setProperty("--persona-tool-anim-secondary-color",S.loadingAnimationSecondaryColor));let ie=y.textContent||C;y.textContent="",vi(y,ie,0)}o.status==="complete"&&!b&&(y.style.display="none")}else K||(o.status==="complete"&&!b?y.style.display="none":y.style.display="");if(i.iconName&&!K){let F=P("span","persona-reasoning-header-icon"),ie=de(i.iconName,16,"currentColor",2);ie&&(F.appendChild(ie),u.appendChild(F))}let ne="currentColor",M=Ci(u,m,{expandable:l,expanded:c,iconColor:ne,metaGap:!1}),T=Fc({bubble:s,previewKind:"reasoning",expanded:c,isActive:d,previewText:g,activePreview:i.activePreview,activeMinHeight:i.activeMinHeight,renderPreview:()=>e?.reasoning?.renderCollapsedPreview?.({message:t,reasoning:o,defaultPreview:g,isActive:d,config:e??{}})});if(!l)return s.append(u,T),rr(s,t,e,"reasoning");let _=P("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");_.style.display=c?"":"none";let k=o.chunks.join(""),Z=P("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Z.textContent=k||(o.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),_.appendChild(Z),Uc({expanded:c,header:u,toggleIcon:M,content:_,collapsedPreview:T,iconColor:ne}),s.append(u,T,_),rr(s,t,e,"reasoning")};var aw=t=>{if(t==null)return!0;if(typeof t=="string"){if(!t.trim())return!0;try{return aw(JSON.parse(t))}catch{return!1}}return typeof t=="object"&&Object.keys(t).length===0},p0=t=>{if(t!==null&&typeof t=="object")return!0;if(typeof t!="string")return!1;try{let e=JSON.parse(t);return e!==null&&typeof e=="object"}catch{return!1}};function lw(t,e,n){let o=e.toolCall;if(!o)return;let s=n.toolCall??{},i=(c,d)=>{let g=G("section",{className:"persona-tool-detail",attrs:{"data-persona-tool-detail":c.toLowerCase()},style:{backgroundColor:s.codeBlockBackgroundColor,borderColor:s.codeBlockBorderColor,borderWidth:s.codeBlockBorderColor?"1px":void 0}}),u=G("div",{className:"persona-tool-detail-label",text:c,style:{color:s.labelTextColor}}),m=bi(d),y=G("pre",{className:`persona-tool-detail-value${p0(d)?" persona-tool-detail-code":""}`,text:m,attrs:m.length>420||m.split(`
29
- `).length>7?{tabindex:"0","aria-label":`${c} content`}:{},style:{color:s.codeBlockTextColor??s.contentTextColor}}),b=G("button",{className:"persona-tool-detail-copy",attrs:{type:"button","data-persona-copy-tool-detail":"","aria-label":`Copy ${c.toLowerCase()}`,title:`Copy ${c.toLowerCase()}`}}),C=de("copy",14,"currentColor",1.7);C&&b.appendChild(C),g.append(u,y,b),t.appendChild(g)};aw(o.args)||i("Request",o.args);let l=o.status==="complete"&&o.result!==void 0?o.result:o.chunks?.join("");l!==void 0&&(typeof l!="string"||l.trim())&&i("Response",l),o.success===!1&&t.appendChild(G("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":"",role:"status"}}))}var lf=new WeakMap;async function cw(t){let e=t.closest("[data-persona-tool-detail]"),n=e?.querySelector("pre");if(!n)return;let o=`Copy ${e?.getAttribute("data-persona-tool-detail")}`;clearTimeout(lf.get(t));try{await navigator.clipboard.writeText(n.textContent??""),t.dataset.copied="true",t.setAttribute("aria-label","Copied"),t.title="Copied";let s=de("check",14,"currentColor",2);s&&t.replaceChildren(s)}catch{t.setAttribute("aria-label","Copy failed \u2014 try again"),t.title="Copy failed \u2014 try again"}lf.set(t,setTimeout(()=>{delete t.dataset.copied,t.setAttribute("aria-label",o),t.title=o;let s=de("copy",14,"currentColor",1.7);s&&t.replaceChildren(s),lf.delete(t)},1800))}var dw=(t,e=!1)=>t.toggleTextColor||t.headerTextColor||(e?"currentColor":"var(--persona-primary, #171717)"),u0=(t,e)=>{let n=t.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).slice(-e).join(`
30
- `);let s=bi(n.args).trim();return s?s.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(0,e).join(`
31
- `):""},cf=(t,e)=>{t.style.backgroundColor=e.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",t.style.borderColor=e.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",t.style.color=e.codeBlockTextColor??"var(--persona-text, #171717)"},g0=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,s=o?.collapsedMode??or.collapsedMode,i=n?.success===!1?n.error||"Tool failed":u0(t,o?.previewMaxLines??or.previewMaxLines),l=n?Wr(e,"tool")==="row"?`${n.status==="complete"?"Used":"Using"} ${n.name?.trim()||"tool"}`:$y(n):"";if(!n)return{summary:l,previewText:i,isActive:!1};let c=n.status!=="complete",d=e?.toolCall??{},g=l;return s==="tool-name"?g=n.name?.trim()||l:s==="tool-preview"&&i&&(g=i),c&&d.activeTextTemplate?g=Ru(n,d.activeTextTemplate,g):!c&&d.completeTextTemplate&&(g=Ru(n,d.completeTextTemplate,g)),n.success===!1&&(g+=" \xB7 Failed"),{summary:g,previewText:i,isActive:c}},df=(t,e,n,o)=>{$c(t,e,{stateSet:n,previewKind:"tool",iconColor:dw(o?.toolCall??{},e.classList.contains("persona-activity-row"))})},pf=(t,e,n=new Set)=>{e=Vc(e,"tool");let o=t.toolCall,s=e?.toolCall??{},i=Oc("persona-tool-bubble",t.id);if(s.backgroundColor&&(i.style.backgroundColor=s.backgroundColor),s.borderColor&&(i.style.borderColor=s.borderColor),s.borderWidth&&(i.style.borderWidth=s.borderWidth),s.borderRadius&&(i.style.borderRadius=s.borderRadius),i.style.boxShadow=s.shadow!==void 0?s.shadow.trim()===""?"none":s.shadow:"var(--persona-tool-bubble-shadow)",!o)return rr(i,t,e,"tool");let l=e?.features?.toolCallDisplay??{},c=l.expandable??or.expandable,d=c&&n.has(t.id),{summary:g,previewText:u,isActive:m}=g0(t,e),y=Nc({expandable:c,expanded:d,bubbleType:"tool"});s.headerBackgroundColor&&(y.style.backgroundColor=s.headerBackgroundColor),s.headerPaddingX&&(y.style.paddingLeft=s.headerPaddingX,y.style.paddingRight=s.headerPaddingX),s.headerPaddingY&&(y.style.paddingTop=s.headerPaddingY,y.style.paddingBottom=s.headerPaddingY);let b=P("div","persona-flex persona-flex-col persona-text-left"),C=P("span","persona-text-xs persona-text-persona-primary");s.headerTextColor&&(C.style.color=s.headerTextColor);let S=String(o.startedAt??Date.now()),E=()=>{let T=P("span","");return T.setAttribute("data-tool-elapsed",S),T.textContent=Mc(o),T},H=s.renderCollapsedSummary?.({message:t,toolCall:o,defaultSummary:g,previewText:u,collapsedMode:l.collapsedMode??or.collapsedMode,isActive:m,config:e??{},elapsed:Mc(o),createElapsedElement:E});typeof H=="string"&&H.trim()?(C.textContent=H,b.appendChild(C)):H instanceof HTMLElement?b.appendChild(H):(C.textContent=g,b.appendChild(C));let I=l.loadingAnimation??or.loadingAnimation,N=s.activeTextTemplate,x=s.completeTextTemplate,D=m?N:x,L=H instanceof HTMLElement,$=(T,_)=>{C.textContent="";let k=o.name?.trim()||"tool",Z=Ec(T,k),F=0;for(let ie of Z){let le=ie.styles.length>0?(()=>{let pe=P("span",ie.styles.map(ve=>`persona-tool-text-${ve}`).join(" "));return C.appendChild(pe),pe})():C;if(ie.isDuration&&m)le.appendChild(E());else{let pe=ie.isDuration?Mc(o):ie.text;_?F=vi(le,pe,F):le.appendChild(document.createTextNode(pe))}}};if(!L)if(m&&I!=="none"){let T=s.loadingAnimationDuration??2e3;if(C.setAttribute("data-preserve-animation","true"),I==="pulse")C.classList.add("persona-tool-loading-pulse"),C.style.setProperty("--persona-tool-anim-duration",`${T}ms`),D&&$(D,!1);else if(C.classList.add(`persona-tool-loading-${I}`),C.style.setProperty("--persona-tool-anim-duration",`${T}ms`),I==="shimmer-color"&&(s.loadingAnimationColor&&C.style.setProperty("--persona-tool-anim-color",s.loadingAnimationColor),s.loadingAnimationSecondaryColor&&C.style.setProperty("--persona-tool-anim-secondary-color",s.loadingAnimationSecondaryColor)),D)$(D,!0);else{let _=C.textContent||g;C.textContent="",vi(C,_,0)}}else D&&$(D,!1);let K=dw(s,Wr(e,"tool")==="row"),se=Ci(y,b,{expandable:c,expanded:d,iconColor:K,metaGap:!0}),ne=Fc({bubble:i,previewKind:"tool",expanded:d,isActive:m,previewText:u,activePreview:l.activePreview,activeMinHeight:l.activeMinHeight,renderPreview:()=>s.renderCollapsedPreview?.({message:t,toolCall:o,defaultPreview:u,isActive:m,config:e??{}})});if(!c)return i.append(y,ne),rr(i,t,e,"tool");let M=P("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(M.style.display=d?"":"none",s.contentBackgroundColor&&(M.style.backgroundColor=s.contentBackgroundColor),s.contentTextColor&&(M.style.color=s.contentTextColor),s.contentPaddingX&&(M.style.paddingLeft=s.contentPaddingX,M.style.paddingRight=s.contentPaddingX),s.contentPaddingY&&(M.style.paddingTop=s.contentPaddingY,M.style.paddingBottom=s.contentPaddingY),e.future?.v5Defaults===!0)lw(M,t,e);else{if(o.name){let T=P("div","persona-text-xs persona-text-persona-muted persona-italic");s.contentTextColor?T.style.color=s.contentTextColor:s.headerTextColor&&(T.style.color=s.headerTextColor),T.textContent=o.name,M.appendChild(T)}if(o.args!==void 0){let T=P("div","persona-space-y-1"),_=P("div","persona-text-xs persona-text-persona-muted");s.labelTextColor&&(_.style.color=s.labelTextColor),_.textContent="Arguments";let k=P("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",cf(k,s),k.textContent=bi(o.args),T.append(_,k),M.appendChild(T)}if(o.chunks&&o.chunks.length){let T=P("div","persona-space-y-1"),_=P("div","persona-text-xs persona-text-persona-muted");s.labelTextColor&&(_.style.color=s.labelTextColor),_.textContent="Activity";let k=P("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",cf(k,s),k.textContent=o.chunks.join(""),T.append(_,k),M.appendChild(T)}if(o.success===!1&&M.appendChild(G("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),o.status==="complete"&&o.result!==void 0){let T=P("div","persona-space-y-1"),_=P("div","persona-text-xs persona-text-persona-muted");s.labelTextColor&&(_.style.color=s.labelTextColor),_.textContent="Result";let k=P("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",cf(k,s),k.textContent=bi(o.result),T.append(_,k),M.appendChild(T)}if(o.status==="complete"&&typeof o.duration=="number"){let T=P("div","persona-text-xs persona-text-persona-muted");s.contentTextColor&&(T.style.color=s.contentTextColor),T.textContent=`Duration: ${o.duration}ms`,M.appendChild(T)}}return Uc({expanded:d,header:y,toggleIcon:se,content:M,collapsedPreview:ne,iconColor:K}),i.append(y,ne,M),rr(i,t,e,"tool")};var{setLoader:dW,load:f0,provide:pW,getSync:m0}=Ht({fallbackImport:()=>import("./approval-ui-3NMYNXBD.js")});var pw=f0;var uw=m0;var{setLoader:fW,load:h0}=Ht({fallbackImport:()=>import("./event-stream-view-GL3ADRY2.js")});var uf=h0;var gf=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:CW,load:y0,provide:wW,getSync:b0}=Ht({fallbackImport:()=>import("./artifacts-ui-IGB5YKLO.js")}),Wi=null,Wd=new Set,gw=t=>{if(Wi)return Wi;Wi=t,t.initArtifactsUi({componentRegistry:tr});for(let o of gf)tr.has(o)||tr.register(o,o==="PersonaArtifactCard"?t.PersonaArtifactCard:t.PersonaArtifactInline,{bubbleChrome:!1});let e=hi();e?t.__provideMarkdownParsers(e):xc(()=>{let o=hi();o&&t.__provideMarkdownParsers(o)}),t.__setIconsExtraLoader(()=>Hy());let n=[...Wd];Wd.clear();for(let o of n)try{o()}catch{}return t};var Bd=()=>y0().then(gw);var ar=()=>{if(Wi)return Wi;let t=b0();return t?gw(t):null},ff=t=>Wi?()=>{}:(Wd.add(t),()=>{Wd.delete(t)});function yn(t){return t?.features?.artifacts?.enabled===!0}function fw(t,e){if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!yn(e))return;let n=e.features?.artifacts?.layout,o=n?.paneBorder?.trim(),s=n?.paneBorderLeft?.trim();o?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",o)):s&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",s))}function v0(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var mw=["panel","seamless","detached"];function mf(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&mw.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function hf(t){return!t||!yn(t)?!1:mf(t)==="detached"}function il(t,e){if(!yn(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-drawer-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),v0(t),fw(t,e);return}let n=e.features?.artifacts?.layout,o=mf(e)==="detached"?"var(--persona-panel-inset)":"0";t.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),t.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),t.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.drawerWidth?t.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):t.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let s=n?.paneBackground?.trim();s?t.style.setProperty("--persona-artifact-pane-bg",s):t.style.removeProperty("--persona-artifact-pane-bg");let i=n?.panePadding?.trim();i?t.style.setProperty("--persona-artifact-pane-padding",i):t.style.removeProperty("--persona-artifact-pane-padding");let l=[[n?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[n?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[n?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[n?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[c,d]of l){let g=c?.trim();g?t.style.setProperty(d,g):t.style.removeProperty(d)}fw(t,e)}function al(t,e){for(let c of mw)t.classList.remove(`persona-artifact-appearance-${c}`);if(t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-chat-shadow"),!yn(e))return;let n=e.features?.artifacts?.layout,o=mf(e);t.classList.add(`persona-artifact-appearance-${o}`);let s=n?.paneBorderRadius?.trim();s&&t.style.setProperty("--persona-artifact-pane-radius",s);let i=n?.paneShadow?.trim();i&&t.style.setProperty("--persona-artifact-pane-shadow",i);let l=n?.chatShadow?.trim();l&&t.style.setProperty("--persona-artifact-chat-shadow",l)}function hw(t,e){return!e||!yn(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var C0=new Set(["__proto__","prototype","constructor"]),w0=new Set(["collapsed","card","panel","inline"]),yw=new Set(["markdown","component"]),x0=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Bs=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),_d=t=>!C0.has(t),yf=t=>typeof t=="string"&&w0.has(t),Ds=t=>Object.keys(t).length>0;function Wo(t,e,n,o){t.push({path:e,code:n,message:o})}var S0="Ignored because this key is not part of the persisted preference schema.",Dd="Ignored an unsupported value.",A0="Expected collapsed, panel, or inline.",M0='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',bw={kind:"mode",message:Dd},Bi={kind:"string",message:"Expected a CSS length string."},lr={kind:"boolean"},T0={paneWidth:Bi,paneMaxWidth:Bi,paneMinWidth:Bi,expandedPanelWidth:Bi,resizableMinWidth:Bi,resizableMaxWidth:Bi,expandLauncherPanelWhenOpen:lr,resizable:lr},E0={kind:"object",message:"Expected a preference object.",children:{showToolCalls:lr,showReasoning:lr,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Dd},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Dd},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Dd},expandable:lr,grouped:lr}},reasoningDisplay:{kind:"object",children:{expandable:lr,activePreview:lr}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:bw,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:bw,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:yw,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:yw}}},filePreview:{kind:"object",children:{enabled:lr}},layout:{kind:"object",children:T0}}}}};function vw(t,e,n,o){if(t!==void 0)switch(e.kind){case"boolean":return typeof t=="boolean"?t:Wo(o,n,"invalid_type","Expected a boolean.");case"string":return typeof t=="string"?t:Wo(o,n,"invalid_type",e.message);case"enum":return typeof t=="string"&&e.values.has(t)?t:Wo(o,n,"invalid_value",e.message);case"mode":return yf(t)?to(t):Wo(o,n,"invalid_value",e.message);case"modeMap":{if(!Bs(t))return Wo(o,n,"invalid_type","Expected an object.");let s=e.keys==="mediaType"?void 0:e.keys,i={};for(let[l,c]of Object.entries(t)){let d=s?l:wi(l);_d(l)&&(s?s.has(l):x0.test(d))?yf(c)?i[d]=to(c):Wo(o,`${n}.${l}`,"invalid_value",A0):Wo(o,`${n}.${l}`,s?"unknown_key":"invalid_value",s?"Ignored an unsupported selector.":M0)}return Ds(i)?i:void 0}case"object":{if(e.bareMode&&yf(t))return to(t);if(!Bs(t))return Wo(o,n,"invalid_type",e.message??"Expected an object.");let s=Object.keys(e.children),i=c=>n?`${n}.${c}`:c;for(let c of Object.keys(t))(!_d(c)||!s.includes(c))&&Wo(o,i(c),"unknown_key",S0);let l={};for(let c of s){let d=e.children[c],g=vw(t[c],d,i(c),o);if(d.deprecated&&t[c]!==void 0&&Wo(o,i(c),"deprecated_key",d.deprecated),g===void 0)continue;let u=d.alias??c,m=l[u];l[u]=Bs(m)&&Bs(g)?{...m,...g}:g}return Ds(l)?l:void 0}}}function P0(t){let e=[];return{preferences:(t===null?void 0:vw(t,E0,"",e))??{},issues:e}}function Di(t){if(Array.isArray(t))return t.map(Di);if(!Bs(t))return t;let e={};for(let[n,o]of Object.entries(t))_d(n)&&o!==void 0&&(e[n]=Di(o));return e}function Cw(t,e){let n=Di(t);for(let[o,s]of Object.entries(e)){if(!_d(o)||s===void 0)continue;let i=n[o];n[o]=Bs(i)&&Bs(s)?Cw(i,s):Di(s)}return n}function k0(t){let e={},n;for(let s of t){let i=P0(s).preferences;n=ww(n,i.artifacts?.display),e=Cw(e,i)}let o=e;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function L0(t,e){if(e===void 0)return t===void 0?void 0:Di(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,s={...n.byMediaType,...e.byMediaType},i={...o?{default:o}:{},...Ds(s)?{byMediaType:s}:{}};return Ds(i)?i:void 0}function ww(t,e){if(e===void 0)return t===void 0?void 0:Di(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,s={...n.byType,...n.byKind,...e.byType,...e.byKind},i=L0(n.files,e.files),l={...o?{default:o}:{},...Ds(s)?{byKind:s}:{},...i!==void 0?{files:i}:{}};return Ds(l)?l:void 0}function I0(t={},e){let n=k0(e),o={...t};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...t.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...t.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let s=t.artifacts??{},i={...s};if(n.artifacts.display!==void 0){let l=ww(s.display,n.artifacts.display);l!==void 0&&(i.display=l)}n.artifacts.filePreview&&(i.filePreview={...s.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(i.layout={...s.layout,...n.artifacts.layout}),o.artifacts=i}return o}function bf(t){let e=t.preferences;return!e||!Ds(e)?t:{...t,features:I0(t.features??{},[e])}}function H0(t,e){if(!t?.trim())return e;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return n?Math.max(0,Number(n[1])):e}function R0(t){if(!t?.trim())return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function W0(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function B0(t,e,n,o){let s=t-o-2*e-n;return Math.max(0,s)}function vf(t,e){let o=(e.getComputedStyle(t).gap||"0px").trim().split(/\s+/)[0]??"0px",s=/^([\d.]+)px$/i.exec(o);if(s)return Number(s[1]);let i=/^([\d.]+)/.exec(o);return i?Number(i[1]):8}function xw(t,e,n,o,s,i,l=200){let c=H0(s,200),d=B0(e,n,o,l);d=Math.max(c,d);let g=R0(i);return g!==null&&(d=Math.min(d,g)),W0(t,c,d)}var{setLoader:PW,load:D0,provide:kW,getSync:_0}=Ht({fallbackImport:()=>import("./forms-ui-PJMI3HQR.js")});var Sw=D0;var Aw=_0;var Cf=class{constructor(){this.plugins=new Map}register(e){this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),e.onRegister?.()}unregister(e){let n=this.plugins.get(e);n&&(n.onUnregister?.(),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,n)=>(n.priority??0)-(e.priority??0))}getForInstance(e){let n=this.getAll();if(!e||e.length===0)return n;let o=new Set(e.map(i=>i.id));return[...n.filter(i=>!o.has(i.id)),...e].sort((i,l)=>(l.priority??0)-(i.priority??0))}clear(){this.plugins.forEach(e=>e.onUnregister?.()),this.plugins.clear()}},wf=new Cf;var Mw=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),O0=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),Tw=(t,e,n)=>{if(!Mw(t)||!Mw(e)||O0.has(n))return e;let o={...t};for(let s of Object.keys(e)){if(e[s]===void 0){delete o[s];continue}let i=n?`${n}.${s}`:s;o[s]=Tw(t[s],e[s],i)}return o};function Ew(t,e){let n=Wc(Ts),o=fb(t,e,n),s=Fu(mb(Tw(t,e,""),n,o),o);return Vu(_c(s),yb(t,e))}var Pw=()=>{let t=new Map,e=(s,i)=>(t.has(s)||t.set(s,new Set),t.get(s).add(i),()=>n(s,i)),n=(s,i)=>{t.get(s)?.delete(i)};return{on:e,off:n,emit:(s,i)=>{t.get(s)?.forEach(l=>{try{l(i)}catch(c){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",c)}})}}};var N0=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},F0=t=>{let e=t.trim(),n=e.indexOf("{");if(n===-1)return null;let o=0;for(let s=n;s<e.length;s+=1){let i=e[s];if(i==="{"&&(o+=1),i==="}"&&(o-=1,o===0))return e.slice(n,s+1)}return null},Sf=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=N0(t),n=F0(e);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:s,...i}=o;return{type:String(s),payload:i,raw:o}}catch{return null}},xf=t=>typeof t=="string"?t:t==null?"":String(t),ll={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:xf(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=xf(n.element);if(o&&e.document?.querySelector){let s=e.document.querySelector(o);s?setTimeout(()=>{s.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:xf(n.text)}}},kw=t=>Array.isArray(t)?t.map(e=>String(e)):[],Af=t=>{let e=new Set(kw(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(kw(t.getSessionMetadata().processedActionMessageIds))},o=()=>{let i=Array.from(e);t.updateSessionMetadata(l=>({...l,processedActionMessageIds:i}))};return{process:i=>{if(i.streaming||i.message.role!=="assistant"||!i.text||e.has(i.message.id))return null;let l=typeof i.raw=="string"&&i.raw||typeof i.message.rawContent=="string"&&i.message.rawContent||typeof i.text=="string"&&i.text||null;!l&&typeof i.text=="string"&&i.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let c=l?t.parsers.reduce((g,u)=>g||u?.({text:l,message:i.message})||null,null):null;if(!c)return null;e.add(i.message.id),o();let d={action:c,message:i.message};t.emit("action:detected",d);for(let g of t.handlers)if(g)try{let u=()=>{t.emit("action:resubmit",d)},m=g(c,{message:i.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:u});if(!m)continue;if(m.handled){let y=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:y,resubmit:m.resubmit}}}catch(u){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:n}};var U0=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},$0=t=>t.map(e=>({...e,streaming:!1})),V0=t=>t.map(e=>({...e,status:"complete"})),Lw=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?U0(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let s={...n,messages:n.messages?$0(n.messages):void 0,artifacts:n.artifacts?V0(n.artifacts):void 0};o.setItem(t,JSON.stringify(s))}catch(s){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let n=e();if(n)try{n.removeItem(t)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var q0=t=>{let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")},Iw=async t=>{let e=globalThis.crypto?.subtle;if(e)try{let n=await e.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}catch{}return q0(t)},z0=async(t,e)=>{let n=await Iw(t);return{storageKey:`${e}visitor:${n}`,leaseKey:`${e}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await Iw(`${t}\0${e}`)}`}};var Hw=(t,e,n)=>{let o="",s="",i="",l=!1,c=!1,d=0,g=null,u=null,m=new Set,y=()=>{if(n||l)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return l=!0,null}},b=()=>{let L=y();if(!L)return g;try{return L.getItem(o)}catch{return l=!0,g}},C=(L,$)=>{if(c||L===g)return;let K=g;g=L,d+=1;let se={previousToken:K,token:L,source:$,revision:d};for(let ne of m)ne(se)},S=L=>{c||L.key!==null&&L.key!==o||C(L.key===null?null:L.newValue??null,"external")},E=(async()=>{let L=await z0(t,e);o=L.storageKey,s=L.leaseKey,i=L.lockName,g=b(),!n&&typeof window<"u"&&window.addEventListener("storage",S)})(),H=L=>new Promise($=>setTimeout($,L)),I=()=>{let L=y();if(!L)return null;try{let $=L.getItem(s);if(!$)return null;let K=JSON.parse($);return typeof K?.expiresAt=="number"&&typeof K?.ownerNonce=="string"?K:null}catch{return null}},N=L=>{let $=y();if($)try{I()?.ownerNonce===L&&$.removeItem(s)}catch{}},x=L=>new Promise($=>{let K=setTimeout(se,L);function se(){clearTimeout(K),window.removeEventListener("storage",ne),$()}function ne(M){(M.key===null||M.key===s)&&se()}window.addEventListener("storage",ne)}),D=async L=>{let $=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,K=Date.now()+15e3;for(;Date.now()<K;){let se=y();if(!se)break;let ne=Date.now(),M=I();if(M&&M.expiresAt>ne&&M.ownerNonce!==$){await x(Math.min(M.expiresAt-ne,500));continue}try{se.setItem(s,JSON.stringify({ownerNonce:$,expiresAt:ne+1e4}))}catch{l=!0;break}if(await H(20+Math.random()*40),I()?.ownerNonce!==$){await x(500);continue}u=$;try{return await L()}finally{u=null,N($)}}return L()};return{ready:E,async get(){return await E,C(b(),"external"),g},async set(L){await E;let $=y();if($)try{$.setItem(o,L)}catch{l=!0}C(L,"local")},async clear(){await E;let L=y();if(L)try{L.removeItem(o)}catch{l=!0}C(null,"local")},revision(){return d},subscribe(L){return m.add(L),()=>{m.delete(L)}},async withFirstInitLock(L){await E;let $=globalThis.navigator?.locks;return $?.request?$.request(i,()=>L()):y()?D(L):L()},matches(L,$,K){return L===t&&$===e&&K===n},destroy(){c=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",S),u&&N(u)}}};var{setLoader:UW,load:j0}=Ht({fallbackImport:()=>import("./history-view-BD6OXLNA.js")});var Mf=j0;var Tf=(t,e)=>{console.warn(`[persona] ${t} threw`,e)},cr=t=>Object.freeze({...t}),Rw=t=>Object.freeze({id:t.id,title:t.title,targetId:t.targetId,preview:t.preview,messageCount:t.messageCount,createdAt:t.createdAt,updatedAt:t.updatedAt}),Ww=t=>t?cr(t):null;function Bw(t){let{plugins:e,config:n}=t,o=!1,s=!1,i=!1,l=!1,c=null,d=[],g=()=>{for(let x of d.splice(0))try{x()}catch(D){Tf("renderHistoryView cleanup",D)}},u=(x,D)=>{for(let L of e){let $=L[x];if($)try{let K=$(D);if(K)return K}catch(K){Tf(x,K)}}return null},m=()=>({presentation:t.getPresentation(),config:n}),y={header:x=>l?u("renderHistoryHeader",Object.freeze({...m(),returnSurface:t.getReturnSurface(),identityStatus:cr(x.identityStatus),pendingAction:Ww(x.pendingAction),copy:cr(x.copy),actions:Object.freeze({close:S.close,startNewConversation:S.startNewConversation}),defaultRenderer:x.defaultRenderer})):null,conversation:x=>l?u("renderHistoryConversation",Object.freeze({...m(),conversation:Rw(x.conversation),active:x.active,pending:x.pending,open:x.open,requestDelete:x.requestDelete,defaultRenderer:x.defaultRenderer})):null,state:x=>l?u("renderHistoryState",Object.freeze({...m(),state:cr(x.state),identityStatus:cr(x.identityStatus),copy:cr(x.copy),...x.retry?{retry:x.retry}:{},...x.startNewConversation?{startNewConversation:x.startNewConversation}:{},defaultRenderer:x.defaultRenderer})):null},b=e.flatMap(x=>(x.railSections??[]).map(D=>({...D,placement:D.placement??"above-conversations",items:[],render:L=>D.render(Object.freeze({collapsed:L,presentation:t.getPresentation(),actions:S}))}))),C=t.createView({slots:y,renderDom:!1,onModelChange:()=>N(),railSections:b}),S=Object.freeze({...C.operations,close:t.close}),E=()=>(l=!0,C.setDomRenderEnabled(!0),C.element),H=x=>Object.freeze({conversations:Object.freeze(x.conversations.map(Rw)),activeConversationId:x.activeConversationId,state:cr(x.state),pendingAction:Ww(x.pendingAction),identityStatus:cr(x.identityStatus),nextCursor:x.nextCursor,presentation:t.getPresentation(),returnSurface:t.getReturnSurface(),config:n,copy:cr(C.copy),actions:S,defaultRenderer:E,requestRender:()=>N(),onCleanup:D=>{d.push(D)}}),I=()=>{l=!1;let x=null;for(let L of e)if(L.renderHistoryView){try{x=L.renderHistoryView(H(C.getModel()))}catch($){Tf("renderHistoryView",$),x=null}if(x)break}let D=!x||x.contains(C.element);return l=D,C.setDomRenderEnabled(D),x??C.element};function N(){if(!(!i||o||s)){s=!0;try{g();let x=I();if(x===c)return;let D=c;c=x,t.onElementChanged(x,D)}finally{s=!1}}}return i=!0,N(),{view:C,get element(){return c??C.element},requestRender:N,dispose:()=>{o=!0,g()}}}var K0=null;function Dw(){return K0}var G0=new Map([["not_found","not_found"],["conversation_deleted","not_found"],["rate_limited","rate_limited"],["authentication_required","authentication_required"],["invalid_identity_proof","authentication_required"],["visitor_identity_mismatch","authentication_required"],["visitor_required","authentication_required"],["identity_provider_failed","identity_provider_failed"],["proof_not_admitted","proof_not_admitted"],["identity_contract_violation","proof_not_admitted"],["unauthorized","authentication_failed"],["visitor_token_missing","authentication_failed"],["conversation_credential_missing","authentication_failed"]]),Q0=new Map([["not_found","That conversation is no longer available."],["rate_limited","Too many history requests."],["authentication_failed","History access was not authorized."],["authentication_required","Sign in again to view account history."],["identity_provider_failed","The identity provider did not respond."],["proof_not_admitted","Account history is not available for this configuration."],["unsupported_scope","This history scope is not supported."],["unavailable","Conversation history is unavailable right now."]]),Ef=t=>Q0.get(t)??"Conversation history is unavailable right now.";function Y0(t){if(t instanceof Ss)return t;if(t instanceof Oe){let e=G0.get(t.code)??"unavailable";return new Ss(e,Ef(e),{...t.retryAfterSeconds!==void 0?{retryAfterSeconds:t.retryAfterSeconds}:{}})}return new Ss("unavailable",Ef("unavailable"))}function _w(t){let e=()=>t.getClient?.()??t.client,n=t.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],o={scopes:n},s=c=>{if(!n.includes(c))throw new Ss("unsupported_scope",Ef("unsupported_scope"))},i=async(c,d)=>{s(c);try{return await d()}catch(g){throw Y0(g)}},l=c=>{let d=!1;return{conversationId:c.session.conversationId??"",conversationRevision:c.session.conversationRevision??"",async commit(){d||(d=!0,c.commit(),await t.onActivationCommitted(c.session))},discard(){d||(d=!0,c.discard())}}};return{capabilities:o,getIdentityStatus(){return e().getHistoryIdentityStatus()},subscribeIdentityStatus(c){return e().subscribeHistoryIdentityStatus(c)},subscribeAvailability(c){return e().subscribeHistoryAvailability(c)},async list(c){return i(c.context.scope,async()=>{let d=await e().listConversations({...c.cursor?{cursor:c.cursor}:{},...c.limit!==void 0?{limit:c.limit}:{},...c.targetId?{targetId:c.targetId}:{},scope:c.context.scope});return{items:d.data,nextCursor:d.nextCursor}})},async getPage(c,d){return i(d.context.scope,async()=>{let g=await e().getConversation(c,{...d.cursor?{messageCursor:d.cursor}:{},scope:d.context.scope}),u=sv(g.messages,{...d.beforeCreatedAt?{beforeCreatedAt:d.beforeCreatedAt}:{}});return{summary:g.summary,messages:Na([],u),conversationRevision:g.conversationRevision??"",nextCursor:g.nextMessageCursor}})},async prepareOpen(c,d){return i(d.context.scope,async()=>l(await e().prepareConversationSession(c)))},async prepareStartNew(c){return i(c.context.scope,async()=>l(await e().prepareNewConversationSession()))},async delete(c,d){await i(d.context.scope,()=>e().deleteConversation(c,{scope:d.context.scope}))},async deleteAll(c){return i(c.context.scope,()=>e().deleteAllConversations({...c.targetId!==void 0?{targetId:c.targetId}:{},scope:c.context.scope}))},async resetDevice(){try{return await e().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var X0="button:not([disabled])";function Od(t){let e=document.activeElement instanceof HTMLElement?document.activeElement:null,n=Math.random().toString(36).slice(2,8),o=`persona-history-confirm-title-${n}`,s=`persona-history-confirm-desc-${n}`,i=G("button",{className:"persona-history-confirm__cancel",text:t.cancelLabel,attrs:{type:"button"}}),l=G("button",{className:"persona-history-confirm__confirm",text:t.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),c=G("div",{className:"persona-history-confirm__dialog",attrs:{role:"alertdialog","aria-modal":"true","aria-labelledby":o,"aria-describedby":s},style:{maxWidth:"22rem",width:"100%",borderRadius:"var(--persona-radius-lg, 0.75rem)",background:"var(--persona-surface, #ffffff)",color:"var(--persona-text, #111827)",boxShadow:"var(--persona-history-confirm-shadow, 0 20px 40px -12px rgba(0, 0, 0, 0.35))",padding:"20px",display:"flex",flexDirection:"column",gap:"12px"}},G("h2",{className:"persona-history-confirm__title",text:t.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),G("p",{className:"persona-history-confirm__description",text:t.description,attrs:{id:s},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),G("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},i,l));for(let g of[i,l])g.style.minHeight="44px",g.style.minWidth="88px",g.style.padding="0 16px",g.style.borderRadius="var(--persona-radius-md, 0.5rem)",g.style.cursor="pointer",g.style.font="inherit";i.style.border="1px solid var(--persona-border, rgba(0,0,0,0.12))",i.style.background="transparent",i.style.color="inherit",l.style.border="none",l.style.background="var(--persona-danger, #b42318)",l.style.color="var(--persona-danger-fg, #ffffff)";let d=G("div",{className:"persona-history-confirm",style:{position:"absolute",inset:"0",zIndex:"40",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"var(--persona-history-confirm-scrim, rgba(15, 23, 42, 0.45))"}},c);return new Promise(g=>{let u=!1,m=b=>{u||(u=!0,d.removeEventListener("keydown",y,!0),d.remove(),e?.focus(),g(b))};function y(b){if(b.key==="Escape"){b.preventDefault(),b.stopPropagation(),m(!1);return}if(b.key!=="Tab")return;let C=Array.from(c.querySelectorAll(X0));if(C.length===0)return;let S=C[0],E=C[C.length-1],H=document.activeElement;b.shiftKey&&(H===S||!c.contains(H))?(b.preventDefault(),E.focus()):!b.shiftKey&&H===E&&(b.preventDefault(),S.focus())}d.addEventListener("keydown",y,!0),d.addEventListener("pointerdown",b=>{b.target===d&&m(!1)}),i.addEventListener("click",()=>m(!1)),l.addEventListener("click",()=>m(!0)),t.host.appendChild(d),i.focus()})}import{parse as JW,STR as ZW,OBJ as eB}from"partial-json";function Ow(t,e){let{config:n,message:o,onPropsUpdate:s}=e,i=tr.get(t.component);if(!i){if(gf.includes(t.component)){Bd().catch(()=>{});let c=P("div","persona-w-full");return c.setAttribute("data-persona-artifact-pending","true"),c}return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null}let l={message:o,config:n,updateProps:c=>{s&&s(c)}};try{return i(t.props,l)}catch(c){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,c),null}}function Nw(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function Pf(t){let e=Nw(t);if(!e)return!1;try{let n=JSON.parse(e);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Fw(t){let e=Nw(t);if(!e)return null;try{let n=JSON.parse(e);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:e}}}catch{}return null}var J0=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Uw(t){let{onSubmit:e,onDismiss:n,title:o="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:i="Share your thoughts (optional)...",submitText:l="Submit",skipText:c="Skip",showComment:d=!0,ratingLabels:g=J0}=t,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let m=null,y=document.createElement("div");y.className="persona-feedback-content";let b=document.createElement("div");b.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,b.appendChild(C);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=s,b.appendChild(S),y.appendChild(b);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 H=[];for(let L=1;L<=5;L++){let $=document.createElement("button");$.type="button",$.className="persona-feedback-rating-btn persona-feedback-star-btn",$.setAttribute("role","radio"),$.setAttribute("aria-checked","false"),$.setAttribute("aria-label",`${L} star${L>1?"s":""}: ${g[L-1]}`),$.title=g[L-1],$.dataset.rating=String(L),$.innerHTML=`
22
+ `,n.addEventListener("click",e);let o=i=>{let l=i.launcher??{},c=rt(i),u=El(i)==="circle";u?(n.dataset.personaLauncherVariant="circle",n.setAttribute("aria-label",l.title??"Open chat")):(n.removeAttribute("data-persona-launcher-variant"),n.removeAttribute("aria-label"));let p=n.querySelector("[data-role='launcher-title']");if(p){let B=l.title??"Chat Assistant";p.textContent=B,p.setAttribute("title",B)}let g=n.querySelector("[data-role='launcher-subtitle']");if(g){let B=l.subtitle??"Here to help you get answers fast";g.textContent=B,g.setAttribute("title",B)}let y=n.querySelector(".persona-flex-col");y&&(l.textHidden||c||u?y.style.display="none":y.style.display="");let h=n.querySelector("[data-role='launcher-icon']");if(h)if(l.agentIconHidden)h.style.display="none";else{let B=l.agentIconSize??"40px";if(h.style.height=B,h.style.width=B,l.agentIconBackgroundColor?(h.style.backgroundColor=l.agentIconBackgroundColor,h.classList.remove("persona-bg-persona-primary")):(h.style.backgroundColor="",h.classList.add("persona-bg-persona-primary")),h.innerHTML="",l.agentIconName){let O=parseFloat(B)||24,V=se(l.agentIconName,O*.6,"var(--persona-text-inverse, #ffffff)",1.5);V?(h.appendChild(V),h.style.display=""):(h.textContent=l.agentIconText??"\u{1F4AC}",h.style.display="")}else l.iconUrl?h.style.display="none":(h.textContent=l.agentIconText??"\u{1F4AC}",h.style.display="")}let C=n.querySelector("[data-role='launcher-image']");if(C){let B=l.agentIconSize??"40px";C.style.height=B,C.style.width=B,l.iconUrl&&!l.agentIconName&&!l.agentIconHidden?(C.src=l.iconUrl,C.style.display="block"):C.style.display="none"}let E=n.querySelector("[data-role='launcher-call-to-action-icon']");if(E){let B=l.callToActionIconSize??"32px";E.style.height=B,E.style.width=B,l.callToActionIconBackgroundColor?(E.style.backgroundColor=l.callToActionIconBackgroundColor,E.classList.remove("persona-bg-persona-primary")):(E.style.backgroundColor="",E.classList.add("persona-bg-persona-primary")),l.callToActionIconColor?(E.style.color=l.callToActionIconColor,E.classList.remove("persona-text-persona-call-to-action")):(E.style.color="",E.classList.add("persona-text-persona-call-to-action"));let O=0;if(l.callToActionIconPadding?(E.style.boxSizing="border-box",E.style.padding=l.callToActionIconPadding,O=(parseFloat(l.callToActionIconPadding)||0)*2):(E.style.boxSizing="",E.style.padding=""),l.callToActionIconHidden||u)E.style.display="none";else if(E.style.display=c?"none":"",E.innerHTML="",l.callToActionIconName){let V=parseFloat(B)||24,J=Math.max(V-O,8),_=se(l.callToActionIconName,J,"currentColor",1.5);_?E.appendChild(_):E.textContent=l.callToActionIconText??"\u2197"}else E.textContent=l.callToActionIconText??"\u2197"}let A=l.position&&ln[l.position]?ln[l.position]:ln["bottom-right"],I="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-launcher persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",L="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-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=c?L:`${I} ${A}`,c||(n.style.zIndex=String(l.zIndex??Dt));let k="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",R="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=l.border??k,n.style.boxShadow=l.shadow!==void 0?l.shadow.trim()===""?"none":l.shadow:R,c?(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=l.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},s=()=>{n.removeEventListener("click",e),n.remove()};return t&&o(t),{element:n,update:o,destroy:s}},QS="teaser-dismissed",Iy=new Set,Ly=t=>{let e=t?.persistState;return`${(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"}${QS}`},XS=(t,e)=>{if(Iy.has(t))return!0;if(!e)return!1;try{return window.localStorage.getItem(t)==="1"}catch{return!1}},JS=(t,e)=>{if(Iy.add(t),!!e)try{window.localStorage.setItem(t,"1")}catch{}},ZS=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,ex=t=>{let e=t?.launcher?.teaser;return!e||!e.text||t?.launcher?.enabled===!1||rt(t??{})?null:e},Hy=(t,e)=>{let n=P("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=t??{},s=null,i=null,l=null,c=null,u=null,p=!1,g=!1,y=!1,h=!1,C=()=>(s?.frequency??"once")==="once"&&o.persistState!==!1,E=()=>{u!==null&&(clearTimeout(u),u=null)},A=()=>{!i||!p||(p=!1,i.hidden=!0)},I=z=>{E(),y=!0,A(),JS(Ly(o),z&&C())},L=z=>{!s||y||I(z==="user"&&p)},k=()=>{u=null,!(!i||y||h)&&(g=!0,p=!0,i.hidden=!1,!(ZS()||typeof i.animate!="function")&&i.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},R=()=>{!s||!i||y||g||h||XS(Ly(o),C())||(E(),u=setTimeout(k,Math.max(0,s.delayMs??0)))},B=()=>{I(C()),e()},O=z=>{z.stopPropagation(),I(C())},J=Ap(t,()=>{L("user"),e()}),_=()=>{E(),c?.removeEventListener("click",B),l?.removeEventListener("click",O),i?.remove(),i=null,c=null,l=null,p=!1},Q=()=>{c=Y("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),c.addEventListener("click",B),l=Y("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),l.addEventListener("click",O),i=Y("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},c,l),n.insertBefore(i,J.element)},G=()=>{let z=o.launcher?.position??"bottom-right",W=ln[z]??ln["bottom-right"];if(!i){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",J.element.style.position="";return}n.className=ss("persona-launcher-surface",W),n.setAttribute("data-teaser",z),n.style.zIndex=String(o.launcher?.zIndex??Dt),J.element.style.position="static"},w=z=>{let W=ex(z);if(s=W,!W){_();return}i||Q(),c.textContent=W.text,l.hidden=W.dismissible===!1,l.setAttribute("aria-label",W.dismissLabel??"Dismiss message"),R()},v=z=>{o=z,J.update(z),w(z),G()},T=(z,W="user")=>{h=z,z&&L(W)},x=()=>{_(),J.destroy(),n.remove()};return n.appendChild(J.element),t&&(w(t),G()),{element:n,launcher:J,get teaser(){return i?{element:i,show:k,dismiss:I}:null},setPanelOpen:T,update:v,destroy:x}};var Ry=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:s}=Ty(t),i=Py(t,e),l={wrapper:n,panel:o,pillRoot:s},c={container:i.container,body:i.body,messagesWrapper:i.messagesWrapper,starterSuggestions:i.starterSuggestions,transcriptSuggestions:i.transcriptSuggestions,composerOverlay:i.composerOverlay,welcomeHost:i.welcomeHost,welcomeIconHolder:i.welcomeIconHolder,greetingHost:i.greetingHost,introTitle:i.introTitle,introSubtitle:i.introSubtitle},u={element:i.header,iconHolder:i.iconHolder,headerTitle:i.headerTitle,headerSubtitle:i.headerSubtitle,closeButton:i.closeButton,closeButtonWrapper:i.closeButtonWrapper,clearChatButton:i.clearChatButton,clearChatButtonWrapper:i.clearChatButtonWrapper},p={footer:i.footer,form:i.composerForm,textarea:i.textarea,sendButton:i.sendButton,sendButtonWrapper:i.sendButtonWrapper,micButton:i.micButton,micButtonWrapper:i.micButtonWrapper,statusText:i.statusText,suggestions:i.suggestions,attachmentButton:i.attachmentButton,attachmentButtonWrapper:i.attachmentButtonWrapper,attachmentInput:i.attachmentInput,attachmentPreviewsContainer:i.attachmentPreviewsContainer,actionsRow:i.actionsRow,leftActions:i.leftActions,rightActions:i.rightActions,setSendButtonMode:i.setSendButtonMode,peekBanner:i.peekBanner,peekTextNode:i.peekTextNode};return{shell:l,panelElements:i,transcript:c,header:u,composer:p,replaceHeader:h=>(u.element.replaceWith(h.header),u.element=h.header,u.iconHolder=h.iconHolder,u.headerTitle=h.headerTitle,u.headerSubtitle=h.headerSubtitle,u.closeButton=h.closeButton,u.closeButtonWrapper=h.closeButtonWrapper,u.clearChatButton=h.clearChatButton,u.clearChatButtonWrapper=h.clearChatButtonWrapper,h),replaceComposer:h=>{p.footer.replaceWith(h),p.footer=h}}},Mp=({config:t,plugins:e,onToggle:n})=>{let o=e.find(i=>i.renderLauncher);if(o?.renderLauncher){let i=o.renderLauncher({config:t,defaultRenderer:()=>Ap(t,n).element,onToggle:n});if(i)return{instance:null,element:i}}let s=Hy(t,n);return{instance:s,element:s.element}};var tx=t=>{let e=t?.persistState;return(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"},nx=(t,e,n)=>`${tx(t)}plugin:${e}:${n}`,Wy=t=>{let e=new Map,n=!1,o=()=>{if(n||t()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return s=>{let i=l=>nx(t(),s,l);return{get:l=>{let c=i(l),u=o();if(u)try{return u.getItem(c)}catch{n=!0}return e.get(c)??null},set:(l,c)=>{let u=i(l),p=o();if(p)try{p.setItem(u,c);return}catch{n=!0}e.set(u,c)},remove:l=>{let c=i(l);e.delete(c);let u=o();if(u)try{u.removeItem(c)}catch{n=!0}}}}};var ox=(t,e)=>{let n=t.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,e).join(`
23
+ `):""},Ep=(t,e,n)=>{hl(t,e,{stateSet:n,previewKind:"reasoning",iconColor:"currentColor"})},Tp=(t,e,n=new Set)=>{e=yl(e,"reasoning");let o=t.reasoning,s=ul("persona-reasoning-bubble",t.id);if(!o)return mo(s,t,e,"reasoning");let i=e?.features?.reasoningDisplay??{},l=i.expandable??rs.expandable,c=l&&n.has(t.id),u=o.status!=="complete",p=ox(t,i.previewMaxLines??rs.previewMaxLines),g=gl({expandable:l,expanded:c,bubbleType:"reasoning"}),y=P("div","persona-flex persona-flex-col persona-text-left"),h=P("span","persona-text-xs persona-text-persona-primary"),C=qo(e,"reasoning")==="row",E=C&&!u?`Thought for ${bi(o.durationMs??(o.completedAt!==void 0&&o.startedAt!==void 0?o.completedAt-o.startedAt:void 0))}`:"Thinking...",A=e?.reasoning??{},I=String(o.startedAt??Date.now()),L=()=>{let W=P("span","");return W.setAttribute("data-tool-elapsed",I),W.textContent=Qa(o),W},k=A.renderCollapsedSummary?.({message:t,reasoning:o,defaultSummary:E,previewText:p,isActive:u,config:e??{},elapsed:Qa(o),createElapsedElement:L});typeof k=="string"&&k.trim()?(h.textContent=k,y.appendChild(h)):k instanceof HTMLElement?y.appendChild(k):(h.textContent=E,y.appendChild(h));let R=P("span","persona-text-xs persona-text-persona-primary");R.textContent=Um(o),C||y.appendChild(R);let B=i.loadingAnimation??rs.loadingAnimation,O=A.activeTextTemplate,V=A.completeTextTemplate,J=u?O:V,_=k instanceof HTMLElement,Q=(W,ee)=>{h.textContent="";let ne=Xa(W,""),he=0;for(let ve of ne){let Xe=ve.styles.length>0?(()=>{let Je=P("span",ve.styles.map(Wt=>`persona-tool-text-${Wt}`).join(" "));return h.appendChild(Je),Je})():h;if(ve.isDuration&&u)Xe.appendChild(L());else{let Je=ve.isDuration?Qa(o):ve.text;ee?he=ms(Xe,Je,he):Xe.appendChild(document.createTextNode(Je))}}};if(!_&&J)if(R.style.display="none",h.style.display="",u&&B!=="none"){let W=A.loadingAnimationDuration??2e3;h.setAttribute("data-preserve-animation","true"),B==="pulse"?(h.classList.add("persona-tool-loading-pulse"),h.style.setProperty("--persona-tool-anim-duration",`${W}ms`),Q(J,!1)):(h.classList.add(`persona-tool-loading-${B}`),h.style.setProperty("--persona-tool-anim-duration",`${W}ms`),B==="shimmer-color"&&(A.loadingAnimationColor&&h.style.setProperty("--persona-tool-anim-color",A.loadingAnimationColor),A.loadingAnimationSecondaryColor&&h.style.setProperty("--persona-tool-anim-secondary-color",A.loadingAnimationSecondaryColor)),Q(J,!0))}else Q(J,!1);else if(!_&&u&&B!=="none"){h.style.display="";let W=A.loadingAnimationDuration??2e3;if(h.setAttribute("data-preserve-animation","true"),B==="pulse")h.classList.add("persona-tool-loading-pulse"),h.style.setProperty("--persona-tool-anim-duration",`${W}ms`);else{h.classList.add(`persona-tool-loading-${B}`),h.style.setProperty("--persona-tool-anim-duration",`${W}ms`),B==="shimmer-color"&&(A.loadingAnimationColor&&h.style.setProperty("--persona-tool-anim-color",A.loadingAnimationColor),A.loadingAnimationSecondaryColor&&h.style.setProperty("--persona-tool-anim-secondary-color",A.loadingAnimationSecondaryColor));let ee=h.textContent||E;h.textContent="",ms(h,ee,0)}o.status==="complete"&&!C&&(h.style.display="none")}else _||(o.status==="complete"&&!C?h.style.display="none":h.style.display="");if(i.iconName&&!_){let W=P("span","persona-reasoning-header-icon"),ee=se(i.iconName,16,"currentColor",2);ee&&(W.appendChild(ee),g.appendChild(W))}let G="currentColor",w=fs(g,y,{expandable:l,expanded:c,iconColor:G,metaGap:!1}),v=ml({bubble:s,previewKind:"reasoning",expanded:c,isActive:u,previewText:p,activePreview:i.activePreview,activeMinHeight:i.activeMinHeight,renderPreview:()=>e?.reasoning?.renderCollapsedPreview?.({message:t,reasoning:o,defaultPreview:p,isActive:u,config:e??{}})});if(!l)return s.append(g,v),mo(s,t,e,"reasoning");let T=P("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");T.style.display=c?"":"none";let x=o.chunks.join(""),z=P("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return z.textContent=x||(o.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),T.appendChild(z),fl({expanded:c,header:g,toggleIcon:w,content:T,collapsedPreview:v,iconColor:G}),s.append(g,v,T),mo(s,t,e,"reasoning")};var By=t=>{if(t==null)return!0;if(typeof t=="string"){if(!t.trim())return!0;try{return By(JSON.parse(t))}catch{return!1}}return typeof t=="object"&&Object.keys(t).length===0},rx=t=>{if(t!==null&&typeof t=="object")return!0;if(typeof t!="string")return!1;try{let e=JSON.parse(t);return e!==null&&typeof e=="object"}catch{return!1}};function Dy(t,e,n){let o=e.toolCall;if(!o)return;let s=n.toolCall??{},i=(c,u)=>{let p=Y("section",{className:"persona-tool-detail",attrs:{"data-persona-tool-detail":c.toLowerCase()},style:{backgroundColor:s.codeBlockBackgroundColor,borderColor:s.codeBlockBorderColor,borderWidth:s.codeBlockBorderColor?"1px":void 0}}),g=Y("div",{className:"persona-tool-detail-label",text:c,style:{color:s.labelTextColor}}),y=ls(u),h=Y("pre",{className:`persona-tool-detail-value${rx(u)?" persona-tool-detail-code":""}`,text:y,attrs:y.length>420||y.split(`
24
+ `).length>7?{tabindex:"0","aria-label":`${c} content`}:{},style:{color:s.codeBlockTextColor??s.contentTextColor}}),C=Y("button",{className:"persona-tool-detail-copy",attrs:{type:"button","data-persona-copy-tool-detail":"","aria-label":`Copy ${c.toLowerCase()}`,title:`Copy ${c.toLowerCase()}`}}),E=se("copy",14,"currentColor",1.7);E&&C.appendChild(E),p.append(g,h,C),t.appendChild(p)};By(o.args)||i("Request",o.args);let l=o.status==="complete"&&o.result!==void 0?o.result:o.chunks?.join("");l!==void 0&&(typeof l!="string"||l.trim())&&i("Response",l),o.success===!1&&t.appendChild(Y("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":"",role:"status"}}))}var kp=new WeakMap;async function Oy(t){let e=t.closest("[data-persona-tool-detail]"),n=e?.querySelector("pre");if(!n)return;let o=`Copy ${e?.getAttribute("data-persona-tool-detail")}`;clearTimeout(kp.get(t));try{await navigator.clipboard.writeText(n.textContent??""),t.dataset.copied="true",t.setAttribute("aria-label","Copied"),t.title="Copied";let s=se("check",14,"currentColor",2);s&&t.replaceChildren(s)}catch{t.setAttribute("aria-label","Copy failed \u2014 try again"),t.title="Copy failed \u2014 try again"}kp.set(t,setTimeout(()=>{delete t.dataset.copied,t.setAttribute("aria-label",o),t.title=o;let s=se("copy",14,"currentColor",1.7);s&&t.replaceChildren(s),kp.delete(t)},1800))}var _y=(t,e=!1)=>t.toggleTextColor||t.headerTextColor||(e?"currentColor":"var(--persona-primary, #171717)"),sx=(t,e)=>{let n=t.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).slice(-e).join(`
25
+ `);let s=ls(n.args).trim();return s?s.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(0,e).join(`
26
+ `):""},Pp=(t,e)=>{t.style.backgroundColor=e.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",t.style.borderColor=e.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",t.style.color=e.codeBlockTextColor??"var(--persona-text, #171717)"},ix=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,s=o?.collapsedMode??$o.collapsedMode,i=n?.success===!1?n.error||"Tool failed":sx(t,o?.previewMaxLines??$o.previewMaxLines),l=n?qo(e,"tool")==="row"?`${n.status==="complete"?"Used":"Using"} ${n.name?.trim()||"tool"}`:jm(n):"";if(!n)return{summary:l,previewText:i,isActive:!1};let c=n.status!=="complete",u=e?.toolCall??{},p=l;return s==="tool-name"?p=n.name?.trim()||l:s==="tool-preview"&&i&&(p=i),c&&u.activeTextTemplate?p=Sd(n,u.activeTextTemplate,p):!c&&u.completeTextTemplate&&(p=Sd(n,u.completeTextTemplate,p)),n.success===!1?p+=" \xB7 Failed":n.superseded&&(p+=" \xB7 Approved, ran again below"),{summary:p,previewText:i,isActive:c}},Lp=(t,e,n,o)=>{hl(t,e,{stateSet:n,previewKind:"tool",iconColor:_y(o?.toolCall??{},e.classList.contains("persona-activity-row"))})},Ip=(t,e,n=new Set)=>{e=yl(e,"tool");let o=t.toolCall,s=e?.toolCall??{},i=ul("persona-tool-bubble",t.id);if(s.backgroundColor&&(i.style.backgroundColor=s.backgroundColor),s.borderColor&&(i.style.borderColor=s.borderColor),s.borderWidth&&(i.style.borderWidth=s.borderWidth),s.borderRadius&&(i.style.borderRadius=s.borderRadius),i.style.boxShadow=s.shadow!==void 0?s.shadow.trim()===""?"none":s.shadow:"var(--persona-tool-bubble-shadow)",!o)return mo(i,t,e,"tool");let l=e?.features?.toolCallDisplay??{},c=l.expandable??$o.expandable,u=c&&n.has(t.id),{summary:p,previewText:g,isActive:y}=ix(t,e),h=gl({expandable:c,expanded:u,bubbleType:"tool"});s.headerBackgroundColor&&(h.style.backgroundColor=s.headerBackgroundColor),s.headerPaddingX&&(h.style.paddingLeft=s.headerPaddingX,h.style.paddingRight=s.headerPaddingX),s.headerPaddingY&&(h.style.paddingTop=s.headerPaddingY,h.style.paddingBottom=s.headerPaddingY);let C=P("div","persona-flex persona-flex-col persona-text-left"),E=P("span","persona-text-xs persona-text-persona-primary");s.headerTextColor&&(E.style.color=s.headerTextColor);let A=String(o.startedAt??Date.now()),I=()=>{let v=P("span","");return v.setAttribute("data-tool-elapsed",A),v.textContent=Ya(o),v},L=s.renderCollapsedSummary?.({message:t,toolCall:o,defaultSummary:p,previewText:g,collapsedMode:l.collapsedMode??$o.collapsedMode,isActive:y,config:e??{},elapsed:Ya(o),createElapsedElement:I});typeof L=="string"&&L.trim()?(E.textContent=L,C.appendChild(E)):L instanceof HTMLElement?C.appendChild(L):(E.textContent=p,C.appendChild(E));let k=l.loadingAnimation??$o.loadingAnimation,R=s.activeTextTemplate,B=s.completeTextTemplate,O=y?R:B,V=L instanceof HTMLElement,J=(v,T)=>{E.textContent="";let x=o.name?.trim()||"tool",z=Xa(v,x),W=0;for(let ee of z){let ne=ee.styles.length>0?(()=>{let he=P("span",ee.styles.map(ve=>`persona-tool-text-${ve}`).join(" "));return E.appendChild(he),he})():E;if(ee.isDuration&&y)ne.appendChild(I());else{let he=ee.isDuration?Ya(o):ee.text;T?W=ms(ne,he,W):ne.appendChild(document.createTextNode(he))}}};if(!V)if(y&&k!=="none"){let v=s.loadingAnimationDuration??2e3;if(E.setAttribute("data-preserve-animation","true"),k==="pulse")E.classList.add("persona-tool-loading-pulse"),E.style.setProperty("--persona-tool-anim-duration",`${v}ms`),O&&J(O,!1);else if(E.classList.add(`persona-tool-loading-${k}`),E.style.setProperty("--persona-tool-anim-duration",`${v}ms`),k==="shimmer-color"&&(s.loadingAnimationColor&&E.style.setProperty("--persona-tool-anim-color",s.loadingAnimationColor),s.loadingAnimationSecondaryColor&&E.style.setProperty("--persona-tool-anim-secondary-color",s.loadingAnimationSecondaryColor)),O)J(O,!0);else{let T=E.textContent||p;E.textContent="",ms(E,T,0)}}else O&&J(O,!1);let _=_y(s,qo(e,"tool")==="row"),Q=fs(h,C,{expandable:c,expanded:u,iconColor:_,metaGap:!0}),G=ml({bubble:i,previewKind:"tool",expanded:u,isActive:y,previewText:g,activePreview:l.activePreview,activeMinHeight:l.activeMinHeight,renderPreview:()=>s.renderCollapsedPreview?.({message:t,toolCall:o,defaultPreview:g,isActive:y,config:e??{}})});if(!c)return i.append(h,G),mo(i,t,e,"tool");let w=P("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(w.style.display=u?"":"none",s.contentBackgroundColor&&(w.style.backgroundColor=s.contentBackgroundColor),s.contentTextColor&&(w.style.color=s.contentTextColor),s.contentPaddingX&&(w.style.paddingLeft=s.contentPaddingX,w.style.paddingRight=s.contentPaddingX),s.contentPaddingY&&(w.style.paddingTop=s.contentPaddingY,w.style.paddingBottom=s.contentPaddingY),e.future?.v5Defaults===!0)Dy(w,t,e);else{if(o.name){let v=P("div","persona-text-xs persona-text-persona-muted persona-italic");s.contentTextColor?v.style.color=s.contentTextColor:s.headerTextColor&&(v.style.color=s.headerTextColor),v.textContent=o.name,w.appendChild(v)}if(o.args!==void 0){let v=P("div","persona-space-y-1"),T=P("div","persona-text-xs persona-text-persona-muted");s.labelTextColor&&(T.style.color=s.labelTextColor),T.textContent="Arguments";let x=P("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");x.style.fontSize="0.75rem",x.style.lineHeight="1rem",Pp(x,s),x.textContent=ls(o.args),v.append(T,x),w.appendChild(v)}if(o.chunks&&o.chunks.length){let v=P("div","persona-space-y-1"),T=P("div","persona-text-xs persona-text-persona-muted");s.labelTextColor&&(T.style.color=s.labelTextColor),T.textContent="Activity";let x=P("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");x.style.fontSize="0.75rem",x.style.lineHeight="1rem",Pp(x,s),x.textContent=o.chunks.join(""),v.append(T,x),w.appendChild(v)}if(o.success===!1&&w.appendChild(Y("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),o.status==="complete"&&o.result!==void 0){let v=P("div","persona-space-y-1"),T=P("div","persona-text-xs persona-text-persona-muted");s.labelTextColor&&(T.style.color=s.labelTextColor),T.textContent="Result";let x=P("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");x.style.fontSize="0.75rem",x.style.lineHeight="1rem",Pp(x,s),x.textContent=ls(o.result),v.append(T,x),w.appendChild(v)}if(o.status==="complete"&&typeof o.duration=="number"){let v=P("div","persona-text-xs persona-text-persona-muted");s.contentTextColor&&(v.style.color=s.contentTextColor),v.textContent=`Duration: ${o.duration}ms`,w.appendChild(v)}}return fl({expanded:u,header:h,toggleIcon:Q,content:w,collapsedPreview:G,iconColor:_}),i.append(h,G,w),mo(i,t,e,"tool")};var{setLoader:hk,load:ax,provide:yk,getSync:lx}=je({fallbackImport:()=>import("./approval-ui-QAKWNFNM.js")});var Fy=ax;var Ny=lx;var{setLoader:Ck,load:cx}=je({fallbackImport:()=>import("./event-stream-view-FOIJHFQO.js")});var Hp=cx;var Rp=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:Ek,load:dx,provide:Tk,getSync:px}=je({fallbackImport:()=>import("./artifacts-ui-NJGMM27I.js")}),xs=null,$l=new Set,Vy=t=>{if(xs)return xs;xs=t,t.initArtifactsUi({componentRegistry:go});for(let o of Rp)go.has(o)||go.register(o,o==="PersonaArtifactCard"?t.PersonaArtifactCard:t.PersonaArtifactInline,{bubbleChrome:!1});let e=is();e?t.__provideMarkdownParsers(e):qa(()=>{let o=is();o&&t.__provideMarkdownParsers(o)}),t.__setIconsExtraLoader(()=>Bm());let n=[...$l];$l.clear();for(let o of n)try{o()}catch{}return t};var zl=()=>dx().then(Vy);var yo=()=>{if(xs)return xs;let t=px();return t?Vy(t):null},Wp=t=>xs?()=>{}:($l.add(t),()=>{$l.delete(t)});function zt(t){return t?.features?.artifacts?.enabled===!0}function $y(t,e){if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!zt(e))return;let n=e.features?.artifacts?.layout,o=n?.paneBorder?.trim(),s=n?.paneBorderLeft?.trim();o?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",o)):s&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",s))}function ux(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var zy=["panel","seamless","detached"];function Bp(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&zy.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function Dp(t){return!t||!zt(t)?!1:Bp(t)==="detached"}function Oi(t,e){if(!zt(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-drawer-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),ux(t),$y(t,e);return}let n=e.features?.artifacts?.layout,o=Bp(e)==="detached"?"var(--persona-panel-inset)":"0";t.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),t.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),t.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.drawerWidth?t.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):t.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let s=n?.paneBackground?.trim();s?t.style.setProperty("--persona-artifact-pane-bg",s):t.style.removeProperty("--persona-artifact-pane-bg");let i=n?.panePadding?.trim();i?t.style.setProperty("--persona-artifact-pane-padding",i):t.style.removeProperty("--persona-artifact-pane-padding");let l=[[n?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[n?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[n?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[n?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[c,u]of l){let p=c?.trim();p?t.style.setProperty(u,p):t.style.removeProperty(u)}$y(t,e)}function _i(t,e){for(let c of zy)t.classList.remove(`persona-artifact-appearance-${c}`);if(t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-chat-shadow"),!zt(e))return;let n=e.features?.artifacts?.layout,o=Bp(e);t.classList.add(`persona-artifact-appearance-${o}`);let s=n?.paneBorderRadius?.trim();s&&t.style.setProperty("--persona-artifact-pane-radius",s);let i=n?.paneShadow?.trim();i&&t.style.setProperty("--persona-artifact-pane-shadow",i);let l=n?.chatShadow?.trim();l&&t.style.setProperty("--persona-artifact-chat-shadow",l)}function Uy(t,e){return!e||!zt(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var gx=new Set(["__proto__","prototype","constructor"]),mx=new Set(["collapsed","card","panel","inline"]),qy=new Set(["markdown","component"]),fx=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Lr=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),ql=t=>!gx.has(t),Op=t=>typeof t=="string"&&mx.has(t),Ir=t=>Object.keys(t).length>0;function Gn(t,e,n,o){t.push({path:e,code:n,message:o})}var hx="Ignored because this key is not part of the persisted preference schema.",Ul="Ignored an unsupported value.",yx="Expected collapsed, panel, or inline.",bx='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',jy={kind:"mode",message:Ul},As={kind:"string",message:"Expected a CSS length string."},bo={kind:"boolean"},vx={paneWidth:As,paneMaxWidth:As,paneMinWidth:As,expandedPanelWidth:As,resizableMinWidth:As,resizableMaxWidth:As,expandLauncherPanelWhenOpen:bo,resizable:bo},Cx={kind:"object",message:"Expected a preference object.",children:{showToolCalls:bo,showReasoning:bo,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Ul},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Ul},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Ul},expandable:bo,grouped:bo}},reasoningDisplay:{kind:"object",children:{expandable:bo,activePreview:bo}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:jy,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:jy,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:qy,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:qy}}},filePreview:{kind:"object",children:{enabled:bo}},layout:{kind:"object",children:vx}}}}};function Ky(t,e,n,o){if(t!==void 0)switch(e.kind){case"boolean":return typeof t=="boolean"?t:Gn(o,n,"invalid_type","Expected a boolean.");case"string":return typeof t=="string"?t:Gn(o,n,"invalid_type",e.message);case"enum":return typeof t=="string"&&e.values.has(t)?t:Gn(o,n,"invalid_value",e.message);case"mode":return Op(t)?Ga(t):Gn(o,n,"invalid_value",e.message);case"modeMap":{if(!Lr(t))return Gn(o,n,"invalid_type","Expected an object.");let s=e.keys==="mediaType"?void 0:e.keys,i={};for(let[l,c]of Object.entries(t)){let u=s?l:zm(l);ql(l)&&(s?s.has(l):fx.test(u))?Op(c)?i[u]=Ga(c):Gn(o,`${n}.${l}`,"invalid_value",yx):Gn(o,`${n}.${l}`,s?"unknown_key":"invalid_value",s?"Ignored an unsupported selector.":bx)}return Ir(i)?i:void 0}case"object":{if(e.bareMode&&Op(t))return Ga(t);if(!Lr(t))return Gn(o,n,"invalid_type",e.message??"Expected an object.");let s=Object.keys(e.children),i=c=>n?`${n}.${c}`:c;for(let c of Object.keys(t))(!ql(c)||!s.includes(c))&&Gn(o,i(c),"unknown_key",hx);let l={};for(let c of s){let u=e.children[c],p=Ky(t[c],u,i(c),o);if(u.deprecated&&t[c]!==void 0&&Gn(o,i(c),"deprecated_key",u.deprecated),p===void 0)continue;let g=u.alias??c,y=l[g];l[g]=Lr(y)&&Lr(p)?{...y,...p}:p}return Ir(l)?l:void 0}}}function wx(t){let e=[];return{preferences:(t===null?void 0:Ky(t,Cx,"",e))??{},issues:e}}function Ms(t){if(Array.isArray(t))return t.map(Ms);if(!Lr(t))return t;let e={};for(let[n,o]of Object.entries(t))ql(n)&&o!==void 0&&(e[n]=Ms(o));return e}function Gy(t,e){let n=Ms(t);for(let[o,s]of Object.entries(e)){if(!ql(o)||s===void 0)continue;let i=n[o];n[o]=Lr(i)&&Lr(s)?Gy(i,s):Ms(s)}return n}function Sx(t){let e={},n;for(let s of t){let i=wx(s).preferences;n=Yy(n,i.artifacts?.display),e=Gy(e,i)}let o=e;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function xx(t,e){if(e===void 0)return t===void 0?void 0:Ms(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,s={...n.byMediaType,...e.byMediaType},i={...o?{default:o}:{},...Ir(s)?{byMediaType:s}:{}};return Ir(i)?i:void 0}function Yy(t,e){if(e===void 0)return t===void 0?void 0:Ms(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,s={...n.byType,...n.byKind,...e.byType,...e.byKind},i=xx(n.files,e.files),l={...o?{default:o}:{},...Ir(s)?{byKind:s}:{},...i!==void 0?{files:i}:{}};return Ir(l)?l:void 0}function Ax(t={},e){let n=Sx(e),o={...t};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...t.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...t.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let s=t.artifacts??{},i={...s};if(n.artifacts.display!==void 0){let l=Yy(s.display,n.artifacts.display);l!==void 0&&(i.display=l)}n.artifacts.filePreview&&(i.filePreview={...s.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(i.layout={...s.layout,...n.artifacts.layout}),o.artifacts=i}return o}function _p(t){let e=t.preferences;return!e||!Ir(e)?t:{...t,features:Ax(t.features??{},[e])}}function Mx(t,e){if(!t?.trim())return e;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return n?Math.max(0,Number(n[1])):e}function Ex(t){if(!t?.trim())return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function Tx(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function kx(t,e,n,o){let s=t-o-2*e-n;return Math.max(0,s)}function Fp(t,e){let o=(e.getComputedStyle(t).gap||"0px").trim().split(/\s+/)[0]??"0px",s=/^([\d.]+)px$/i.exec(o);if(s)return Number(s[1]);let i=/^([\d.]+)/.exec(o);return i?Number(i[1]):8}function Qy(t,e,n,o,s,i,l=200){let c=Mx(s,200),u=kx(e,n,o,l);u=Math.max(c,u);let p=Ex(i);return p!==null&&(u=Math.min(u,p)),Tx(t,c,u)}var{setLoader:Wk,load:Px,provide:Bk,getSync:Lx}=je({fallbackImport:()=>import("./forms-ui-PJMI3HQR.js")});var Xy=Px;var Jy=Lx;var Np=class{#e=new Map;register(e){this.#e.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.#e.set(e.id,e),e.onRegister?.()}unregister(e){let n=this.#e.get(e);n&&(n.onUnregister?.(),this.#e.delete(e))}getAll(){return Array.from(this.#e.values()).sort((e,n)=>(n.priority??0)-(e.priority??0))}getForInstance(e){let n=this.getAll();if(!e||e.length===0)return n;let o=new Set(e.map(i=>i.id));return[...n.filter(i=>!o.has(i.id)),...e].sort((i,l)=>(l.priority??0)-(i.priority??0))}clear(){this.#e.forEach(e=>e.onUnregister?.()),this.#e.clear()}},Vp=new Np;var Zy=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Ix=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),eb=(t,e,n)=>{if(!Zy(t)||!Zy(e)||Ix.has(n))return e;let o={...t};for(let s of Object.keys(e)){if(e[s]===void 0){delete o[s];continue}let i=n?`${n}.${s}`:s;o[s]=eb(t[s],e[s],i)}return o};function tb(t,e){let n=Em(za),o=km(t,e,n),s=Tm(Pm(eb(t,e,""),n,o),o);return Im(Ua(s),Hm(t,e))}var nb=()=>{let t=new Map,e=(s,i)=>(t.has(s)||t.set(s,new Set),t.get(s).add(i),()=>n(s,i)),n=(s,i)=>{t.get(s)?.delete(i)};return{on:e,off:n,emit:(s,i)=>{t.get(s)?.forEach(l=>{try{l(i)}catch(c){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",c)}})}}};var Hx=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},Rx=t=>{let e=t.trim(),n=e.indexOf("{");if(n===-1)return null;let o=0;for(let s=n;s<e.length;s+=1){let i=e[s];if(i==="{"&&(o+=1),i==="}"&&(o-=1,o===0))return e.slice(n,s+1)}return null},zp=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=Hx(t),n=Rx(e);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:s,...i}=o;return{type:String(s),payload:i,raw:o}}catch{return null}},$p=t=>typeof t=="string"?t:t==null?"":String(t),Fi={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:$p(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=$p(n.element);if(o&&e.document?.querySelector){let s=e.document.querySelector(o);s?setTimeout(()=>{s.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:$p(n.text)}}},ob=t=>Array.isArray(t)?t.map(e=>String(e)):[],Up=t=>{let e=new Set(ob(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(ob(t.getSessionMetadata().processedActionMessageIds))},o=()=>{let i=Array.from(e);t.updateSessionMetadata(l=>({...l,processedActionMessageIds:i}))};return{process:i=>{if(i.streaming||i.message.role!=="assistant"||!i.text||e.has(i.message.id))return null;let l=typeof i.raw=="string"&&i.raw||typeof i.message.rawContent=="string"&&i.message.rawContent||typeof i.text=="string"&&i.text||null;!l&&typeof i.text=="string"&&i.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let c=l?t.parsers.reduce((p,g)=>p||g?.({text:l,message:i.message})||null,null):null;if(!c)return null;e.add(i.message.id),o();let u={action:c,message:i.message};t.emit("action:detected",u);for(let p of t.handlers)if(p)try{let g=()=>{t.emit("action:resubmit",u)},y=p(c,{message:i.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:g});if(!y)continue;if(y.handled){let h=y.persistMessage!==!1;return{text:y.displayText!==void 0?y.displayText:"",persist:h,resubmit:y.resubmit}}}catch(g){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",g)}return{text:"",persist:!0}},syncFromMetadata:n}};var Wx=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},Bx=t=>t.map(e=>({...e,streaming:!1})),Dx=t=>t.map(e=>({...e,status:"complete"})),rb=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?Wx(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let s={...n,messages:n.messages?Bx(n.messages):void 0,artifacts:n.artifacts?Dx(n.artifacts):void 0};o.setItem(t,JSON.stringify(s))}catch(s){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let n=e();if(n)try{n.removeItem(t)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var Ox=t=>{let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")},sb=async t=>{let e=globalThis.crypto?.subtle;if(e)try{let n=await e.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}catch{}return Ox(t)},_x=async(t,e)=>{let n=await sb(t);return{storageKey:`${e}visitor:${n}`,leaseKey:`${e}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await sb(`${t}\0${e}`)}`}};var ib=(t,e,n)=>{let o="",s="",i="",l=!1,c=!1,u=0,p=null,g=null,y=new Set,h=()=>{if(n||l)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return l=!0,null}},C=()=>{let _=h();if(!_)return p;try{return _.getItem(o)}catch{return l=!0,p}},E=(_,Q)=>{if(c||_===p)return;let G=p;p=_,u+=1;let w={previousToken:G,token:_,source:Q,revision:u};for(let v of y)v(w)},A=_=>{c||_.key!==null&&_.key!==o||E(_.key===null?null:_.newValue??null,"external")},I=(async()=>{let _=await _x(t,e);o=_.storageKey,s=_.leaseKey,i=_.lockName,p=C(),!n&&typeof window<"u"&&window.addEventListener("storage",A)})(),L=_=>new Promise(Q=>setTimeout(Q,_)),k=()=>{let _=h();if(!_)return null;try{let Q=_.getItem(s);if(!Q)return null;let G=JSON.parse(Q);return typeof G?.expiresAt=="number"&&typeof G?.ownerNonce=="string"?G:null}catch{return null}},R=_=>{let Q=h();if(Q)try{k()?.ownerNonce===_&&Q.removeItem(s)}catch{}},B=new Set,O=_=>c?Promise.reject(new Error("Visitor store destroyed before its first init could start")):_(),V=_=>new Promise(Q=>{let G=setTimeout(w,_);function w(){clearTimeout(G),B.delete(w),window.removeEventListener("storage",v),Q()}function v(T){(T.key===null||T.key===s)&&w()}B.add(w),window.addEventListener("storage",v)}),J=async _=>{let Q=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,G=Date.now()+15e3;for(;!c&&Date.now()<G;){let w=h();if(!w)break;let v=Date.now(),T=k();if(T&&T.expiresAt>v&&T.ownerNonce!==Q){await V(Math.min(T.expiresAt-v,500));continue}try{w.setItem(s,JSON.stringify({ownerNonce:Q,expiresAt:v+1e4}))}catch{l=!0;break}if(await L(20+Math.random()*40),k()?.ownerNonce!==Q){await V(500);continue}g=Q;try{return await O(_)}finally{g=null,R(Q)}}return O(_)};return{ready:I,async get(){return await I,E(C(),"external"),p},async set(_){await I;let Q=h();if(Q)try{Q.setItem(o,_)}catch{l=!0}E(_,"local")},async clear(){await I;let _=h();if(_)try{_.removeItem(o)}catch{l=!0}E(null,"local")},revision(){return u},subscribe(_){return y.add(_),()=>{y.delete(_)}},async withFirstInitLock(_){await I;let Q=globalThis.navigator?.locks;return Q?.request?Q.request(i,()=>O(_)):h()?J(_):O(_)},matches(_,Q,G){return _===t&&Q===e&&G===n},destroy(){c=!0,y.clear(),typeof window<"u"&&window.removeEventListener("storage",A),g&&R(g);for(let _ of[...B])_()}}};var{setLoader:Kk,load:Fx}=je({fallbackImport:()=>import("./history-view-NCFBI5GR.js")});var ab=Fx;var{setLoader:Qk,load:Nx,provide:Xk,getSync:Vx}=je({fallbackImport:()=>import("./history-shell-QDQ44PSE.js")});var lb=Nx;var jl=Vx;var $x=null;function cb(){return $x}import{parse as tP,STR as nP,OBJ as oP}from"partial-json";function db(t,e){let{config:n,message:o,onPropsUpdate:s}=e,i=go.get(t.component);if(!i){if(Rp.includes(t.component)){zl().catch(()=>{});let c=P("div","persona-w-full");return c.setAttribute("data-persona-artifact-pending","true"),c}return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null}let l={message:o,config:n,updateProps:c=>{s&&s(c)}};try{return i(t.props,l)}catch(c){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,c),null}}function pb(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function qp(t){let e=pb(t);if(!e)return!1;try{let n=JSON.parse(e);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function ub(t){let e=pb(t);if(!e)return null;try{let n=JSON.parse(e);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:e}}}catch{}return null}var zx=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function gb(t){let{onSubmit:e,onDismiss:n,title:o="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:i="Share your thoughts (optional)...",submitText:l="Submit",skipText:c="Skip",showComment:u=!0,ratingLabels:p=zx}=t,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-csat",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Customer satisfaction feedback");let y=null,h=document.createElement("div");h.className="persona-feedback-content";let C=document.createElement("div");C.className="persona-feedback-header";let E=document.createElement("h3");E.className="persona-feedback-title",E.textContent=o,C.appendChild(E);let A=document.createElement("p");A.className="persona-feedback-subtitle",A.textContent=s,C.appendChild(A),h.appendChild(C);let I=document.createElement("div");I.className="persona-feedback-rating persona-feedback-rating-csat",I.setAttribute("role","radiogroup"),I.setAttribute("aria-label","Satisfaction rating from 1 to 5");let L=[];for(let V=1;V<=5;V++){let J=document.createElement("button");J.type="button",J.className="persona-feedback-rating-btn persona-feedback-star-btn",J.setAttribute("role","radio"),J.setAttribute("aria-checked","false"),J.setAttribute("aria-label",`${V} star${V>1?"s":""}: ${p[V-1]}`),J.title=p[V-1],J.dataset.rating=String(V),J.innerHTML=`
32
27
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
33
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>
34
29
  </svg>
35
- `,$.addEventListener("click",()=>{m=L,H.forEach((K,se)=>{let ne=se<L;K.classList.toggle("selected",ne),K.setAttribute("aria-checked",se===L-1?"true":"false")})}),H.push($),E.appendChild($)}y.appendChild(E);let I=null;if(d){let L=document.createElement("div");L.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=i,I.rows=3,I.setAttribute("aria-label","Additional comments"),L.appendChild(I),y.appendChild(L)}let N=document.createElement("div");N.className="persona-feedback-actions";let x=document.createElement("button");x.type="button",x.className="persona-feedback-btn persona-feedback-btn-skip",x.textContent=c,x.addEventListener("click",()=>{n?.(),u.remove()});let D=document.createElement("button");return D.type="button",D.className="persona-feedback-btn persona-feedback-btn-submit",D.textContent=l,D.addEventListener("click",async()=>{if(m===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}D.disabled=!0,D.textContent="Submitting...";try{let L=I?.value.trim()||void 0;await e(m,L),u.remove()}catch(L){D.disabled=!1,D.textContent=l,console.error("[CSAT Feedback] Failed to submit:",L)}}),N.appendChild(x),N.appendChild(D),y.appendChild(N),u.appendChild(y),u}function $w(t){let{onSubmit:e,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:i="What could we do better? (optional)...",submitText:l="Submit",skipText:c="Skip",showComment:d=!0,lowLabel:g="Not likely",highLabel:u="Very likely"}=t,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let y=null,b=document.createElement("div");b.className="persona-feedback-content";let C=document.createElement("div");C.className="persona-feedback-header";let S=document.createElement("h3");S.className="persona-feedback-title",S.textContent=o,C.appendChild(S);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=s,C.appendChild(E),b.appendChild(C);let H=document.createElement("div");H.className="persona-feedback-rating persona-feedback-rating-nps",H.setAttribute("role","radiogroup"),H.setAttribute("aria-label","Likelihood rating from 0 to 10");let I=document.createElement("div");I.className="persona-feedback-labels";let N=document.createElement("span");N.className="persona-feedback-label-low",N.textContent=g;let x=document.createElement("span");x.className="persona-feedback-label-high",x.textContent=u,I.appendChild(N),I.appendChild(x);let D=document.createElement("div");D.className="persona-feedback-numbers";let L=[];for(let M=0;M<=10;M++){let T=document.createElement("button");T.type="button",T.className="persona-feedback-rating-btn persona-feedback-number-btn",T.setAttribute("role","radio"),T.setAttribute("aria-checked","false"),T.setAttribute("aria-label",`Rating ${M} out of 10`),T.textContent=String(M),T.dataset.rating=String(M),M<=6?T.classList.add("persona-feedback-detractor"):M<=8?T.classList.add("persona-feedback-passive"):T.classList.add("persona-feedback-promoter"),T.addEventListener("click",()=>{y=M,L.forEach((_,k)=>{_.classList.toggle("selected",k===M),_.setAttribute("aria-checked",k===M?"true":"false")})}),L.push(T),D.appendChild(T)}H.appendChild(I),H.appendChild(D),b.appendChild(H);let $=null;if(d){let M=document.createElement("div");M.className="persona-feedback-comment-container",$=document.createElement("textarea"),$.className="persona-feedback-comment",$.placeholder=i,$.rows=3,$.setAttribute("aria-label","Additional comments"),M.appendChild($),b.appendChild(M)}let K=document.createElement("div");K.className="persona-feedback-actions";let se=document.createElement("button");se.type="button",se.className="persona-feedback-btn persona-feedback-btn-skip",se.textContent=c,se.addEventListener("click",()=>{n?.(),m.remove()});let ne=document.createElement("button");return ne.type="button",ne.className="persona-feedback-btn persona-feedback-btn-submit",ne.textContent=l,ne.addEventListener("click",async()=>{if(y===null){D.classList.add("persona-feedback-shake"),setTimeout(()=>D.classList.remove("persona-feedback-shake"),500);return}ne.disabled=!0,ne.textContent="Submitting...";try{let M=$?.value.trim()||void 0;await e(y,M),m.remove()}catch(M){ne.disabled=!1,ne.textContent=l,console.error("[NPS Feedback] Failed to submit:",M)}}),K.appendChild(se),K.appendChild(ne),b.appendChild(K),m.appendChild(b),m}var _i="persona-chat-history",tP=30*1e3,nP=641,Oi="data-persona-composer-reason",oP={"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 rP(t){if(!t)return[];let e=[],n=Array.from(t.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let s=o.getAsFile();if(!s)continue;if(s.name){e.push(s);continue}let i=oP[s.type]??"png";e.push(new File([s],`clipboard-image-${Date.now()}.${i}`,{type:s.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let o of Array.from(t.files??[]))o.type.startsWith("image/")&&e.push(o);return e}function Nd(t){if(!t)return!1;let e=t.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function sP(t){return t?t===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:t.storage??"session",keyPrefix:t.keyPrefix??"persona-",persist:{openState:t.persist?.openState??!0,voiceState:t.persist?.voiceState??!0,focusInput:t.persist?.focusInput??!0},clearOnChatClear:t.clearOnChatClear??!0}:null}function iP(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var kf=t=>!t||typeof t!="object"?{}:{...t},jw=t=>t.map(e=>({...e,streaming:!1})),Kw=(t,e,n)=>{let o=t?.markdown?By(t.markdown):null,s=Dy(t?.sanitize);t?.postprocessMessage&&s&&t?.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.");let i=!1,l=c=>{let d=c.text??"",g=c.message.rawContent??null;if(e){let y=e.process({text:d,raw:g??d,message:c.message,streaming:c.streaming});y!==null&&(d=y.text,y.persist||(c.message.__skipPersist=!0),y.resubmit&&!c.streaming&&n&&n())}let u=hi()!==null,m;if(t?.postprocessMessage){let y=t.postprocessMessage({...c,text:d,raw:g??c.text??""});m=s?s(y):y}else if(o){let y=c.streaming?Tb(d):d,b=o(y);m=s&&u?s(b):b}else m=Sc(d);return m};return c=>{try{return l(c)}catch(d){return i||(i=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",d)),Sc(c.text??"")}}};function Gw(t){let e=P("div","persona-attachment-drop-overlay");t?.background&&e.style.setProperty("--persona-drop-overlay-bg",t.background),t?.backdropBlur!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",t.backdropBlur),t?.border&&e.style.setProperty("--persona-drop-overlay-border",t.border),t?.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",t.borderRadius),t?.inset&&e.style.setProperty("--persona-drop-overlay-inset",t.inset),t?.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",t.labelSize),t?.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",t.labelColor);let n=t?.iconName??"upload",o=t?.iconSize??"48px",s=t?.iconColor??"rgba(59, 130, 246, 0.6)",i=t?.iconStrokeWidth??.5,l=de(n,o,s,i);if(l&&e.appendChild(l),t?.label){let c=P("span","persona-drop-overlay-label");c.textContent=t.label,e.appendChild(c)}return e}var aP=(t,e)=>{let n={...t};for(let[o,s]of Object.entries(e)){let i=n[o];n[o]=i?{...i,...s}:s}return n},lP=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:aP(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),Qw=(t,e,n)=>{if(t==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');t.id&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.hasAttribute("data-persona-root")||t.setAttribute("data-persona-root","true");let o=_c(e),s=new Set,i=new Set,l=vb((r,a)=>{Dt.delete(r);let p=Array.from(ye.querySelectorAll("[data-message-id]")).find(f=>f.dataset.messageId===r);p&&(a==="tool"?df(r,p,s,o):sf(r,p,i))}),c=new Map,d=()=>{Lv({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};d();let g=o.features;o=bf(o);let u=wf.getForInstance(o.plugins),m=AC(t),y=[],b=!1,C=iw(()=>o),S=null,E=null,H=null,I=!1,N=null,x=r=>{S=r,r.initApprovalUi({webMcpToolTitle:Ac});let a=r.createBuiltInApprovalPlugin(c);E=a.plugin,H=a.teardown},D=()=>{if(S)return S;let r=uw();return r?(x(r),r):(pw().then(a=>{I||S||(x(a),N?.())}).catch(()=>{}),null)},L=!1,$=!1,K=null,se=(r,a,p,f)=>{if(!r.querySelector("[data-tv-form]"))return;let h=Aw();if(h){h.enhanceWithForms(r,a,p,f);return}Sw().then(()=>{L||$||!K||($=!0,K())}).catch(()=>{})};o.components&&tr.registerAll(o.components);let ne=Pw(),T=o.persistState===!1?null:o.storageAdapter??Lw(),_=!!o.clientToken&&typeof o.reconnectStream!="function",k={},Z=null,F,ie=new Promise(r=>{F=r}),le,pe=!1,ve=r=>{if(o.onStateLoaded)try{let a=o.onStateLoaded(r);if(a&&typeof a=="object"&&"state"in a){let{state:p,open:f}=a;return f&&(pe=!0),p}return a}catch(a){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",a)}return r};if(T?.load)try{let r=T.load();if(r&&typeof r.then=="function")Z=r.then(a=>ve(a??{messages:[],metadata:{}}));else{let p=ve(r??{messages:[],metadata:{}});p.metadata&&(k=kf(p.metadata)),p.messages?.length&&(o={...o,initialMessages:p.messages}),p.artifacts?.length&&(o={...o,initialArtifacts:p.artifacts,initialSelectedArtifactId:p.selectedArtifactId??null}),le=p.draft}}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",r)}else if(o.onStateLoaded)try{let r=ve({messages:[],metadata:{}});r.messages?.length&&(o={...o,initialMessages:r.messages})}catch(r){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",r)}Z||F();let Ce=()=>k,me=r=>{k=r({...k})??{},Qs()},vt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Sf],st=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ll.message,ll.messageAndClick],he=Af({parsers:vt,handlers:st,getSessionMetadata:Ce,updateSessionMetadata:me,emit:ne.emit,documentRef:typeof document<"u"?document:null});he.syncFromMetadata();let W=o.launcher?.enabled??!0,We=o.launcher?.autoExpand??!1,Fe=o.autoFocusInput??!1,bn=We,sn=W,Kt=o.layout?.header?.layout,kn=!1,Be=()=>el(o),Ge=()=>W||Be(),Pe=Be()?!1:W?We:!0,Bo=!1,V=null,w=()=>{Bo=!0,V&&clearTimeout(V),V=setTimeout(()=>{Bo&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Bo=!1)},1e4)},O=Kw(o,he,w),j=o.features?.showReasoning??!0,X=o.features?.showToolCalls??!0,Y=o.features?.showEventStreamToggle??!1,ge=o.features?.scrollToBottom??{},xe=o.features?.scrollBehavior??{},Se=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",Wt=`${Se()}event-stream`,Xe=null,$e=o.features?.eventStream?.maxEvents??2e3,pt=null,Gt=null,Mt=null,cn=!1,ut=null,ro=!1,dr=null,Ud=0,Df=(r,a)=>{pt?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:r,timestamp:Date.now(),payload:JSON.stringify(a)})},$d=(r,a)=>{Gt?.processEvent(r,a),pt?Df(r,a):Mt&&(Mt.length>=$e&&Mt.shift(),Mt.push({type:r,payload:a}))},dl=()=>{pt||!Y||(Mt??(Mt=[]),uf().then(r=>{if(cn||pt||!Y)return;Xe=new r.EventStreamStore(Wt),pt=new r.EventStreamBuffer($e,Xe),Gt=Gt??new r.ThroughputTracker,Xe.open().then(()=>pt?.restore()).catch(p=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",p)});let a=Mt??[];Mt=null;for(let p of a)Gt?.processEvent(p.type,p.payload),Df(p.type,p.payload)}).catch(()=>{}))};Y&&dl();let Tt=!1,Ot=null,Vd=()=>{},Do=()=>{},_f=()=>{},Of=()=>{},qd=()=>{},ax=()=>ro||Tt&&Ot==="panel",_s={onCopy:r=>{ne.emit("message:copy",r),A?.isClientTokenMode()&&A.submitMessageFeedback(r.id,"copy").catch(a=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",a)}),o.messageActions?.onCopy?.(r)},onFeedback:r=>{ne.emit("message:feedback",r),A?.isClientTokenMode()&&A.submitMessageFeedback(r.messageId,r.type).catch(a=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",a)}),o.messageActions?.onFeedback?.(r)}},kP=o.statusIndicator??{},zd=(r,a=o.statusIndicator??{})=>r==="idle"?a.idleText??Rt.idle:r==="connecting"?a.connectingText??Rt.connecting:r==="connected"?a.connectedText??Rt.connected:r==="error"?a.errorText??Rt.error:r==="paused"?a.pausedText??Rt.paused:r==="resuming"?a.resumingText??Rt.resuming:Rt[r];function Fi(r,a,p,f){if(!Be()&&(p.mode==="transient"||r.classList.contains("persona-mb-2"))&&(Gu(r,vn,p),Ps(r,p,f)),!r.hasAttribute(Oi))if(f==="idle"&&p.idleLink){r.textContent="";let h=document.createElement("a");h.href=p.idleLink,h.target="_blank",h.rel="noopener noreferrer",h.textContent=a,h.style.color="inherit",h.style.textDecoration="none",r.appendChild(h)}else r.textContent=a}let Ln=sw({config:o,showClose:Ge()}),{wrapper:je,panel:we,pillRoot:Qt}=Ln.shell,De=Ln.panelElements,{container:ce,body:ee,messagesWrapper:ye,starterSuggestions:jd,transcriptSuggestions:Ui,suggestions:pr,textarea:ae,sendButton:Ae,composerForm:vn,statusText:Qe,welcomeHost:Yt,welcomeIconHolder:lx,greetingHost:In,introKicker:cx,introTitle:dx,introSubtitle:px,closeButton:Ue,iconHolder:Et,headerTitle:ur,headerSubtitle:Vr,header:Me,footer:ke,actionsRow:ux}=De,Kd=De.leftActions,pl=De.rightActions,ho=De.sendButtonWrapper,Nf=De.setSendButtonMode,oe=De.micButton,Hn=De.micButtonWrapper,St=De.attachmentButton,Cn=De.attachmentButtonWrapper,yt=De.attachmentInput,wn=De.attachmentPreviewsContainer;ce.classList.add("persona-relative"),ee.classList.add("persona-relative");let gx=12,$i=()=>ge.label??"",fx=()=>ge.iconName??"arrow-down",mx=()=>ge.enabled!==!1,Rn=()=>xe.mode??"anchor-top",gr=()=>Rn()==="follow"||Rn()==="anchor-top"&&Zi,Vi=()=>xe.anchorTopOffset??16,hx=()=>xe.restorePosition??"bottom",Ff=()=>xe.pauseOnInteraction===!0,Uf=()=>xe.showActivityWhilePinned!==!1,$f=()=>xe.announce===!0,Gd=()=>xe.scrollbar??"on-scroll",Nt=P("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");Nt.type="button",Nt.style.display="none",Nt.setAttribute("data-persona-scroll-to-bottom","true");let qi=P("span","persona-flex persona-items-center"),Qd=P("span",""),qr=P("span","");qr.setAttribute("data-persona-scroll-to-bottom-count",""),qr.style.display="none",Nt.append(qi,Qd,qr),ce.appendChild(Nt);let Vn=P("div","persona-stream-anchor-spacer");Vn.setAttribute("aria-hidden","true"),Vn.setAttribute("data-persona-anchor-spacer",""),Vn.style.flexShrink="0",Vn.style.pointerEvents="none",Vn.style.height="0px",Vn.style.display="none",ee.appendChild(Vn);let _o=P("div","persona-sr-only");_o.setAttribute("aria-live","polite"),_o.setAttribute("aria-atomic","true"),_o.setAttribute("role","status"),_o.setAttribute("data-persona-live-region",""),Object.assign(_o.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),ce.appendChild(_o);let zi=null,ul=null,gl=r=>{!$f()||!r||(ul=r,zi===null&&(zi=setTimeout(()=>{zi=null,ul&&$f()&&(_o.textContent=ul),ul=null},400)))},ji=()=>{let r=t.ownerDocument.defaultView??window;return(o.launcher?.mobileFullscreen??!0)&&r.innerWidth<=(o.launcher?.mobileBreakpoint??640)&&(W||xt(o))||o.launcher?.fullHeight===!0&&!o.launcher.sidebarMode&&!xt(o)},zr=()=>Rd(o,ji()),fl="empty",ml=0,Yd=()=>ml||parseFloat(t.style.getPropertyValue("--persona-composer-lift"))||0,jr=()=>{let a=ke.style.display==="none"?0:ke.offsetHeight;Nt.style.bottom=`${a+Yd()+gx}px`};jr();let Xd=()=>{$s||(ke.style.marginBottom=ml>0?`${ml}px`:"")},hl=()=>{let r=_g(o,Be()),a=zr();t.setAttribute("data-persona-welcome-fullscreen",String(ji())),t.setAttribute("data-persona-welcome-layout",a.layout??"top"),t.setAttribute("data-persona-welcome-layout-explicit",o.welcome?.layout??""),t.setAttribute("data-persona-welcome-anchor",a.anchor??"bottom");let f=ke.style.display==="none"?0:ke.offsetHeight,h=a.anchor==="center"&&fl==="empty"?Ya(a.anchorComposerTop)??Ya("44%"):null,v=h!==null&&a.layout==="centered"&&o.welcome?.anchor===void 0&&o.welcome?.anchorComposerTop===void 0,B=v?getComputedStyle(ee):null,q=parseFloat(t.style.getPropertyValue("--persona-composer-overlay-height"))||0,U=parseFloat(t.style.getPropertyValue("--persona-composer-lift"))||0,z=Math.max(0,(parseFloat(B?.paddingBottom??"")||0)-(r==="overlay"?q+U:0)),Q=v?ee.getBoundingClientRect().top-ce.getBoundingClientRect().top:0,re=!v||Yt.hidden?0:(Yt.querySelector("[data-persona-welcome-plugin]")??Yt).offsetHeight,ue=h===null||Be()?0:v?Math.max(0,Math.round((ce.clientHeight-Q-re-z-f)/2)):wC({columnHeight:ce.clientHeight,footerHeight:f,fraction:h});t.style.setProperty("--persona-composer-overlay-height",`${f}px`),t.style.setProperty("--persona-composer-lift",`${r==="overlay"?ue:0}px`),ml=r==="block"?ue:0,Xd(),jr()},Vf=()=>{let r=!!$i();Nt.setAttribute("aria-label",$i()||"Jump to latest"),Nt.title=$i(),Nt.setAttribute("data-persona-scroll-to-bottom-has-label",r?"true":"false"),qi.innerHTML="";let a=de(fx(),"14px","currentColor",2);a?(qi.appendChild(a),qi.style.display=""):qi.style.display="none",Qd.textContent=$i(),Qd.style.display=r?"":"none"};Vf();let tt=null,Bt=null,be=Av(),yx=r=>{try{ce.dispatchEvent(new CustomEvent("persona:composer:state",{detail:r,bubbles:!0,composed:!0}))}catch{}};be.subscribe(yx);let yo=()=>{be.setText(ae?.value??"")},Kr=()=>{be.setMentionRefs(Bt?.getMentionRefs()??[])},bx=r=>({id:r.id,name:r.file.name,mimeType:r.file.type,size:r.file.size,status:r.status,progress:r.progress,error:r.error}),qf=r=>{let a=Object.freeze(r.map(bx));be.setAttachments(a);try{o.attachments?.onChange?.(a)}catch(p){console.error("[AgentWidget] attachments.onChange failed:",p)}Tp()};be.setSelectedModelId(o.composer?.selectedModelId);let Ki=()=>o.composer?.modes??[],Os=()=>Qv(Ki(),o.composer?.modeGroups);{let r=fd(o.composer?.defaultActiveModeIds??[],Ki());r.length&&be.setActiveModeIds(r)}function zf(r){if(be.getState().selectedModelId!==r){be.setSelectedModelId(r),fr?.repaint();try{o.composer?.onModelChange?.(r)}catch(a){console.error("[AgentWidget] composer.onModelChange failed:",a)}}}function yl(r){be.setActiveModeIds(r),Oo?.render(r,Os()),Ns.forEach(a=>a.repaint()),vo?.resolve(),$l(),so()}function Jd(r){yl(Yv(be.getState().activeModeIds,r,Ki(),o.composer?.modeGroups))}let fr=null,Zd=null,Oo=null,Ns=new Map,mr=null;function bo(r){be.setQuote(r),mr?.render(be.getState().quote),so(),Dm()}let jf=!1;function ep(){let r=o.composer?.streamingSubmitBehavior??"block";return r!=="interrupt"?r:o.clientToken?"interrupt":(!jf&&o.debug===!0&&(jf=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let hr=null;function Fs(r){be.setPendingSubmission(r),hr?.render(be.getState().pendingSubmission),so()}let vx=r=>{let a=Ns.get(r);if(a)return a;let p=Zv({groupId:r,getGroup:()=>o.composer?.modeGroups?.find(f=>f.id===r),getModes:()=>Ki().filter(f=>f.groupId===r),getActiveIds:()=>be.getState().activeModeIds,onSelect:f=>Jd(f)});return Ns.set(r,p),p},Cx=()=>{let r=[],a=be.getState().activeModeIds,p=new Set;if(Ki().forEach((f,h)=>{if(gd(f.groupId,o.composer?.modeGroups)){let v=f.groupId;if(p.has(v))return;p.add(v);let B=vx(v);B.action.order=kg(h),B.action.label=o.composer?.modeGroups?.find(q=>q.id===v)?.label??v,r.push(B.action);return}r.push({id:Kv(f.id),kind:"button",placement:"start",order:kg(h),presentation:f.presentation??"auto",label:f.label,shortLabel:f.shortLabel,iconName:f.iconName,pressed:a.includes(f.id),onSelect:()=>Jd(f.id)})}),o.composer?.models?.length&&!u.some(f=>f.renderComposer)){let f=o.composer?.modelPicker?.presentation??"native";(!fr||Zd!==f)&&(Zd=f,fr=zv({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>be.getState().selectedModelId,onSelect:h=>zf(h),presentation:f,getSuffix:()=>o.composer?.modelPicker?.suffix})),r.push(fr.action)}return r},tp=null,Kf=u.find(r=>r.renderHeader);if(Kf?.renderHeader){let r=Kf.renderHeader({config:o,defaultRenderer:()=>{let a=Rs({config:o,showClose:Ge()});return nl(ce,a,o),a.header},onClose:()=>gt(!1,"user")});if(r){let a=Me;a&&(a.replaceWith(r),Me=r,Ln.header.element=r)}}let Gf=()=>{ut&&(ee.style.display="none",ke.parentNode?.insertBefore(ut.element,ke),ut.update())},np=()=>{if(!pt){dl();return}if(ro=!0,ut?Gf():uf().then(a=>{ut||!ro||!pt||(ut=a.createEventStreamView({buffer:pt,getFullHistory:()=>pt.getAllFromStore(),onClose:()=>Us(),config:o,plugins:u,getThroughput:()=>Gt?.getMetric()??{status:"idle"},renderIconByName:de}),Gf())}).catch(()=>{Us()}),ot){ot.style.boxShadow=`inset 0 0 0 1.5px ${mn.actionIconColor}`;let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(p=>p&&ot.classList.add(p))}let r=()=>{if(!ro)return;let a=Date.now();a-Ud>=200&&(ut?.update(),Ud=a),dr=requestAnimationFrame(r)};Ud=0,dr=requestAnimationFrame(r),qt(),ne.emit("eventStream:opened",{timestamp:Date.now()})},Us=()=>{if(ro){if(ro=!1,ut&&ut.element.remove(),ee.style.display="",ot){ot.style.boxShadow="";let r=o.features?.eventStream?.classNames?.toggleButtonActive;r&&r.split(/\s+/).forEach(a=>a&&ot.classList.remove(a))}dr!==null&&(cancelAnimationFrame(dr),dr=null),qt(),ne.emit("eventStream:closed",{timestamp:Date.now()})}},ot=null;if(Y){let r=o.features?.eventStream?.classNames,a="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"+(r?.toggleButton?" "+r.toggleButton:"");ot=P("button",a),ot.style.width="28px",ot.style.height="28px",ot.style.color=mn.actionIconColor,ot.type="button",ot.setAttribute("aria-label","Event Stream"),ot.title="Event Stream";let p=$t(Vw,"18px","currentColor",1.5);p&&ot.appendChild(p);let f=De.clearChatButtonWrapper,h=De.closeButtonWrapper,v=f||h;v&&v.parentNode===Me?Me.insertBefore(ot,v):Me.appendChild(ot),ot.addEventListener("click",()=>{ro?Us():np()})}let Qf=r=>{let a=o.attachments;if(!a?.enabled)return;let p=r.querySelector("[data-persona-composer-attachment-previews]")??r.querySelector(".persona-attachment-previews");if(!p){p=P("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),p.setAttribute("data-persona-composer-attachment-previews",""),p.style.display="none";let h=r.querySelector("[data-persona-composer-form]");h?.parentNode?h.parentNode.insertBefore(p,h):r.insertBefore(p,r.firstChild)}if(!(r.querySelector("[data-persona-composer-attachment-input]")??r.querySelector('input[type="file"]'))){let h=P("input");h.type="file",h.setAttribute("data-persona-composer-attachment-input",""),h.accept=(a.allowedTypes??sr).join(","),h.multiple=(a.maxFiles??4)>1,h.style.display="none",h.setAttribute("aria-label",a.buttonTooltipText??"Attach files"),r.appendChild(h)}},$s=!1,Yf=r=>{let a=u.find(h=>h.renderComposer);if(!a?.renderComposer)return null;let p=o.composer,f=b?A.isStreaming():!1;return a.renderComposer({config:o,defaultRenderer:r,requestRender:()=>wy(),storage:C(a.id),onSubmit:h=>{!A||A.isStreaming()||mc(h.trim(),{consumeDraft:!1})},streaming:f,disabled:f,openAttachmentPicker:()=>{So()||yt?.click()},models:p?.models,selectedModelId:be.getState().selectedModelId??p?.selectedModelId,onModelChange:h=>zf(h),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{tp?.()}:void 0})},Xf=Yf(()=>ol({config:o}).footer);Xf&&(Ln.replaceComposer(Xf),ke=Ln.composer.footer,$s=!0);let Je=null,wx=r=>{vn=r.form,ae=r.input,ho=r.sendButton?r.sendButton.parentElement:null,r.sendButton&&(Ae=r.sendButton),r.micButton&&(oe=r.micButton,Hn=r.micButton.parentElement),r.found.status&&(Qe=r.found.status),r.found.suggestions&&(pr=r.found.suggestions),r.attachmentButton&&(St=r.attachmentButton,Cn=r.attachmentButton.parentElement),yt=r.attachmentInput??null,wn=r.attachmentPreviews??null,r.found.actionsRow&&(ux=r.found.actionsRow),Kd=r.found.actionsStart,pl=r.found.actionsEnd};function op(){let r=ae;if(!r)return;let a=o.composer?.inputAttributes,p=!a?.ariaLabel&&!(r instanceof HTMLTextAreaElement)?r.getAttribute("aria-label"):null;id(r,a),p&&r.setAttribute("aria-label",p),sd(r,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:qa(r)}),Rv(r,rd(o.composer?.maxLines,Be()?5:3))}let Jf=r=>{Je=Tv(r,{debug:o.debug===!0}),Je&&wx(Je),op()};Qf(ke),Jf(ke),yo();let Gi=Ur(o,Be());Gi&&(ye.style.maxWidth=Gi,ye.style.marginLeft="auto",ye.style.marginRight="auto",ye.style.width="100%",In.style.maxWidth=Gi,In.style.marginLeft="auto",In.style.marginRight="auto",In.style.width="100%",jd.style.maxWidth=Gi,Ui.style.maxWidth=Gi,Ui.style.marginLeft="auto",Ui.style.marginRight="auto",Ui.style.width="100%");let Zf=()=>{let r=Ur(o,Be());if(!(!r||Be()))for(let a of[vn,pr,wn,Qe])a&&(a.style.maxWidth=r,a.style.marginLeft="auto",a.style.marginRight="auto",a.style.width="100%")};Zf();let em=()=>{!o.attachments?.enabled||!yt||!wn||(tt?tt.remountPreviews(wn):(tt=Va.fromConfig(o.attachments,qf),tt.setPreviewsContainer(wn)),Je?.addListener(yt,"change",r=>{let a=r.target;tt?.handleFileSelect(a.files),a.value=""}),ce.querySelector(".persona-attachment-drop-overlay")||ce.appendChild(Gw(o.attachments.dropOverlay)))};em();let xx=()=>Bt?.prefetch(),tm=()=>{if(!o.contextMentions?.enabled||!ae)return;let r=Je?.header??null,a=r?Wu(r):void 0;if(Bt=fC({config:o,textarea:ae,anchor:vn??ae,getMessages:()=>A.getMessages(),liveRegionHost:ce,chipRow:a}),Bt&&!a){let p=ae;p.parentElement?.insertBefore(Bt.contextRow,p)}};tm();let vo=null,Sx={getState:()=>be.getState(),getValue:()=>ae?.value??"",setValue:r=>{ae&&(ae.value=r,ae.dispatchEvent(new Event("input",{bubbles:!0})),yo())},submit:()=>{Yy(Je?.form??null)},openAttachmentPicker:()=>{So()||yt?.click()},toggleVoice:()=>{tp?.()},requestRender:()=>vo?.resolve()},Ax=()=>{let r=[];return(Bt?.affordanceButtons??[]).forEach((p,f)=>{r.push({id:`core:mention-${f}`,placement:"start",order:Ro.mention+f,element:p,managed:!0})}),Cn&&r.push({id:"core:attachment",placement:"start",order:Ro.attachment,element:Cn}),Hn&&r.push({id:"core:mic",placement:"end",order:Ro.mic,element:Hn}),ho&&r.push({id:"core:send",placement:"end",order:Ro.send,element:ho}),r},nm=()=>{vo?.destroy(),vo=$v({getBindings:()=>Je,collect:()=>({builtIns:Ax(),configActions:[...Cx(),...o.composer?.actions??[]],plugins:u,contributionContext:{config:o,getState:()=>be.getState(),requestRender:()=>vo?.resolve()},debug:o.debug===!0}),actionContext:Sx,getState:()=>be.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(r,a)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${a.actionId}" failed:`,r)}}),vo.resolve()};nm();let rp=()=>{if(Oo?.destroy(),Oo=null,!Os().length)return;let r=Je?.header;r&&(Oo=jv({row:Wu(r),onRemove:a=>Jd(a),initialIds:be.getState().activeModeIds}),Oo.render(be.getState().activeModeIds,Os()))};rp();let om=()=>{mr?.destroy(),mr=null,hr?.destroy(),hr=null;let r=Je?.header;r&&(mr=eC({onDismiss:()=>bo(void 0)}),r.appendChild(mr.element),mr.render(be.getState().quote),ep()==="defer-one"&&(hr=tC({onEdit:()=>XS(),onRemove:()=>Fs(void 0)}),r.appendChild(hr.element),hr.render(be.getState().pendingSubmission)))};om();let sp=aC(),Mx=()=>{let r=Je?.header?.querySelector(Qy);if(r)return r.childElementCount>0;let a=be.getState();return a.mentionRefs.length>0||fd(a.activeModeIds,Os()).length>0};function so(){let r=be.getState(),a=sp.observe(lC(ae),r.text);ke.toggleAttribute("data-persona-composer-compact",iC({text:r.text,wrapped:a,hasAttachments:r.attachments.length>0,hasChips:Mx(),hasQuote:r.quote!==void 0,hasPendingSubmission:r.pendingSubmission!==void 0}))}function rm(){o.composer?.layout==="single-row"&&!Be()?ke.setAttribute("data-persona-composer-layout","single-row"):ke.removeAttribute("data-persona-composer-layout")}rm(),be.subscribe(()=>{vo?.sync(),Tp(),Fl(),so(),Dm()}),Fl();let sm=!1,Tx=r=>{if(sm||o.debug!==!0)return;let a=["messages","composer"].filter(p=>r[p]);a.length&&(sm=!0,console.warn(`[persona] layout.slots.${a.join(" and layout.slots.")} ${a.length>1?"are":"is"} deprecated and unsupported: the renderer never runs. Use the message render hooks for the transcript and the renderComposer plugin hook for the composer.`))};(()=>{let r=o.layout?.slots??{};Tx(r);let a=f=>{switch(f){case"body-top":return ee.querySelector("[data-persona-intro-card]");case"messages":return ye;case"footer-top":return pr;case"composer":return vn;case"footer-bottom":return Qe;default:return null}},p=(f,h)=>{switch(f){case"header-left":case"header-center":case"header-right":if(f==="header-left")Me.insertBefore(h,Me.firstChild);else if(f==="header-right")Me.appendChild(h);else{let v=Me.querySelector(".persona-flex-col");v?v.parentNode?.insertBefore(h,v.nextSibling):Me.appendChild(h)}break;case"body-top":{let v=ee.querySelector("[data-persona-intro-card]");v?v.replaceWith(h):ee.insertBefore(h,ee.firstChild);break}case"body-bottom":ee.appendChild(h);break;case"footer-top":pr.replaceWith(h);break;case"footer-bottom":Qe.replaceWith(h);break;default:break}};for(let[f,h]of Object.entries(r))if(h)try{let v=h({config:o,defaultContent:()=>a(f)});v&&p(f,v)}catch(v){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${f}":`,v)}})(),ye.addEventListener("click",r=>{let a=r.target;if(!(a instanceof Element))return;let p=a.closest("button[data-persona-copy-tool-detail]");p&&(r.preventDefault(),r.stopPropagation(),cw(p))});let ip=r=>{let p=r.target.closest('button[data-expand-header="true"]');if(!p)return;let f=p.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!f)return;let h=f.getAttribute("data-message-id");if(!h)return;wr(),Js();let v=p.getAttribute("data-bubble-type");if(f.classList.contains("persona-activity-row")){l.manual(h);let B=f.parentElement?.closest("[data-persona-tool-group]");B?.dataset.messageId&&l.manual(B.dataset.messageId)}if(v==="reasoning")i.has(h)?i.delete(h):i.add(h),sf(h,f,i);else if(v==="tool")s.has(h)?s.delete(h):s.add(h),df(h,f,s,o);else if(v==="approval"&&S){let q=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",U=c.get(h)??q;c.set(h,!U),S.updateApprovalDetailsUI(h,f,o,c)}Dt.delete(h)};ye.addEventListener("pointerdown",r=>{r.target.closest('button[data-expand-header="true"]')&&(r.preventDefault(),ip(r))}),ye.addEventListener("click",r=>{r.detail===0&&r.target.closest(".persona-activity-row")&&ip(r)}),ye.addEventListener("keydown",r=>{let a=r.target;(r.key==="Enter"||r.key===" ")&&a.closest('button[data-expand-header="true"]')&&(r.preventDefault(),ip(r))}),ye.addEventListener("copy",r=>{let{clipboardData:a}=r;if(!a)return;let p=ye.getRootNode(),f=typeof p.getSelection=="function"?p.getSelection():window.getSelection();if(!f||f.isCollapsed)return;let h=f.toString(),v=MC(h);!v||v===h||(a.setData("text/plain",v),r.preventDefault())});let ap=new Map,im=null,am="idle",Ex={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Px=(r,a)=>{let{icon:p,label:f}=Ex[a];r.setAttribute("aria-label",f),r.title=f,r.setAttribute("aria-pressed",a==="idle"?"false":"true"),r.classList.toggle("persona-message-action-active",a!=="idle"),r.classList.toggle("persona-message-action-loading",a==="loading");let h=de(p,14,"currentColor",2);h&&(r.innerHTML="",r.appendChild(h))},lm=()=>{ye.querySelectorAll('[data-action="read-aloud"]').forEach(a=>{let f=a.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Px(a,f&&f===im?am:"idle")})};ye.addEventListener("click",r=>{let p=r.target.closest(".persona-message-action-btn[data-action]");if(!p)return;r.preventDefault(),r.stopPropagation();let f=p.closest("[data-actions-for]");if(!f)return;let h=f.getAttribute("data-actions-for");if(!h)return;let v=p.getAttribute("data-action");if(v==="copy"){let q=A.getMessages().find(U=>U.id===h);if(q&&_s.onCopy){let U=q.content||"";navigator.clipboard.writeText(U).then(()=>{p.classList.add("persona-message-action-success");let z=$t(qw,14,"currentColor",2);z&&(p.innerHTML="",p.appendChild(z)),setTimeout(()=>{p.classList.remove("persona-message-action-success");let Q=$t(zw,14,"currentColor",2);Q&&(p.innerHTML="",p.appendChild(Q))},2e3)}).catch(z=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",z)}),_s.onCopy(q)}}else if(v==="read-aloud")A.toggleReadAloud(h);else if(v==="upvote"||v==="downvote"){let q=(ap.get(h)??null)===v,U=v==="upvote"?"thumbs-up":"thumbs-down";if(q){ap.delete(h),p.classList.remove("persona-message-action-active");let z=de(U,14,"currentColor",2);z&&(p.innerHTML="",p.appendChild(z))}else{let z=v==="upvote"?"downvote":"upvote",Q=f.querySelector(`[data-action="${z}"]`);if(Q){Q.classList.remove("persona-message-action-active");let Ze=de(z==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ze&&(Q.innerHTML="",Q.appendChild(Ze))}ap.set(h,v),p.classList.add("persona-message-action-active");let re=de(U,14,"currentColor",2);re&&(re.setAttribute("fill","currentColor"),p.innerHTML="",p.appendChild(re)),p.classList.remove("persona-message-action-pop"),p.offsetWidth,p.classList.add("persona-message-action-pop");let Ne=A.getMessages().find(nt=>nt.id===h);Ne&&_s.onFeedback&&_s.onFeedback({type:v,messageId:Ne.id,message:Ne})}}else if(v==="regenerate")bl?.regenerate(h);else if(v==="edit")bl?.edit(h);else if(v==="quote")bl?.quote(h);else if(v?.startsWith(kd)){let B=v.slice(kd.length),q=o.messageActions?.custom?.find(z=>z.id===B),U=A.getMessages().find(z=>z.id===h);if(!q||!U)return;try{q.onSelect(U)}catch(z){console.error(`[AgentWidget] messageActions.custom "${B}" onSelect failed:`,z)}}});let bl=null;ye.addEventListener("click",r=>{let p=r.target.closest("button[data-approval-action]");if(!p)return;r.preventDefault(),r.stopPropagation();let f=p.closest(".persona-approval-bubble");if(!f)return;let h=f.getAttribute("data-message-id");if(!h)return;let v=p.getAttribute("data-approval-action");if(!v)return;let B=v==="approve"?"approved":"denied",U=A.getMessages().find(Q=>Q.id===h);if(!U?.approval)return;let z=f.querySelector("[data-approval-buttons]");z&&z.querySelectorAll("button").forEach(re=>{re.disabled=!0,re.style.opacity="0.5",re.style.cursor="not-allowed"}),U.approval.toolType==="webmcp"?A.resolveWebMcpApproval(h,B):A.resolveApproval(U.approval,B)});let Ve=null,cm=!1,Qi=null,Gr=()=>{},Yi="none",vl=null,qn={artifacts:[],selectedId:null},No=!1,io=!1,Xi=!1,Vs=!1,dm=()=>Vs||qn.artifacts.some(r=>Br(o.features?.artifacts,r)==="panel"),Cl=()=>qn.artifacts.length>0&&!No&&dm(),it={current:null},lp=(r,a)=>{let p=A.getArtifactById(a),f=p?.markdown,h=p?.title||"artifact",v=p?.file,B=p?.artifactType??"markdown";if(!f){let z=r.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(z){let re=A.getMessages().find(ue=>ue.id===z);if(re?.rawContent)try{let ue=JSON.parse(re.rawContent);f=ue?.props?.markdown,h=ue?.props?.title||h,ue?.props?.file&&typeof ue.props.file=="object"&&(v=ue.props.file),!p&&typeof ue?.props?.artifactType=="string"&&(B=ue.props.artifactType)}catch{}}}return{markdown:f,title:h,file:v,artifactType:B}};ye.addEventListener("click",r=>{let p=r.target.closest("[data-download-artifact]");if(!p)return;r.preventDefault(),r.stopPropagation();let f=p.getAttribute("data-download-artifact");if(!f||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:f})===!0)return;let{markdown:v,title:B,file:q}=lp(p,f);if(!v)return;let U=ar();U&&U.triggerArtifactDownload(U.downloadInfoFor({title:B,markdown:v,file:q}))}),ye.addEventListener("click",r=>{let p=r.target.closest("[data-artifact-custom-action]");if(!p)return;r.preventDefault(),r.stopPropagation();let f=p.getAttribute("data-artifact-custom-action");if(!f)return;let h=p.closest("[data-artifact-inline]"),v=h?null:p.closest("[data-open-artifact]"),B=h?h.getAttribute("data-artifact-inline"):v?.getAttribute("data-open-artifact")??null,U=(h?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(nt=>nt.id===f);if(!U)return;let{markdown:z,title:Q,file:re,artifactType:ue}=lp(p,B??""),Ne={artifactId:B,title:Q,artifactType:ue,markdown:z,file:re};try{Promise.resolve(U.onClick(Ne)).catch(()=>{})}catch{}}),ye.addEventListener("click",r=>{let p=r.target.closest("[data-copy-artifact]");if(!p)return;r.preventDefault(),r.stopPropagation();let f=p.getAttribute("data-copy-artifact");if(!f)return;let h=A.getArtifactById(f),v=ar();if(!v)return;let B="";if(h)B=v.artifactCopyText(h);else{let{markdown:q,file:U,artifactType:z}=lp(p,f);z==="markdown"&&(B=v.artifactCopyText({id:f,artifactType:"markdown",status:"complete",markdown:q??"",...U?{file:U}:{}}))}B&&navigator.clipboard.writeText(B).then(()=>{let q=$t(qw,16,"currentColor",2);q&&(p.replaceChildren(q),setTimeout(()=>{let U=$t(zw,16,"currentColor",2);U&&p.replaceChildren(U)},1500))}).catch(()=>{})}),ye.addEventListener("click",r=>{let p=r.target.closest("[data-expand-artifact-inline]");if(!p)return;r.preventDefault(),r.stopPropagation();let f=p.getAttribute("data-expand-artifact-inline");!f||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:f})===!0||(No=!1,Vs=!0,io=!0,Xi=!0,A.selectArtifact(f),ao())}),ye.addEventListener("click",r=>{let a=r.target;if(a.closest("[data-download-artifact]")||a.closest("[data-artifact-custom-action]"))return;let p=a.closest("[data-open-artifact]");if(!p)return;let f=p.getAttribute("data-open-artifact");!f||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:f})===!0||(r.preventDefault(),r.stopPropagation(),No=!1,Vs=!0,A.selectArtifact(f),ao())}),ye.addEventListener("keydown",r=>{if(r.key!=="Enter"&&r.key!==" ")return;let a=r.target;!a.hasAttribute("data-open-artifact")&&!a.hasAttribute("data-expand-artifact-inline")||(r.preventDefault(),a.click())});let qs=De.composerOverlay,zs=(r,a,p)=>{let f=a.trim();if(!f||!it.current)return;let h=r.getAttribute("data-tool-call-id")??"",v=p.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:h,answer:f,answers:p.structured,values:p.values??(p.source==="multi"?f.split(", "):[f]),isFreeText:v,source:p.source},bubbles:!0,composed:!0})),Ti(qs,h);let B=it.current.getMessages().find(q=>q.toolCall?.id===h);B?.agentMetadata?.awaitingLocalTool?it.current.resolveAskUserQuestion(B,p.structured??f):it.current.sendMessage(f)},Qr=r=>{let a=it.current;if(!a)return;let p=r.getAttribute("data-tool-call-id")??"",f=a.getMessages().find(h=>h.toolCall?.id===p);f&&a.persistAskUserQuestionProgress(f,{answers:zc(r,f),currentIndex:no(r)})},pm=r=>Object.entries(r).map(([a,p])=>`${a}: ${Array.isArray(p)?p.join(", "):p}`).join(" | "),cp=r=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let a=no(r),p=Mi(r);if(a>=p-1)return;let f=it.current?.getMessages().find(h=>h.toolCall?.id===r.getAttribute("data-tool-call-id"));f&&(Kc(r,f,o,a+1),Qr(r))};qs.addEventListener("click",r=>{let p=r.target.closest("[data-ask-user-action]");if(!p)return;let f=p.closest("[data-persona-ask-sheet-for]");if(!f)return;let h=p.getAttribute("data-ask-user-action");if(r.preventDefault(),r.stopPropagation(),h==="dismiss"){let v=f.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:v},bubbles:!0,composed:!0})),Ti(qs,v);let B=it.current?.getMessages().find(q=>q.toolCall?.id===v);B?.agentMetadata?.awaitingLocalTool&&(it.current?.markAskUserQuestionResolved(B),it.current?.resolveAskUserQuestion(B,"(dismissed)"));return}if(h==="pick"){let v=p.getAttribute("data-option-label");if(!v)return;let B=f.getAttribute("data-multi-select")==="true",q=Dr(f);if(q&&B){let U=Ls(f)[no(f)],z=new Set(Array.isArray(U)?U:[]);z.has(v)?z.delete(v):z.add(v),_r(f,Array.from(z)),Qr(f);return}if(q){_r(f,v),Qr(f),cp(f);return}if(B){let U=p.getAttribute("aria-pressed")==="true";p.setAttribute("aria-pressed",U?"false":"true"),p.classList.toggle("persona-ask-pill-selected",!U);let z=f.querySelector('[data-ask-user-action="submit-multi"]');z&&(z.disabled=ng(f).length===0);return}zs(f,v,{source:"pick",values:[v]});return}if(h==="submit-multi"){let v=ng(f);if(v.length===0)return;zs(f,v.join(", "),{source:"multi",values:v});return}if(h==="open-free-text"){let v=f.querySelector('[data-ask-free-text-row="true"]');v&&(v.classList.remove("persona-hidden"),v.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(h==="focus-free-text"){f.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(h==="submit-free-text"){let B=f.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!B.trim())return;if(Dr(f)){_r(f,B.trim()),Qr(f),cp(f);return}zs(f,B,{source:"free-text"});return}if(h==="next"||h==="back"){if(!it.current)return;let v=f.getAttribute("data-tool-call-id")??"",B=it.current.getMessages().find(re=>re.toolCall?.id===v);if(!B)return;let U=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(U){let re=Ls(f)[no(f)];(typeof re!="string"||re!==U)&&_r(f,U)}let z=h==="next"?1:-1,Q=no(f)+z;Kc(f,B,o,Q),Qr(f);return}if(h==="submit-all"){if(!it.current)return;let v=f.getAttribute("data-tool-call-id")??"",B=it.current.getMessages().find(re=>re.toolCall?.id===v);if(!B)return;let U=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";U&&_r(f,U);let z=zc(f,B);it.current.persistAskUserQuestionProgress(B,{answers:z,currentIndex:no(f)});let Q=pm(z);zs(f,Q||"(submitted)",{source:"submit-all",structured:z});return}if(h==="skip"){if(!it.current)return;let v=f.getAttribute("data-tool-call-id")??"",B=it.current.getMessages().find(ue=>ue.toolCall?.id===v);if(!B)return;let q=Dr(f),U=no(f),z=Mi(f),Q=U>=z-1;if(!q){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:v},bubbles:!0,composed:!0})),Ti(qs,v),B.agentMetadata?.awaitingLocalTool&&(it.current.markAskUserQuestionResolved(B),it.current.resolveAskUserQuestion(B,"(dismissed)"));return}_r(f,"");let re=f.querySelector('[data-ask-free-text-input="true"]');if(re&&(re.value=""),Q){let ue=zc(f,B),Ne=pm(ue);zs(f,Ne||"(skipped)",{source:"submit-all",structured:ue});return}Kc(f,B,o,U+1),Qr(f);return}}),qs.addEventListener("keydown",r=>{if(r.key!=="Enter")return;let p=r.target;if(!p.matches?.('[data-ask-free-text-input="true"]'))return;let f=p.closest("[data-persona-ask-sheet-for]");if(!f)return;r.preventDefault();let h=p.value;if(h.trim()){if(Dr(f)){_r(f,h.trim()),Qr(f),cp(f);return}zs(f,h,{source:"free-text"})}});let um=r=>{if(!/^[1-9]$/.test(r.key)||r.metaKey||r.ctrlKey||r.altKey)return;let a=r.target;if(a?.tagName==="INPUT"||a?.tagName==="TEXTAREA"||a?.isContentEditable)return;let p=qs.querySelector("[data-persona-ask-sheet-for]");if(!p||p.getAttribute("data-ask-layout")!=="rows"||p.getAttribute("data-multi-select")==="true")return;let f=Number(r.key),v=p.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[f-1];v&&(r.preventDefault(),v.click())};document.addEventListener("keydown",um);let Co=null,Ct=null,Ji=null,wl=null,xl=()=>{},gm=!1,Sl="",Al="";function dp(){wl?.(),wl=null}let kx=()=>{let r=si&&ms?.isConnected?ms:null,a=r?r.getBoundingClientRect().width:0;return a<=0?200:a+360},fm=()=>{if(!Co||!Ct)return;let r=t.classList.contains("persona-artifact-welded-split"),a=t.ownerDocument.defaultView??window,p=a.innerWidth<=640;if(!r||t.classList.contains("persona-artifact-narrow-host")||p){Ct.style.removeProperty("position"),Ct.style.removeProperty("left"),Ct.style.removeProperty("top"),Ct.style.removeProperty("bottom"),Ct.style.removeProperty("width"),Ct.style.removeProperty("z-index");return}let f=Co.firstElementChild;if(!f||f===Ct)return;let h=10;Ct.style.position="absolute",Ct.style.top="0",Ct.style.bottom="0",Ct.style.width=`${h}px`,Ct.style.zIndex="5";let v=vf(Co,a),B=f.offsetWidth+v/2-h/2;Ct.style.left=`${Math.max(0,B)}px`},Ml=()=>{},mm=()=>{let r=t.ownerDocument.defaultView??window,a=o.launcher?.mobileFullscreen??!0,p=o.launcher?.mobileBreakpoint??640;return!a||r.innerWidth>p?!1:W||xt(o)},Tl=()=>!yn(o)||!Cl()||t.classList.contains("persona-artifact-narrow-host")||mm()||(t.ownerDocument.defaultView??window).innerWidth<nP?"none":hf(o)?"detached":"welded",ao=()=>{if(!Ve||!yn(o))return;il(t,o),al(t,o),Ml();let r=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,a=we.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",a>0&&a<=r);let p=Cl();Ve.setVisible(p),Ve.update(qn),No?(Ve.setMobileOpen(!1),Ve.element.classList.add("persona-hidden"),Ve.backdrop?.classList.add("persona-hidden"),io=!1,Xi=!1):qn.artifacts.length>0&&dm()?(Ve.element.classList.remove("persona-hidden"),Ve.setMobileOpen(!0)):(Ve.setMobileOpen(!1),Ve.element.classList.add("persona-hidden"),Ve.backdrop?.classList.add("persona-hidden"),io=!1,Xi=!1);let f=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ve.setExpandToggleVisible(f),Ve.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ve.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),Ve.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ve.setTabFade(o.features?.artifacts?.layout?.tabFade),Ve.setRenderTabBar(o.features?.artifacts?.renderTabBar),!f&&!Xi&&(io=!1),io!==gm){let v=Ve.element;io?(Sl=v.style.width,Al=v.style.maxWidth,v.style.removeProperty("width"),v.style.removeProperty("max-width")):(Sl&&(v.style.width=Sl),Al&&(v.style.maxWidth=Al),Sl="",Al=""),gm=io}t.classList.toggle("persona-artifact-expanded",io),Ve.setExpanded(io);let h=Tl();h!==Yi&&(Yi=h,Gr()),xl()};if(yn(o)){we.style.position="relative";let r=P("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),a=P("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");r.appendChild(ce),Co=a,a.appendChild(r),we.appendChild(a);let p=h=>{cm||Ve||(Ve=h.createArtifactPane(o,{onSelect:v=>it.current?.selectArtifact(v),onDismiss:()=>{No=!0,ao()},onToggleExpand:()=>{let v=!io,B=qn.selectedId??qn.artifacts[qn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:B,expanded:v})!==!0&&(io=v,v||(Xi=!1),ao())}}),Ve.element.classList.add("persona-hidden"),a.appendChild(Ve.element),Ve.backdrop&&we.appendChild(Ve.backdrop),xl(),ao())},f=ar();f?p(f):(ff(()=>{let h=ar();h&&p(h)}),Bd().catch(()=>{})),xl=()=>{if(!Co||!Ve)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Ji?.(),Ji=null,dp(),Ct&&(Ct.remove(),Ct=null),Ve.element.style.removeProperty("width"),Ve.element.style.removeProperty("maxWidth");return}if(!Ct){let v=P("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");v.setAttribute("role","separator"),v.setAttribute("aria-orientation","vertical"),v.setAttribute("aria-label","Resize artifacts panel"),v.tabIndex=0;let B=t.ownerDocument,q=B.defaultView??window,U=z=>{if(!Ve||z.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||q.innerWidth<=640)return;z.preventDefault(),dp();let Q=z.clientX,re=Ve.element.getBoundingClientRect().width,ue=o.features?.artifacts?.layout,Ne=Ze=>{let Tn=Co.getBoundingClientRect().width,bt=t.classList.contains("persona-artifact-welded-split"),At=vf(Co,q),un=bt?0:v.getBoundingClientRect().width||6,Lt=re-(Ze.clientX-Q),at=xw(Lt,Tn,At,un,ue?.resizableMinWidth,ue?.resizableMaxWidth,kx());Ve.element.style.width=`${at}px`,Ve.element.style.maxWidth="none",fm()},nt=()=>{B.removeEventListener("pointermove",Ne),B.removeEventListener("pointerup",nt),B.removeEventListener("pointercancel",nt),wl=null;try{v.releasePointerCapture(z.pointerId)}catch{}};wl=nt,B.addEventListener("pointermove",Ne),B.addEventListener("pointerup",nt),B.addEventListener("pointercancel",nt);try{v.setPointerCapture(z.pointerId)}catch{}};v.addEventListener("pointerdown",U),Ct=v,Co.insertBefore(v,Ve.element),Ji=()=>{v.removeEventListener("pointerdown",U)}}if(Ct){let v=Cl();Ct.classList.toggle("persona-hidden",!v),fm()}},Ml=()=>{if(!W||!Ve||(o.launcher?.sidebarMode??!1)||xt(o)&&oo(o).reveal==="emerge")return;let v=t.ownerDocument.defaultView??window,B=o.launcher?.mobileFullscreen??!0,q=o.launcher?.mobileBreakpoint??640;if(B&&v.innerWidth<=q||!hw(o,W))return;let U=Ws(o).width,z=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Cl()?(we.style.width=z,we.style.maxWidth=z):(we.style.width=U,we.style.maxWidth=U)},typeof ResizeObserver<"u"&&(Qi=new ResizeObserver(()=>{ao()}),Qi.observe(we))}else we.appendChild(ce);Be()&&Qt&&(De.peekBanner&&Qt.appendChild(De.peekBanner),Qt.appendChild(ke)),t.appendChild(je),Qt&&t.appendChild(Qt);let pp=()=>{let r=mm()||Be()&&o.launcher?.composerBar?.expandedSize==="fullscreen"||o.launcher?.fullHeight===!0&&!o.launcher?.sidebarMode&&!xt(o);if(ye.style.gap=r?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",ye.style.setProperty("--persona-transcript-gap",ye.style.gap),Be()){we.style.width="100%",we.style.maxWidth="100%";let Ee=o.launcher?.composerBar??{},_e=je.dataset.state==="expanded",Re=Ee.expandedSize??"anchored";if(!(_e&&Re!=="fullscreen")){ce.style.background="",ce.style.border="",ce.style.borderRadius="",ce.style.overflow="",ce.style.boxShadow="";return}let Ut=o.theme?.components?.panel,En=ir(o),Jo=(Zo,xs)=>Zo==null||Zo===""?xs:on(En,Zo)??Zo,Iu="1px solid var(--persona-border)",ws="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Hu="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ce.style.background="var(--persona-surface, #ffffff)",ce.style.border=Jo(Ut?.border,Iu),ce.style.borderRadius=Jo(Ut?.borderRadius,Hu),ce.style.boxShadow=Jo(Ut?.shadow,ws),ce.style.overflow="hidden";return}let a=xt(o),p=o.launcher?.sidebarMode??!1,f=a||p||(o.launcher?.fullHeight??!1),h=o.launcher?.enabled===!1,v=o.launcher?.detachedPanel===!0,B=o.theme?.components?.panel,q=o.darkTheme?.components?.panel,U=Ga(o)==="dark"?fo(B??{},q??{}):B,z=ir(o),Q=(Ee,_e)=>Ee==null||Ee===""?_e:on(z,Ee)??Ee,re=t.ownerDocument.defaultView??window,ue=o.launcher?.mobileFullscreen??!0,Ne=o.launcher?.mobileBreakpoint??640,nt=re.innerWidth<=Ne,Ze=ue&&nt&&W,Tn=a&&ue&&nt,bt=o.launcher?.position??"bottom-left",At=bt==="bottom-left"||bt==="top-left",un=o.launcher?.zIndex??ln,Lt=(Ee,_e,Re)=>`var(--persona-components-panel-modes-${Ee}-${_e}, ${Re})`,at=U?.modes?.floating,Eo=Q(at?.border??U?.border,Lt("floating","border","var(--persona-panel-border, 1px solid var(--persona-border))")),Po=Q(at?.shadow??U?.shadow,Lt("floating","shadow","var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))")),Jn=Q(at?.borderRadius??U?.borderRadius,Lt("floating","borderRadius","var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))")),Zn=v&&!Ze&&!Tn,Lr=Ze||Tn?"mobile":Zn?"floating":a?"docked":p?"sidebar":h?"inline":"floating",ko=U?.modes?.[Lr];Zn?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let po=Zn?Eo:p||Ze?"none":Eo,Ir=Zn?Po:Ze?"none":p?At?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":h?"none":Po;a&&!Ze&&!Zn&&(Ir="none",po="none");let Aa=Zn?Jn:p||Ze?"0":Jn,Cs=Q(ko?.border??U?.border,Lt(Lr,"border",po)),R=Q(ko?.shadow??U?.shadow,Lt(Lr,"shadow",Ir)),Le=Q(ko?.borderRadius??U?.borderRadius,Lt(Lr,"borderRadius",Aa)),Ie=Tl(),te=Ie==="detached",lt=Ie==="welded";t.classList.toggle("persona-artifact-detached-split",te),t.classList.toggle("persona-artifact-welded-split",lt);let _t="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",ft=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&yn(o)&&hf(o)&&h&&!a;t.classList.toggle("persona-artifact-chat-flush",ft);let It=te||ft?"none":R,zt=te?Eo:lt?"none":Cs,Te=te?Jn:Le;ft&&(zt="none",Te="0");let mt=ko?.borderRadius!=null&&ko.borderRadius!==""||U?.borderRadius!=null&&U.borderRadius!=="",He=ft&&!mt?"0":Le,jt=ee.scrollTop;t.style.cssText="",je.style.cssText="",we.style.cssText="",ce.style.cssText="",ee.style.cssText="",$s||(ke.style.cssText=""),ro&&(ee.style.display="none"),(f||h)&&(t.style.minWidth="0");let eo=()=>{if(jt<=0)return;(ee.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ee.scrollTop===jt)return;let _e=ee.scrollHeight-ee.clientHeight;_e<=0||(ee.scrollTop=Math.min(jt,_e))})};if(Ze){je.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"),je.style.cssText=`
30
+ `,J.addEventListener("click",()=>{y=V,L.forEach((_,Q)=>{let G=Q<V;_.classList.toggle("selected",G),_.setAttribute("aria-checked",Q===V-1?"true":"false")})}),L.push(J),I.appendChild(J)}h.appendChild(I);let k=null;if(u){let V=document.createElement("div");V.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=i,k.rows=3,k.setAttribute("aria-label","Additional comments"),V.appendChild(k),h.appendChild(V)}let R=document.createElement("div");R.className="persona-feedback-actions";let B=document.createElement("button");B.type="button",B.className="persona-feedback-btn persona-feedback-btn-skip",B.textContent=c,B.addEventListener("click",()=>{n?.(),g.remove()});let O=document.createElement("button");return O.type="button",O.className="persona-feedback-btn persona-feedback-btn-submit",O.textContent=l,O.addEventListener("click",async()=>{if(y===null){I.classList.add("persona-feedback-shake"),setTimeout(()=>I.classList.remove("persona-feedback-shake"),500);return}O.disabled=!0,O.textContent="Submitting...";try{let V=k?.value.trim()||void 0;await e(y,V),g.remove()}catch(V){O.disabled=!1,O.textContent=l,console.error("[CSAT Feedback] Failed to submit:",V)}}),R.appendChild(B),R.appendChild(O),h.appendChild(R),g.appendChild(h),g}function mb(t){let{onSubmit:e,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:i="What could we do better? (optional)...",submitText:l="Submit",skipText:c="Skip",showComment:u=!0,lowLabel:p="Not likely",highLabel:g="Very likely"}=t,y=document.createElement("div");y.className="persona-feedback-container persona-feedback-nps",y.setAttribute("role","dialog"),y.setAttribute("aria-label","Net Promoter Score feedback");let h=null,C=document.createElement("div");C.className="persona-feedback-content";let E=document.createElement("div");E.className="persona-feedback-header";let A=document.createElement("h3");A.className="persona-feedback-title",A.textContent=o,E.appendChild(A);let I=document.createElement("p");I.className="persona-feedback-subtitle",I.textContent=s,E.appendChild(I),C.appendChild(E);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 k=document.createElement("div");k.className="persona-feedback-labels";let R=document.createElement("span");R.className="persona-feedback-label-low",R.textContent=p;let B=document.createElement("span");B.className="persona-feedback-label-high",B.textContent=g,k.appendChild(R),k.appendChild(B);let O=document.createElement("div");O.className="persona-feedback-numbers";let V=[];for(let w=0;w<=10;w++){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 ${w} out of 10`),v.textContent=String(w),v.dataset.rating=String(w),w<=6?v.classList.add("persona-feedback-detractor"):w<=8?v.classList.add("persona-feedback-passive"):v.classList.add("persona-feedback-promoter"),v.addEventListener("click",()=>{h=w,V.forEach((T,x)=>{T.classList.toggle("selected",x===w),T.setAttribute("aria-checked",x===w?"true":"false")})}),V.push(v),O.appendChild(v)}L.appendChild(k),L.appendChild(O),C.appendChild(L);let J=null;if(u){let w=document.createElement("div");w.className="persona-feedback-comment-container",J=document.createElement("textarea"),J.className="persona-feedback-comment",J.placeholder=i,J.rows=3,J.setAttribute("aria-label","Additional comments"),w.appendChild(J),C.appendChild(w)}let _=document.createElement("div");_.className="persona-feedback-actions";let Q=document.createElement("button");Q.type="button",Q.className="persona-feedback-btn persona-feedback-btn-skip",Q.textContent=c,Q.addEventListener("click",()=>{n?.(),y.remove()});let G=document.createElement("button");return G.type="button",G.className="persona-feedback-btn persona-feedback-btn-submit",G.textContent=l,G.addEventListener("click",async()=>{if(h===null){O.classList.add("persona-feedback-shake"),setTimeout(()=>O.classList.remove("persona-feedback-shake"),500);return}G.disabled=!0,G.textContent="Submitting...";try{let w=J?.value.trim()||void 0;await e(h,w),y.remove()}catch(w){G.disabled=!1,G.textContent=l,console.error("[NPS Feedback] Failed to submit:",w)}}),_.appendChild(Q),_.appendChild(G),C.appendChild(_),y.appendChild(C),y}var Es="persona-chat-history",Yx=30*1e3,Qx=641,Ts="data-persona-composer-reason",Xx={"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 Jx(t){if(!t)return[];let e=[],n=Array.from(t.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let s=o.getAsFile();if(!s)continue;if(s.name){e.push(s);continue}let i=Xx[s.type]??"png";e.push(new File([s],`clipboard-image-${Date.now()}.${i}`,{type:s.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let o of Array.from(t.files??[]))o.type.startsWith("image/")&&e.push(o);return e}function Kl(t){if(!t)return!1;let e=t.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function Zx(t){return t?t===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:t.storage??"session",keyPrefix:t.keyPrefix??"persona-",persist:{openState:t.persist?.openState??!0,voiceState:t.persist?.voiceState??!0,focusInput:t.persist?.focusInput??!0},clearOnChatClear:t.clearOnChatClear??!0}:null}function eA(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var jp=t=>!t||typeof t!="object"?{}:{...t},bb=t=>t.map(e=>({...e,streaming:!1})),vb=(t,e,n)=>{let o=t?.markdown?_m(t.markdown):null,s=Fm(t?.sanitize);t?.postprocessMessage&&s&&t?.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.");let i=!1,l=c=>{let u=c.text??"",p=c.message.rawContent??null;if(e){let h=e.process({text:u,raw:p??u,message:c.message,streaming:c.streaming});h!==null&&(u=h.text,h.persist||(c.message.__skipPersist=!0),h.resubmit&&!c.streaming&&n&&n())}let g=is()!==null,y;if(t?.postprocessMessage){let h=t.postprocessMessage({...c,text:u,raw:p??c.text??""});y=s?s(h):h}else if(o){let h=c.streaming?Uf(u):u,C=o(h);y=s&&g?s(C):C}else y=ja(u);return y};return c=>{try{return l(c)}catch(u){return i||(i=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",u)),ja(c.text??"")}}};function Cb(t){let e=P("div","persona-attachment-drop-overlay");t?.background&&e.style.setProperty("--persona-drop-overlay-bg",t.background),t?.backdropBlur!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",t.backdropBlur),t?.border&&e.style.setProperty("--persona-drop-overlay-border",t.border),t?.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",t.borderRadius),t?.inset&&e.style.setProperty("--persona-drop-overlay-inset",t.inset),t?.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",t.labelSize),t?.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",t.labelColor);let n=t?.iconName??"upload",o=t?.iconSize??"48px",s=t?.iconColor??"rgba(59, 130, 246, 0.6)",i=t?.iconStrokeWidth??.5,l=se(n,o,s,i);if(l&&e.appendChild(l),t?.label){let c=P("span","persona-drop-overlay-label");c.textContent=t.label,e.appendChild(c)}return e}var tA=(t,e)=>{let n={...t};for(let[o,s]of Object.entries(e)){let i=n[o];n[o]=i?{...i,...s}:s}return n},nA=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:tA(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),wb=(t,e,n)=>{if(t==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');t.id&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.hasAttribute("data-persona-root")||t.setAttribute("data-persona-root","true");let o=Ua(e),s=new Set,i=new Set,l=Of((r,a)=>{It.delete(r);let d=Array.from(ce.querySelectorAll("[data-message-id]")).find(m=>m.dataset.messageId===r);d&&(a==="tool"?Lp(r,d,s,o):Ep(r,d,i))}),c=new Map,u=()=>{af({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};u();let p=o.features;o=_p(o);let g=Vp.getForInstance(o.plugins),y=Mf(t),h=[],C=!1,E=Wy(()=>o),A=null,I=null,L=null,k=!1,R=null,B=r=>{A=r,r.initApprovalUi({webMcpToolTitle:Ka});let a=r.createBuiltInApprovalPlugin(c);I=a.plugin,L=a.teardown},O=()=>{if(A)return A;let r=Ny();return r?(B(r),r):(Fy().then(a=>{k||A||(B(a),R?.())}).catch(()=>{}),null)},V=!1,J=!1,_=null,Q=(r,a,d,m)=>{if(!r.querySelector("[data-tv-form]"))return;let f=Jy();if(f){f.enhanceWithForms(r,a,d,m);return}Xy().then(()=>{V||J||!_||(J=!0,_())}).catch(()=>{})};o.components&&go.registerAll(o.components);let G=nb(),v=o.persistState===!1?null:o.storageAdapter??rb(),T=!!o.clientToken&&typeof o.reconnectStream!="function",x={},z=null,W,ee=new Promise(r=>{W=r}),ne=()=>{},he=new Promise(r=>{ne=r}),ve,Xe=!1,Je=r=>{if(o.onStateLoaded)try{let a=o.onStateLoaded(r);if(a&&typeof a=="object"&&"state"in a){let{state:d,open:m}=a;return m&&(Xe=!0),d}return a}catch(a){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",a)}return r};if(v?.load)try{let r=v.load();if(r&&typeof r.then=="function")z=r.then(a=>Je(a??{messages:[],metadata:{}}));else{let d=Je(r??{messages:[],metadata:{}});d.metadata&&(x=jp(d.metadata)),d.messages?.length&&(o={...o,initialMessages:d.messages}),d.artifacts?.length&&(o={...o,initialArtifacts:d.artifacts,initialSelectedArtifactId:d.selectedArtifactId??null}),ve=d.draft}}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",r)}else if(o.onStateLoaded)try{let r=Je({messages:[],metadata:{}});r.messages?.length&&(o={...o,initialMessages:r.messages})}catch(r){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",r)}z||W();let Wt=()=>x,$e=r=>{x=r({...x})??{},Ur()},Ce=o.actionParsers&&o.actionParsers.length?o.actionParsers:[zp],H=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Fi.message,Fi.messageAndClick],Me=Up({parsers:Ce,handlers:H,getSessionMetadata:Wt,updateSessionMetadata:$e,emit:G.emit,documentRef:typeof document<"u"?document:null});Me.syncFromMetadata();let de=o.launcher?.enabled??!0,In=o.launcher?.autoExpand??!1,Ps=o.autoFocusInput??!1,Zp=In,eu=de,tu=o.layout?.header?.layout,Yl=!1,Ae=()=>Ii(o),Ve=()=>de||Ae(),Se=Ae()?!1:de?In:!0,Ls=!1,Hr=null,nu=()=>{Ls=!0,Hr&&clearTimeout(Hr),Hr=setTimeout(()=>{Ls&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Ls=!1)},1e4)},Xt=vb(o,Me,nu),Is=o.features?.showReasoning??!0,Hs=o.features?.showToolCalls??!0,Jt=o.features?.showEventStreamToggle??!1,Vi=o.features?.scrollToBottom??{},vo=o.features?.scrollBehavior??{},$i=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",Rb=`${$i()}event-stream`,Rr=null,ou=o.features?.eventStream?.maxEvents??2e3,Lt=null,wn=null,Yn=null,ru=!1,Ot=null,Sn=!1,Co=null,Ql=0,su=(r,a)=>{Lt?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:r,timestamp:Date.now(),payload:JSON.stringify(a)})},Xl=(r,a)=>{wn?.processEvent(r,a),Lt?su(r,a):Yn&&(Yn.length>=ou&&Yn.shift(),Yn.push({type:r,payload:a}))},zi=()=>{Lt||!Jt||(Yn??=[],Hp().then(r=>{if(ru||Lt||!Jt)return;Rr=new r.EventStreamStore(Rb),Lt=new r.EventStreamBuffer(ou,Rr),wn=wn??new r.ThroughputTracker,Rr.open().then(()=>Lt?.restore()).catch(d=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",d)});let a=Yn??[];Yn=null;for(let d of a)wn?.processEvent(d.type,d.payload),su(d.type,d.payload)}).catch(()=>{}))};Jt&&zi();let Rs=!1,Ui=null,qi=()=>{},ji=()=>{},iu=()=>{},au=()=>{},Ki=()=>{},Wb=()=>Sn||Rs&&Ui==="panel",Wr={onCopy:r=>{G.emit("message:copy",r),S?.isClientTokenMode()&&S.submitMessageFeedback(r.id,"copy").catch(a=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",a)}),o.messageActions?.onCopy?.(r)},onFeedback:r=>{G.emit("message:feedback",r),S?.isClientTokenMode()&&S.submitMessageFeedback(r.messageId,r.type).catch(a=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",a)}),o.messageActions?.onFeedback?.(r)}},AA=o.statusIndicator??{},Jl=(r,a=o.statusIndicator??{})=>r==="idle"?a.idleText??gt.idle:r==="connecting"?a.connectingText??gt.connecting:r==="connected"?a.connectedText??gt.connected:r==="error"?a.errorText??gt.error:r==="paused"?a.pausedText??gt.paused:r==="resuming"?a.resumingText??gt.resuming:gt[r];function Ws(r,a,d,m){if(!Ae()&&(d.mode==="transient"||r.classList.contains("persona-mb-2"))&&(vd(r,Ut,d),ui(r,d,m)),!r.hasAttribute(Ts))if(m==="idle"&&d.idleLink){r.textContent="";let f=document.createElement("a");f.href=d.idleLink,f.target="_blank",f.rel="noopener noreferrer",f.textContent=a,f.style.color="inherit",f.style.textDecoration="none",r.appendChild(f)}else r.textContent=a}let Zt=Ry({config:o,showClose:Ve()}),{wrapper:Pe,panel:le,pillRoot:St}=Zt.shell,Re=Zt.panelElements,{container:re,body:j,messagesWrapper:ce,starterSuggestions:Zl,transcriptSuggestions:Bs,suggestions:wo,textarea:Z,sendButton:pe,composerForm:Ut,statusText:We,welcomeHost:xt,welcomeIconHolder:Bb,greetingHost:en,introKicker:Db,introTitle:Ob,introSubtitle:_b,closeButton:xe,iconHolder:at,headerTitle:So,headerSubtitle:Yo,header:Ke,footer:Le,actionsRow:Fb}=Re,ec=Re.leftActions,Gi=Re.rightActions,Hn=Re.sendButtonWrapper,lu=Re.setSendButtonMode,te=Re.micButton,tn=Re.micButtonWrapper,st=Re.attachmentButton,qt=Re.attachmentButtonWrapper,et=Re.attachmentInput,jt=Re.attachmentPreviewsContainer;re.classList.add("persona-relative"),j.classList.add("persona-relative");let Nb=12,Ds=()=>Vi.label??"",Vb=()=>Vi.iconName??"arrow-down",$b=()=>Vi.enabled!==!1,nn=()=>vo.mode??"anchor-top",xo=()=>nn()==="follow"||nn()==="anchor-top"&&Ys,Os=()=>vo.anchorTopOffset??16,zb=()=>vo.restorePosition??"bottom",cu=()=>vo.pauseOnInteraction===!0,du=()=>vo.showActivityWhilePinned!==!1,pu=()=>vo.announce===!0,tc=()=>vo.scrollbar??"on-scroll",ft=P("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");ft.type="button",ft.style.display="none",ft.setAttribute("data-persona-scroll-to-bottom","true");let _s=P("span","persona-flex persona-items-center"),nc=P("span",""),Qo=P("span","");Qo.setAttribute("data-persona-scroll-to-bottom-count",""),Qo.style.display="none",ft.append(_s,nc,Qo),re.appendChild(ft);let cn=P("div","persona-stream-anchor-spacer");cn.setAttribute("aria-hidden","true"),cn.setAttribute("data-persona-anchor-spacer",""),cn.style.flexShrink="0",cn.style.pointerEvents="none",cn.style.height="0px",cn.style.display="none",j.appendChild(cn);let Qn=P("div","persona-sr-only");Qn.setAttribute("aria-live","polite"),Qn.setAttribute("aria-atomic","true"),Qn.setAttribute("role","status"),Qn.setAttribute("data-persona-live-region",""),Object.assign(Qn.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),re.appendChild(Qn);let Fs=null,Yi=null,Ns=r=>{!pu()||!r||(Yi=r,Fs===null&&(Fs=setTimeout(()=>{Fs=null,Yi&&pu()&&(Qn.textContent=Yi),Yi=null},400)))},Vs=()=>{let r=t.ownerDocument.defaultView??window;return(o.launcher?.mobileFullscreen??!0)&&r.innerWidth<=(o.launcher?.mobileBreakpoint??640)&&(de||rt(o))||o.launcher?.fullHeight===!0&&!o.launcher.sidebarMode&&!rt(o)},Xo=()=>Vl(o,Vs()),Qi="empty",Xi=0,oc=()=>Xi||parseFloat(t.style.getPropertyValue("--persona-composer-lift"))||0,Jo=()=>{let a=Le.style.display==="none"?0:Le.offsetHeight;ft.style.bottom=`${a+oc()+Nb}px`};Jo();let rc=()=>{Fr||(Le.style.marginBottom=Xi>0?`${Xi}px`:"")},Ji=()=>{let r=sp(o,Ae()),a=Xo();t.setAttribute("data-persona-welcome-fullscreen",String(Vs())),t.setAttribute("data-persona-welcome-layout",a.layout??"top"),t.setAttribute("data-persona-welcome-layout-explicit",o.welcome?.layout??""),t.setAttribute("data-persona-welcome-anchor",a.anchor??"bottom");let m=Le.style.display==="none"?0:Le.offsetHeight,f=a.anchor==="center"&&Qi==="empty"?ki(a.anchorComposerTop)??ki("44%"):null,b=f!==null&&a.layout==="centered"&&o.welcome?.anchor===void 0&&o.welcome?.anchorComposerTop===void 0,D=b?getComputedStyle(j):null,$=parseFloat(t.style.getPropertyValue("--persona-composer-overlay-height"))||0,F=parseFloat(t.style.getPropertyValue("--persona-composer-lift"))||0,q=Math.max(0,(parseFloat(D?.paddingBottom??"")||0)-(r==="overlay"?$+F:0)),K=b?j.getBoundingClientRect().top-re.getBoundingClientRect().top:0,X=!b||xt.hidden?0:(xt.querySelector("[data-persona-welcome-plugin]")??xt).offsetHeight,ae=f===null||Ae()?0:b?Math.max(0,Math.round((re.clientHeight-K-X-q-m)/2)):Jh({columnHeight:re.clientHeight,footerHeight:m,fraction:f});t.style.setProperty("--persona-composer-overlay-height",`${m}px`),t.style.setProperty("--persona-composer-lift",`${r==="overlay"?ae:0}px`),Xi=r==="block"?ae:0,rc(),Jo()},uu=()=>{let r=!!Ds();ft.setAttribute("aria-label",Ds()||"Jump to latest"),ft.title=Ds(),ft.setAttribute("data-persona-scroll-to-bottom-has-label",r?"true":"false"),_s.innerHTML="";let a=se(Vb(),"14px","currentColor",2);a?(_s.appendChild(a),_s.style.display=""):_s.style.display="none",nc.textContent=Ds(),nc.style.display=r?"":"none"};uu();let _e=null,lt=null,ie=gh(),Ub=r=>{try{re.dispatchEvent(new CustomEvent("persona:composer:state",{detail:r,bubbles:!0,composed:!0}))}catch{}};ie.subscribe(Ub);let Rn=()=>{ie.setText(Z?.value??"")},Zo=()=>{ie.setMentionRefs(lt?.getMentionRefs()??[])},qb=r=>({id:r.id,name:r.file.name,mimeType:r.file.type,size:r.file.size,status:r.status,progress:r.progress,error:r.error}),gu=r=>{let a=Object.freeze(r.map(qb));ie.setAttachments(a);try{o.attachments?.onChange?.(a)}catch(d){console.error("[AgentWidget] attachments.onChange failed:",d)}Dc()};ie.setSelectedModelId(o.composer?.selectedModelId);let $s=()=>o.composer?.modes??[],Br=()=>Ph($s(),o.composer?.modeGroups);{let r=Ml(o.composer?.defaultActiveModeIds??[],$s());r.length&&ie.setActiveModeIds(r)}function mu(r){if(ie.getState().selectedModelId!==r){ie.setSelectedModelId(r),Ao?.repaint();try{o.composer?.onModelChange?.(r)}catch(a){console.error("[AgentWidget] composer.onModelChange failed:",a)}}}function Zi(r){ie.setActiveModeIds(r),Xn?.render(r,Br()),Dr.forEach(a=>a.repaint()),xn?.resolve(),Ea(),An()}function sc(r){Zi(Lh(ie.getState().activeModeIds,r,$s(),o.composer?.modeGroups))}let Ao=null,ic=null,Xn=null,Dr=new Map,Mo=null;function Wn(r){ie.setQuote(r),Mo?.render(ie.getState().quote),An(),sg()}let fu=!1;function ac(){let r=o.composer?.streamingSubmitBehavior??"block";return r!=="interrupt"?r:o.clientToken?"interrupt":(!fu&&o.debug===!0&&(fu=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let Eo=null;function Or(r){ie.setPendingSubmission(r),Eo?.render(ie.getState().pendingSubmission),An()}let jb=r=>{let a=Dr.get(r);if(a)return a;let d=Rh({groupId:r,getGroup:()=>o.composer?.modeGroups?.find(m=>m.id===r),getModes:()=>$s().filter(m=>m.groupId===r),getActiveIds:()=>ie.getState().activeModeIds,onSelect:m=>sc(m)});return Dr.set(r,d),d},Kb=()=>{let r=[],a=ie.getState().activeModeIds,d=new Set;if($s().forEach((m,f)=>{if(Al(m.groupId,o.composer?.modeGroups)){let b=m.groupId;if(d.has(b))return;d.add(b);let D=jb(b);D.action.order=Jd(f),D.action.label=o.composer?.modeGroups?.find($=>$.id===b)?.label??b,r.push(D.action);return}r.push({id:Th(m.id),kind:"button",placement:"start",order:Jd(f),presentation:m.presentation??"auto",label:m.label,shortLabel:m.shortLabel,iconName:m.iconName,pressed:a.includes(m.id),onSelect:()=>sc(m.id)})}),o.composer?.models?.length&&!g.some(m=>m.renderComposer)){let m=o.composer?.modelPicker?.presentation??"native";(!Ao||ic!==m)&&(ic=m,Ao=Mh({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>ie.getState().selectedModelId,onSelect:f=>mu(f),presentation:m,getSuffix:()=>o.composer?.modelPicker?.suffix})),r.push(Ao.action)}return r},lc=null,hu=g.find(r=>r.renderHeader);if(hu?.renderHeader){let r=hu.renderHeader({config:o,defaultRenderer:()=>{let a=kr({config:o,showClose:Ve()});return Ri(re,a,o),a.header},onClose:()=>Ge(!1,"user")});if(r){let a=Ke;a&&(a.replaceWith(r),Ke=r,Zt.header.element=r)}}let yu=()=>{Ot&&(j.style.display="none",Le.parentNode?.insertBefore(Ot.element,Le),Ot.update())},cc=()=>{if(!Lt){zi();return}if(Sn=!0,Ot?yu():Hp().then(a=>{Ot||!Sn||!Lt||(Ot=a.createEventStreamView({buffer:Lt,getFullHistory:()=>Lt.getAllFromStore(),onClose:()=>_r(),config:o,plugins:g,getThroughput:()=>wn?.getMetric()??{status:"idle"},renderIconByName:se}),yu())}).catch(()=>{_r()}),Ne){Ne.style.boxShadow=`inset 0 0 0 1.5px ${Vt.actionIconColor}`;let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(d=>d&&Ne.classList.add(d))}let r=()=>{if(!Sn)return;let a=Date.now();a-Ql>=200&&(Ot?.update(),Ql=a),Co=requestAnimationFrame(r)};Ql=0,Co=requestAnimationFrame(r),Ht(),G.emit("eventStream:opened",{timestamp:Date.now()})},_r=()=>{if(Sn){if(Sn=!1,Ot&&Ot.element.remove(),j.style.display="",Ne){Ne.style.boxShadow="";let r=o.features?.eventStream?.classNames?.toggleButtonActive;r&&r.split(/\s+/).forEach(a=>a&&Ne.classList.remove(a))}Co!==null&&(cancelAnimationFrame(Co),Co=null),Ht(),G.emit("eventStream:closed",{timestamp:Date.now()})}},Ne=null;if(Jt){let r=o.features?.eventStream?.classNames,a="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"+(r?.toggleButton?" "+r.toggleButton:"");Ne=P("button",a),Ne.style.width="28px",Ne.style.height="28px",Ne.style.color=Vt.actionIconColor,Ne.type="button",Ne.setAttribute("aria-label","Event Stream"),Ne.title="Event Stream";let d=yt(fb,"18px","currentColor",1.5);d&&Ne.appendChild(d);let m=Re.clearChatButtonWrapper,f=Re.closeButtonWrapper,b=m||f;b&&b.parentNode===Ke?Ke.insertBefore(Ne,b):Ke.appendChild(Ne),Ne.addEventListener("click",()=>{Sn?_r():cc()})}let bu=r=>{let a=o.attachments;if(!a?.enabled)return;let d=r.querySelector("[data-persona-composer-attachment-previews]")??r.querySelector(".persona-attachment-previews");if(!d){d=P("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),d.setAttribute("data-persona-composer-attachment-previews",""),d.style.display="none";let f=r.querySelector("[data-persona-composer-form]");f?.parentNode?f.parentNode.insertBefore(d,f):r.insertBefore(d,r.firstChild)}if(!(r.querySelector("[data-persona-composer-attachment-input]")??r.querySelector('input[type="file"]'))){let f=P("input");f.type="file",f.setAttribute("data-persona-composer-attachment-input",""),f.accept=(a.allowedTypes??us).join(","),f.multiple=(a.maxFiles??4)>1,f.style.display="none",f.setAttribute("aria-label",a.buttonTooltipText??"Attach files"),r.appendChild(f)}},Fr=!1,vu=r=>{let a=g.find(f=>f.renderComposer);if(!a?.renderComposer)return null;let d=o.composer,m=C?S.isStreaming():!1;return a.renderComposer({config:o,defaultRenderer:r,requestRender:()=>fm(),storage:E(a.id),onSubmit:f=>{!S||S.isStreaming()||Wa(f.trim(),{consumeDraft:!1})},streaming:m,disabled:m,openAttachmentPicker:()=>{_n()||et?.click()},models:d?.models,selectedModelId:ie.getState().selectedModelId??d?.selectedModelId,onModelChange:f=>mu(f),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{lc?.()}:void 0})},Cu=vu(()=>Wi({config:o}).footer);Cu&&(Zt.replaceComposer(Cu),Le=Zt.composer.footer,Fr=!0);let Be=null,Gb=r=>{Ut=r.form,Z=r.input,Hn=r.sendButton?r.sendButton.parentElement:null,r.sendButton&&(pe=r.sendButton),r.micButton&&(te=r.micButton,tn=r.micButton.parentElement),r.found.status&&(We=r.found.status),r.found.suggestions&&(wo=r.found.suggestions),r.attachmentButton&&(st=r.attachmentButton,qt=r.attachmentButton.parentElement),et=r.attachmentInput??null,jt=r.attachmentPreviews??null,r.found.actionsRow&&(Fb=r.found.actionsRow),ec=r.found.actionsStart,Gi=r.found.actionsEnd};function dc(){let r=Z;if(!r)return;let a=o.composer?.inputAttributes,d=!a?.ariaLabel&&!(r instanceof HTMLTextAreaElement)?r.getAttribute("aria-label"):null;mf(r,a),d&&r.setAttribute("aria-label",d),gf(r,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:kd(r)}),pf(r,df(o.composer?.maxLines,Ae()?5:3))}let wu=r=>{Be=fh(r,{debug:o.debug===!0}),Be&&Gb(Be),dc()};bu(Le),wu(Le),Rn();let zs=Ko(o,Ae());zs&&(ce.style.maxWidth=zs,ce.style.marginLeft="auto",ce.style.marginRight="auto",ce.style.width="100%",en.style.maxWidth=zs,en.style.marginLeft="auto",en.style.marginRight="auto",en.style.width="100%",Zl.style.maxWidth=zs,Bs.style.maxWidth=zs,Bs.style.marginLeft="auto",Bs.style.marginRight="auto",Bs.style.width="100%");let Su=()=>{let r=Ko(o,Ae());if(!(!r||Ae()))for(let a of[Ut,wo,jt,We])a&&(a.style.maxWidth=r,a.style.marginLeft="auto",a.style.marginRight="auto",a.style.width="100%")};Su();let xu=()=>{!o.attachments?.enabled||!et||!jt||(_e?_e.remountPreviews(jt):(_e=xi.fromConfig(o.attachments,gu),_e.setPreviewsContainer(jt)),Be?.addListener(et,"change",r=>{let a=r.target;_e?.handleFileSelect(a.files),a.value=""}),re.querySelector(".persona-attachment-drop-overlay")||re.appendChild(Cb(o.attachments.dropOverlay)))};xu();let Yb=()=>lt?.prefetch(),pc=()=>{if(!o.contextMentions?.enabled||!Z)return;let r=Fd();if(!r){let m=Z;vl().then(()=>{lt||Z!==m||!m.isConnected||(pc(),xn?.resolve())},()=>{});return}let a=Be?.header??null,d=a?Ld(a):void 0;if(lt=r.createContextMentionOrchestrator({deps:{loadContextMentions:wf,loadContextMentionsInline:Sf,renderLucideIcon:se,createMentionButton:yf},config:o,textarea:Z,anchor:Ut??Z,getMessages:()=>S.getMessages(),liveRegionHost:re,chipRow:d}),lt&&!d){let m=Z;m.parentElement?.insertBefore(lt.contextRow,m)}};pc();let xn=null,Qb={getState:()=>ie.getState(),getValue:()=>Z?.value??"",setValue:r=>{Z&&(Z.value=r,Z.dispatchEvent(new Event("input",{bubbles:!0})),Rn())},submit:()=>{Cf(Be?.form??null)},openAttachmentPicker:()=>{_n()||et?.click()},toggleVoice:()=>{lc?.()},requestRender:()=>xn?.resolve()},Xb=()=>{let r=[];return(lt?.affordanceButtons??[]).forEach((d,m)=>{r.push({id:`core:mention-${m}`,placement:"start",order:Kn.mention+m,element:d,managed:!0})}),qt&&r.push({id:"core:attachment",placement:"start",order:Kn.attachment,element:qt}),tn&&r.push({id:"core:mic",placement:"end",order:Kn.mic,element:tn}),Hn&&r.push({id:"core:send",placement:"end",order:Kn.send,element:Hn}),r},Au=()=>{xn?.destroy(),xn=Sh({getBindings:()=>Be,collect:()=>({builtIns:Xb(),configActions:[...Kb(),...o.composer?.actions??[]],plugins:g,contributionContext:{config:o,getState:()=>ie.getState(),requestRender:()=>xn?.resolve()},debug:o.debug===!0}),actionContext:Qb,getState:()=>ie.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(r,a)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${a.actionId}" failed:`,r)}}),xn.resolve()};Au();let uc=()=>{if(Xn?.destroy(),Xn=null,!Br().length)return;let r=Be?.header;r&&(Xn=Eh({row:Ld(r),onRemove:a=>sc(a),initialIds:ie.getState().activeModeIds}),Xn.render(ie.getState().activeModeIds,Br()))};uc();let Mu=()=>{Mo?.destroy(),Mo=null,Eo?.destroy(),Eo=null;let r=Be?.header;r&&(Mo=Wh({onDismiss:()=>Wn(void 0)}),r.appendChild(Mo.element),Mo.render(ie.getState().quote),ac()==="defer-one"&&(Eo=Bh({onEdit:()=>Kv(),onRemove:()=>Or(void 0)}),r.appendChild(Eo.element),Eo.render(ie.getState().pendingSubmission)))};Mu();let gc=Vh(),Jb=()=>{let r=Be?.header?.querySelector(bf);if(r)return r.childElementCount>0;let a=ie.getState();return a.mentionRefs.length>0||Ml(a.activeModeIds,Br()).length>0};function An(){let r=ie.getState(),a=gc.observe($h(Z),r.text);Le.toggleAttribute("data-persona-composer-compact",Nh({text:r.text,wrapped:a,hasAttachments:r.attachments.length>0,hasChips:Jb(),hasQuote:r.quote!==void 0,hasPendingSubmission:r.pendingSubmission!==void 0}))}function Eu(){o.composer?.layout==="single-row"&&!Ae()?Le.setAttribute("data-persona-composer-layout","single-row"):Le.removeAttribute("data-persona-composer-layout")}Eu(),ie.subscribe(()=>{xn?.sync(),Dc(),xa(),An(),sg()}),xa();let Tu=!1,Zb=r=>{if(Tu||o.debug!==!0)return;let a=["messages","composer"].filter(d=>r[d]);a.length&&(Tu=!0,console.warn(`[persona] layout.slots.${a.join(" and layout.slots.")} ${a.length>1?"are":"is"} deprecated and unsupported: the renderer never runs. Use the message render hooks for the transcript and the renderComposer plugin hook for the composer.`))};(()=>{let r=o.layout?.slots??{};Zb(r);let a=m=>{switch(m){case"body-top":return j.querySelector("[data-persona-intro-card]");case"messages":return ce;case"footer-top":return wo;case"composer":return Ut;case"footer-bottom":return We;default:return null}},d=(m,f)=>{switch(m){case"header-left":case"header-center":case"header-right":if(m==="header-left")Ke.insertBefore(f,Ke.firstChild);else if(m==="header-right")Ke.appendChild(f);else{let b=Ke.querySelector(".persona-flex-col");b?b.parentNode?.insertBefore(f,b.nextSibling):Ke.appendChild(f)}break;case"body-top":{let b=j.querySelector("[data-persona-intro-card]");b?b.replaceWith(f):j.insertBefore(f,j.firstChild);break}case"body-bottom":j.appendChild(f);break;case"footer-top":wo.replaceWith(f);break;case"footer-bottom":We.replaceWith(f);break;default:break}};for(let[m,f]of Object.entries(r))if(f)try{let b=f({config:o,defaultContent:()=>a(m)});b&&d(m,b)}catch(b){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${m}":`,b)}})(),ce.addEventListener("click",r=>{let a=r.target;if(!(a instanceof Element))return;let d=a.closest("button[data-persona-copy-tool-detail]");d&&(r.preventDefault(),r.stopPropagation(),Oy(d))});let mc=r=>{let d=r.target.closest('button[data-expand-header="true"]');if(!d)return;let m=d.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!m)return;let f=m.getAttribute("data-message-id");if(!f)return;Io(),Kr();let b=d.getAttribute("data-bubble-type");if(m.classList.contains("persona-activity-row")){l.manual(f);let D=m.parentElement?.closest("[data-persona-tool-group]");D?.dataset.messageId&&l.manual(D.dataset.messageId)}if(b==="reasoning")i.has(f)?i.delete(f):i.add(f),Ep(f,m,i);else if(b==="tool")s.has(f)?s.delete(f):s.add(f),Lp(f,m,s,o);else if(b==="approval"&&A){let $=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",F=c.get(f)??$;c.set(f,!F),A.updateApprovalDetailsUI(f,m,o,c)}It.delete(f)};ce.addEventListener("pointerdown",r=>{r.target.closest('button[data-expand-header="true"]')&&(r.preventDefault(),mc(r))}),ce.addEventListener("click",r=>{r.detail===0&&r.target.closest(".persona-activity-row")&&mc(r)}),ce.addEventListener("keydown",r=>{let a=r.target;(r.key==="Enter"||r.key===" ")&&a.closest('button[data-expand-header="true"]')&&(r.preventDefault(),mc(r))}),ce.addEventListener("copy",r=>{let{clipboardData:a}=r;if(!a)return;let d=ce.getRootNode(),m=typeof d.getSelection=="function"?d.getSelection():window.getSelection();if(!m||m.isCollapsed)return;let f=m.toString(),b=Zh(f);!b||b===f||(a.setData("text/plain",b),r.preventDefault())});let fc=new Map,ku=null,Pu="idle",ev={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},tv=(r,a)=>{let{icon:d,label:m}=ev[a];r.setAttribute("aria-label",m),r.title=m,r.setAttribute("aria-pressed",a==="idle"?"false":"true"),r.classList.toggle("persona-message-action-active",a!=="idle"),r.classList.toggle("persona-message-action-loading",a==="loading");let f=se(d,14,"currentColor",2);f&&(r.innerHTML="",r.appendChild(f))},Lu=()=>{ce.querySelectorAll('[data-action="read-aloud"]').forEach(a=>{let m=a.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;tv(a,m&&m===ku?Pu:"idle")})};ce.addEventListener("click",r=>{let d=r.target.closest(".persona-message-action-btn[data-action]");if(!d)return;r.preventDefault(),r.stopPropagation();let m=d.closest("[data-actions-for]");if(!m)return;let f=m.getAttribute("data-actions-for");if(!f)return;let b=d.getAttribute("data-action");if(b==="copy"){let $=S.getMessages().find(F=>F.id===f);if($&&Wr.onCopy){let F=$.content||"";navigator.clipboard.writeText(F).then(()=>{d.classList.add("persona-message-action-success");let q=yt(hb,14,"currentColor",2);q&&(d.innerHTML="",d.appendChild(q)),setTimeout(()=>{d.classList.remove("persona-message-action-success");let K=yt(yb,14,"currentColor",2);K&&(d.innerHTML="",d.appendChild(K))},2e3)}).catch(q=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",q)}),Wr.onCopy($)}}else if(b==="read-aloud")S.toggleReadAloud(f);else if(b==="upvote"||b==="downvote"){let $=(fc.get(f)??null)===b,F=b==="upvote"?"thumbs-up":"thumbs-down";if($){fc.delete(f),d.classList.remove("persona-message-action-active");let q=se(F,14,"currentColor",2);q&&(d.innerHTML="",d.appendChild(q))}else{let q=b==="upvote"?"downvote":"upvote",K=m.querySelector(`[data-action="${q}"]`);if(K){K.classList.remove("persona-message-action-active");let De=se(q==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);De&&(K.innerHTML="",K.appendChild(De))}fc.set(f,b),d.classList.add("persona-message-action-active");let X=se(F,14,"currentColor",2);X&&(X.setAttribute("fill","currentColor"),d.innerHTML="",d.appendChild(X)),d.classList.remove("persona-message-action-pop"),d.offsetWidth,d.classList.add("persona-message-action-pop");let He=S.getMessages().find(Fe=>Fe.id===f);He&&Wr.onFeedback&&Wr.onFeedback({type:b,messageId:He.id,message:He})}}else if(b==="regenerate")ea?.regenerate(f);else if(b==="edit")ea?.edit(f);else if(b==="quote")ea?.quote(f);else if(b?.startsWith(Ol)){let D=b.slice(Ol.length),$=o.messageActions?.custom?.find(q=>q.id===D),F=S.getMessages().find(q=>q.id===f);if(!$||!F)return;try{$.onSelect(F)}catch(q){console.error(`[AgentWidget] messageActions.custom "${D}" onSelect failed:`,q)}}});let ea=null;ce.addEventListener("click",r=>{let d=r.target.closest("button[data-approval-action]");if(!d)return;r.preventDefault(),r.stopPropagation();let m=d.closest(".persona-approval-bubble");if(!m)return;let f=m.getAttribute("data-message-id");if(!f)return;let b=d.getAttribute("data-approval-action");if(!b)return;let D=b==="approve"?"approved":"denied",F=S.getMessages().find(K=>K.id===f);if(!F?.approval)return;let q=m.querySelector("[data-approval-buttons]");q&&q.querySelectorAll("button").forEach(X=>{X.disabled=!0,X.style.opacity="0.5",X.style.cursor="not-allowed"}),F.approval.toolType==="webmcp"?S.resolveWebMcpApproval(f,D):S.resolveApproval(F.approval,D)});let Ee=null,Iu=!1,Us=null,er=()=>{},qs="none",ta=null,dn={artifacts:[],selectedId:null},Jn=!1,Mn=!1,js=!1,Nr=!1,Hu=()=>Nr||dn.artifacts.some(r=>as(o.features?.artifacts,r)==="panel"),na=()=>dn.artifacts.length>0&&!Jn&&Hu(),pn={current:null},hc=(r,a)=>{let d=S.getArtifactById(a),m=d?.markdown,f=d?.title||"artifact",b=d?.file,D=d?.artifactType??"markdown";if(!m){let q=r.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(q){let X=S.getMessages().find(ae=>ae.id===q);if(X?.rawContent)try{let ae=JSON.parse(X.rawContent);m=ae?.props?.markdown,f=ae?.props?.title||f,ae?.props?.file&&typeof ae.props.file=="object"&&(b=ae.props.file),!d&&typeof ae?.props?.artifactType=="string"&&(D=ae.props.artifactType)}catch{}}}return{markdown:m,title:f,file:b,artifactType:D}};ce.addEventListener("click",r=>{let d=r.target.closest("[data-download-artifact]");if(!d)return;r.preventDefault(),r.stopPropagation();let m=d.getAttribute("data-download-artifact");if(!m||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:m})===!0)return;let{markdown:b,title:D,file:$}=hc(d,m);if(!b)return;let F=yo();F&&F.triggerArtifactDownload(F.downloadInfoFor({title:D,markdown:b,file:$}))}),ce.addEventListener("click",r=>{let d=r.target.closest("[data-artifact-custom-action]");if(!d)return;r.preventDefault(),r.stopPropagation();let m=d.getAttribute("data-artifact-custom-action");if(!m)return;let f=d.closest("[data-artifact-inline]"),b=f?null:d.closest("[data-open-artifact]"),D=f?f.getAttribute("data-artifact-inline"):b?.getAttribute("data-open-artifact")??null,F=(f?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(Fe=>Fe.id===m);if(!F)return;let{markdown:q,title:K,file:X,artifactType:ae}=hc(d,D??""),He={artifactId:D,title:K,artifactType:ae,markdown:q,file:X};try{Promise.resolve(F.onClick(He)).catch(()=>{})}catch{}}),ce.addEventListener("click",r=>{let d=r.target.closest("[data-copy-artifact]");if(!d)return;r.preventDefault(),r.stopPropagation();let m=d.getAttribute("data-copy-artifact");if(!m)return;let f=S.getArtifactById(m),b=yo();if(!b)return;let D="";if(f)D=b.artifactCopyText(f);else{let{markdown:$,file:F,artifactType:q}=hc(d,m);q==="markdown"&&(D=b.artifactCopyText({id:m,artifactType:"markdown",status:"complete",markdown:$??"",...F?{file:F}:{}}))}D&&navigator.clipboard.writeText(D).then(()=>{let $=yt(hb,16,"currentColor",2);$&&(d.replaceChildren($),setTimeout(()=>{let F=yt(yb,16,"currentColor",2);F&&d.replaceChildren(F)},1500))}).catch(()=>{})}),ce.addEventListener("click",r=>{let d=r.target.closest("[data-expand-artifact-inline]");if(!d)return;r.preventDefault(),r.stopPropagation();let m=d.getAttribute("data-expand-artifact-inline");!m||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:m})===!0||(Jn=!1,Nr=!0,Mn=!0,js=!0,S.selectArtifact(m),En())}),ce.addEventListener("click",r=>{let a=r.target;if(a.closest("[data-download-artifact]")||a.closest("[data-artifact-custom-action]"))return;let d=a.closest("[data-open-artifact]");if(!d)return;let m=d.getAttribute("data-open-artifact");!m||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:m})===!0||(r.preventDefault(),r.stopPropagation(),Jn=!1,Nr=!0,S.selectArtifact(m),En())}),ce.addEventListener("keydown",r=>{if(r.key!=="Enter"&&r.key!==" ")return;let a=r.target;!a.hasAttribute("data-open-artifact")&&!a.hasAttribute("data-expand-artifact-inline")||(r.preventDefault(),a.click())});let Ks=Re.composerOverlay,yc=r=>{vl().catch(()=>{}),Zm(r,o,Ks)},Ru=null,nv={mount:t,overlay:Ks,sessionRef:pn,config:()=>o},oa=!1,Wu=r=>a=>{let d=a.target,m=d?.closest?.("[data-persona-ask-sheet-for]");if(!m||!(r==="click"?!!d?.closest("[data-ask-user-action]"):a.key==="Enter"&&!!d?.matches?.('[data-ask-free-text-input="true"]')))return;let b=$=>{Ru??=$.createAskUserSheetHandlers(nv),Ru[r](a)},D=Fd();if(D){b(D);return}oa||(oa=!0,vl().then($=>{oa=!1,m.isConnected&&b($)},()=>{oa=!1}))};Ks.addEventListener("click",Wu("click")),Ks.addEventListener("keydown",Wu("keydown"));let Bu=r=>{if(!/^[1-9]$/.test(r.key)||r.metaKey||r.ctrlKey||r.altKey)return;let a=r.target;if(a?.tagName==="INPUT"||a?.tagName==="TEXTAREA"||a?.isContentEditable)return;let d=Ks.querySelector("[data-persona-ask-sheet-for]");if(!d||d.getAttribute("data-ask-layout")!=="rows"||d.getAttribute("data-multi-select")==="true")return;let m=Number(r.key),b=d.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[m-1];b&&(r.preventDefault(),b.click())};document.addEventListener("keydown",Bu);let Zn=null,ot=null,Gs=null,ra=null,sa=()=>{},Du=!1,ia="",aa="";function bc(){ra?.(),ra=null}let ov=()=>{let r=tt?.railShell?tt.railHost:null,a=r?.isConnected?r:null,d=a?a.getBoundingClientRect().width:0;return d<=0?200:d+360},Ou=()=>{if(!Zn||!ot)return;let r=t.classList.contains("persona-artifact-welded-split"),a=t.ownerDocument.defaultView??window,d=a.innerWidth<=640;if(!r||t.classList.contains("persona-artifact-narrow-host")||d){ot.style.removeProperty("position"),ot.style.removeProperty("left"),ot.style.removeProperty("top"),ot.style.removeProperty("bottom"),ot.style.removeProperty("width"),ot.style.removeProperty("z-index");return}let m=Zn.firstElementChild;if(!m||m===ot)return;let f=10;ot.style.position="absolute",ot.style.top="0",ot.style.bottom="0",ot.style.width=`${f}px`,ot.style.zIndex="5";let b=Fp(Zn,a),D=m.offsetWidth+b/2-f/2;ot.style.left=`${Math.max(0,D)}px`},la=()=>{},_u=()=>{let r=t.ownerDocument.defaultView??window,a=o.launcher?.mobileFullscreen??!0,d=o.launcher?.mobileBreakpoint??640;return!a||r.innerWidth>d?!1:de||rt(o)},ca=()=>!zt(o)||!na()||t.classList.contains("persona-artifact-narrow-host")||_u()||(t.ownerDocument.defaultView??window).innerWidth<Qx?"none":Dp(o)?"detached":"welded",En=()=>{if(!Ee||!zt(o))return;Oi(t,o),_i(t,o),la();let r=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,a=le.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",a>0&&a<=r);let d=na();Ee.setVisible(d),Ee.update(dn),Jn?(Ee.setMobileOpen(!1),Ee.element.classList.add("persona-hidden"),Ee.backdrop?.classList.add("persona-hidden"),Mn=!1,js=!1):dn.artifacts.length>0&&Hu()?(Ee.element.classList.remove("persona-hidden"),Ee.setMobileOpen(!0)):(Ee.setMobileOpen(!1),Ee.element.classList.add("persona-hidden"),Ee.backdrop?.classList.add("persona-hidden"),Mn=!1,js=!1);let m=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ee.setExpandToggleVisible(m),Ee.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ee.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),Ee.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ee.setTabFade(o.features?.artifacts?.layout?.tabFade),Ee.setRenderTabBar(o.features?.artifacts?.renderTabBar),!m&&!js&&(Mn=!1),Mn!==Du){let b=Ee.element;Mn?(ia=b.style.width,aa=b.style.maxWidth,b.style.removeProperty("width"),b.style.removeProperty("max-width")):(ia&&(b.style.width=ia),aa&&(b.style.maxWidth=aa),ia="",aa=""),Du=Mn}t.classList.toggle("persona-artifact-expanded",Mn),Ee.setExpanded(Mn);let f=ca();f!==qs&&(qs=f,er()),sa()};if(zt(o)){le.style.position="relative";let r=P("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),a=P("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");r.appendChild(re),Zn=a,a.appendChild(r),le.appendChild(a);let d=f=>{Iu||Ee||(Ee=f.createArtifactPane(o,{onSelect:b=>pn.current?.selectArtifact(b),onDismiss:()=>{Jn=!0,En()},onToggleExpand:()=>{let b=!Mn,D=dn.selectedId??dn.artifacts[dn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:D,expanded:b})!==!0&&(Mn=b,b||(js=!1),En())}}),Ee.element.classList.add("persona-hidden"),a.appendChild(Ee.element),Ee.backdrop&&le.appendChild(Ee.backdrop),sa(),En())},m=yo();m?d(m):(Wp(()=>{let f=yo();f&&d(f)}),zl().catch(()=>{})),sa=()=>{if(!Zn||!Ee)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Gs?.(),Gs=null,bc(),ot&&(ot.remove(),ot=null),Ee.element.style.removeProperty("width"),Ee.element.style.removeProperty("maxWidth");return}if(!ot){let b=P("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");b.setAttribute("role","separator"),b.setAttribute("aria-orientation","vertical"),b.setAttribute("aria-label","Resize artifacts panel"),b.tabIndex=0;let D=t.ownerDocument,$=D.defaultView??window,F=q=>{if(!Ee||q.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||$.innerWidth<=640)return;q.preventDefault(),bc();let K=q.clientX,X=Ee.element.getBoundingClientRect().width,ae=o.features?.artifacts?.layout,He=De=>{let Gt=Zn.getBoundingClientRect().width,nt=t.classList.contains("persona-artifact-welded-split"),it=Fp(Zn,$),Ft=nt?0:b.getBoundingClientRect().width||6,pt=X-(De.clientX-K),ze=Qy(pt,Gt,it,Ft,ae?.resizableMinWidth,ae?.resizableMaxWidth,ov());Ee.element.style.width=`${ze}px`,Ee.element.style.maxWidth="none",Ou()},Fe=()=>{D.removeEventListener("pointermove",He),D.removeEventListener("pointerup",Fe),D.removeEventListener("pointercancel",Fe),ra=null;try{b.releasePointerCapture(q.pointerId)}catch{}};ra=Fe,D.addEventListener("pointermove",He),D.addEventListener("pointerup",Fe),D.addEventListener("pointercancel",Fe);try{b.setPointerCapture(q.pointerId)}catch{}};b.addEventListener("pointerdown",F),ot=b,Zn.insertBefore(b,Ee.element),Gs=()=>{b.removeEventListener("pointerdown",F)}}if(ot){let b=na();ot.classList.toggle("persona-hidden",!b),Ou()}},la=()=>{if(!de||!Ee||(o.launcher?.sidebarMode??!1)||rt(o)&&Cn(o).reveal==="emerge")return;let b=t.ownerDocument.defaultView??window,D=o.launcher?.mobileFullscreen??!0,$=o.launcher?.mobileBreakpoint??640;if(D&&b.innerWidth<=$||!Uy(o,de))return;let F=Pr(o).width,q=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";na()?(le.style.width=q,le.style.maxWidth=q):(le.style.width=F,le.style.maxWidth=F)},typeof ResizeObserver<"u"&&(Us=new ResizeObserver(()=>{En()}),Us.observe(le))}else le.appendChild(re);Ae()&&St&&(Re.peekBanner&&St.appendChild(Re.peekBanner),St.appendChild(Le)),t.appendChild(Pe),St&&t.appendChild(St);let vc=()=>{let r=_u()||Ae()&&o.launcher?.composerBar?.expandedSize==="fullscreen"||o.launcher?.fullHeight===!0&&!o.launcher?.sidebarMode&&!rt(o);if(ce.style.gap=r?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",ce.style.setProperty("--persona-transcript-gap",ce.style.gap),Ae()){le.style.width="100%",le.style.maxWidth="100%";let ge=o.launcher?.composerBar??{},we=Pe.dataset.state==="expanded",be=ge.expandedSize??"anchored";if(!(we&&be!=="fullscreen")){re.style.background="",re.style.border="",re.style.borderRadius="",re.style.overflow="",re.style.boxShadow="";return}let ht=o.theme?.components?.panel,Yt=ho(o),co=(po,wr)=>po==null||po===""?wr:Pt(Yt,po)??po,yd="1px solid var(--persona-border)",Cr="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",bd="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";re.style.background="var(--persona-surface, #ffffff)",re.style.border=co(ht?.border,yd),re.style.borderRadius=co(ht?.borderRadius,bd),re.style.boxShadow=co(ht?.shadow,Cr),re.style.overflow="hidden";return}let a=rt(o),d=o.launcher?.sidebarMode??!1,m=a||d||(o.launcher?.fullHeight??!1),f=o.launcher?.enabled===!1,b=o.launcher?.detachedPanel===!0,D=o.theme?.components?.panel,$=o.darkTheme?.components?.panel,F=Ei(o)==="dark"?Sr(D??{},$??{}):D,q=ho(o),K=(ge,we)=>ge==null||ge===""?we:Pt(q,ge)??ge,X=t.ownerDocument.defaultView??window,ae=o.launcher?.mobileFullscreen??!0,He=o.launcher?.mobileBreakpoint??640,Fe=X.innerWidth<=He,De=ae&&Fe&&de,Gt=a&&ae&&Fe,nt=o.launcher?.position??"bottom-left",it=nt==="bottom-left"||nt==="top-left",Ft=o.launcher?.zIndex??Dt,pt=(ge,we,be)=>`var(--persona-components-panel-modes-${ge}-${we}, ${be})`,ze=F?.modes?.floating,Vn=K(ze?.border??F?.border,pt("floating","border","var(--persona-panel-border, 1px solid var(--persona-border))")),$n=K(ze?.shadow??F?.shadow,pt("floating","shadow","var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))")),hn=K(ze?.borderRadius??F?.borderRadius,pt("floating","borderRadius","var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))")),yn=b&&!De&&!Gt,Fo=De||Gt?"mobile":yn?"floating":a?"docked":d?"sidebar":f?"inline":"floating",zn=F?.modes?.[Fo];yn?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let kn=yn?Vn:d||De?"none":Vn,No=yn?$n:De?"none":d?it?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":f?"none":$n;a&&!De&&!yn&&(No="none",kn="none");let pi=yn?hn:d||De?"0":hn,vr=K(zn?.border??F?.border,pt(Fo,"border",kn)),M=K(zn?.shadow??F?.shadow,pt(Fo,"shadow",No)),me=K(zn?.borderRadius??F?.borderRadius,pt(Fo,"borderRadius",pi)),fe=ca(),U=fe==="detached",Ue=fe==="welded";t.classList.toggle("persona-artifact-detached-split",U),t.classList.toggle("persona-artifact-welded-split",Ue);let mt="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",Ye=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&zt(o)&&Dp(o)&&f&&!a;t.classList.toggle("persona-artifact-chat-flush",Ye);let ut=U||Ye?"none":M,Ct=U?Vn:Ue?"none":vr,ue=U?hn:me;Ye&&(Ct="none",ue="0");let Qe=zn?.borderRadius!=null&&zn.borderRadius!==""||F?.borderRadius!=null&&F.borderRadius!=="",ye=Ye&&!Qe?"0":me,wt=j.scrollTop;t.style.cssText="",Pe.style.cssText="",le.style.cssText="",re.style.cssText="",j.style.cssText="",Fr||(Le.style.cssText=""),Sn&&(j.style.display="none"),(m||f)&&(t.style.minWidth="0");let bn=()=>{if(wt<=0)return;(j.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(j.scrollTop===wt)return;let we=j.scrollHeight-j.clientHeight;we<=0||(j.scrollTop=Math.min(wt,we))})};if(De){Pe.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"),Pe.style.cssText=`
36
31
  position: fixed !important;
37
32
  inset: 0 !important;
38
33
  width: 100% !important;
@@ -42,9 +37,9 @@ _Details: ${n.message}_`:o}var mg=t=>({isError:!0,content:[{type:"text",text:t}]
42
37
  padding: 0 !important;
43
38
  display: flex !important;
44
39
  flex-direction: column !important;
45
- z-index: ${un} !important;
40
+ z-index: ${Ft} !important;
46
41
  background-color: var(--persona-surface, #ffffff) !important;
47
- `,we.style.cssText=`
42
+ `,le.style.cssText=`
48
43
  position: relative !important;
49
44
  display: flex !important;
50
45
  flex-direction: column !important;
@@ -57,7 +52,7 @@ _Details: ${n.message}_`:o}var mg=t=>({isError:!0,content:[{type:"text",text:t}]
57
52
  padding: 0 !important;
58
53
  box-shadow: none !important;
59
54
  border-radius: 0 !important;
60
- `,ce.style.cssText=`
55
+ `,re.style.cssText=`
61
56
  display: flex !important;
62
57
  flex-direction: column !important;
63
58
  flex: 1 1 0% !important;
@@ -68,33 +63,33 @@ _Details: ${n.message}_`:o}var mg=t=>({isError:!0,content:[{type:"text",text:t}]
68
63
  overflow: hidden !important;
69
64
  border-radius: 0 !important;
70
65
  border: none !important;
71
- `,ee.style.flex="1 1 0%",ee.style.minHeight="0",ee.style.overflowY="auto",ke.style.flexShrink="0",Xd(),kn=!0,eo();return}let Jt=Ws(o);if(!p&&!a)h&&f?(we.style.width="100%",we.style.maxWidth="100%"):(we.style.width=Jt.width,we.style.maxWidth=Jt.maxWidth);else if(a)if(oo(o).reveal==="emerge"&&!v){let _e=oo(o).width;we.style.width=_e,we.style.maxWidth=_e}else we.style.width="100%",we.style.maxWidth="100%";if(Ml(),we.style.boxShadow=It,we.style.borderRadius=He,te?we.style.border="none":lt&&(we.style.border=Cs),ce.style.border=zt,ce.style.borderRadius=Te,ce.style.boxShadow=te&&!ft?_t:"",ft&&(ce.style.background="transparent",ee.style.background="transparent",ke.style.background="transparent",ke.style.borderTop="none"),lt){let Ee=o.features?.artifacts?.layout;vl=Ee?.unifiedSplitOuterRadius?.trim()||Ee?.paneBorderRadius?.trim()||Le}else vl=null;let ct=ko?.border!=null||U?.border!=null;if(a&&!Ze&&!Zn&&!te&&!lt&&!ct&&(ce.style.border="none",oo(o).side==="right"?ce.style.borderLeft="1px solid var(--persona-border)":ce.style.borderRight="1px solid var(--persona-border)"),a&&!Ze&&lt&&!ct&&(oo(o).side==="right"?we.style.borderLeft="1px solid var(--persona-border)":we.style.borderRight="1px solid var(--persona-border)"),f&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",h&&(t.style.width="100%"),je.style.display="flex",je.style.flexDirection="column",je.style.flex="1 1 0%",je.style.minHeight="0",je.style.maxHeight="100%",je.style.height="100%",h&&(je.style.overflow="hidden"),we.style.display="flex",we.style.flexDirection="column",we.style.flex="1 1 0%",we.style.minHeight="0",we.style.maxHeight="100%",we.style.height="100%",te||(we.style.overflow="hidden"),ce.style.display="flex",ce.style.flexDirection="column",ce.style.flex="1 1 0%",ce.style.minHeight="0",ce.style.maxHeight="100%",ce.style.overflow="hidden",ee.style.flex="1 1 0%",ee.style.minHeight="0",ee.style.overflowY="auto",ke.style.flexShrink="0"),h&&(Zn||te||ft)&&!a&&(ft||(je.style.padding="var(--persona-panel-inset)"),je.style.background="var(--persona-panel-canvas-bg)"),je.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&&!h&&!a&&($n[bt]??$n["bottom-right"]).split(" ").forEach(_e=>je.classList.add(_e)),p){let Ee=nr(o).sidebarWidth?o.launcher?.sidebarWidth??"420px":on(ir(o),"components.panel.width")??"420px";v?je.style.cssText=`
66
+ `,j.style.flex="1 1 0%",j.style.minHeight="0",j.style.overflowY="auto",Le.style.flexShrink="0",rc(),Yl=!0,bn();return}let Mt=Pr(o);if(!d&&!a)f&&m?(le.style.width="100%",le.style.maxWidth="100%"):(le.style.width=Mt.width,le.style.maxWidth=Mt.maxWidth);else if(a)if(Cn(o).reveal==="emerge"&&!b){let we=Cn(o).width;le.style.width=we,le.style.maxWidth=we}else le.style.width="100%",le.style.maxWidth="100%";if(la(),le.style.boxShadow=ut,le.style.borderRadius=ye,U?le.style.border="none":Ue&&(le.style.border=vr),re.style.border=Ct,re.style.borderRadius=ue,re.style.boxShadow=U&&!Ye?mt:"",Ye&&(re.style.background="transparent",j.style.background="transparent",Le.style.background="transparent",Le.style.borderTop="none"),Ue){let ge=o.features?.artifacts?.layout;ta=ge?.unifiedSplitOuterRadius?.trim()||ge?.paneBorderRadius?.trim()||me}else ta=null;let qe=zn?.border!=null||F?.border!=null;if(a&&!De&&!yn&&!U&&!Ue&&!qe&&(re.style.border="none",Cn(o).side==="right"?re.style.borderLeft="1px solid var(--persona-border)":re.style.borderRight="1px solid var(--persona-border)"),a&&!De&&Ue&&!qe&&(Cn(o).side==="right"?le.style.borderLeft="1px solid var(--persona-border)":le.style.borderRight="1px solid var(--persona-border)"),m&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",f&&(t.style.width="100%"),Pe.style.display="flex",Pe.style.flexDirection="column",Pe.style.flex="1 1 0%",Pe.style.minHeight="0",Pe.style.maxHeight="100%",Pe.style.height="100%",f&&(Pe.style.overflow="hidden"),le.style.display="flex",le.style.flexDirection="column",le.style.flex="1 1 0%",le.style.minHeight="0",le.style.maxHeight="100%",le.style.height="100%",U||(le.style.overflow="hidden"),re.style.display="flex",re.style.flexDirection="column",re.style.flex="1 1 0%",re.style.minHeight="0",re.style.maxHeight="100%",re.style.overflow="hidden",j.style.flex="1 1 0%",j.style.minHeight="0",j.style.overflowY="auto",Le.style.flexShrink="0"),f&&(yn||U||Ye)&&!a&&(Ye||(Pe.style.padding="var(--persona-panel-inset)"),Pe.style.background="var(--persona-panel-canvas-bg)"),Pe.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"),!d&&!f&&!a&&(ln[nt]??ln["bottom-right"]).split(" ").forEach(we=>Pe.classList.add(we)),d){let ge=xr(o).sidebarWidth?o.launcher?.sidebarWidth??"420px":Pt(ho(o),"components.panel.width")??"420px";b?Pe.style.cssText=`
72
67
  position: fixed !important;
73
68
  top: var(--persona-panel-inset) !important;
74
69
  bottom: var(--persona-panel-inset) !important;
75
- width: ${Ee} !important;
70
+ width: ${ge} !important;
76
71
  height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
77
72
  max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
78
73
  margin: 0 !important;
79
74
  padding: 0 !important;
80
75
  display: flex !important;
81
76
  flex-direction: column !important;
82
- z-index: ${un} !important;
83
- ${At?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
84
- `:je.style.cssText=`
77
+ z-index: ${Ft} !important;
78
+ ${it?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
79
+ `:Pe.style.cssText=`
85
80
  position: fixed !important;
86
81
  top: 0 !important;
87
82
  bottom: 0 !important;
88
- width: ${Ee} !important;
83
+ width: ${ge} !important;
89
84
  height: 100vh !important;
90
85
  max-height: 100vh !important;
91
86
  margin: 0 !important;
92
87
  padding: 0 !important;
93
88
  display: flex !important;
94
89
  flex-direction: column !important;
95
- z-index: ${un} !important;
96
- ${At?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
97
- `,we.style.cssText=`
90
+ z-index: ${Ft} !important;
91
+ ${it?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
92
+ `,le.style.cssText=`
98
93
  position: relative !important;
99
94
  display: flex !important;
100
95
  flex-direction: column !important;
@@ -105,10 +100,10 @@ _Details: ${n.message}_`:o}var mg=t=>({isError:!0,content:[{type:"text",text:t}]
105
100
  min-height: 0 !important;
106
101
  margin: 0 !important;
107
102
  padding: 0 !important;
108
- box-shadow: ${It} !important;
109
- border-radius: ${He} !important;
110
- ${te?"border: none !important;":lt?`border: ${Cs} !important;`:""}
111
- `,we.style.setProperty("width","100%","important"),we.style.setProperty("max-width","100%","important"),ce.style.cssText=`
103
+ box-shadow: ${ut} !important;
104
+ border-radius: ${ye} !important;
105
+ ${U?"border: none !important;":Ue?`border: ${vr} !important;`:""}
106
+ `,le.style.setProperty("width","100%","important"),le.style.setProperty("max-width","100%","important"),re.style.cssText=`
112
107
  display: flex !important;
113
108
  flex-direction: column !important;
114
109
  flex: 1 1 0% !important;
@@ -117,16 +112,16 @@ _Details: ${n.message}_`:o}var mg=t=>({isError:!0,content:[{type:"text",text:t}]
117
112
  min-height: 0 !important;
118
113
  max-height: 100% !important;
119
114
  overflow: hidden !important;
120
- border-radius: ${Te} !important;
121
- border: ${zt} !important;
122
- ${te&&!ft?`box-shadow: ${_t} !important;`:""}
123
- ${ft?"background: transparent !important;":""}
124
- `,$s||(ke.style.cssText=`
115
+ border-radius: ${ue} !important;
116
+ border: ${Ct} !important;
117
+ ${U&&!Ye?`box-shadow: ${mt} !important;`:""}
118
+ ${Ye?"background: transparent !important;":""}
119
+ `,Fr||(Le.style.cssText=`
125
120
  flex-shrink: 0 !important;
126
121
  border-top: none !important;
127
122
  padding: 8px 16px 12px 16px !important;
128
- ${ft?"background: transparent !important;":""}
129
- `)}if(!h&&!a){let Ee="max-height: -moz-available !important; max-height: stretch !important;",_e=p?"":"padding-top: 1.25em !important;",Re=p?"":`z-index: ${o.launcher?.zIndex??ln} !important;`;je.style.cssText+=Ee+_e+Re}Xd(),eo()},up=()=>{t.style.setProperty("--persona-content-max-width",Ur(o,Be()))},hm=!1;function ym(){o.layout?.topFade&&ee.scrollTop>1?ee.setAttribute("data-persona-top-fade","true"):ee.removeAttribute("data-persona-top-fade")}let gp=()=>{ym();let r=_g(o,Be());Be()&&o.composer?.placement&&o.debug===!0&&!hm&&(hm=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let a=zr();t.setAttribute("data-persona-composer-placement",r),t.setAttribute("data-persona-conversation-state",fl),t.setAttribute("data-persona-welcome-anchor",a.anchor??"bottom"),t.style.setProperty("--persona-composer-anchor-gap",a.composerGap??wd),hl()},bm=()=>{if(Be())return;let r=xt(o),a=o.launcher?.sidebarMode??!1;if(r||a||(o.launcher?.fullHeight??!1)||!W)return;let f=t.ownerDocument.defaultView??window,h=o.launcher?.mobileFullscreen??!0,v=o.launcher?.mobileBreakpoint??640;if(h&&f.innerWidth<=v)return;let B=Ws(o);we.style.height=B.height,we.style.maxHeight=B.maxHeight};pp(),Qa(t,o),il(t,o),al(t,o),up(),gp(),Gr=()=>{pp(),bm(),Qa(t,o),il(t,o),al(t,o),up(),gp(),vl?t.style.setProperty("--persona-artifact-welded-outer-radius",vl):t.style.removeProperty("--persona-artifact-welded-outer-radius"),Do(),Vd()};let fe=[];fe.push(()=>{cm=!0}),fe.push(()=>{y.forEach(r=>r()),m.destroy()}),fe.push(()=>{document.removeEventListener("keydown",um)}),fe.push(()=>{zi!==null&&clearTimeout(zi)});let wo=null,xo=null;fe.push(()=>{wo?.(),wo=null,xo?.(),xo=null}),Qi&&fe.push(()=>{Qi?.disconnect(),Qi=null}),fe.push(()=>{Ji?.(),Ji=null,dp(),Ct&&(Ct.remove(),Ct=null),Ve?.element.style.removeProperty("width"),Ve?.element.style.removeProperty("maxWidth"),Ve?.destroy()}),Y&&fe.push(()=>{cn=!0,Mt=null,dr!==null&&(cancelAnimationFrame(dr),dr=null),ut?.destroy(),ut=null,pt?.destroy(),pt=null,Xe=null});let Yr=null,vm=()=>{Yr&&(Yr(),Yr=null),o.colorScheme==="auto"&&(Yr=Cd(()=>{Qa(t,o)}))};vm(),fe.push(()=>{Yr&&(Yr(),Yr=null)}),fe.push(()=>{I=!0,H?.()}),fe.push(()=>{L=!0});let Cm=!1;fe.push(()=>{Cm=!0});let fp=(r,a)=>{let p=Ta(r,a);return p||!ib.includes(r)?p:(HC().then(f=>{if(Cm)return;Du(f.wipe),Du(f.glyphCycle);let h=Ta(r,a);h&&ka(h,t)}).catch(()=>{}),null)},El=o.features?.streamAnimation;if(El?.type&&El.type!=="none"){let r=fp(El.type,El.plugins);r&&ka(r,t),fe.push(()=>ab(t))}let Fo=tl(pr),wm=tl(jd),xm=tl(Ui),Xr=[Fo,wm,xm];fe.push(()=>{Xr.forEach(r=>r.destroy())});let Jr=null,A,Zr=null,Sm=!1,Am=0,Mm=null,Tm=r=>r.reduce((a,p)=>p.role==="user"?a+1:a,0),Em=r=>{for(let a=r.length-1;a>=0;a--)if(_a(r[a]))return r[a].id??null;return null},Pm=!1,Lx=()=>{Pm||o.debug!==!0||(Pm=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".'))},km=!1,Lm=!1,Im=(r,a)=>{km||o.debug!==!0||!a.enabled||a.expose||Sm||Lm&&(A.isStreaming()||r.some(_a)||(km=!0,console.info("[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.")))},es=r=>{if(!A)return;let a=r??A.getMessages(),p=re=>{re.render([],A,ae,a)},f=re=>{Xr.forEach(ue=>{ue!==re&&p(ue)})};Zr&&(Tm(a)>Am||Em(a)!==Mm)&&(Zr=null);let h=Nr(o);Im(a,h);let v=h.enabled?Qb(a):null,B=Zr??v,q=Zr?"host":"agent";if(B){let re=o.suggestions?.followUps,ue=re?.placement??(re?"auto":"composer"),nt=(ue==="auto"?Be()?"composer":"after-message":ue)==="after-message"?xm:Fo;f(nt),nt.render(B,A,ae,a,o.suggestionChipsConfig,{source:q,surface:"followUp",variant:re?.variant??"chip",behavior:re?.behavior??"send",overflow:re?.overflow??"wrap",maxItems:re?.maxItems??4,config:o,plugins:u,submitPrompt:fc});return}if(a.some(re=>re.role==="user")){Xr.forEach(p);return}let U=o.future?.v5Defaults===!0,z=ji(),Q=o.suggestions?.starters??(U?{}:void 0);if(Q){let re=Ri(zr(),a),ue=Q.placement??"auto",Ne=ue==="auto"?re?"welcome":"composer":ue;if(Ne==="welcome"&&!re){Lx(),Xr.forEach(p);return}let nt=Ne==="welcome"?wm:Fo;f(nt),nt.render(Q.items??o.suggestionChips,A,ae,a,o.suggestionChipsConfig,{surface:"starter",variant:Q.variant??(U&&!z?"chip":"card"),behavior:Q.behavior??"send",overflow:Q.overflow??"wrap",maxItems:Q.maxItems??(U&&!z?3:4),config:o,plugins:u,submitPrompt:fc});return}f(Fo),Fo.render(o.suggestionChips,A,ae,a,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:o,plugins:u,submitPrompt:fc})},Hm=()=>{Zr&&(Zr=null,es())},Ix=r=>{let a=Array.isArray(r)?[...r]:[];if(!a.length){Hm();return}let p=A?A.getMessages():[];Zr=a,Sm=!0,Am=Tm(p),Mm=Em(p),es(p)},Wn=!1,Dt=PC(),js=new Map,ts=new Map,yr=new Map,ns=null,br=null;function os(){if(!ns)return;let r=ns;ns=null,br?.destroy(),br=null,Dt.delete(r),ce.querySelector(`#wrapper-${r}`)?.removeAttribute("data-preserve-runtime"),A&&zn(ye,A.getMessages(),O)}let rs=0,Hx=hi()!==null,Bn=tb(),Dn=0,vr=null,xn=!1,Pl=!1,Cr=0,Vt=null,ss=null,mp=!1,Ks=!1,is=null,Zi=!0,kl=!1,Gs=null,Ll=!1,wr=()=>{Ll=!0,Dx()},hp=null,Rx=4,Uo=24,Wx=80,Bx=1e3,$o=null,Rm=()=>{t.setAttribute("data-persona-scrollbar",Gd()),Gd()!=="on-scroll"&&($o!==null&&clearTimeout($o),$o=null,ee.removeAttribute("data-persona-scrollbar-visible"))},Dx=()=>{Gd()==="on-scroll"&&(ee.setAttribute("data-persona-scrollbar-visible",""),$o!==null&&clearTimeout($o),$o=setTimeout(()=>{$o=null,As(ee,Uo)&&ee.removeAttribute("data-persona-scrollbar-visible")},Bx))};Rm(),fe.push(()=>{$o!==null&&clearTimeout($o)});let yp=new Map,Ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};so();let Wm=o.voiceRecognition?.autoResume??!1,Vo=r=>{ne.emit("voice:state",{active:Ke.active,source:r,timestamp:Date.now()})},lo=()=>{me(r=>({...r,voiceState:{active:Ke.active,timestamp:Date.now(),manuallyDeactivated:Ke.manuallyDeactivated}}))},_x=()=>{if(o.voiceRecognition?.enabled===!1)return;let r=kf(k.voiceState),a=!!r.active,p=Number(r.timestamp??0);Ke.manuallyDeactivated=!!r.manuallyDeactivated,a&&Date.now()-p<tP&&setTimeout(()=>{Ke.active||(Ke.manuallyDeactivated=!1,gn(o.voiceRecognition?.provider)?A.toggleVoice().then(()=>{Ke.active=A.isVoiceActive(),Vo("restore"),A.isVoiceActive()&&fi()}):yc("restore"))},1e3)},Ox=()=>A?jw(A.getMessages()).filter(r=>!r.__skipPersist):[],Il=null,Bm=(r,a)=>{typeof console<"u"&&console.error(r,a)},Hl=(r,a)=>{let p=()=>{try{let B=r();return!B||typeof B.then!="function"?null:Promise.resolve(B).catch(q=>{Bm(a,q)})}catch(B){return Bm(a,B),null}},f=Il,h=f?f.then(()=>p()??void 0):p();if(!h)return;let v=h.finally(()=>{Il===v&&(Il=null)});Il=v};function Qs(r){if(!T?.save)return;let a=r?jw(r):A?Ox():[],p=_&&A?.getResumableHandle();p&&(k={...k,durableResume:{executionId:p.executionId,after:p.lastEventId}});let f={messages:a,metadata:k,artifacts:qn.artifacts,selectedArtifactId:qn.selectedId,...as?{draft:as}:{}};Hl(()=>T.save(f),"[AgentWidget] Failed to persist state:")}let as,Rl=()=>!T?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,ea=sC({write:()=>{if(!Rl())return;let r=be.getState(),a=oC({text:r.text,mentionRefs:r.mentionRefs,contentSegments:mu(),selectedModelId:r.selectedModelId,activeModeIds:r.activeModeIds,quote:r.quote});JSON.stringify(a)!==JSON.stringify(as)&&(as=a,Qs())}});function Dm(){Rl()&&ea.schedule()}function bp(){ea.flush()}function _m(r){if(!Rl())return;let a=rC(r,{mentionSourceIds:(o.contextMentions?.sources??[]).map(p=>p.id),modelIds:(o.composer?.models??[]).map(p=>p.id),modes:o.composer?.modes??[]});a&&(as=r,ae&&!ae.value&&(ae.value=a.text,ae.dispatchEvent(new Event("input",{bubbles:!0})),yo()),a.selectedModelId&&(be.setSelectedModelId(a.selectedModelId),fr?.repaint()),yl(a.activeModeIds??[]),a.quote&&bo(a.quote),ea.cancel())}function Wl(){ea.cancel(),as&&(as=void 0,Rl()&&Qs())}let Ys=null,Om=()=>je.querySelector("#persona-scroll-container")||ee,Xs=()=>{Ys!==null&&(cancelAnimationFrame(Ys),Ys=null),xn=!1},Nm=()=>{vr!==null&&(cancelAnimationFrame(vr),vr=null),Pl=!1,Xs()},Nx=()=>Wn&&Cp()&&(Rn()!=="anchor-top"||Uf()),vp=()=>{let r=$i()||"Jump to latest",a=Nx();Nt.toggleAttribute("data-persona-scroll-to-bottom-streaming",a),Cr>0?(qr.textContent=String(Cr),qr.style.display="",Nt.setAttribute("aria-label",`${r} (${Cr} new)`)):(qr.textContent="",qr.style.display="none",Nt.setAttribute("aria-label",a?`${r} (response streaming below)`:r))},Fm=()=>{Cr!==0&&(Cr=0,vp())},Fx=()=>{let r=Vt?.spacerHeight??0;return r<=0?As(ee,Uo):Ol(r)-ee.scrollTop-ee.clientHeight<=Uo},Cp=()=>gr()?!Bn.isFollowing():!Fx(),wp=()=>!!A&&A.getMessages().length>0,qt=()=>{if(!mx()||ax()){Nt.parentNode&&Nt.remove(),Nt.style.display="none";return}Nt.parentNode!==ce&&ce.appendChild(Nt),jr();let a=er(ee)>0&&Cp()&&wp();a?vp():Fm(),Nt.style.display=a?"":"none"},Js=()=>{Bn.pause()&&(Nm(),qt())},Sn=()=>{Bn.resume(),Fm(),qt()},xr=(r=!1)=>{gr()&&wp()&&Bn.isFollowing()&&(!r&&!Wn||(vr!==null&&(cancelAnimationFrame(vr),vr=null),Pl=!0,vr=requestAnimationFrame(()=>{vr=null,Pl=!1,Bn.isFollowing()&&Ux(Om(),r?220:140)})))},Um=(r,a,p,f=()=>!0)=>{let h=r.scrollTop,v=a(),B=v-h;if(Xs(),Math.abs(B)<1){xn=!0,r.scrollTop=v,Dn=r.scrollTop,xn=!1;return}let q=performance.now();xn=!0;let U=Q=>1-Math.pow(1-Q,3),z=Q=>{if(!f()){Xs();return}let re=a();re!==v&&(v=re,B=v-h);let ue=Q-q,Ne=Math.min(ue/p,1),nt=U(Ne),Ze=h+B*nt;r.scrollTop=Ze,Dn=r.scrollTop,Ne<1?Ys=requestAnimationFrame(z):(r.scrollTop=v,Dn=r.scrollTop,Ys=null,xn=!1)};Ys=requestAnimationFrame(z)},Ux=(r,a=500)=>{let p=er(r)-r.scrollTop;if(Math.abs(p)<1){Dn=r.scrollTop;return}if(Math.abs(p)>=Wx){Xs(),xn=!0,r.scrollTop=er(r),Dn=r.scrollTop,xn=!1;return}Um(r,()=>er(r),a,()=>Bn.isFollowing())},Bl=()=>{if(!wp()){qt();return}let r=Om();xn=!0,r.scrollTop=er(r),Dn=r.scrollTop,xn=!1,qt()},ls=r=>{let a=0,p=r;for(;p&&p!==ee;)a+=p.offsetTop,p=p.offsetParent;return a},$x=()=>{let r=ee.getRootNode();return(typeof r.getSelection=="function"?r.getSelection():null)??ee.ownerDocument.getSelection()},Dl=()=>rb($x(),ee),xp=()=>{if(hx()!=="last-user-turn")return!1;let r=A?.getMessages()??[];if(r.length<2)return!1;let a=[...r].reverse().find(v=>v.role==="user");if(!a)return!1;let p=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(a.id):a.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),f=ee.querySelector(`[data-message-id="${p}"]`);if(!f)return!1;let h=Math.min(Math.max(0,ls(f)-Vi()),er(ee));return xn=!0,ee.scrollTop=h,Dn=ee.scrollTop,xn=!1,Rn()==="follow"&&!As(ee,Uo)&&Bn.pause(),qt(),!0},_l=r=>{let a=Math.max(0,Math.round(r));Vn.style.height=`${a}px`,Vn.style.display=a>0?"":"none",Vt&&(Vt.spacerHeight=Math.max(0,r))},Ol=r=>{let a=parseFloat(getComputedStyle(ee).paddingBottom)||0,p=0;for(let h of Array.from(ee.children)){if(h===Vn||h.offsetHeight===0)continue;let v=ls(h)+h.offsetHeight;v>p&&(p=v)}let f=ee.scrollHeight-r;return p>0?Math.min(p+a,f):f},Vx=()=>{if(!Vt||Vt.spacerHeight<=0)return;let r=Ol(Vt.spacerHeight),a=Math.max(0,Math.round(ee.scrollTop)+ee.clientHeight-r+Uo);a<Vt.spacerHeight&&(_l(a),qt())},co=()=>{ss!==null&&(cancelAnimationFrame(ss),ss=null),Xs(),Vt=null,Vn.style.height="0px",Vn.style.display="none"},$m=r=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Sp=r=>ee.querySelector(`[data-message-id="${$m(r)}"]`),Vm=r=>{ss!==null&&cancelAnimationFrame(ss),ss=requestAnimationFrame(()=>{ss=null;let a=$m(r),p=ee.querySelector(`[data-message-id="${a}"]`);if(!p)return;let f=ls(p),h=Vt?.spacerHeight??0,v=Ol(h),{targetScrollTop:B,spacerHeight:q}=Bu({anchorOffsetTop:f,topOffset:Vi(),viewportHeight:ee.clientHeight,contentHeight:v,slack:Uo});Vt={initialSpacerHeight:q,contentHeightAtAnchor:v,spacerHeight:q},_l(q),Um(ee,()=>p.isConnected?Math.max(0,ls(p)-Vi()):B,220)})},An=()=>{if(Rn()!=="anchor-top"||!Vt||!Gs)return;let r=Sp(Gs);if(!r)return;Xs();let a=Vt.spacerHeight,p=Ol(a),{targetScrollTop:f,spacerHeight:h}=Bu({anchorOffsetTop:ls(r),topOffset:Vi(),viewportHeight:ee.clientHeight,contentHeight:p,slack:Uo});Vt={initialSpacerHeight:h,contentHeightAtAnchor:p,spacerHeight:h},_l(h),xn=!0,ee.scrollTop=f,Dn=ee.scrollTop,xn=!1,qt()},qx=()=>{if(gr()){if(!Bn.isFollowing()||As(ee,1))return;xr(!Wn);return}if(Vt&&Vt.initialSpacerHeight>0){let r=ee.scrollHeight-Vt.spacerHeight,a=sb({initialSpacerHeight:Vt.initialSpacerHeight,contentHeightAtAnchor:Vt.contentHeightAtAnchor,currentContentHeight:r});a!==Vt.spacerHeight&&_l(a)}qt()},zx=r=>{let a=Rn();a==="follow"?(Sn(),xr(!0)):a==="anchor-top"&&(Zi=!1,kl=!0,Ll=!1,Gs=r,Vm(r))},jx=()=>{if(Rn()==="anchor-top"){if(kl){Zi=!1;return}Zi=!0,co(),Sn(),xr(!0)}},Kx=96,Gx=r=>{if(is===null)return!0;let a=Sp(is),p=Sp(r);if(!a||!p)return!0;let f=ls(p)-ls(a);return Vi()+f>ee.clientHeight-Kx},Qx=r=>{if(Rn()!=="anchor-top"||!kl||Ll||Dl())return;let a=is===null;for(let p of r){if(!a){p.id===is&&(a=!0);continue}if(eb(p)){if(p.id===Gs||!Gx(p.id))return;Gs=p.id,Vm(p.id);return}}},Yx=r=>{let a=new Map;r.forEach(p=>{let f=yp.get(p.id);a.set(p.id,{streaming:p.streaming,role:p.role}),!f&&p.role==="assistant"&&(ne.emit("assistant:message",p),!Ks&&(Rn()!=="anchor-top"||Uf())&&Cp()&&(Cr+=1,vp(),qt(),gl(Cr===1?"1 new message below.":`${Cr} new messages below.`))),p.role==="assistant"&&f?.streaming&&p.streaming===!1&&ne.emit("assistant:complete",p),p.variant==="approval"&&p.approval&&(f?p.approval.status!=="pending"&&ne.emit("approval:resolved",{approval:p.approval,decision:p.approval.status}):ne.emit("approval:requested",{approval:p.approval,message:p}))}),yp.clear(),a.forEach((p,f)=>{yp.set(f,p)})},ta=(r,a)=>{let p=a==="user"?"user":"assistant",f=o.layout?.messages?.[p],h=f?.width??"content",v=f?.maxWidth??(h==="full"?`var(--persona-message-${p}-max-width, 100%)`:void 0);r.classList.add("persona-message-row"),r.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),r.classList.add(`persona-message-row-${a}`,`persona-message-width-${h}`),r.classList.toggle("persona-justify-end",a==="user"),r.setAttribute("data-message-role",a),r.setAttribute("data-message-width",h),v?r.style.setProperty("--persona-message-row-max-width",v):r.style.removeProperty("--persona-message-row-max-width")},qo=(r,a)=>{let p=document.createElement("div");return p.className="persona-flex",p.id=`wrapper-${r}`,p.setAttribute("data-wrapper-id",r),ta(p,a),p},Xx=(r,a,p)=>{let f=new Set;for(let R of a){let Le=R.variant==="tool"?"tool":R.variant==="reasoning"?"reasoning":null;if(!Le||Wr(o,Le)!=="row")continue;let Ie=Le==="tool"?o.features?.toolCallDisplay:o.features?.reasoningDisplay;Ie?.expandable!==!1&&(f.add(R.id),l.observe(R,Le,Le==="tool"?s:i,Ie))}let h=document.createElement("div"),B=(()=>{let R=u.find(Le=>Le.renderLoadingIndicator);if(R?.renderLoadingIndicator)return R.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),q=(R,Le)=>Le==null?!1:typeof Le=="string"?(R.textContent=Le,!0):(R.appendChild(Le),!0),U=new Set,z=new Map,Q=new Set,re=u.some(R=>R.renderAskUserQuestion),ue=[],Ne=[],nt=o.enableComponentStreaming!==!1,Ze=o.approval!==!1,Tn=[],bt=o.messageActions,At=bt?.showRegenerate===!0&&bt.enabled!==!1&&it.current?.isStreaming()!==!0?bv(a):null,un=bt?.showEdit===!0&&bt.enabled!==!1,Lt=bt?.showQuote===!0&&bt.enabled!==!1,at=null,Eo=o.features?.reasoningDisplay?.completedVisibility,Po=R=>Eo==="removed"?!0:Eo==="removed-when-short"?Uy(R,o.features?.reasoningDisplay?.shortThinkThreshold):!1,Jn=o.features?.toolCallDisplay?.completedVisibility==="removed",Zn=R=>R.variant==="reasoning"&&R.reasoning?.status==="complete"?Po(R.reasoning):Jn&&R.variant==="tool"&&R.toolCall?.status==="complete";if(a.forEach(R=>{if(Zn(R))return;if(U.add(R.id),z.set(R.id,R.role),ns===R.id&&br){let He=qo(R.id,R.role);He.setAttribute("data-persona-message-edit-stub","true"),He.setAttribute("data-preserve-runtime","true"),h.appendChild(He),at={messageId:R.id,element:br.element};return}let Le=re&&ks(R),Ie=Ze&&R.variant==="approval"&&!!R.approval,te=!Le&&R.role==="assistant"&&!R.variant&&nt&&Pf(R);!Ie&&yr.has(R.id)&&(r.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime"),yr.delete(R.id)),!te&&ts.has(R.id)&&(r.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime"),ts.delete(R.id));let lt=ks(R)?`:${R.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${R.agentMetadata?.askUserQuestionAnswers?Object.keys(R.agentMetadata.askUserQuestionAnswers).length:0}`:"",_t={canRegenerate:At===R.id,canEdit:un&&cg(R),canQuote:Lt&&!R.variant&&(R.content?.trim().length??0)>0},an=`${_t.canRegenerate?"r":""}${_t.canEdit?"e":""}${_t.canQuote?"q":""}`,Xt=EC(R,rs)+lt+`:${an}`,ft=Le||Ie||te?null:kC(Dt,R.id,Xt);if(ft){h.appendChild(ft.cloneNode(!0)),ks(R)&&R.toolCall?.id&&R.agentMetadata?.awaitingLocalTool===!0&&!R.agentMetadata?.askUserQuestionAnswered&&(Q.add(R.toolCall.id),jc(R,o,De.composerOverlay));return}let It=null,zt=u.find(He=>!!(R.variant==="reasoning"&&He.renderReasoning||R.variant==="tool"&&He.renderToolCall||!R.variant&&He.renderMessage)),Te=o.layout?.messages;if(ks(R)&&R.agentMetadata?.askUserQuestionAnswered===!0){js.delete(R.id),r.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime");return}if(_a(R)&&Nr(o).enabled)return;if(ks(R)&&o.features?.askUserQuestion?.enabled!==!1){let He=u.find(jt=>typeof jt.renderAskUserQuestion=="function");if(He&&it.current){let jt=js.get(R.id),eo=jt!==Xt,Jt=null;if(eo){let{payload:_e,complete:Re}=Ai(R),Hr=R.id,Ut=()=>it.current?.getMessages().find(En=>En.id===Hr);Jt=He.renderAskUserQuestion({message:R,payload:_e,complete:Re,resolve:En=>{let Jo=Ut();Jo&&it.current?.resolveAskUserQuestion(Jo,En)},dismiss:()=>{let En=Ut();En?.agentMetadata?.awaitingLocalTool&&(it.current?.markAskUserQuestionResolved(En),it.current?.resolveAskUserQuestion(En,"(dismissed)"))},config:o})}let ct=jt!=null;if(eo&&Jt===null&&!ct){R.agentMetadata?.awaitingLocalTool===!0&&!R.agentMetadata?.askUserQuestionAnswered&&(Q.add(R.toolCall.id),jc(R,o,De.composerOverlay));return}let Ee=qo(R.id,R.role);Ee.setAttribute("data-ask-plugin-stub","true"),Ee.setAttribute("data-preserve-runtime","true"),h.appendChild(Ee),ue.push({messageId:R.id,fingerprint:Xt,bubble:Jt});return}else{R.agentMetadata?.awaitingLocalTool===!0&&!R.agentMetadata?.askUserQuestionAnswered&&(Q.add(R.toolCall.id),jc(R,o,De.composerOverlay));return}}else if(Ie){let He=D();if(!He){h.appendChild(qo(R.id,R.role));return}let jt=u.find(Ee=>typeof Ee.renderApproval=="function")??E,Jt=yr.get(R.id)!==Xt,ct=null;if(Jt&&jt?.renderApproval){let Ee=R.id,_e=(Re,Hr)=>{let Ut=it.current?.getMessages().find(En=>En.id===Ee);Ut?.approval&&(Ut.approval.toolType==="webmcp"?it.current?.resolveWebMcpApproval(Ut.id,Re):it.current?.resolveApproval(Ut.approval,Re,Hr))};ct=jt.renderApproval({message:R,defaultRenderer:()=>He.createApprovalBubble(R,o,c),config:o,approve:Re=>_e("approved",Re),deny:Re=>_e("denied",Re)})}if(Jt&&ct===null)r.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime"),yr.delete(R.id),It=He.createApprovalBubble(R,o,c);else{let Ee=qo(R.id,R.role);Ee.setAttribute("data-approval-plugin-stub","true"),Ee.setAttribute("data-preserve-runtime","true"),h.appendChild(Ee),Tn.push({messageId:R.id,fingerprint:Xt,bubble:ct});return}}else if(zt)if(R.variant==="reasoning"&&R.reasoning&&zt.renderReasoning){if(!j)return;It=zt.renderReasoning({message:R,defaultRenderer:()=>af(R,o,i),config:o})}else if(R.variant==="tool"&&R.toolCall&&zt.renderToolCall){if(!X)return;It=zt.renderToolCall({message:R,defaultRenderer:()=>pf(R,o,s),config:o})}else zt.renderMessage&&(It=zt.renderMessage({message:R,defaultRenderer:()=>{let He=Qg(R,p,Te,o.messageActions,_s,{loadingIndicatorRenderer:B,widgetConfig:o,actionEligibility:_t});return R.role!=="user"&&se(He,R,o,A),He},config:o}));if(!It&&te){let He=Fw(R);if(He){let jt=ts.get(R.id),eo=jt!==Xt,Jt=o.wrapComponentDirectiveInBubble!==!1&&tr.getOptions(He.component)?.bubbleChrome!==!1,ct=null;if(eo){let Ee=Ow(He,{config:o,message:R,transform:p});if(Ee&&He.component==="PersonaArtifactInline"){let _e=Ee.hasAttribute("data-artifact-inline")?Ee:Ee.querySelector("[data-artifact-inline]"),Re=_e?.getAttribute("data-artifact-inline")??"",Hr=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Re):Re,Ut=Re?r.querySelector(`#wrapper-${R.id}`)?.querySelector(`[data-artifact-inline="${Hr}"]`)??null:null;_e&&Ut&&Ut!==_e&&ar()?.hasLiveInlineArtifactBlock(Ut)&&(_e===Ee?Ee=Ut:_e.replaceWith(Ut))}if(Ee)if(Jt){let _e=document.createElement("div");if(_e.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),_e.id=`bubble-${R.id}`,_e.setAttribute("data-message-id",R.id),R.content&&R.content.trim()){let Re=document.createElement("div");Re.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Re.innerHTML=p({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),_e.appendChild(Re)}_e.appendChild(Ee),ct=_e}else{let _e=document.createElement("div");if(_e.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",_e.id=`bubble-${R.id}`,_e.setAttribute("data-message-id",R.id),_e.setAttribute("data-persona-component-directive","true"),R.content&&R.content.trim()){let Re=document.createElement("div");Re.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Re.innerHTML=p({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),_e.appendChild(Re)}_e.appendChild(Ee),ct=_e}}if(ct||jt!=null){let Ee=qo(R.id,R.role);Ee.setAttribute("data-component-directive-stub","true"),Ee.setAttribute("data-preserve-runtime","true"),h.appendChild(Ee),Ne.push({messageId:R.id,fingerprint:Xt,bubble:ct});return}}}if(!It)if(R.variant==="reasoning"&&R.reasoning){if(!j)return;It=af(R,o,i)}else if(R.variant==="tool"&&R.toolCall){if(!X)return;It=pf(R,o,s)}else if(R.variant==="approval"&&R.approval){if(o.approval===!1)return;let He=D();if(!He)return;It=He.createApprovalBubble(R,o,c)}else{let He=o.layout?.messages;He?.renderUserMessage&&R.role==="user"?It=He.renderUserMessage({message:R,config:o,streaming:!!R.streaming}):He?.renderAssistantMessage&&R.role==="assistant"?It=He.renderAssistantMessage({message:R,config:o,streaming:!!R.streaming}):It=Qg(R,p,He,o.messageActions,_s,{loadingIndicatorRenderer:B,widgetConfig:o,actionEligibility:_t}),R.role!=="user"&&It&&se(It,R,o,A)}let mt=qo(R.id,R.role);mt.appendChild(It),LC(Dt,R.id,Xt,mt),h.appendChild(mt)}),De.composerOverlay&&De.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Le=>{let Ie=Le.getAttribute("data-persona-ask-sheet-for");Ie&&!Q.has(Ie)&&Ti(De.composerOverlay,Ie)}),o.features?.toolCallDisplay?.grouped){let R=[],Le=[],Ie=o.features.toolCallDisplay.groupedMode==="summary";a.forEach(te=>{if(te.variant==="tool"&&te.toolCall&&X){if(Jn&&te.toolCall.status==="complete")return;Le.push(te);return}te.variant==="reasoning"&&(!j||te.reasoning?.status==="complete"&&Po(te.reasoning))||((Le.length>1||Ie&&Le.length>0)&&R.push(Le),Le=[])}),(Le.length>1||Ie&&Le.length>0)&&R.push(Le),R.forEach(te=>{let lt=te.map(Te=>Array.from(h.children).find(mt=>mt instanceof HTMLElement&&mt.getAttribute("data-wrapper-id")===Te.id)).filter(Te=>!!Te);if(lt.length<(Ie?1:2))return;let _t=qo(`tool-group-${te[0].id}`,"assistant");if(_t.setAttribute("data-persona-tool-group-row","true"),o.features?.toolCallDisplay?.groupedMode==="collapsible"){let Te=`tool-group-${te[0].id}`,mt=te.some(ct=>ct.toolCall?.status!=="complete"),He={...te[0],id:Te,toolCall:{id:Te,name:`${te.length} tools`,status:mt?"running":"complete",chunks:te.flatMap(ct=>ct.toolCall?.chunks??[]),success:!te.some(ct=>ct.toolCall?.success===!1)}};f.add(Te),l.observe(He,"tool",s,o.features.toolCallDisplay);let jt=`${mt?"Using":"Used"} ${te.length} tools`,eo=o.toolCall?.renderGroupedSummary?.({messages:te,toolCalls:te.map(ct=>ct.toolCall),defaultSummary:jt,config:o}),Jt=Cb(He,o,s.has(Te),eo??jt);Jt.bubble.classList.add("persona-tool-group"),Jt.body.dataset.personaToolGroupStack="true",lt[0].before(_t),_t.appendChild(Jt.bubble),lt.forEach((ct,Ee)=>{ct.style.setProperty("--persona-message-row-max-width","100%"),ct.style.setProperty("--persona-activity-stagger",`${Ee*40}ms`),ct.classList.add("persona-activity-group-child"),Jt.body.appendChild(ct)});return}let an=document.createElement("div");an.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",an.setAttribute("data-persona-tool-group","true");let Xt=document.createElement("div");Xt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",Xt.id=`tool-group-summary-${te[0].id}`;let ft=`Called ${te.length} ${te.length===1?"tool":"tools"}`,It=o.toolCall?.renderGroupedSummary?.({messages:te,toolCalls:te.map(Te=>Te.toolCall).filter(Te=>!!Te),defaultSummary:ft,config:o});q(Xt,It)||(Xt.textContent=ft);let zt=document.createElement("div");zt.className="persona-tool-group-stack persona-flex persona-flex-col",zt.id=`tool-group-stack-${te[0].id}`,zt.setAttribute("data-persona-tool-group-stack","true"),an.appendChild(Xt),Ie||an.appendChild(zt),_t.appendChild(an),lt[0].before(_t),lt.forEach((Te,mt)=>{if(Ie){Te.remove();return}Te.style.setProperty("--persona-message-row-max-width","100%");let He=document.createElement("div");He.className="persona-tool-group-item persona-relative",He.setAttribute("data-persona-tool-group-item","true"),mt<lt.length-1&&He.setAttribute("data-persona-tool-group-connector","true"),He.appendChild(Te),zt.appendChild(He)})})}l.prune(f),IC(Dt,U);let Lr=R=>R.variant==="tool"&&!X||R.variant==="reasoning"&&!j||Zn(R),ko=a.some(R=>R.role==="assistant"&&R.streaming&&!Lr(R)),po=a.length-1;for(;po>=0&&Lr(a[po]);)po--;let Ir=po>=0?a[po]:void 0,Aa=po<a.length-1,Cs=Ir?.role==="assistant"&&!Ir.streaming&&Ir.variant!=="approval"&&!Aa;if(Wn&&a.some(R=>R.role==="user")&&!ko&&!Cs){let R={config:o,streaming:!0,location:"standalone",defaultRenderer:rl},Le=u.find(te=>te.renderLoadingIndicator),Ie=null;if(Le?.renderLoadingIndicator&&(Ie=Le.renderLoadingIndicator(R)),Ie===null&&o.loadingIndicator?.render&&(Ie=o.loadingIndicator.render(R)),Ie===null&&(Ie=rl()),Ie){let te=document.createElement("div"),lt=o.loadingIndicator?.showBubble!==!1,_t=o.layout?.messages?.layout??"bubble";te.className=lt?sl("assistant",_t).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),te.setAttribute("data-typing-indicator","true"),lt&&(te.style.color="var(--persona-message-assistant-text, var(--persona-text))",_t!=="flat"&&(te.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",te.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),te.appendChild(Ie);let an=qo("typing-indicator","assistant");an.appendChild(te),h.appendChild(an)}}if(!Wn&&a.length>0){let R=a[a.length-1],Le={config:o,lastMessage:R,messageCount:a.length},Ie=u.find(lt=>lt.renderIdleIndicator),te=null;if(Ie?.renderIdleIndicator&&(te=Ie.renderIdleIndicator(Le)),te===null&&o.loadingIndicator?.renderIdle&&(te=o.loadingIndicator.renderIdle(Le)),te){let lt=document.createElement("div"),_t=o.loadingIndicator?.showBubble!==!1;lt.className=_t?["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-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),lt.setAttribute("data-idle-indicator","true"),lt.appendChild(te);let an=qo("idle-indicator","assistant");an.appendChild(lt),h.appendChild(an)}}if(Lb(h),Md(r,h),Qu(r),at){let{messageId:R,element:Le}=at,Ie=r.querySelector(`#wrapper-${R}`);Ie&&Le.parentElement!==Ie&&(ta(Ie,z.get(R)??"user"),Ie.replaceChildren(Le))}if(ue.length>0)for(let{messageId:R,fingerprint:Le,bubble:Ie}of ue){let te=r.querySelector(`#wrapper-${R}`);te&&(ta(te,z.get(R)??"assistant"),Ie!==null&&(te.replaceChildren(Ie),te.setAttribute("data-bubble-fp",Le),js.set(R,Le)))}if(js.size>0)for(let R of js.keys())U.has(R)||js.delete(R);if(Ne.length>0)for(let{messageId:R,fingerprint:Le,bubble:Ie}of Ne){let te=r.querySelector(`#wrapper-${R}`);te&&(ta(te,z.get(R)??"assistant"),Ie!==null&&(te.replaceChildren(Ie),te.setAttribute("data-bubble-fp",Le),ts.set(R,Le)))}if(ts.size>0)for(let R of ts.keys())U.has(R)||ts.delete(R);if(Tn.length>0)for(let{messageId:R,fingerprint:Le,bubble:Ie}of Tn){let te=r.querySelector(`#wrapper-${R}`);te&&(ta(te,z.get(R)??"assistant"),Ie!==null&&(te.replaceChildren(Ie),te.setAttribute("data-bubble-fp",Le),yr.set(R,Le)))}if(yr.size>0)for(let R of yr.keys())U.has(R)||yr.delete(R)},Ap=!1,Nl=()=>{Ap||(Ap=!0,Wy().catch(()=>{Ap=!1}))},zn=(r,a,p)=>{a.length>0&&Nl(),Xx(r,a,p),lm()},na=null,Jx=()=>{if(na)return;let r=p=>{let f=p.composedPath();f.includes(je)||Qt&&f.includes(Qt)||gt(!1,"user")};na=r,(t.ownerDocument??document).addEventListener("pointerdown",r,!0)},qm=()=>{if(!na)return;(t.ownerDocument??document).removeEventListener("pointerdown",na,!0),na=null};fe.push(()=>qm());let oa=null,Zx=()=>{if(oa)return;let r=p=>{p.key==="Escape"&&(p.isComposing||gt(!1,"user"))};oa=r,(t.ownerDocument??document).addEventListener("keydown",r,!0)},zm=()=>{if(!oa)return;(t.ownerDocument??document).removeEventListener("keydown",oa,!0),oa=null};fe.push(()=>zm());let ra=!1,jm=new Set,eS=()=>{let r=o.launcher?.composerBar?.peek?.streamAnimation;return r||o.features?.streamAnimation},Zs=()=>{if(!Be())return;let r=De.peekBanner,a=De.peekTextNode;if(!r||!a)return;if(Pe){r.classList.remove("persona-pill-peek--visible");return}let p=A?.getMessages()??[],f;for(let bt=p.length-1;bt>=0;bt--){let At=p[bt];if(At.role==="assistant"&&At.content){f=At;break}}if(!f){r.classList.remove("persona-pill-peek--visible");return}let h=f.content,v=!!f.streaming,B=eS(),q=Ic(B),U=q.type!=="none"?fp(q.type,B?.plugins):null,z=U?.isAnimating?.(f)===!0,Q=U!==null&&(v||z);Q&&U&&!jm.has(U.name)&&(ka(U,t),jm.add(U.name));let re=Q&&U?.containerClass?U.containerClass:null,ue=a.dataset.personaPeekStreamClass??null;ue&&ue!==re&&(a.classList.remove(ue),delete a.dataset.personaPeekStreamClass),re&&ue!==re&&(a.classList.add(re),a.dataset.personaPeekStreamClass=re),Q?(a.style.setProperty("--persona-stream-step",`${q.speed}ms`),a.style.setProperty("--persona-stream-duration",`${q.duration}ms`)):(a.style.removeProperty("--persona-stream-step"),a.style.removeProperty("--persona-stream-duration"));let Ne=Q?Hc(h,q.buffer,U,f,v):h;if(Q&&q.placeholder==="skeleton"&&v&&(!Ne||!Ne.trim())){let bt=document.createElement("div"),At=Pa();At.classList.add("persona-pill-peek__skeleton"),bt.appendChild(At),Md(a,bt)}else{let bt=Math.max(0,Ne.length-100),At=Ne.length>100?Ne.slice(-100):Ne,un=Sc(At);if(!Q||!U){let Lt=Ne.length>100?`\u2026${At}`:At;a.textContent!==Lt&&(a.textContent=Lt)}else{let Lt=un;(U.wrap==="char"||U.wrap==="word")&&(Lt=Ea(un,U.wrap,`peek-${f.id}`,{skipTags:U.skipTags,startIndex:bt}));let at=document.createElement("div");if(at.innerHTML=Lt,U.useCaret&&At.length>0){let Eo=Rc(),Po=at.querySelectorAll(".persona-stream-char, .persona-stream-word"),Jn=Po[Po.length-1];Jn?.parentNode?Jn.parentNode.insertBefore(Eo,Jn.nextSibling):at.appendChild(Eo)}Md(a,at),U.onAfterRender?.({container:a,bubble:r,messageId:f.id,message:f,speed:q.speed,duration:q.duration})}}let Tn=Wn||ra;r.classList.toggle("persona-pill-peek--visible",Tn)};if(Be()){let r=De.peekBanner;if(r){let f=h=>{h.preventDefault(),h.stopPropagation(),gt(!0,"user")};r.addEventListener("pointerdown",f),fe.push(()=>{r.removeEventListener("pointerdown",f)})}let a=()=>{ra||(ra=!0,Zs())},p=()=>{ra&&(ra=!1,Zs())};we.addEventListener("pointerenter",a),we.addEventListener("pointerleave",p),fe.push(()=>{we.removeEventListener("pointerenter",a),we.removeEventListener("pointerleave",p)}),Qt&&(Qt.addEventListener("pointerenter",a),Qt.addEventListener("pointerleave",p),fe.push(()=>{Qt.removeEventListener("pointerenter",a),Qt.removeEventListener("pointerleave",p)}))}let tS=r=>{let a=o.launcher?.composerBar??{},p=a.expandedSize??"anchored",f=a.bottomOffset??"16px",h=a.collapsedMaxWidth,v=a.expandedMaxWidth??"880px",B=a.expandedTopOffset??"5vh",q=a.modalMaxWidth??"880px",U=a.modalMaxHeight??"min(90vh, 800px)",z="calc(100vw - 32px)",Q="var(--persona-pill-area-height, 80px)",re=je.style;if(re.left="",re.right="",re.top="",re.bottom="",re.transform="",re.width="",re.maxWidth="",re.height="",re.maxHeight="",Qt){let ue=Qt.style;ue.bottom=f,ue.width=h??""}if(r&&p!=="fullscreen"){if(p==="modal"){re.top="50%",re.left="50%",re.transform="translate(-50%, -50%)",re.bottom="auto",re.right="auto",re.width=q,re.maxWidth=z,re.maxHeight=U,re.height=U;return}re.left="50%",re.transform="translateX(-50%)",re.bottom=`calc(${f} + ${Q})`,re.top=B,re.width=v,re.maxWidth=z}},sa=()=>{if(Pe&&Nl(),!Ge())return;if(Be()){let z=(o.launcher?.composerBar??{}).expandedSize??"anchored",Q=Pe?"expanded":"collapsed";je.dataset.state=Q,je.dataset.expandedSize=z,Qt&&(Qt.dataset.state=Q,Qt.dataset.expandedSize=z),je.style.removeProperty("display"),je.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),tS(Pe),ce.style.display=Pe?"flex":"none",Gr(),Pe?(Jx(),Zx()):(qm(),zm()),Zs();return}let r=xt(o),a=t.ownerDocument.defaultView??window,p=o.launcher?.mobileBreakpoint??640,f=o.launcher?.mobileFullscreen??!0,h=a.innerWidth<=p,v=f&&h&&W,B=oo(o).reveal;Pe?(je.style.removeProperty("display"),je.style.display=r?"flex":"",je.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-95","persona-opacity-0"),we.classList.add("persona-scale-100","persona-opacity-100"),Pt?(Pt.setPanelOpen(!0),Pt.element.style.display="none"):pn&&(pn.style.display="none")):(r?r&&(B==="overlay"||B==="push")&&!v?(je.style.removeProperty("display"),je.style.display="flex",je.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(je.style.setProperty("display","none","important"),je.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(je.style.display="",je.classList.add("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100"),we.classList.add("persona-scale-95","persona-opacity-0")),Pt?(Pt.setPanelOpen(!1),Pt.element.style.display=r?"none":""):pn&&(pn.style.display=r?"none":""))},gt=(r,a="user")=>{if(!Ge()||Pe===r)return;let p=Pe;Pe=r,sa();let f=(()=>{let v=o.launcher?.sidebarMode??!1,B=t.ownerDocument.defaultView??window,q=o.launcher?.mobileFullscreen??!0,U=o.launcher?.mobileBreakpoint??640,z=B.innerWidth<=U,Q=xt(o)&&q&&z,re=Be()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return v||q&&z&&W||Q||re})();if(Pe&&f){if(!wo){let v=t.getRootNode(),B=v instanceof ShadowRoot?v.host:t.closest(".persona-host");B&&(wo=Fg(B,o.launcher?.zIndex??ln))}xo||(xo=Ug(t.ownerDocument))}else Pe||(wo?.(),wo=null,xo?.(),xo=null);Pe&&(wa(),xp()||(Rn()==="follow"?xr(!0):Bl()));let h={open:Pe,source:a,timestamp:Date.now()};Pe&&!p?ne.emit("widget:opened",h):!Pe&&p&&ne.emit("widget:closed",h),ne.emit("widget:state",{open:Pe,launcherEnabled:W,voiceActive:Ke.active,streaming:A.isStreaming()})},Sr={inputDisabled:!1,sendDisabled:!1},So=()=>Sr.inputDisabled,Mp=()=>gn(o.voiceRecognition?.provider)&&!!A&&(A.isBargeInActive()||["listening","processing","speaking"].includes(A.getVoiceStatus())),cs=()=>Sr.inputDisabled||Sr.sendDisabled,nS=()=>(Sr.inputDisabled?Sr.inputReason:void 0)??(Sr.sendDisabled?Sr.sendReason:void 0);function Tp(){if(!Ae)return;if(be.getState().phase==="streaming"){Ae.disabled=!1;return}let r=tt?!tt.isReady():!1;Ae.disabled=cs()||r}function Fl(){if(!ho)return;let r=be.getState(),a=o.sendButton?.visibility==="when-text"&&r.phase!=="streaming"&&r.text.trim().length===0&&r.attachments.length===0;ho.toggleAttribute("data-persona-send-hidden",a)}function oS(){let r=nS();if(Be()){let a=vn??ke;r?a.setAttribute("title",r):a.removeAttribute("title"),ke.toggleAttribute(Oi,!!r);return}if(r){Qe.setAttribute("role","status"),Qe.setAttribute("aria-live","polite"),Qe.setAttribute(Oi,""),Qe.textContent=r,Ps(Qe,o.statusIndicator??{},"idle");return}if(Qe.hasAttribute(Oi)&&(Qe.removeAttribute("role"),Qe.removeAttribute("aria-live"),Qe.removeAttribute(Oi),b)){let a=A.getStatus();Fi(Qe,zd(a),o.statusIndicator??{},a)}}function Ep(){let r=wg(o.composer?.inputDisabled),a=wg(o.composer?.sendDisabled);Sr={inputDisabled:r.disabled,inputReason:r.reason,sendDisabled:a.disabled,sendReason:a.reason},be.setInputDisabled(r.disabled),be.setSendDisabled(a.disabled);let p=be.getState().phase==="streaming",f=r.disabled,h=p||f;ae&&(ae instanceof HTMLTextAreaElement?ae.disabled=f:ae.setAttribute("contenteditable",f?"false":"true"),ae.setAttribute("aria-disabled",f?"true":"false")),St&&(St.disabled=f),yt&&(yt.disabled=f);for(let v of Bt?.affordanceButtons??[])v.querySelectorAll("button").forEach(B=>{B.disabled=f});oe&&(oe.disabled=f||p&&!Mp()),Xr.forEach(v=>{v.elements.forEach(B=>{B.toggleAttribute("data-disabled",h),B instanceof HTMLButtonElement||B.setAttribute("aria-disabled",h?"true":"false")}),v.buttons.forEach(B=>{B.disabled=h})}),Hp.forEach(v=>{v.toggleAttribute("data-disabled",h),v instanceof HTMLButtonElement?v.disabled=h:v.setAttribute("aria-disabled",h?"true":"false"),v.querySelectorAll("button").forEach(B=>{B.disabled=h})}),ke.dataset.personaComposerStreaming=p?"true":"false",ke.dataset.personaComposerInputDisabled=f?"true":"false",ke.dataset.personaComposerSendDisabled=cs()?"true":"false",ke.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(v=>{(v instanceof HTMLButtonElement||v instanceof HTMLInputElement||v instanceof HTMLTextAreaElement||v instanceof HTMLSelectElement)&&(v.disabled=p)}),Tp(),oS()}let ia=r=>{be.setStreaming(r),Nf(r?"stop":"send"),Ep()},ds=()=>{Ke.active||ae&&ae.focus()};ne.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>ds(),200)});let ps=null,aa=!1,Pp=!Yt.hidden,Ar=null,kp=!Z,Ul=null;fe.push(()=>{Ul?.cancel(),Ul=null});let rS=r=>{let a=YC(r);if(a===fl)return;fl=a,t.setAttribute("data-persona-conversation-state",a);let p=Yd();hl(),kp&&(Ul?.cancel(),Ul=GC(ke,a==="active"?p:Yd(),a==="active"?"drop":"rise",zr().layout==="centered"?320:260)),An()},Km=null,Gm,Qm=null,ei=null,Lp=!1,ti=r=>{let a=zr(),p=`${a.variant}|${a.layout}|${a.dismiss}|${a.anchor??"bottom"}|${a.align??""}|${a.iconPlacement}|${a.kicker??""}|${a.title}|${a.subtitle}`;(p!==Km||a.icon!==Gm)&&(Km=p,Gm=a.icon,Id({host:Yt,iconHolder:lx,kicker:cx,title:dx,subtitle:px,starterSuggestions:jd},a));let f=a.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${a.message}`;f!==Qm&&(Qm=f,Hd(In,a.message,o));let h=r??(A?A.getMessages():o.initialMessages);rS(h);let v=aa,B=!v&&Ri(a,h),q=B!==Pp;if(Pp=B,ei){Ar?.cancel(),Ar=null,v!==Lp&&(Lp=v,v?Jg(ee,Yt,null):Xg(ee,Yt,ei)),Hi(ee,Yt,!v);return}if(q&&!B&&!v&&a.dismiss==="on-first-message"&&kp){Ar=KC(Yt,z=>{Ar===z&&(Ar=null),!Pp&&!ei&&(Hi(ee,Yt,!1),An()),z?.cancel()});return}if(Ar){if(!B&&!v)return;Ar.cancel(),Ar=null}let U=!Yt.hidden;Hi(ee,Yt,B),!B&&U&&An()},Ip=[],Hp=[],Rp=!1,Ym=null,Xm,Jm=()=>{Hp.length=0;let r=Ip.splice(0,Ip.length);for(let a of r)try{a()}catch(p){console.warn("[persona] renderWelcome cleanup threw",p)}};fe.push(Jm);let sS=(r,a)=>{let p=Vg(r,a);if(!p)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),P("span");let f=o.suggestions?.starters,h=qg({item:{...p,behavior:p.behavior??f?.behavior??"send"},index:a,surface:"starter",source:"config",variant:f?.variant??"card",streaming:b?A.isStreaming():!1,config:o,plugins:u,chipsConfig:o.suggestionChipsConfig,session:A,getTextarea:()=>ae,eventTarget:Yt,submitPrompt:fc});return Hp.push(h),h},Wp=()=>{if(Rp)return;Rp=!0;let r=zr();Ym=`${r.variant}|${r.layout}|${r.dismiss}|${r.title}|${r.subtitle}|${r.message??""}`,Xm=r.icon;try{Jm(),Jg(ee,Yt,ei),ei=null,Lp=!1;let a=A?A.getMessages():o.initialMessages,p=Ri(r,a),f=0,h=null;for(let v of u)if(v.renderWelcome&&(h=v.renderWelcome({config:r,variant:r.variant,visible:p,defaultRenderer:()=>Yt,sendMessage:B=>{if(!A||A.isStreaming())return;let q=B.trim();q&&A.sendMessage(q)},requestRender:()=>Wp(),renderStarter:B=>sS(B,f++),storage:C(v.id),onCleanup:B=>{Ip.push(B)}}),h))break;h&&h!==Yt&&(ei=h,Xg(ee,Yt,h))}finally{Rp=!1}ti()},iS=()=>{let r=zr();`${r.variant}|${r.layout}|${r.dismiss}|${r.title}|${r.subtitle}|${r.message??""}`===Ym&&r.icon===Xm||Wp()},$l=()=>{ti(),$s||(ae.placeholder=Jv(be.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!A?.isStreaming()&&(Ae.textContent=o.copy?.sendButtonLabel??"Send")),ae.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ae.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},aS=!!o.setStoredConversationId,ni=r=>me(a=>{let p={...a};return delete p[r],p}),Vl=r=>{let a=k[r];return typeof a=="string"?a:null},Zm=()=>{let r=k.durableResume;if(!r||typeof r!="object")return null;let a=r;return typeof a.executionId=="string"&&a.executionId.length>0&&typeof a.after=="string"&&a.after.length>0?{executionId:a.executionId,after:a.after}:null};o.clientToken&&(o={...o,getStoredSessionId:()=>Vl("sessionId"),setStoredSessionId:r=>{me(a=>({...a,sessionId:r}))},clearStoredSessionId:o.clearStoredSessionId??(()=>ni("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>Vl("conversationId")),setStoredConversationId:o.setStoredConversationId??(r=>{me(a=>({...a,conversationId:r}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>ni("conversationId"))});let eh=()=>o.clientToken??null,th=r=>Hw(r,Se(),o.persistState===!1),nh=eh(),jn=nh?th(nh):null,zo={...jn?{visitorStore:jn}:{},historyBootstrapReady:ie,getStoredMessageCursor:()=>Vl("historyMessageCursor"),setStoredMessageCursor:r=>{if(r===null){ni("historyMessageCursor");return}me(a=>({...a,historyMessageCursor:r}))},getPendingDisplayProjections:()=>{let r=k.pendingDisplayProjections;if(!r||typeof r!="object")return null;let a=r;return typeof a.conversationId!="string"||!Array.isArray(a.messageIds)?null:{conversationId:a.conversationId,messageIds:a.messageIds.filter(p=>typeof p=="string")}},setPendingDisplayProjections:r=>{if(!r){ni("pendingDisplayProjections");return}me(a=>({...a,pendingDisplayProjections:r}))},getStoredResumableHandle:Zm,setStoredResumableHandle:r=>{if(!r){ni("durableResume");return}me(a=>({...a,durableResume:r}))},shouldResumeDurableConversation:()=>_&&Zm()!==null,...aS?{}:{getStoredConversationRevision:()=>Vl("conversationRevision"),setStoredConversationRevision:r=>{if(r===null){ni("conversationRevision");return}me(a=>({...a,conversationRevision:r}))}}};if(_){let r=o.onExecutionState,a=t.ownerDocument.defaultView,p=!1,f=()=>p=!0,h=()=>p=!1;a?.addEventListener("pagehide",f),a?.addEventListener("pageshow",h),fe.push(()=>{a?.removeEventListener("pagehide",f),a?.removeEventListener("pageshow",h)}),o={...o,reconnectStream:o.reconnectStream??(v=>A.getClient().reconnectClientTokenStream(v)),onExecutionState:v=>{(v||!p)&&zo.setStoredResumableHandle?.(v?{executionId:v.executionId,after:v.lastEventId}:null),r?.(v)}}}let lS=()=>{let r=eh();if(r&&jn?.matches(r,Se(),o.persistState===!1)||!r&&!jn)return;jn?.destroy(),jn=r?th(r):null;let a={...zo};jn?a.visitorStore=jn:delete a.visitorStore,zo=a,A.setHistoryInternals(zo)},us=null,cS=()=>{us==null&&(us=setInterval(()=>{let r=ye.querySelectorAll("[data-tool-elapsed]");if(r.length===0){clearInterval(us),us=null;return}let a=Date.now();r.forEach(p=>{let f=Number(p.getAttribute("data-tool-elapsed"));f&&(p.textContent=p.closest(".persona-activity-row")?Ra(a-f):Vy(a-f))})},100))},Bp=(r,a)=>{if(Object.is(r,a))return!0;if(r===null||a===null||typeof r!="object"||typeof a!="object")return!1;if(Array.isArray(r)||Array.isArray(a))return!Array.isArray(r)||!Array.isArray(a)||r.length!==a.length?!1:r.every((B,q)=>Bp(B,a[q]));let p=r,f=a,h=Object.keys(p),v=Object.keys(f);return h.length===v.length&&h.every(B=>Object.prototype.hasOwnProperty.call(f,B)&&Bp(p[B],f[B]))},oh=r=>{let{content:a,rawContent:p,llmContent:f,...h}=r;return h},Dp=r=>r.role==="assistant"&&r.streaming===!0&&!r.variant&&!r.toolCall&&!r.tools&&!r.approval&&!r.reasoning&&!r.contentParts&&!r.stopReason&&!Pf(r),dS=(r,a,p)=>{if(r.length!==a.length)return!1;let f=r[p.index],h=a[p.index];return!f||!h||f.id!==p.id||h.id!==p.id?!1:(!Object.is(f.content,h.content)||!Object.is(f.rawContent,h.rawContent)||!Object.is(f.llmContent,h.llmContent))&&Dp(f)&&Dp(h)&&Bp(oh(f),oh(h))},_p=null,oi=null,gs=null,jo=null,Op=null,pS=r=>{if(!_)return Qs(r);Op=r,queueMicrotask(()=>{Op===r&&(Op=null,Qs(r))})},ql=r=>{_p=r;let a,p;oi=null;for(let h=r.length-1;h>=0;h-=1){let v=r[h];if(!a&&v.role==="user"&&(a=v),!p&&v.role==="assistant"&&(p=v),!oi&&Dp(v)&&(oi={index:h,id:v.id}),a&&p&&oi)break}zn(ye,r,O),ar()?.updateInlineArtifactBlocks(ye,qn.artifacts,{suppressTransition:Wn}),cS(),ti(r),es(r),xr(!Wn),Yx(r),r.length===0&&(co(),Zi=!0,kl=!1,Gs=null,Ll=!1),!mp||Ks?(mp=!0,is=a?.id??null,hp=p?.id??null):a&&a.id!==is?(is=a.id,zx(a.id)):p&&p.id!==hp&&jx(),p&&(hp=p.id),Qx(r);let f=Ke.lastUserMessageId;a&&a.id!==f&&(Ke.lastUserMessageId=a.id,ne.emit("user:message",a)),Ke.lastUserMessageWasVoice=!!a?.viaVoice,pS(r),Zs()},Np=()=>{jo!==null&&(cancelAnimationFrame(jo),jo=null);let r=gs;gs=null,r&&ql(r)},rh=()=>{jo!==null&&cancelAnimationFrame(jo),jo=null,gs=null},uS=r=>{let a=gs??_p;if(Wn&&a&&oi&&dS(a,r,oi)){gs=r,jo===null&&(jo=requestAnimationFrame(()=>{jo=null;let p=gs;gs=null,p&&ql(p)}));return}if(r.length===0){rh(),ql(r);return}Np(),ql(r)};A=new ed(o,{onMessagesChanged(r){uS(r)},onStatusChanged(r){let a=o.statusIndicator??{};Fi(Qe,(f=>f==="idle"?a.idleText??Rt.idle:f==="connecting"?a.connectingText??Rt.connecting:f==="connected"?a.connectedText??Rt.connected:f==="error"?a.errorText??Rt.error:f==="paused"?a.pausedText??Rt.paused:f==="resuming"?a.resumingText??Rt.resuming:Rt[f])(r),a,r),qd()},onStreamingChanged(r){r||(A?.getMessages().length===0?rh():Np()),Wn=r,ia(r),qd(),A&&zn(ye,A.getMessages(),O),r||(xr(!0),Vx(),Lm=!0,A&&Im(A.getMessages(),Nr(o))),qt(),gl(r?"Responding\u2026":"Response complete."),Zs()},onVoiceStatusChanged(r){if(ne.emit("voice:status",{status:r,timestamp:Date.now()}),!(r!=="disconnected"&&!gn(o.voiceRecognition?.provider)))switch(r){case"listening":Xo(),fi();break;case"processing":Xo(),fA();break;case"speaking":Xo(),mA();break;default:r==="idle"&&A.isBargeInActive()?(Xo(),fi(),oe?.setAttribute("aria-label","End voice session")):(Ke.active=!1,Xo(),Vo("system"),lo());break}},onArtifactsState(r){qn=r,r.artifacts.length===0&&(Vs=!1),ar()?.updateInlineArtifactBlocks(ye,r.artifacts,{suppressTransition:Wn}),ao(),Qs()},onHistoryStateChanged(r){_f(r)},onHistoryNotice(r){Of(r)},onReconnect(r){let{executionId:a,lastEventId:p}=r.handle;r.phase==="paused"?ne.emit("stream:paused",{executionId:a,after:p}):r.phase==="resuming"?ne.emit("stream:resuming",{executionId:a,after:p,attempt:r.attempt??1}):ne.emit("stream:resumed",{executionId:a,after:p})}},zo),it.current=A,fe.push(()=>A.cancel()),fe.push(()=>{A.destroy(),jn?.destroy(),jn=null});let Fp=null;if(A.onReadAloudChange((r,a)=>{im=r,am=a,lm();let p=r??Fp;r&&(Fp=r);let f=p?A.getMessages().find(h=>h.id===p)??null:null;ne.emit("message:read-aloud",{messageId:p,message:f,state:a,timestamp:Date.now()}),a==="idle"&&(Fp=null)}),b=!0,mp=!0,o.voiceRecognition?.enabled===!0&&gn(o.voiceRecognition.provider))try{A.setupVoice()}catch(r){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",r)}let gS=720,fS=250,Ye=_u(o.features?.history?.copy),_n=null,Up=!1,rt=null,zl=null,jl="conversation",$p=null,dn=null,Ao=null,Kl=A.getHistoryState(),Vp=null,la=0,qp=null,Gl=null,Ql=null,zp=`persona-history-${Math.random().toString(36).slice(2,8)}`,jp=()=>o.features?.history?.enabled===!0,Mo=()=>jp()&&!!_n&&!Up,sh=()=>{let r=A.getStatus();return Wn||r==="paused"||r==="resuming"},Kp=()=>{let r=o.features?.history?.scope;if(r)return r;let a=o.getIdentityProof?"verified-user":"browser",p=_n?.capabilities.scopes;return!p||p.includes(a)?a:p[0]??a},ri=()=>zl?.scope??Kp(),ih=()=>A.getClientSession()?.targetId??null,ah=r=>`${r.state}:${"reason"in r?r.reason:""}`,mS=r=>{let a=ah(r);a!==Vp&&(Vp=a,ne.emit("history:identityStatusChanged",{status:r,timestamp:Date.now()}))},Yl=r=>{r&&(_o.textContent="",_o.textContent=r)},lh=null,ch=null,hS=()=>{if(!jp())return null;let r=Dw();if(r)return r();let a=o.features?.history?.provider;return a?typeof a!="function"?a:(lh!==a&&(lh=a,ch=a()),ch):A.isClientTokenMode()?_w({client:A.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:p=>A.bindActivatedSession(p),getClient:()=>A.getClient()}):null},dh=()=>{Gl?.(),Gl=null,Ql?.(),Ql=null,Up=!1,_n=hS();let r={...zo};_n?r.historyProvider=_n:delete r.historyProvider,zo=r,A.setHistoryInternals(zo),_n&&(Gl=_n.subscribeAvailability?.(a=>{Up=!a,a||Mn({restoreFocus:!1}),Tr()})??null,Ql=_n.subscribeIdentityStatus(a=>mS(a)),Vp=ah(_n.getIdentityStatus()))},Gp=()=>{let r=o.features?.history?.presentation??"panel";if(r==="panel"||r==="auto"&&!(!W||xt(o)))return"panel";let a=Co??ce;return(a.getBoundingClientRect().width||a.clientWidth)>=gS?"rail":"panel"},Kn=(r,a)=>{a?(r.setAttribute("aria-hidden","true"),r.setAttribute("inert","")):(r.removeAttribute("aria-hidden"),r.removeAttribute("inert"))},Xl="data-persona-history-suppressed",On=null,Mr=null,fs=null,ca=null,Qp=null,ph="",uh=()=>Me===Qp?ph:o.layout?.showHeader===!1?"none":"",yS=()=>Ot==="panel"&&!!fs&&ca===fs.element&&o.layout?.showHeader!==!1&&uh()!=="none",bS=()=>{for(let r of Array.from(Me.children))r!==On&&r.setAttribute(Xl,"")},vS=()=>{for(let r of Array.from(ce.querySelectorAll(`[${Xl}]`)))r.removeAttribute(Xl)},CS=()=>{let r=fs;if(!r)return;if(Array.from(Me.children).some(f=>f!==On&&!f.hasAttribute(Xl))){Mr&&Mr!==Me&&(Mr.style.removeProperty("min-height"),Mr=null);let f=Me.offsetHeight;f>0&&(Me.style.minHeight=`${f}px`,Mr=Me)}On||(On=P("div","persona-history-header-host")),r.setHeaderPlacement("external");let p=r.getHeaderElement();p.parentNode!==On&&On.replaceChildren(p),On.parentNode!==Me&&Me.appendChild(On),bS()},gh=()=>{Mr&&(Mr.style.removeProperty("min-height"),Mr=null),On&&(fs?.setHeaderPlacement("inline"),On.remove(),On=null,vS())},Jl=null,Yp=()=>{if(Jl){if(ee.style.display="none",Kn(ee,!0),ke.hidden=!0,Kn(ke,!0),yS()){CS(),Me.style.display=uh(),Kn(Me,!1);return}gh(),Me.style.display="none",Kn(Me,!0)}};Vd=Yp;let wS=r=>{let a=ee.style.display,p=ke.hidden,f=ke,h=Me,v=Me.style.display;Qp=h,ph=v,Jl=()=>{Jl=null,gh(),Qp=null,ee.style.display=a,Kn(ee,!1),f.hidden=p,Kn(f,!1),ke!==f&&(ke.hidden=!1,Kn(ke,!1)),h.style.display=v,Kn(h,!1),Me!==h&&(Me.style.display=o.layout?.showHeader===!1?"none":"",Kn(Me,!1))},ke.parentNode?.insertBefore(r,ke),Yp()},si=null,ms=null,da=null,ii=null,fh=()=>[Me,De.closeButtonWrapper,De.clearChatButtonWrapper,ee,ke],xS=52,Zl=()=>o.features?.history?.rail?.collapsible!==!1,ai=()=>o.features?.history?.rail?.side==="right"?"right":"left",Xp=200,Jp=400,Zp=r=>Math.min(Jp,Math.max(Xp,Math.round(r))),SS=()=>o.features?.history?.rail?.resizable===!0,pa,AS=()=>{if(pa===void 0&&(pa=null,o.persistState!==!1))try{let r=Number(window.localStorage.getItem(`${Se()}rail-width`));r&&(pa=r)}catch{}return pa},ua=()=>Zp(AS()??o.features?.history?.rail?.width??260),MS=r=>{if(pa=r,o.persistState!==!1)try{window.localStorage.setItem(`${Se()}rail-width`,String(r))}catch{}},ec=()=>Zl()&&o.features?.history?.rail?.collapsedBehavior==="overlay",Ft=!1,mh=r=>{let a=P("img");return a.src=r,a.alt="",a.setAttribute("aria-hidden","true"),a},TS=()=>{let r=o.features?.history?.rail?.brand;if(!r)return;let a=!1,p;return f=>{if(r.render)try{return r.render({collapsed:f})??null}catch(h){return a||(a=!0,console.warn("[persona] history rail brand threw",h)),null}return p===void 0&&(r.iconUrl?p=mh(r.iconUrl):p=r.icon?de(r.icon,20):null),p?p.cloneNode(!0):null}},ES=()=>o.features?.history?.rail?.sections?.map(r=>{let a=!1,p=f=>{a||(a=!0,console.warn("[persona] history rail section threw",r.id,f))};return{id:r.id,title:r.title,placement:r.placement??"above-conversations",items:r.items.map(f=>{let h;return{id:f.id,label:f.label,badge:f.badge,iconNode:()=>{if(h!==void 0)return h;try{f.renderIcon?h=f.renderIcon()??null:f.iconUrl?h=mh(f.iconUrl):h=f.icon?de(f.icon,20):null}catch(v){p(v),h=null}return h},onSelect:()=>{try{f.onSelect()}catch(v){p(v)}}}})}})??[],PS=r=>{let a=ES();for(let p of r)a.some(f=>f.id===p.id)?console.warn("[persona] duplicate history rail section id",p.id):a.push(p);return a.length?a:void 0},ga=null,hh=()=>`${Se()}rail-collapsed`,eu=()=>{if(ga===null&&(ga=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let r=window.localStorage.getItem(hh());r&&(ga=r==="1")}catch{}return ga},tu=r=>{if(ga=r,o.persistState!==!1)try{window.localStorage.setItem(hh(),r?"1":"0")}catch{}},fa=()=>Ot==="rail"&&Zl()&&!ec()&&eu(),nu=()=>{},yh=()=>{if(ec()){nu();return}tu(!eu()),rt?.view.setCollapsed(fa()),Do(),An()},ou=()=>{let r=o.features?.history?.rail?.collapseShortcut;return!r||!Sd(r)?null:{combo:r,hint:Ad(r),aria:Xa(r)}},bh=()=>{y.forEach(a=>a()),y=[];let r=ou();r&&y.push(m.register({id:"history-rail-collapse",combo:r.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>Tt&&Ot==="rail"&&Zl()||ci(),run:()=>ec()?nu():yh()}));for(let a of o.layout?.header?.trailingActions??[])a.shortcut&&y.push(m.register({id:`header-action-${a.id}`,combo:a.shortcut,run:()=>{let p=t.querySelector(`[data-persona-header-action="${a.id}"]`);p?p.click():o.layout?.header?.onAction?.(a.id)}}));for(let a of u)for(let p of a.shortcuts??[])y.push(m.register({...p,id:`${a.id}:${p.id}`}))};bh();let kS=300,tc="var(--persona-history-overlay-margin,8px)",Gn=null,Ko=null,nc=0,Go=null,li=null,hs=!1,ru=0,vh=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,ci=()=>Mo()&&ec()&&(Ot??Gp())==="rail",LS=()=>Tt&&!Ft,ma=()=>{li!==null&&clearTimeout(li),li=null},IS=()=>{Mf().catch(()=>{})},Ch=()=>{ma(),Ft&&(li=setTimeout(()=>{li=null,!(hs||!Ft)&&(Go?.contains(document.activeElement)||Mn({restoreFocus:!1}))},kS))},HS=(r,a)=>{let p=Go?.getBoundingClientRect();if(!p)return!1;let f=Gn?.getBoundingClientRect(),h=f?Math.min(f.top,p.top):p.top;return r>=p.left&&r<=p.right&&a>=h&&a<=p.bottom||!!f&&r>=f.left&&r<=f.right&&a>=f.top&&a<=f.bottom},su=r=>{Ft&&(hs=HS(r.clientX,r.clientY),hs?ma():li===null&&Ch())},wh=r=>{Tt||!ci()||(Ft=!0,ya({invoker:Gn,keyboard:r?.keyboard===!0}).then(()=>{Tt?!hs&&document.activeElement!==Gn&&Mn():Ft=!1}))},xh=()=>{let r=ca?.querySelector('[data-persona-history-focus="collapse"]');r&&(r.setAttribute("aria-label",Ft?Ye.expandLabel:Ye.collapseLabel),r.setAttribute("aria-expanded",Ft?"false":"true"))},Sh=()=>{tu(!1);let r=rt;if(!Ft||!r){ya({invoker:Gn});return}let a=document.activeElement===Gn;Ft=!1,oc(),r.element.remove(),au(r.element),xh(),a&&sc(),An(),Tr()},RS=()=>{tu(!0),Mn()};nu=()=>{!Tt||Ft?Sh():RS()};let WS=()=>{let r=ou(),a=Hs({ariaLabel:Ye.expandLabel,iconName:"panel-left",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-rail-trigger",tooltip:!1,attrs:{"data-persona-rail-trigger":"","aria-controls":zp,...r?{"aria-keyshortcuts":r.aria}:{}}}),p=a.button;p.addEventListener("mouseenter",()=>{hs=!0,ma(),!(vh()||Date.now()<ru)&&wh()}),p.addEventListener("mouseleave",()=>{hs=!1,ru=0,Ch()}),p.addEventListener("focus",()=>{Tt||IS()}),p.addEventListener("click",f=>{Mo()&&(f.detail!==0&&vh()&&!Tt?wh():Sh())}),Gn=p,Ko=a.wrapper},ha=()=>{if(Ko&&!Ko.isConnected&&(Ko=null,Gn=null),!ci()){Ko?.remove(),Ko=null,Gn=null;return}Gn||WS();let r=Ko,a=Gn;if(!r||!a)return;let p=ai()!=="right"?Me.firstChild:null;(p??Me.lastChild)!==r&&Me.insertBefore(r,p),r.style.display=LS()||nc>0?"none":"",a.setAttribute("aria-label",Ye.expandLabel),a.setAttribute("aria-expanded",Tt?"true":"false"),Go&&Do()},Ah=r=>{if(!Ft)return;let a=r.target;a instanceof Node&&(Go?.contains(a)||Ko?.contains(a)||a instanceof Element&&a.closest('.persona-dropdown-menu,[role="alertdialog"]')||Mn({restoreFocus:!1}))};document.addEventListener("pointerdown",Ah,!0),fe.push(()=>{document.removeEventListener("pointerdown",Ah,!0),document.removeEventListener("pointermove",su),di?.(),ma()});let iu=null,di=null,Mh=16,Th=r=>{MS(Zp(r)),Do(),An()},BS=()=>{let r=P("div","persona-rail-resizer");return r.tabIndex=0,r.setAttribute("role","separator"),r.setAttribute("aria-orientation","vertical"),r.setAttribute("aria-valuemin",String(Xp)),r.setAttribute("aria-valuemax",String(Jp)),r.addEventListener("pointerdown",a=>{let p=ms;if(!p||a.button!==0)return;a.preventDefault(),di?.();let f=a.clientX,h=p.getBoundingClientRect().width||ua(),v=ai()==="right"?-1:1,B=h,q=t.ownerDocument;p.style.transition="none";let U=Q=>{B=Zp(h+v*(Q.clientX-f)),p.style.flex=`0 0 ${B}px`,r.setAttribute("aria-valuenow",String(B))},z=()=>{di=null,q.removeEventListener("pointermove",U),q.removeEventListener("pointerup",z),q.removeEventListener("pointercancel",z),p.style.removeProperty("transition");try{r.releasePointerCapture(a.pointerId)}catch{}Th(B)};di=z,q.addEventListener("pointermove",U),q.addEventListener("pointerup",z),q.addEventListener("pointercancel",z);try{r.setPointerCapture(a.pointerId)}catch{}}),r.addEventListener("keydown",a=>{let p=ai()==="right"?-Mh:Mh,f=ua(),h=a.key==="ArrowRight"?f+p:a.key==="ArrowLeft"?f-p:a.key==="Home"?Xp:a.key==="End"?Jp:null;h!==null&&(a.preventDefault(),Th(h))}),r},DS=(r,a)=>{if(!SS()||fa()){di?.(),iu?.remove();return}let p=iu??BS();iu=p,p.setAttribute("aria-label",Ye.resizeLabel),p.setAttribute("aria-valuenow",String(ua())),p.nextElementSibling!==a&&r.insertBefore(p,a)};Do=()=>{rt?.view.setRailSide(ai());let r=ai()==="right",a=Go;if(a){let q=Gn?Gn.getBoundingClientRect().bottom-ce.getBoundingClientRect().top:0;a.style.top=`calc(${Math.max(0,Math.round(q))}px + ${tc})`,a.style.width=`${ua()}px`,a.style.left=r?"":tc,a.style.right=r?tc:""}let p=ms,f=si,h=da;if(!p||!f||!h)return;p.style.flex=`0 0 ${fa()?xS:ua()}px`;let v="1px solid var(--persona-divider,#e5e7eb)";p.style.borderRight=r?"":v,p.style.borderLeft=r?v:"";let B=r?h:p;f.firstElementChild!==B&&f.append(B,r?p:h),DS(f,r?p:h)};let Eh=r=>{if(ii&&ms){ii.replaceWith(r),ii=null,Do();return}let a=P("div","persona-history-rail-shell");a.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let p=P("div","persona-history-rail-conversation");p.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let f=P("div","persona-history-rail-host");f.style.cssText="display:flex;min-height:0;overflow:hidden",ce.insertBefore(a,Me.parentNode===ce?Me:ee);for(let h of fh())h?.parentNode===ce&&p.appendChild(h);a.append(f,p),f.appendChild(r),si=a,ms=f,da=p,Do()},_S=()=>{if(si)return;let r=P("div","persona-history-rail-placeholder");r.style.cssText="flex:1 1 auto;min-height:0",ii=r,Eh(r),An()},Ph=()=>{ii&&(oc(),An())},OS=r=>{let a=P("div","persona-history-rail-overlay");a.style.cssText=`position:absolute;bottom:${tc};display:flex;overflow:hidden;z-index:${Pc-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,ce.style.position="relative",ce.appendChild(a),a.appendChild(r),document.addEventListener("pointermove",su),Go=a,Do(),xh()},oc=()=>{Jl?.(),Go&&(hs&&(ru=Date.now()+150),document.removeEventListener("pointermove",su),Go.remove(),Go=null);let r=si;if(r){di?.();for(let a of fh())a&&r.contains(a)&&ce.insertBefore(a,r);r.remove(),si=null,ms=null,da=null,ii=null}},kh=r=>{ca=r,r.id=zp,r.style.flex="1 1 auto",r.style.minHeight="0"},au=r=>{kh(r),(Ot!=="rail"||Ft)&&Ph(),Ot!=="rail"?wS(r):Ft?OS(r):Eh(r)},rc=()=>{if(ha(),Fh(),!Tt||!rt)return;let r=Gp();if(r===Ot)return;let a=document.activeElement,p=a instanceof HTMLElement&&(rt.element.contains(a)||On?.contains(a)===!0)?a:null;oc(),rt.element.remove(),rt.view.setHeaderPlacement("inline"),Ot=r,rt.view.setPresentation(r),rt.view.setCollapsed(fa()),rt.requestRender(),rt.element.isConnected||au(rt.element),p?.isConnected?p.focus():sc(),qt(),An(),Tr()},Lh=(r,a)=>On?.querySelector(a)??r.querySelector(a),sc=()=>{let r=rt?.element??ca;if(!r)return;let a=Lh(r,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(a){a.focus();return}let p=Lh(r,".persona-history-title")??r;p.tabIndex=-1,p.focus()},ya=async r=>{if(!Mo()||Tt)return;let a=_n;if(!a)return;if(!Ft&&ci()&&eu()){ha();return}ic();let p=++la;jl=r?.returnSurface??"conversation",$p=r?.invoker??dn;let f=ci()&&!Ft;f&&(nc+=1,ha(),_S());let h;try{h=await Mf()}catch{Yl(Ye.openHistoryLabel),f&&(nc-=1,p===la&&(Ph(),ha()));return}if(f&&(nc-=1),p!==la||Tt)return;zl={scope:Kp()},Ot=Gp(),Tt=!0;let v=Ot==="panel"&&o.layout?.showHeader!==!1&&Me.style.display!=="none"?"external":"inline",B=o.features?.history?.rowAvatar,q=ou(),U=q?{hint:q.hint,aria:q.aria}:null,z={provider:a,context:zl,targetId:ih(),presentation:Ot,collapsible:Zl(),collapsed:fa(),railSide:ai(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:TS(),onToggleCollapse:yh,...U?{collapseShortcut:U}:{},headerPlacement:v,showScopeStatus:o.features?.history?.showScopeStatus!==!1,showDelete:o.features?.history?.showDelete!==!1,showDeleteAll:o.features?.history?.showDeleteAll!==!1,...o.features?.history?.listActions?.length?{listActions:o.features.history.listActions}:{},rowAvatar:B===!1?!1:typeof B=="string"?B:o.launcher?.iconUrl,activeConversationId:A.getActiveConversationId(),...o.features?.history?.grouping?{grouping:o.features.history.grouping}:{},...o.features?.history?.copy?{copy:o.features.history.copy}:{},...o.features?.history?.pageSize!==void 0?{pageSize:o.features.history.pageSize}:{},onSelect:Q=>cu(Q,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:Q=>ys(Q),attachTooltip:tn,onStartNew:()=>du({focusComposer:!0}),onClose:()=>Mn(),onRequestDeleteConversation:Q=>Nh(Q),onRequestClearHistory:()=>qS(),...a.resetDevice?{onRequestResetIdentity:()=>zS()}:{}};rt=Bw({plugins:u,config:o,getPresentation:()=>Ot??"panel",getReturnSurface:()=>jl,close:()=>Mn(),createView:({slots:Q,renderDom:re,onModelChange:ue,railSections:Ne})=>(fs=h.createHistoryView({...z,railSections:PS(Ne),slots:Q,renderDom:re,onModelChange:ue,onAnnounce:Yl}),fs),onElementChanged:(Q,re)=>{if(!re?.isConnected)return au(Q);kh(Q),re.replaceWith(Q),Yp()}}),rt.view.setNewConversationRequired(Kl.recovery==="new_conversation_required"),r?.focus!==!1&&(Ot!=="rail"||r?.keyboard===!0)&&sc(),qt(),An(),Tr(),ne.emit("history:opened",{presentation:Ot,returnSurface:jl,timestamp:Date.now()})},ic=()=>{},Mn=r=>{if(!Tt)return;la+=1;let a=jl,p=$p,f=rt,h=r?.restoreFocus!==!1;Tt=!1;let v=!1,B=null,q=()=>{if(!v){if(v=!0,ic=()=>{},B!==null&&clearTimeout(B),Ft=!1,ma(),oc(),f?.dispose(),f?.view.destroy(),f?.element.remove(),rt===f&&(rt=null,fs=null,ca=null,Ot=null,zl=null,$p=null),qt(),An(),Tr(),h){let z=p??dn;z?.isConnected?z.focus():ds()}ne.emit("history:closed",{returnSurface:a,timestamp:Date.now()})}},U=f&&f.element===f.view.element?f.view.playExit():null;if(!U){q();return}ic=q,B=setTimeout(q,fS),U.then(q)},Ih=r=>{if(!(r.key!=="Escape"||!Tt||!rt)){if(Ot==="rail"){let a=r.target;if(!(a instanceof Node)||!(rt.element.contains(a)||Ft&&Ko?.contains(a)===!0))return}r.preventDefault(),r.stopPropagation(),Mn()}};ce.addEventListener("keydown",Ih),fe.push(()=>ce.removeEventListener("keydown",Ih));let ac=null,Hh=!1,ba=()=>{if(!ur)return;let r=o.layout?.header?.titleSource==="conversation",a=r&&ac?.trim()||null;ur.textContent=a??o.launcher?.title??"Chat Assistant";let p=ur.closest(".persona-combo-btn");if(!p)return;let f=!r||A.getActiveConversationId()!==null;p.setAttribute("data-persona-menu-locked",f?"false":"true"),p.setAttribute("aria-haspopup",f?"true":"false"),f||p.setAttribute("aria-expanded","false"),p.style.cursor=f?"pointer":"default";let h=p.querySelector("svg");h&&(h.style.display=f?"":"none")},NS=r=>{r!==ac&&(ac=r,ba())},ys=r=>{Hh=r?.starred===!0,NS(r&&r.title.trim()||null),ba()};ba(),ce.addEventListener("persona:title-menu-builtin",r=>{let a=r.detail?.actionId,p=A.getActiveConversationId();p&&(a==="delete"?Nh(p):a==="star"&&A.canUpdateConversations()&&pu(p,{starred:!Hh}).catch(()=>{}))});let lc=0,FS=250,cc=null,dc=()=>{cc&&clearTimeout(cc),cc=null};fe.push(dc);let Rh=()=>{dc();let r=ps;r&&(aa=!0,r.hidden=!1,ye.style.display="none",ti())},pc=()=>{lc+=1,dc(),ps&&(ps.remove(),ps=null,aa=!1,ye.style.removeProperty("display"),Kn(ke,!1),ti())},US=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;ye.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},lu=(r,a)=>G("div",{className:Nn("persona-conversation-loading-bubble",a&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:r}}),Wh=()=>G("div",{className:"persona-conversation-loading-body"},lu("58%",!1),lu("72%",!0),lu("44%",!1)),Bh=r=>{ps?.remove(),ps=r,r.hidden=!aa,ee.insertBefore(r,ye),dc(),aa||(cc=setTimeout(Rh,FS)),Kn(ke,!0)},$S=()=>{let r={config:o,streaming:!1,location:"conversation-open",defaultRenderer:Wh},a=null,p=u.find(f=>f.renderLoadingIndicator);p?.renderLoadingIndicator&&(a=p.renderLoadingIndicator(r)),a===null&&o.loadingIndicator?.render&&(a=o.loadingIndicator.render(r)),Bh(G("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Ye.openConversationLoadingLabel}},a??Wh()))},VS=r=>{let a=()=>{cu(r,{focusComposer:!0}).catch(()=>{})},p=Mo()?()=>{pc(),ya()}:void 0,f=(q,U)=>{let z=G("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:q});return z.addEventListener("click",U),z},h=()=>G("div",{className:"persona-conversation-loading-error-body"},G("p",{className:"persona-conversation-loading-error-title",text:Ye.openConversationErrorTitle}),G("div",{className:"persona-conversation-loading-error-actions"},f(Ye.openConversationRetryLabel,a),p?f(Ye.openConversationBackLabel,p):null)),v=Object.freeze({conversationId:r,config:o,copy:Object.freeze({title:Ye.openConversationErrorTitle,retryLabel:Ye.openConversationRetryLabel,backLabel:Ye.openConversationBackLabel}),retry:a,...p?{back:p}:{},defaultRenderer:h}),B=null;for(let q of u)if(q.renderHistoryOpenError){try{B=q.renderHistoryOpenError(v)}catch(U){console.warn("[persona] renderHistoryOpenError threw",U),B=null}if(B)break}Bh(G("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},B??h())),Rh()};ne.on("history:closed",()=>{ps&&Kn(ke,!0)});let cu=async(r,{focusComposer:a=!1}={})=>{let p=ri(),f=!!rt;rt?.view.setActiveConversationId(r),pc();let h=lc;$S(),Tt&&(Ot==="panel"||Ft)&&Mn({restoreFocus:!1}),Ks=!0;try{await A.openConversation(r,{scope:p})}catch(v){throw h===lc&&VS(r),v}finally{Ks=!1}h===lc&&(pc(),Dt.clear(),co(),Sn(),xp()||Bl(),US(),Qo(),f||ys(null),ne.emit("history:conversationOpened",{conversationId:r,title:ac,scope:p,timestamp:Date.now()}),a&&ds())},du=async({focusComposer:r=!1}={})=>{pc(),await A.startNewConversation({scope:ri()}),ys(null),Dt.clear(),co(),Sn(),Bl(),Qo();let a=A.getActiveConversationId();rt?.view.setActiveConversationId(a),ne.emit("history:conversationStarted",{conversationId:a,timestamp:Date.now()}),Tt&&(Ot==="panel"||Ft)&&Mn({restoreFocus:!1}),r&&ds()},pu=async(r,a)=>{let p=await A.updateConversation(r,{...a,...a.title!==void 0?{title:a.title.trim()}:{}});return rt?.view.applyConversationSummary(p),!rt&&r===A.getActiveConversationId()&&ys(p),p},Dh=async r=>{let a=ri(),p=A.getActiveConversationId()===r;await A.deleteConversation(r,{scope:a}),rt?.view.removeConversationSummary(r),p&&(ys(null),Dt.clear(),co(),Sn(),Qo()),ne.emit("history:conversationDeleted",{conversationId:r,scope:a,wasActive:p,timestamp:Date.now()})},_h=async r=>{let a=r?.scope??ri(),p=r?.allTargets?null:r?.targetId??ih(),f=await A.clearConversationHistory({...p?{targetId:p}:{},scope:a});return ys(null),Dt.clear(),co(),Sn(),Qo(),ne.emit("history:cleared",{deleted:f.deleted,scope:a,targetId:p,timestamp:Date.now()}),f},Oh=async()=>{if(!_n?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let r=!1;try{r=(await A.resetHistoryDevice()).remoteRevocationConfirmed}finally{ys(null),A.clearArtifacts(),Dt.clear(),_p=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),k={},he.syncFromMetadata(),T?.clear&&Hl(()=>T.clear(),"[AgentWidget] Failed to clear storage adapter:"),co(),Sn(),Qo(),Mn({restoreFocus:!1}),ds(),Pe||Pt?.launcher.element.focus()}return Yl(r?Ye.identityResetNotice:Ye.identityResetUnconfirmedNotice),ne.emit("history:identityReset",{remoteRevocationConfirmed:r,timestamp:Date.now()}),{remoteRevocationConfirmed:r}},uu=()=>Co?we:ce,Nh=async r=>await Od({host:uu(),title:Ye.deleteConversationConfirmTitle,description:Ye.deleteConversationConfirm,confirmLabel:Ye.deleteConversationConfirmLabel,cancelLabel:Ye.confirmCancelLabel})?(await Dh(r),"deleted"):"cancelled",qS=async()=>{let r=ri()==="verified-user";return await Od({host:uu(),title:Ye.clearHistoryConfirmTitle,description:r?Ye.clearHistoryVerifiedConfirm:Ye.clearHistoryConfirm,confirmLabel:Ye.clearHistoryConfirmLabel,cancelLabel:Ye.confirmCancelLabel})?(await _h(),"cleared"):"cancelled"},zS=async()=>{if(!await Od({host:uu(),title:Ye.resetIdentityConfirmTitle,description:Ye.resetIdentityConfirm,confirmLabel:Ye.resetIdentityConfirmLabel,cancelLabel:Ye.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:a}=await Oh();return{outcome:"reset",remoteRevocationConfirmed:a}},Qn=P("button","persona-history-earlier");Qn.type="button",Qn.textContent=Ye.showEarlierMessagesLabel,Qn.setAttribute("data-persona-history-earlier",""),Object.assign(Qn.style,{alignSelf:"center",minHeight:"44px",padding:"0 16px",borderRadius:"999px",border:"1px solid var(--persona-border, rgba(0,0,0,0.12))",background:"transparent",color:"inherit",font:"inherit",cursor:"pointer",flexShrink:"0"});let Qo=()=>{if(!(Mo()&&!!Kl.nextMessageCursor&&!!A.getActiveConversationId())){Qn.remove();return}Qn.textContent=Ye.showEarlierMessagesLabel,Qn.parentNode!==ee&&ee.insertBefore(Qn,ee.firstChild)};Qn.addEventListener("click",()=>{let r=A.getActiveConversationId(),a=Kl.nextMessageCursor;if(!r||!a||Qn.disabled)return;Qn.disabled=!0;let p=ee.scrollHeight,f=ee.scrollTop;A.loadOlderMessages(r,a,{scope:ri()}).then(()=>{ee.scrollTop=f+(ee.scrollHeight-p),An()}).catch(()=>{}).finally(()=>{Qn.disabled=!1,Qo()})});let jS=()=>{let r=Hs({ariaLabel:Ye.openHistoryLabel,iconName:"history",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-history-toggle",attrs:{"data-persona-history-toggle":""}});return r.button.addEventListener("click",a=>{if(!(!Mo()||sh())){if(Tt){Mn();return}ya({invoker:r.button,keyboard:a.detail===0})}}),r},Fh=()=>{if(!Mo()){Ao?.remove(),dn=null,Ao=null;return}if(Ao&&!Ao.isConnected&&(dn=null,Ao=null),!dn&&Me){let f=jS();dn=f.button,Ao=f.wrapper;let h=De.clearChatButtonWrapper||De.closeButtonWrapper;h?.parentNode&&Me.contains(h)?h.parentNode.insertBefore(Ao,h):Me.appendChild(Ao)}if(!dn||!Ao)return;let r=ci()||Tt&&Ot==="rail";if(Ao.style.display=r?"none":"",r){document.activeElement===dn&&sc();return}let a=sh();dn.disabled=a,dn.setAttribute("aria-disabled",a?"true":"false");let p=a?Ye.openHistoryBusyLabel:Ye.openHistoryLabel;dn.setAttribute("aria-label",p),(o.features?.history?.presentation??"panel")==="panel"?(dn.removeAttribute("aria-expanded"),dn.removeAttribute("aria-controls")):(dn.setAttribute("aria-expanded",Tt?"true":"false"),dn.setAttribute("aria-controls",zp))},uc=!1,KS=()=>{let r=De.clearChatButton;if(r){if(Mo()){uc||(qp=r.getAttribute("aria-label")??"",uc=!0),r.setAttribute("aria-label",Ye.newConversationLabel),r.removeAttribute("title");return}uc&&(uc=!1,qp&&r.setAttribute("aria-label",qp))}},Tr=()=>{Ye=_u(o.features?.history?.copy),Fh(),ha(),KS(),Qo()};qd=Tr,_f=r=>{Kl=r,rt?.view.setNewConversationRequired(r.recovery==="new_conversation_required"),ia(r.sendBlocked||Wn),Qo()},Of=r=>{(r.code==="history_continuity_reset"||r.code==="conversation_deleted_recovered")&&(Dt.clear(),co(),Sn()),Yl(r.message),rt?.view.refresh()},dh(),Tr(),fe.push(()=>{Gl?.(),Ql?.(),la+=1,ic(),rt?.dispose(),rt?.view.destroy(),rt=null}),o.clientToken&&(o.features?.history?.enabled===!0||o.sessionInit==="mount")&&A.initClientSession().then(()=>{if(Mo())return A.reconcileBootConversation({scope:Kp()})}).then(()=>{Qo()}).catch(r=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",r)});let gu=()=>A.warmClientSession(),Uh=r=>{let a=o.sessionInit??"input",p=Je?.input??ae,f=r.target;p&&(r.type==="input"?(a==="input"||a==="focus")&&f===p&&r.inputType&&p.value.trim():a==="focus"&&(r.type==="keyup"?f===p&&r.key==="Tab":(Je?.form??vn)?.contains(f)))&&gu()},$h=["input","pointerdown","keyup"];$h.forEach(r=>t.addEventListener(r,Uh));let Vh,fu,qh=()=>{let r=fu;fu=void 0;try{typeof r=="function"&&r()}catch{}},zh=()=>{let r=o.clientToken&&typeof o.sessionInit=="function"?o.sessionInit:void 0;if(r!==Vh){qh(),Vh=r;try{fu=r?.({warm:gu,mount:t})}catch{}}};zh(),fe.push(()=>{$h.forEach(r=>t.removeEventListener(r,Uh)),qh()}),(Y||o.onSSEEvent)&&A.setSSEEventCallback((r,a)=>{o.onSSEEvent?.(r,a),$d(r,a)});let jh=()=>{let r=o.resume??(_?zo.getStoredResumableHandle?.():null);r&&typeof o.reconnectStream=="function"&&A.resumeFromHandle(r)};Z?Z.then(r=>{if(r){if(r.metadata&&(k=kf(r.metadata),he.syncFromMetadata()),r.messages?.length){Ks=!0;try{A.hydrateMessages(r.messages)}finally{Ks=!1}Nl()}r.artifacts?.length&&A.hydrateArtifacts(r.artifacts,r.selectedArtifactId??null),_m(r.draft)}}).catch(r=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",r)}).finally(()=>{kp=!0,F(),jh()}):(_m(le),jh());let GS=()=>{!Be()||Pe||!(o.launcher?.composerBar?.expandOnSubmit??!0)||gt(!0,"auto")},QS=(r,a)=>r?a?{refs:[...r.refs,...a.refs],finalize:async()=>{let[p,f]=await Promise.allSettled([r.finalize(),a.finalize()]),h=[];return p.status==="fulfilled"?h.push(p.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",p.reason),f.status==="fulfilled"?h.push(f.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",f.reason),lP(h)}}:r:a,mu=()=>{let a=ae.getInlineMessageFields?.();return a&&a.contentSegments.some(f=>f.kind==="mention")?a.contentSegments:void 0},Yo=!1,bs=null,gc=()=>{ae.value="",ae.style.height="auto",yo(),Ca()},hu="data-persona-composer-notice",pi=null;function YS(r){gl(r),!(Be()||!Qe)&&(Qe.hasAttribute(Oi)||(Qe.setAttribute(hu,""),Qe.setAttribute("role","status"),Qe.setAttribute("aria-live","polite"),Qe.textContent=r,Ps(Qe,o.statusIndicator??{},"idle"),pi&&clearTimeout(pi),pi=setTimeout(()=>{if(pi=null,!!Qe?.hasAttribute(hu)&&(Qe.removeAttribute(hu),Qe.removeAttribute("role"),Qe.removeAttribute("aria-live"),b)){let a=A.getStatus();Fi(Qe,zd(a),o.statusIndicator??{},a)}},4e3)))}function XS(){let r=be.getState().pendingSubmission;r&&(Fs(void 0),ae&&(ae.value=r.text,ae.dispatchEvent(new Event("input",{bubbles:!0})),yo()),r.options.selectedModelId&&(be.setSelectedModelId(r.options.selectedModelId),fr?.repaint()),r.options.activeModeIds?.length&&yl(r.options.activeModeIds),r.options.quote&&bo(r.options.quote),ae?.focus())}let JS=r=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",r)},Kh=(r={})=>{let a=(r.overrideText??ae?.value??"").trim();return r.resolveInlineCommand&&a?(Bt?.takeInlineCommand(a)??Promise.resolve(null)).then(p=>Gh(r,a,p)):Gh(r,a,null)},Gh=(r,a,p)=>{if(p?.kind==="action"){gc(),Bt?.clear(),Kr();return}let f=p?.kind==="server"?p.mentions:null,h=p?.kind==="prompt"?p.sendText:a,v=r.pending?.contentParts,B=(tt?.hasAttachments()??!1)||(v?.length??0)>0;if(!dC({text:h,hasAttachments:B,attachmentsReady:tt?.isReady()??!0,hasMentions:Bt?.hasMentions()??!1,hasServerMentions:!!f,inputDisabled:So(),sendDisabled:cs()}))return;let q=A.isStreaming()?ep():"block";if(q==="defer-one"&&!r.pending){if(be.getState().pendingSubmission){YS("One message is already queued. Edit or remove it first.");return}ZS({intent:r,sendText:h,serverMentions:f});return}let U={text:h,mentionRefs:[...Bt?.getMentionRefs()??[],...f?.refs??[]],contentSegments:p?.kind==="prompt"?void 0:mu(),options:{...be.getState().selectedModelId&&{selectedModelId:be.getState().selectedModelId},...be.getState().activeModeIds.length>0&&{activeModeIds:[...be.getState().activeModeIds]},...be.getState().quote&&{quote:{...be.getState().quote}}},viaVoice:r.viaVoice};r.pending&&(U.options={...r.pending.options},U.contentSegments=r.pending.contentSegments,U.mentionRefs=[...r.pending.mentionRefs],U.viaVoice=r.pending.viaVoice);let z=()=>{if(v?.length)return[...v];if(!tt?.hasAttachments())return;let Ze=[...tt.getContentParts()];return U.text&&Ze.push(Io(U.text)),Ze};U.contentParts=z();let Q=()=>{os(),GS();let Ze=Bt?.collectForSubmit()??null,Tn=QS(Ze,f),bt=z();r.consumeDraft!==!1&&gc();let At={selectedModelId:U.options.selectedModelId,activeModeIds:U.options.activeModeIds},un=q==="interrupt";un&&A.cancel(),A.sendMessage(U.text,{contentParts:bt,mentions:Tn??void 0,contentSegments:U.contentSegments,viaVoice:U.viaVoice,composerOptions:At,...U.options.quote&&{quote:U.options.quote},...un&&{interrupt:!0}}),tt?.hasAttachments()&&tt.clearAttachments(),Ze&&Bt?.clear(),Kr();let Lt=be.getState().activeModeIds,at=Xv(Lt,o.composer?.modes);at.length!==Lt.length&&yl(at),be.getState().quote&&bo(void 0),Wl(),sp.release(),so()},re=o.composer?.onBeforeSend;if(!re){Q();return}let ue=new AbortController;bs=ue;let Ne=Ze=>{if(bs=null,Ze.status==="error"){JS(Ze.error);return}Ze.status==="proceed"&&Q()},nt=pC(re,U,ue.signal);if(!(nt instanceof Promise)){Ne(nt);return}return be.setPreparing(!0),nt.then(Ne).finally(()=>be.setPreparing(!1))};function ZS(r){let a=be.getState(),p=tt?.hasAttachments()??!1,f=p?[...tt.getContentParts()]:[];p&&r.sendText&&f.push(Io(r.sendText));let h=Lg({text:r.sendText,contentParts:f.length?f:void 0,mentionRefs:[...Bt?.getMentionRefs()??[],...r.serverMentions?.refs??[]],contentSegments:mu(),options:{...a.selectedModelId&&{selectedModelId:a.selectedModelId},...a.activeModeIds.length>0&&{activeModeIds:[...a.activeModeIds]},...a.quote&&{quote:{...a.quote}}},viaVoice:r.intent.viaVoice});Fs(h),r.intent.consumeDraft!==!1&&gc(),p&&tt.clearAttachments(),Bt?.clear(),Kr(),a.quote&&bo(void 0),Wl(),sp.release(),so(),gl("Message queued. It sends when the response finishes.")}function eA(){let r=be.getState().pendingSubmission;r&&(Fs(void 0),mc(r.text,{consumeDraft:!1,pending:r}))}function tA(r){if(o.messageActions?.showEdit!==!0)return;let a=A.getMessages().find(p=>p.id===r);!a||!cg(a)||ns!==r&&(os(),ns=r,br=nC({messageId:r,initialText:a.content,onSave:p=>nA(r,p),onCancel:()=>os()}),Dt.delete(r),zn(ye,A.getMessages(),O),br.focus())}function nA(r,a){let p=br;if(ns=null,br=null,p?.destroy(),Dt.delete(r),!A.resubmitFrom(r,{reason:"edit",replacement:{text:a,mentionRefs:[],options:{}}})){zn(ye,A.getMessages(),O);return}An()}function oA(r){if(A.isStreaming())return;let a=lg(A.getMessages(),r);a&&(os(),A.resubmitFrom(a,{reason:"retry"})&&An())}bl={regenerate:oA,edit:tA,quote:r=>{let p=A.getMessages().find(f=>f.id===r)?.content?.trim();p&&(bo({text:p,messageId:r}),ae?.focus())}};let va=async r=>{if(!Yo){Yo=!0;try{await Kh({resolveInlineCommand:!0,...r})}finally{Yo=!1}}};function fc(r){cs()||(gc(),mc(r,{consumeDraft:!1}))}let mc=(r,a)=>{if(Yo)return;Yo=!0;let p=()=>{Yo=!1};try{let f=Kh({...a,overrideText:r});f instanceof Promise?f.finally(p):p()}catch(f){throw p(),f}},rA=r=>{if(r.preventDefault(),A.isStreaming()){A.cancel(),Gt?.reset(),ut?.update();return}Yo||va()},sA=()=>o.features?.composerHistory!==!1,yu={...Ng},bu=!1,Ca=()=>{yu={...Ng}},iA=()=>A.getMessages().filter(r=>r.role==="user").map(r=>r.content??"").filter(r=>r.length>0),aA=r=>{if(!ae)return;bu=!0,ae.value=r,ae.dispatchEvent(new Event("input",{bubbles:!0})),bu=!1;let a=ae.value.length;ae.setSelectionRange(a,a)},lA=r=>{bu||(r.isComposing||Bt?.handleInput(r.inputType??void 0),Ca())},cA=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:qa(ae)}),dA=r=>{if(ae&&!So()&&!(!r.isComposing&&Bt?.handleKeydown(r))){if(sA()&&(r.key==="ArrowUp"||r.key==="ArrowDown")&&!r.shiftKey&&!r.metaKey&&!r.ctrlKey&&!r.altKey&&!r.isComposing){let a=ae.selectionStart===0&&ae.selectionEnd===0,p=TC({direction:r.key==="ArrowUp"?"up":"down",history:iA(),currentValue:ae.value,atStart:a,state:yu});if(yu=p.state,p.handled){r.preventDefault(),p.value!==void 0&&aA(p.value);return}}if(Bv(r,cA())){if(A.isStreaming()){if(r.preventDefault(),ep()==="block"||Yo||cs())return;Ca(),va();return}if(Yo){r.preventDefault();return}if(cs()){r.preventDefault();return}Ca(),r.preventDefault(),Ae.click()}}},Qh=r=>{if(!(r.key!=="Escape"||r.isComposing)&&r.composedPath().includes(ce)){if(bs){bs.abort(),bs=null,r.preventDefault(),r.stopImmediatePropagation();return}A.isStreaming()&&(A.cancel(),Gt?.reset(),ut?.update(),Ca(),r.preventDefault(),r.stopImmediatePropagation())}},pA=async r=>{if(o.attachments?.enabled!==!0||!tt||So())return;let a=rP(r.clipboardData);a.length!==0&&(r.preventDefault(),await tt.handleFiles(a))},Yn=null,To=!1,ui=null,wt=null,vu=()=>o.voiceRecognition?.completionBehavior==="review";function vs(r){oe?.setAttribute("data-state",r),r==="recording"?gA():Su()}let Yh="--persona-voice-level",Cu=.5,gi=null,wu=-1,hc=0,Xh=()=>{let r=[],a=Hn??oe?.parentElement??null;return a&&r.push(a),ke&&r.push(ke),r},xu=r=>{let a=Math.round(Math.max(0,Math.min(1,r))*100)/100;if(a!==wu){wu=a;for(let p of Xh())p.style.setProperty(Yh,String(a))}},uA=()=>{wu=-1,hc=0;for(let r of Xh())r.style.removeProperty(Yh)};function gA(){if(gi!==null)return;if(typeof requestAnimationFrame!="function"){xu(b?A.getVoiceLevel()??Cu:Cu);return}let r=()=>{gi=requestAnimationFrame(r);let a=b?A.getVoiceLevel():null;if(a===null){xu(Cu);return}hc+=(a-hc)*.3,xu(hc)};gi=requestAnimationFrame(r)}function Su(){gi!==null&&(cancelAnimationFrame(gi),gi=null),uA()}let Jh=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,yc=(r="user")=>{if(To||A.isStreaming())return;let a=Jh();if(!a)return;Yn=new a;let p=o.voiceRecognition??{},f=p.pauseDuration??2e3;Yn.continuous=p.provider?.browser?.continuous??!0,Yn.interimResults=!0,Yn.lang=p.provider?.browser?.language??"en-US";let h=ae.value;Yn.onresult=v=>{let B="",q="";for(let z=0;z<v.results.length;z++){let Q=v.results[z],re=Q[0].transcript;Q.isFinal?B+=re+" ":q=re}let U=h+B+q;ae.value=U,yo(),ui&&clearTimeout(ui),(B||q)&&(ui=window.setTimeout(()=>{if(ae.value.trim()&&Yn&&To){if(Er(),vu())return;va({viaVoice:!0})}},f))},Yn.onerror=v=>{v.error!=="no-speech"&&Er()},Yn.onend=()=>{if(To){let v=ae.value.trim();!vu()&&v&&v!==h.trim()&&va({viaVoice:!0}),Er()}};try{if(Yn.start(),To=!0,Ke.active=!0,r!=="system"&&(Ke.manuallyDeactivated=!1),Vo(r),lo(),so(),oe){let v=o.voiceRecognition??{};wt={backgroundColor:oe.style.backgroundColor,color:oe.style.color,borderColor:oe.style.borderColor,iconName:v.iconName??"mic",iconSize:parseFloat(v.iconSize??"")||fn};let B=v.recordingBackgroundColor,q=v.recordingIconColor,U=v.recordingBorderColor;if(oe.classList.add("persona-voice-recording"),vs("recording"),oe.style.backgroundColor=B??"var(--persona-voice-recording-bg, #ef4444)",oe.style.color=q??"var(--persona-voice-recording-indicator, #ffffff)",q){let z=oe.querySelector("svg");z&&z.setAttribute("stroke",q)}U&&(oe.style.borderColor=U),oe.setAttribute("aria-label","Stop voice recognition")}}catch{Er("system")}},Er=(r="user")=>{if(To){if(To=!1,ui&&(clearTimeout(ui),ui=null),Yn){try{Yn.stop()}catch{}Yn=null}if(Ke.active=!1,Vo(r),lo(),so(),oe){if(oe.classList.remove("persona-voice-recording"),vs("idle"),wt){oe.style.backgroundColor=wt.backgroundColor,oe.style.color=wt.color,oe.style.borderColor=wt.borderColor;let a=oe.querySelector("svg");a&&a.setAttribute("stroke",wt.color||"currentColor"),wt=null}oe.setAttribute("aria-label","Start voice recognition")}}},Au=()=>{if(!oe||wt)return;let r=o.voiceRecognition??{};wt={backgroundColor:oe.style.backgroundColor,color:oe.style.color,borderColor:oe.style.borderColor,iconName:r.iconName??"mic",iconSize:parseFloat(r.iconSize??"")||fn}},Mu=(r,a)=>{if(!oe)return;let p=oe.querySelector("svg");p&&p.remove();let f=wt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??"")||fn),h=de(r,f,a,1.5);h&&oe.appendChild(h)},bc=()=>{oe&&oe.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},fi=()=>{if(!oe)return;Au();let r=o.voiceRecognition??{},a=r.recordingBackgroundColor,p=r.recordingIconColor,f=r.recordingBorderColor;if(bc(),oe.classList.add("persona-voice-recording"),vs("recording"),oe.style.backgroundColor=a??"var(--persona-voice-recording-bg, #ef4444)",oe.style.color=p??"var(--persona-voice-recording-indicator, #ffffff)",p){let h=oe.querySelector("svg");h&&h.setAttribute("stroke",p)}f&&(oe.style.borderColor=f),oe.setAttribute("aria-label","Stop voice recognition")},fA=()=>{if(!oe)return;Au();let r=o.voiceRecognition??{},a=A.getVoiceInterruptionMode(),p=r.processingIconName??"loader",f=r.processingIconColor??wt?.color??"",h=r.processingBackgroundColor??wt?.backgroundColor??"",v=r.processingBorderColor??wt?.borderColor??"";bc(),oe.classList.add("persona-voice-processing"),vs("processing"),oe.style.backgroundColor=h,oe.style.borderColor=v;let B=f||"currentColor";oe.style.color=B,Mu(p,B),oe.setAttribute("aria-label","Processing voice input"),a==="none"&&(oe.style.cursor="default")},mA=()=>{if(!oe)return;Au();let r=o.voiceRecognition??{},a=A.getVoiceInterruptionMode(),p=a==="cancel"?"square":a==="barge-in"?"mic":"volume-2",f=r.speakingIconName??p,h=r.speakingIconColor??(a==="barge-in"?r.recordingIconColor??wt?.color??"":wt?.color??""),v=r.speakingBackgroundColor??(a==="barge-in"?r.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":wt?.backgroundColor??""),B=r.speakingBorderColor??(a==="barge-in"?r.recordingBorderColor??"":wt?.borderColor??"");bc(),oe.classList.add("persona-voice-speaking"),vs("speaking"),oe.style.backgroundColor=v,oe.style.borderColor=B;let q=h||"currentColor";oe.style.color=q,Mu(f,q);let U=a==="cancel"?"Stop playback and re-record":a==="barge-in"?"Speak to interrupt":"Agent is speaking";oe.setAttribute("aria-label",U),a==="none"&&(oe.style.cursor="default"),a==="barge-in"&&oe.classList.add("persona-voice-recording")},Xo=()=>{oe&&(bc(),vs("idle"),wt&&(oe.style.backgroundColor=wt.backgroundColor??"",oe.style.color=wt.color??"",oe.style.borderColor=wt.borderColor??"",Mu(wt.iconName,wt.color||"currentColor"),wt=null),oe.style.cursor="",oe.setAttribute("aria-label","Start voice recognition"))},Tu=()=>{if(!So()){if(gn(o.voiceRecognition?.provider)){let r=A.getVoiceStatus(),a=A.getVoiceInterruptionMode();if(a==="none"&&(r==="processing"||r==="speaking"))return;if(a==="cancel"&&(r==="processing"||r==="speaking")){A.stopVoicePlayback();return}if(A.isBargeInActive()){A.stopVoicePlayback(),A.deactivateBargeIn().then(()=>{Ke.active=!1,Ke.manuallyDeactivated=!0,lo(),Vo("user"),Xo()});return}A.toggleVoice().then(()=>{Ke.active=A.isVoiceActive(),Ke.manuallyDeactivated=!A.isVoiceActive(),lo(),Vo("user"),A.isVoiceActive()?fi():Xo()});return}if(To){let r=ae.value.trim();Ke.manuallyDeactivated=!0,lo(),Er("user"),r&&!vu()&&va()}else Ke.manuallyDeactivated=!1,lo(),yc("user")}};tp=Tu;let Zh=()=>A.prewarmVoice(),ey=()=>{let r=o.voiceRecognition;return r?.enabled!==!0?!1:r.prewarm??(o.clientToken?"hover":!1)},ty=r=>{ey()==="hover"&&oe?.contains(r.target)&&Zh()},ny=["pointerover","pointerdown","focusin"];ny.forEach(r=>t.addEventListener(r,ty));let oy,ry=null,Eu,sy=()=>{let r=Eu;Eu=void 0;try{typeof r=="function"&&r()}catch{}},Pu=()=>{let r=ey(),a=typeof r=="function"&&oe?r:void 0,p=a?oe:null;if(!(a===oy&&p===ry)&&(sy(),oy=a,ry=p,!(!a||!p)))try{Eu=a({warm:Zh,micButton:p,mount:t})}catch{}};Pu(),fe.push(()=>{ny.forEach(r=>t.removeEventListener(r,ty)),sy()}),oe&&fe.push(()=>{gn(o.voiceRecognition?.provider)?(A.isVoiceActive()&&A.toggleVoice(),Xo()):Er("system")});let hA=ne.on("assistant:complete",()=>{be.getState().pendingSubmission&&setTimeout(()=>{A.isStreaming()||eA()},0)});fe.push(hA);let yA=ne.on("assistant:complete",()=>{Wm&&(Ke.active||Ke.manuallyDeactivated||Wm==="assistant"&&!Ke.lastUserMessageWasVoice||setTimeout(()=>{!Ke.active&&!Ke.manuallyDeactivated&&(gn(o.voiceRecognition?.provider)?A.toggleVoice().then(()=>{Ke.active=A.isVoiceActive(),Vo("auto"),A.isVoiceActive()&&fi()}):yc("auto"))},600))});fe.push(yA);let bA=ne.on("action:resubmit",()=>{setTimeout(()=>{A&&!A.isStreaming()&&A.continueConversation()},100)});fe.push(bA);let iy=()=>{gt(!Pe,"user")},Pt=null,pn=null;if(W&&!Be()){let{instance:r,element:a}=rf({config:o,plugins:u,onToggle:iy});Pt=r,r||(pn=a)}Pt?t.appendChild(Pt.element):pn&&t.appendChild(pn),sa(),es(),$l(),Wp(),ia(A.isStreaming()),xp()||(Rn()==="follow"?xr(!0):Bl()),_x(),Fe&&(!W||Be()?setTimeout(()=>ds(),0):Pe&&setTimeout(()=>ds(),200));let Pr=null,ay=()=>{Pr&&(Pr.disconnect(),Pr.observe(ke),Pr.observe(ce),Pr.observe(Yt))},ly=ji(),wa=()=>{if(Be()){jr(),sa();return}let r=xt(o),a=o.launcher?.sidebarMode??!1,p=t.ownerDocument.defaultView??window,f=o.launcher?.mobileFullscreen??!0,h=o.launcher?.mobileBreakpoint??640,v=p.innerWidth<=h,B=f&&v&&W;try{if(B){Gr(),Yi=Tl();return}let q=!1;kn&&(kn=!1,Gr(),q=!0);let U=Tl();if(!q&&U!==Yi&&(Gr(),q=!0),Yi=U,q&&xl(),!W&&!r){we.style.height="",we.style.width="";return}if(!a&&!r){let z=Ws(o);we.style.width=z.width,we.style.maxWidth=z.maxWidth}Ml(),bm()}finally{jr(),hl();let q=ji();if(q!==ly&&(ly=q,ti(),es()),sa(),Pe&&W){let z=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),Q=o.launcher?.sidebarMode??!1,re=o.launcher?.mobileFullscreen??!0,ue=xt(o)&&re&&z,Ne=Q||re&&z&&W||ue;if(Ne&&!xo){let nt=t.getRootNode(),Ze=nt instanceof ShadowRoot?nt.host:t.closest(".persona-host");Ze&&!wo&&(wo=Fg(Ze,o.launcher?.zIndex??ln)),xo=Ug(t.ownerDocument)}else Ne||(wo?.(),wo=null,xo?.(),xo=null)}}};wa();let vc=t.ownerDocument.defaultView??window;if(vc.addEventListener("resize",wa),fe.push(()=>vc.removeEventListener("resize",wa)),typeof ResizeObserver<"u"){Pr=new ResizeObserver(()=>{hl()}),ay(),fe.push(()=>{Pr?.disconnect(),Pr=null});let r=new ResizeObserver(()=>{rc()});r.observe(ce),fe.push(()=>r.disconnect())}vc.addEventListener("resize",rc),fe.push(()=>vc.removeEventListener("resize",rc)),Dn=ee.scrollTop;let cy=er(ee),dy=()=>{ym();let r=ee.scrollTop,a=er(ee),p=a<cy;if(cy=a,!gr()){Dn=r,qt();return}let{action:f,nextLastScrollTop:h}=nb({following:Bn.isFollowing(),currentScrollTop:r,lastScrollTop:Dn,nearBottom:As(ee,Uo),userScrollThreshold:Rx,isAutoScrolling:xn||Pl||p,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Dn=h,f==="resume"){Dl()||Sn();return}f==="pause"&&Js()};if(ee.addEventListener("scroll",dy,{passive:!0}),fe.push(()=>ee.removeEventListener("scroll",dy)),typeof ResizeObserver<"u"){let r=new ResizeObserver(()=>{qx(),Qu(ye)});r.observe(ye),r.observe(ee),fe.push(()=>r.disconnect())}let py=()=>{gr()&&Bn.isFollowing()&&Dl()&&Js()},uy=ee.ownerDocument;uy.addEventListener("selectionchange",py),fe.push(()=>{uy.removeEventListener("selectionchange",py)});let vA=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),gy=r=>{vA.has(r.key)&&(wr(),Ff()&&gr()&&Bn.isFollowing()&&Js())},fy=r=>{r.target?.closest("a, button, [tabindex], input, textarea, select")&&(wr(),Ff()&&gr()&&Bn.isFollowing()&&Js())};ee.addEventListener("keydown",gy),ee.addEventListener("focusin",fy),fe.push(()=>{ee.removeEventListener("keydown",gy),ee.removeEventListener("focusin",fy)});let my=r=>{if(r.deltaY!==0&&wr(),!gr())return;let a=ob({following:Bn.isFollowing(),deltaY:r.deltaY,nearBottom:As(ee,Uo),resumeWhenNearBottom:!0});a==="pause"?Js():a==="resume"&&!Dl()&&Sn()};ee.addEventListener("wheel",my,{passive:!0}),ee.addEventListener("touchmove",wr,{passive:!0}),ee.addEventListener("pointerdown",wr,{passive:!0}),fe.push(()=>{ee.removeEventListener("touchmove",wr),ee.removeEventListener("pointerdown",wr)}),fe.push(()=>ee.removeEventListener("wheel",my)),Nt.addEventListener("click",()=>{co(),ee.scrollTop=ee.scrollHeight,Dn=ee.scrollTop,Sn(),xr(!0),qt()}),fe.push(()=>Nt.remove()),fe.push(()=>{Nm(),co()});let hy=()=>{Ue&&(Jr&&(Ue.removeEventListener("click",Jr),Jr=null),Ge()?(Ue.style.display="",Jr=()=>{gt(!1,"user")},Ue.addEventListener("click",Jr)):Ue.style.display="none")};hy(),(()=>{let{clearChatButton:r}=De;r&&r.addEventListener("click",()=>{if(Mo()){du({focusComposer:!0}).catch(p=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",p)});return}A.clearMessages(),o.layout?.topFade&&(ee.scrollTop=0),ee.removeAttribute("data-persona-top-fade"),Dt.clear(),Sn(),Ti(De.composerOverlay);try{localStorage.removeItem(_i),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${_i}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==_i)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 a=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(a),T?.clear&&Hl(()=>T.clear(),"[AgentWidget] Failed to clear storage adapter:"),k={},he.syncFromMetadata(),tt?.clearAttachments(),Wl(),Fs(void 0),bo(void 0),os(),pt?.clear(),Gt?.reset(),ut?.update()})})();let yy=[["keydown",dA],["input",lA],["input",yo],["input",Kr],["keyup",Kr],["paste",pA],["focus",xx]],by=r=>{if(r)for(let[a,p]of yy)Je?.addListener(r,a,p)},CA=r=>{if(r)for(let[a,p]of yy)Je?.removeListener(r,a,p)},vy=()=>{Je&&(Je.addListener(Je.form,"submit",rA),Je.addListener(Je.footer,"click",Kr),by(ae),oe&&Je.addListener(oe,"click",Tu),Pu())};vy();let Cy=()=>{Bt?.onComposerSwap((r,a)=>{CA(a),ae=r,Je&&(Je.input=r),by(r),op(),Ep(),yo()})};Cy();let ku=!1;function wy(){if(!ku){ku=!0;try{let r=ae?.value??"",a=ke.ownerDocument??document,p=ae?a.activeElement===ae:!1;Su(),Je?.destroy(),Je=null,Bt?.destroy(),Bt=null;let f=null,h=()=>(f=Be()?Pd({config:o}):ol({config:o}),f.footer),v=Yf(h)??h();Ln.replaceComposer(v),ke=Ln.composer.footer;let B=f!==null&&v===f.footer;$s=!B,Nf=B?f.setSendButtonMode:()=>{},Qf(ke),Jf(ke),Zf(),em(),tm(),Cy(),nm(),rp(),om(),vy();let q=Xr.indexOf(Fo);if(Fo.destroy(),Fo=tl(pr),q>=0&&(Xr[q]=Fo),ae&&(ae.value=r),yo(),Kr(),$l(),es(),ia(A.isStreaming()),o.statusIndicator?.mode==="transient"&&!Be()){let U=A.getStatus();Fi(Qe,zd(U),o.statusIndicator,U)}Ke.active&&vs("recording"),Gr(),ay(),jr(),so(),Fl(),p&&ae?.focus()}finally{ku=!1}}}let xa=t.ownerDocument??document;xa.addEventListener("keydown",Qh,!0);let xy=()=>{bp()},Sy=()=>{xa.visibilityState==="hidden"&&bp()};typeof window<"u"&&(window.addEventListener("pagehide",xy),xa.addEventListener("visibilitychange",Sy),fe.push(()=>{window.removeEventListener("pagehide",xy),xa.removeEventListener("visibilitychange",Sy)}));let Ay="persona-attachment-drop-active",Sa=0,Lu=()=>{Sa=0,ce.classList.remove(Ay)},mi=()=>o.attachments?.enabled===!0&&tt!==null&&!So(),My=r=>{!Nd(r.dataTransfer)||!mi()||(Sa++,Sa===1&&ce.classList.add(Ay))},Ty=r=>{!Nd(r.dataTransfer)||!mi()||(Sa--,Sa<=0&&Lu())},Ey=r=>{!Nd(r.dataTransfer)||!mi()||(r.preventDefault(),r.dataTransfer.dropEffect="copy")},Py=r=>{if(!Nd(r.dataTransfer)||!mi())return;r.preventDefault(),r.stopPropagation(),Lu();let a=Array.from(r.dataTransfer.files??[]);a.length!==0&&tt.handleFiles(a)},kr=!0;ce.addEventListener("dragenter",My,kr),ce.addEventListener("dragleave",Ty,kr),t.addEventListener("dragover",Ey,kr),t.addEventListener("drop",Py,kr);let Cc=t.ownerDocument,ky=r=>{mi()&&r.preventDefault()},Ly=r=>{mi()&&r.preventDefault()};Cc.addEventListener("dragover",ky),Cc.addEventListener("drop",Ly),fe.push(()=>{Je?.destroy(),Je=null,Su(),vo?.destroy(),vo=null,Oo?.destroy(),Oo=null,mr?.destroy(),mr=null,hr?.destroy(),hr=null,fr=null,Zd=null,bp(),ea.destroy(),pi&&clearTimeout(pi),os(),bs?.abort(),bs=null,tt?.destroy(),tt=null,be.destroy(),xa.removeEventListener("keydown",Qh,!0),Bt?.destroy()}),fe.push(()=>{ce.removeEventListener("dragenter",My,kr),ce.removeEventListener("dragleave",Ty,kr),t.removeEventListener("dragover",Ey,kr),t.removeEventListener("drop",Py,kr),Cc.removeEventListener("dragover",ky),Cc.removeEventListener("drop",Ly),Lu()}),fe.push(()=>{A.cancel()}),Pt?fe.push(()=>{Pt?.destroy()}):pn&&fe.push(()=>{pn?.remove()});let kt={update(r){let a=o.future?.v5Defaults===!0,p=o.toolCall,f=o.messageActions,h=o.layout?.messages,v=o.colorScheme,B=o.loadingIndicator,q=o.iterationDisplay,U=o.features?.showReasoning,z=o.features?.showToolCalls,Q=o.features?.toolCallDisplay,re=o.features?.reasoningDisplay,ue=o.features?.streamAnimation?.type,Ne=o.features?.history?.enabled===!0,nt=o.features?.history?.provider,Ze=o.getIdentityProof,Tn=o.clientToken,bt=o.contextMentions;o=Ew({...o,features:g},r),g=o.features,o=bf(o),d(),pp(),Qa(t,o),il(t,o),al(t,o),Do(),ao(),o.colorScheme!==v&&vm();let At=wf.getForInstance(o.plugins);u.length=0,u.push(...At),bh(),W=o.launcher?.enabled??!0,We=o.launcher?.autoExpand??!1,j=o.features?.showReasoning??!0,X=o.features?.showToolCalls??!0,ge=o.features?.scrollToBottom??{};let un=Rn();xe=o.features?.scrollBehavior??{},un!==Rn()&&(co(),Sn()),Rm(),Vf(),qt();let Lt=Y;if(Y=o.features?.showEventStreamToggle??!1,Y&&!Lt){if(pt||(dl(),A.setSSEEventCallback((J,qe)=>{o.onSSEEvent?.(J,qe),$d(J,qe)})),!ot&&Me){let J=o.features?.eventStream?.classNames,qe="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(J?.toggleButton?" "+J.toggleButton:"");ot=P("button",qe),ot.style.width="28px",ot.style.height="28px",ot.style.color=mn.actionIconColor,ot.type="button",ot.setAttribute("aria-label","Event Stream"),ot.title="Event Stream";let ze=$t(Vw,"18px","currentColor",1.5);ze&&ot.appendChild(ze);let et=De.clearChatButtonWrapper,ht=De.closeButtonWrapper,rn=et||ht;rn&&rn.parentNode===Me?Me.insertBefore(ot,rn):Me.appendChild(ot),ot.addEventListener("click",()=>{ro?Us():np()})}}else!Y&&Lt&&(Us(),ot&&(ot.remove(),ot=null),pt?.clear(),Xe?.destroy(),pt=null,Xe=null,Gt?.reset(),Gt=null,Mt=null);if(o.launcher?.enabled===!1&&Pt&&(Pt.destroy(),Pt=null),o.launcher?.enabled===!1&&pn&&(pn.remove(),pn=null),o.launcher?.enabled!==!1&&!Pt&&!pn){let{instance:J,element:qe}=rf({config:o,plugins:u,onToggle:iy});Pt=J,J||(pn=qe),t.appendChild(qe)}Pt&&Pt.update(o),ba(),Vr&&o.launcher?.subtitle!==void 0&&(Vr.textContent=o.launcher.subtitle);let at=o.layout?.header;if(at?.layout!==Kt&&Me){let J=at?Ed(o,at,{showClose:Ge(),onClose:()=>gt(!1,"user")}):Rs({config:o,showClose:Ge(),onClose:()=>gt(!1,"user")});Ln.replaceHeader(J),Me=Ln.header.element,Et=Ln.header.iconHolder,ur=Ln.header.headerTitle,Vr=Ln.header.headerSubtitle,Ue=Ln.header.closeButton,Kt=at?.layout,ba()}else if(at){if(Et&&(Et.style.display=at.showIcon===!1?"none":""),ur&&(ur.style.display=at.showTitle===!1?"none":""),Vr&&(Vr.style.display=at.showSubtitle===!1?"none":""),Ue){let J=Ge()&&at.showCloseButton!==!1;Ue.style.display=J?"":"none"}if(De.clearChatButtonWrapper){let J=at.showClearChat;if(J!==void 0){De.clearChatButtonWrapper.style.display=J?"":"none";let{closeButtonWrapper:qe}=De;qe&&!qe.classList.contains("persona-absolute")&&(J?qe.classList.remove("persona-ml-auto"):qe.classList.add("persona-ml-auto"))}}}let Po=o.layout?.showHeader!==!1;Me&&(Me.style.display=Po?"":"none");let Jn=o.layout?.showFooter!==!1;ke&&(ke.style.display=Jn?"":"none"),jr(),qt(),W!==sn?W?gt(We,"auto"):(Pe=!0,sa()):We!==bn&&gt(We,"auto"),bn=We,sn=W,wa(),hy();let ko=JSON.stringify(o.toolCall)!==JSON.stringify(p),po=JSON.stringify(o.messageActions)!==JSON.stringify(f),Ir=JSON.stringify(o.layout?.messages)!==JSON.stringify(h),Aa=o.loadingIndicator?.render!==B?.render||o.loadingIndicator?.renderIdle!==B?.renderIdle||o.loadingIndicator?.showBubble!==B?.showBubble,Cs=o.iterationDisplay!==q,R=(o.features?.showReasoning??!0)!==(U??!0)||(o.features?.showToolCalls??!0)!==(z??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(Q)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(re);(o.future?.v5Defaults===!0!==a||ko||po||Ir||Aa||Cs||R)&&A&&(rs++,zn(ye,A.getMessages(),O));let Ie=o.features?.streamAnimation?.type;if(Ie!==ue&&Ie&&Ie!=="none"){let J=fp(Ie,o.features?.streamAnimation?.plugins);J&&ka(J,t)}let te=o.launcher??{},lt=te.headerIconHidden??!1,_t=o.layout?.header?.showIcon,an=lt||_t===!1,Xt=te.headerIconName,ft=te.headerIconSize??Ha;if(Et){let J=Me,qe=J?.querySelector(".persona-flex-col");if(an)Et.style.display="none",J&&qe&&!J.contains(qe)&&J.insertBefore(qe,J.firstChild);else{if(Et.style.display="",Et.style.height=ft,Et.style.width=ft,J&&qe&&(J.contains(Et)?Et.nextSibling!==qe&&(Et.remove(),J.insertBefore(Et,qe)):J.insertBefore(Et,qe)),Xt){let et=parseFloat(ft)||24,ht=de(Xt,et*.6,"currentColor",1);ht?(ht.style.width=`calc(${et}px * var(--persona-components-header-iconScale, 0.6))`,ht.style.height=`calc(${et}px * var(--persona-components-header-iconScale, 0.6))`,Et.replaceChildren(ht)):Et.textContent=te.agentIconText??"\u{1F4AC}"}else if(te.iconUrl){let et=Et.querySelector("img");if(et)et.src=te.iconUrl,et.style.height=ft,et.style.width=ft;else{let ht=document.createElement("img");ht.src=te.iconUrl,ht.alt="",ht.className="persona-rounded-xl persona-object-cover",ht.style.height=ft,ht.style.width=ft,Et.replaceChildren(ht)}}else{let et=Et.querySelector("svg"),ht=Et.querySelector("img");(et||ht)&&Et.replaceChildren(),Et.textContent=te.agentIconText??"\u{1F4AC}"}let ze=Et.querySelector("img");ze&&(ze.style.height=ft,ze.style.width=ft)}}let It=o.layout?.header?.showTitle,zt=o.layout?.header?.showSubtitle;if(ur&&(ur.style.display=It===!1?"none":""),Vr&&(Vr.style.display=zt===!1?"none":""),Ue){let J=Ge()&&o.layout?.header?.showCloseButton!==!1;if(Ue.style.display=J?"":"none",!Be()){let Zt=te.closeButtonSize??"";Ue.style.height=Zt,Ue.style.width=Zt,Ue.style.minWidth=Zt,Ue.style.minHeight=Zt}let qe=te.closeButtonPlacement??"inline",{closeButtonWrapper:ze}=De,et=qe==="top-right",ht=ze?.classList.contains("persona-absolute");if(ze&&et!==ht)if(ze.remove(),et){ze.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Zt=da??ce;Zt.style.position="relative",Zt.appendChild(ze)}else{let Zt=te.clearChat?.placement??"inline",en=te.clearChat?.enabled??!0;ze.className=en&&Zt==="inline"?"":"persona-ml-auto",Me&&Me.appendChild(ze)}if(Ue.style.color=te.closeButtonColor||mn.actionIconColor,te.closeButtonBackgroundColor?(Ue.style.backgroundColor=te.closeButtonBackgroundColor,Ue.classList.remove("hover:persona-bg-gray-100")):(Ue.style.backgroundColor="",Ue.classList.add("hover:persona-bg-gray-100")),te.closeButtonBorderWidth||te.closeButtonBorderColor){let Zt=te.closeButtonBorderWidth||"0px",en=te.closeButtonBorderColor||"transparent";Ue.style.border=`${Zt} solid ${en}`,Ue.classList.remove("persona-border-none")}else Ue.style.border="",Ue.classList.add("persona-border-none");te.closeButtonBorderRadius?(Ue.style.borderRadius=te.closeButtonBorderRadius,Ue.classList.remove("persona-rounded-full")):(Ue.style.borderRadius="",Ue.classList.add("persona-rounded-full")),te.closeButtonPaddingX?(Ue.style.paddingLeft=te.closeButtonPaddingX,Ue.style.paddingRight=te.closeButtonPaddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),te.closeButtonPaddingY?(Ue.style.paddingTop=te.closeButtonPaddingY,Ue.style.paddingBottom=te.closeButtonPaddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom=""),Td(Ue,te.closeButtonIconName??"x",{iconSize:Be()?ef:void 0,iconText:te.closeButtonIconText??"\xD7"});let rn=te.closeButtonTooltipText??"Close chat",go=te.closeButtonShowTooltip??!0;Ue.setAttribute("aria-label",rn),ze&&tn({anchor:Ue,trigger:ze,text:()=>Ue?.getAttribute("aria-label")??rn,enabled:go})}let{clearChatButton:Te,clearChatButtonWrapper:mt}=De;if(Te){let J=te.clearChat??{},qe=J.enabled??!0,ze=o.layout?.header?.showClearChat,et=ze!==void 0?ze:qe,ht=J.placement??"inline";if(mt){mt.style.display=et?"":"none";let{closeButtonWrapper:rn}=De;!Be()&&rn&&!rn.classList.contains("persona-absolute")&&(et?rn.classList.remove("persona-ml-auto"):rn.classList.add("persona-ml-auto"));let go=ht==="top-right",Zt=mt.classList.contains("persona-absolute");if(!Be()&&go!==Zt&&et){if(mt.remove(),go){mt.className="persona-absolute persona-top-4 persona-z-50",mt.style.right="48px";let Lo=da??ce;Lo.style.position="relative",Lo.appendChild(mt)}else{mt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",mt.style.right="";let Lo=De.closeButtonWrapper;Me&&Lo&&Lo.parentElement===Me?Me.insertBefore(mt,Lo):Me&&Me.appendChild(mt)}let en=De.closeButtonWrapper;en&&!en.classList.contains("persona-absolute")&&(go?en.classList.add("persona-ml-auto"):en.classList.remove("persona-ml-auto"))}}if(et){if(!Be()){let en=J.size??"";Te.style.height=en,Te.style.width=en,Te.style.minWidth=en,Te.style.minHeight=en}let rn=J.iconColor??"";if(Te.style.color=rn||mn.actionIconColor,Td(Te,J.iconName??"refresh-cw",{iconSize:Be()?tf:void 0}),J.backgroundColor?(Te.style.backgroundColor=J.backgroundColor,Te.classList.remove("hover:persona-bg-gray-100")):(Te.style.backgroundColor="",Te.classList.add("hover:persona-bg-gray-100")),J.borderWidth||J.borderColor){let en=J.borderWidth||"0px",Lo=J.borderColor||"transparent";Te.style.border=`${en} solid ${Lo}`,Te.classList.remove("persona-border-none")}else Te.style.border="",Te.classList.add("persona-border-none");J.borderRadius?(Te.style.borderRadius=J.borderRadius,Te.classList.remove("persona-rounded-full")):(Te.style.borderRadius="",Te.classList.add("persona-rounded-full")),J.paddingX?(Te.style.paddingLeft=J.paddingX,Te.style.paddingRight=J.paddingX):(Te.style.paddingLeft="",Te.style.paddingRight=""),J.paddingY?(Te.style.paddingTop=J.paddingY,Te.style.paddingBottom=J.paddingY):(Te.style.paddingTop="",Te.style.paddingBottom="");let go=J.tooltipText??"Clear chat",Zt=J.showTooltip??!0;Te.setAttribute("aria-label",go),mt&&tn({anchor:Te,trigger:mt,text:()=>Te?.getAttribute("aria-label")??go,enabled:Zt})}}let He=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Sf],jt=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ll.message,ll.messageAndClick];he=Af({parsers:He,handlers:jt,getSessionMetadata:Ce,updateSessionMetadata:me,emit:ne.emit,documentRef:typeof document<"u"?document:null}),O=Kw(o,he,w),lS(),A.updateConfig(o),zh(),(o.features?.history?.enabled===!0!==Ne||o.features?.history?.provider!==nt||o.getIdentityProof!==Ze||o.clientToken!==Tn)&&(Mn({restoreFocus:!1}),dh()),Tr(),rc(),zn(ye,A.getMessages(),O),es(),$l(),iS(),ia(A.isStreaming()),bt!==o.contextMentions&&wy();let eo=o.voiceRecognition?.enabled===!0,Jt=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),ct=gn(o.voiceRecognition?.provider);if(eo&&(Jt||ct))if(!oe||!Hn){let J=Pi(o);if(J){oe=J.button,Hn=J.wrapper;let qe=ho&&ho.parentElement===pl?ho:null;pl?pl.insertBefore(Hn,qe):vn?.appendChild(Hn),Je&&(Je.micButton=oe),Je?.addListener(oe,"click",Tu),oe.disabled=So()||A.isStreaming()&&!Mp()}}else{let J=o.voiceRecognition??{},qe=o.sendButton??{},ze=J.iconName??"mic",et=J.iconSize,ht=parseFloat(et??"")||fn;oe.classList.add(Fn),oe.classList.toggle(mo,!et),oe.style.width=et??"",oe.style.height=et??"",oe.style.minWidth=et??"",oe.style.minHeight=et??"";let rn=J.iconColor??qe.textColor;oe.innerHTML="";let go=de(ze,ht,rn||"currentColor",1.5);go?oe.appendChild(go):oe.textContent="\u{1F3A4}";let Zt=J.backgroundColor??qe.backgroundColor;Zt?oe.style.backgroundColor=Zt:oe.style.backgroundColor="",rn?oe.style.color=rn:oe.style.color="var(--persona-text, #111827)",J.borderWidth?(oe.style.borderWidth=J.borderWidth,oe.style.borderStyle="solid"):(oe.style.borderWidth="",oe.style.borderStyle=""),J.borderColor?oe.style.borderColor=J.borderColor:oe.style.borderColor="",J.paddingX?(oe.style.paddingLeft=J.paddingX,oe.style.paddingRight=J.paddingX):(oe.style.paddingLeft="",oe.style.paddingRight=""),J.paddingY?(oe.style.paddingTop=J.paddingY,oe.style.paddingBottom=J.paddingY):(oe.style.paddingTop="",oe.style.paddingBottom="");let en=J.tooltipText??"Start voice recognition",Lo=J.showTooltip??!1;oe.setAttribute("aria-label",en),Hn&&tn({anchor:oe,trigger:Hn,text:()=>oe?.getAttribute("aria-label")??en,enabled:Lo}),Hn.style.display="",oe.disabled=So()||A.isStreaming()&&!Mp()}else oe&&Hn&&(Hn.style.display="none",gn(o.voiceRecognition?.provider)?A.isVoiceActive()&&A.toggleVoice():To&&Er());if(Pu(),o.attachments?.enabled===!0){if(!Cn||!St){let J=o.attachments??{};wn||(wn=P("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),wn.style.display="none",(ae.parentElement??vn).insertBefore(wn,ae)),yt||(yt=document.createElement("input"),yt.type="file",yt.accept=(J.allowedTypes??sr).join(","),yt.multiple=(J.maxFiles??4)>1,yt.style.display="none",yt.setAttribute("aria-label","Attach files"),(ae.parentElement??vn).insertBefore(yt,ae)),Cn=P("div","persona-send-button-wrapper"),St=P("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Fn} ${mo}`),St.type="button",St.setAttribute("aria-label",J.buttonTooltipText??"Attach file");let qe=J.buttonIconName??"paperclip";St.style.fontSize="18px",St.style.lineHeight="1";let ze=de(qe,fn,"currentColor",1.5);ze?St.appendChild(ze):St.textContent="\u{1F4CE}",St.addEventListener("click",ht=>{ht.preventDefault(),yt?.click()}),Cn.appendChild(St);let et=J.buttonTooltipText??"Attach file";tn({anchor:St,trigger:Cn,text:()=>St?.getAttribute("aria-label")??et}),Kd?Kd.append(Cn):vn.appendChild(Cn),Je&&(Je.attachmentButton=St,Je.attachmentInput=yt??void 0,Je.attachmentPreviews=wn??void 0),!tt&&yt&&wn&&(tt=Va.fromConfig(J,qf),tt.setPreviewsContainer(wn),Je?.addListener(yt,"change",async()=>{tt&&yt?.files&&(await tt.handleFileSelect(yt.files),yt.value="")}))}else{Cn.style.display="";let J=o.attachments??{};yt&&(yt.accept=(J.allowedTypes??sr).join(","),yt.multiple=(J.maxFiles??4)>1),tt&&tt.updateConfig({allowedTypes:J.allowedTypes,maxFileSize:J.maxFileSize,maxFiles:J.maxFiles,adapter:J.adapter})}if(ce.querySelector(".persona-attachment-drop-overlay")?.remove(),ce.appendChild(Gw(o.attachments?.dropOverlay)),St){let J=o.attachments??{},qe=J.buttonTooltipText??"Attach file";St.setAttribute("aria-label",qe),St.textContent="";let ze=de(J.buttonIconName??"paperclip",fn,"currentColor",1.5);ze?St.appendChild(ze):St.textContent="\u{1F4CE}",Cn&&tn({anchor:St,trigger:Cn,text:()=>St?.getAttribute("aria-label")??qe})}}else Cn&&(Cn.style.display="none"),tt&&tt.clearAttachments(),ce.querySelector(".persona-attachment-drop-overlay")?.remove();let Re=o.sendButton??{},Hr=Re.useIcon??!1,Ut=Re.iconText??"\u2191",En=Re.iconName,Jo=Re.tooltipText??"Send message",Iu=Re.showTooltip??!1,ws=Re.size,Hu=parseFloat(ws??"")||Sg,Zo=Re.backgroundColor,xs=Re.textColor;if(Hr){if(Ae.style.width=ws??"",Ae.style.height=ws??"",Ae.style.minWidth=ws??"",Ae.style.minHeight=ws??"",Ae.style.fontSize="18px",Ae.style.lineHeight="1",xs?Ae.style.color=xs:Ae.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!A.isStreaming())if(Ae.innerHTML="",En){let J=parseFloat(Re.iconSize??"")||Math.round(Hu*.5),qe=xs?.trim()||"currentColor",ze=Re.iconStrokeWidth??2,et=de(En,J,qe,ze),ht=de(Re.stopIconName??"square",J,qe,ze);et&&ht?Ae.appendChild(Ag(et,ht)):et?Ae.appendChild(et):Ae.textContent=Ut}else Ae.textContent=Ut;Ae.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Fn}`,Zo?(Ae.style.backgroundColor=Zo,Ae.classList.remove("persona-bg-persona-primary")):(Ae.style.backgroundColor="",Ae.classList.add("persona-bg-persona-primary"))}else Ae.textContent=o.copy?.sendButtonLabel??"Send",Ae.style.width="",Ae.style.height="",Ae.style.minWidth="",Ae.style.minHeight="",Ae.style.fontSize="",Ae.style.lineHeight="",Ae.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Zo?(Ae.style.backgroundColor=Zo,Ae.classList.remove("persona-bg-persona-accent")):Ae.classList.add("persona-bg-persona-accent"),xs?Ae.style.color=xs:Ae.classList.add("persona-text-white");Re.borderWidth?(Ae.style.borderWidth=Re.borderWidth,Ae.style.borderStyle="solid"):(Ae.style.borderWidth="",Ae.style.borderStyle=""),Re.borderColor?Ae.style.borderColor=Re.borderColor:Ae.style.borderColor="",Re.paddingX?(Ae.style.paddingLeft=Re.paddingX,Ae.style.paddingRight=Re.paddingX):(Ae.style.paddingLeft="",Ae.style.paddingRight=""),Re.paddingY?(Ae.style.paddingTop=Re.paddingY,Ae.style.paddingBottom=Re.paddingY):(Ae.style.paddingTop="",Ae.style.paddingBottom=""),A.isStreaming()||Ae.setAttribute("aria-label",Jo),Fl(),ho&&tn({anchor:Ae,trigger:ho,text:()=>Ae.getAttribute("aria-label")??Jo,enabled:Iu}),rm(),gp();let Iy=fd(be.getState().activeModeIds,o.composer?.modes);be.setActiveModeIds(Iy),Os().length>0!==!!Oo&&rp(),Oo?.render(Iy,Os());for(let J of[...Ns.keys()])gd(J,o.composer?.modeGroups)||Ns.delete(J);Ns.forEach(J=>J.repaint()),fr?.repaint(),vo?.resolve();let wc=Ur(o,Be());if(up(),wc){ye.style.maxWidth=wc,ye.style.marginLeft="auto",ye.style.marginRight="auto",ye.style.width="100%",In.style.maxWidth=wc,In.style.marginLeft="auto",In.style.marginRight="auto",In.style.width="100%";for(let J of[vn,pr,wn,Qe])J&&(J.style.maxWidth=wc,J.style.marginLeft="auto",J.style.marginRight="auto",J.style.width="100%")}else{ye.style.maxWidth="",ye.style.marginLeft="",ye.style.marginRight="",ye.style.width="",In.style.maxWidth="",In.style.marginLeft="",In.style.marginRight="",In.style.width="";for(let J of[vn,pr,wn,Qe])J&&(J.style.maxWidth="",J.style.marginLeft="",J.style.marginRight="",J.style.width="")}let uo=o.statusIndicator??{};if(Gu(Qe,vn,uo),Ps(Qe,uo,A?.getStatus()??"idle"),A){let J=A.getStatus();Fi(Qe,(ze=>ze==="idle"?uo.idleText??Rt.idle:ze==="connecting"?uo.connectingText??Rt.connecting:ze==="connected"?uo.connectedText??Rt.connected:ze==="error"?uo.errorText??Rt.error:ze==="paused"?uo.pausedText??Rt.paused:ze==="resuming"?uo.resumingText??Rt.resuming:Rt[ze])(J),uo,J)}Qe.classList.remove("persona-text-left","persona-text-center","persona-text-right");let SA=uo.align==="left"?"persona-text-left":uo.align==="center"?"persona-text-center":"persona-text-right";Qe.classList.add(SA),op(),Ep(),so(),Vd()},open(){Ge()&&gt(!0,"api")},close(){Ge()&&gt(!1,"api")},toggle(){Ge()&&gt(!Pe,"api")},reconnect(){A.reconnectNow()},clearChat(){No=!1,l.clear(),s.clear(),i.clear(),c.clear(),A.clearMessages(),o.layout?.topFade&&(ee.scrollTop=0),ee.removeAttribute("data-persona-top-fade"),Dt.clear(),Sn();try{localStorage.removeItem(_i),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${_i}`)}catch(a){console.error("[AgentWidget] Failed to clear default localStorage:",a)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==_i)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(a){console.error("[AgentWidget] Failed to clear custom localStorage:",a)}let r=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(r),T?.clear&&Hl(()=>T.clear(),"[AgentWidget] Failed to clear storage adapter:"),k={},he.syncFromMetadata(),tt?.clearAttachments(),Wl(),Fs(void 0),bo(void 0),os(),pt?.clear(),Gt?.reset(),ut?.update()},setMessage(r){return!ae||A.isStreaming()||So()?!1:(!Pe&&Ge()&&gt(!0,"system"),ae.value=r,ae.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(r){if(A.isStreaming()||cs())return!1;let a=r?.trim()||ae.value.trim();return a?(!Pe&&Ge()&&gt(!0,"system"),ae.value="",ae.style.height="auto",yo(),mc(a,{consumeDraft:!1}),!0):!1},getComposerState(){return be.getState()},setQuote(r){let a=r?.text?.trim();a&&bo({...r,text:a})},clearQuote(){bo(void 0)},startVoiceRecognition(){return A.isStreaming()?!1:gn(o.voiceRecognition?.provider)?(A.isVoiceActive()||A.isBargeInActive()||(!Pe&&Ge()&&gt(!0,"system"),Ke.manuallyDeactivated=!1,lo(),A.toggleVoice().then(()=>{Ke.active=A.isVoiceActive(),Vo("user"),A.isVoiceActive()&&fi()})),!0):To?!0:Jh()?(!Pe&&Ge()&&gt(!0,"system"),Ke.manuallyDeactivated=!1,lo(),yc("user"),!0):!1},stopVoiceRecognition(){return gn(o.voiceRecognition?.provider)?!A.isVoiceActive()&&!A.isBargeInActive()?!1:((A.isBargeInActive()?A.deactivateBargeIn():A.toggleVoice()).then(()=>{Ke.active=!1,Ke.manuallyDeactivated=!0,lo(),Vo("user"),Xo()}),!0):To?(Ke.manuallyDeactivated=!0,lo(),Er("user"),!0):!1},injectMessage(r){return!Pe&&Ge()&&gt(!0,"system"),A.injectMessage(r)},injectAssistantMessage(r){!Pe&&Ge()&&gt(!0,"system");let a=A.injectAssistantMessage(r);return Bo&&(Bo=!1,V&&(clearTimeout(V),V=null),setTimeout(()=>{A&&!A.isStreaming()&&A.continueConversation()},100)),a},injectUserMessage(r){return!Pe&&Ge()&&gt(!0,"system"),A.injectUserMessage(r)},injectSystemMessage(r){return!Pe&&Ge()&&gt(!0,"system"),A.injectSystemMessage(r)},injectMessageBatch(r){return!Pe&&Ge()&&gt(!0,"system"),A.injectMessageBatch(r)},injectComponentDirective(r){return!Pe&&Ge()&&gt(!0,"system"),A.injectComponentDirective(r)},injectTestMessage(r){!Pe&&Ge()&&gt(!0,"system"),A.injectTestEvent(r)},async connectStream(r,a){return A.connectStream(r,a)},__pushEventStreamEvent(r){Y&&(dl(),$d(r.type,r.payload))},showEventStream(){Y&&np()},hideEventStream(){ro&&Us()},isEventStreamVisible(){return ro},listConversations(r){return A.listConversations(r)},getActiveConversationId(){return A.getActiveConversationId()},openConversation(r,a){return cu(r,{focusComposer:a?.focus===!0})},startNewConversation(r){return du({focusComposer:r?.focus===!0})},warmSession(){gu()},deleteConversation(r){return Dh(r)},renameConversation(r,a){return pu(r,{title:a})},setConversationStarred(r,a){return pu(r,{starred:a})},clearConversationHistory(r){return _h(r)},resetHistoryIdentity(){return Oh()},async getVisitorToken(){let r=jn;if(!r)return null;let a=await r.get();return r===jn?a:null},getHistoryIdentityStatus(){return _n?_n.getIdentityStatus():jp()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(r){return ya({...r?.returnSurface?{returnSurface:r.returnSurface}:{},...r?.focus!==void 0?{focus:r.focus}:{}})},hideHistory(r){Mn(r?.restoreFocus!==void 0?{restoreFocus:r.restoreFocus}:void 0)},isHistoryVisible(){return Tt},showArtifacts(){yn(o)&&(No=!1,Vs=!0,ao(),Ve?.setMobileOpen(!0))},hideArtifacts(){yn(o)&&(No=!0,ao())},upsertArtifact(r){return yn(o)?(Br(o.features?.artifacts,{artifactType:r.artifactType,...r.artifactType==="markdown"&&r.file?{file:r.file}:{},...r.presentation?{presentation:r.presentation}:{}})==="panel"&&(No=!1,Vs=!0),A.upsertArtifact(r)):null},selectArtifact(r){yn(o)&&A.selectArtifact(r)},clearArtifacts(){yn(o)&&A.clearArtifacts()},getArtifacts(){return A?.getArtifacts()??[]},getSelectedArtifactId(){return A?.getSelectedArtifactId()??null},focusInput(){return W&&!Pe&&!Be()||!ae?!1:(ae.focus(),!0)},async resolveApproval(r,a,p){let h=A.getMessages().find(v=>v.variant==="approval"&&v.approval?.id===r);if(!h?.approval)throw new Error(`Approval not found: ${r}`);if(h.approval.toolType==="webmcp"){A.resolveWebMcpApproval(h.id,a);return}return A.resolveApproval(h.approval,a,p)},setFollowUpSuggestions(r){Ix(r)},clearFollowUpSuggestions(){Hm()},getMessages(){return A.getMessages()},getStatus(){return A.getStatus()},getPersistentMetadata(){return{...k}},updatePersistentMetadata(r){me(r)},on(r,a){return ne.on(r,a)},off(r,a){ne.off(r,a)},isOpen(){return Ge()&&Pe},isVoiceActive(){return Ke.active},toggleReadAloud(r){A.toggleReadAloud(r)},stopReadAloud(){A.stopSpeaking()},getReadAloudState(r){return A.getReadAloudState(r)},onReadAloudChange(r){return A.onReadAloudChange(r)},getState(){return{open:Ge()&&Pe,launcherEnabled:W,voiceActive:Ke.active,streaming:A.isStreaming()}},showCSATFeedback(r){!Pe&&Ge()&&gt(!0,"system");let a=ye.querySelector(".persona-feedback-container");a&&a.remove();let p=Uw({onSubmit:async(f,h)=>{A.isClientTokenMode()&&await A.submitCSATFeedback(f,h),r?.onSubmit?.(f,h)},onDismiss:r?.onDismiss,...r});ye.appendChild(p),p.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(r){!Pe&&Ge()&&gt(!0,"system");let a=ye.querySelector(".persona-feedback-container");a&&a.remove();let p=$w({onSubmit:async(f,h)=>{A.isClientTokenMode()&&await A.submitNPSFeedback(f,h),r?.onSubmit?.(f,h)},onDismiss:r?.onDismiss,...r});ye.appendChild(p),p.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(r,a){return A.submitCSATFeedback(r,a)},async submitNPSFeedback(r,a){return A.submitNPSFeedback(r,a)},destroy(){Np(),us!=null&&(clearInterval(us),us=null),l.clear(),s.clear(),i.clear(),c.clear(),fe.forEach(r=>r()),je.remove(),Qt?.remove(),Pt?.destroy(),pn?.remove(),Jr&&Ue.removeEventListener("click",Jr)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let r=window.AgentWidgetBrowser,a={controller:kt,getMessages:kt.getMessages,getStatus:kt.getStatus,getMetadata:kt.getPersistentMetadata,updateMetadata:kt.updatePersistentMetadata,clearHistory:()=>kt.clearChat(),setVoiceActive:p=>p?kt.startVoiceRecognition():kt.stopVoiceRecognition()};window.AgentWidgetBrowser=a,fe.push(()=>{window.AgentWidgetBrowser===a&&(window.AgentWidgetBrowser=r)})}if(typeof window<"u"){let r=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),a=z=>{let Q=z.detail;(!Q?.instanceId||Q.instanceId===r)&&kt.focusInput()};if(window.addEventListener("persona:focusInput",a),fe.push(()=>{window.removeEventListener("persona:focusInput",a)}),Y){let z=re=>{let ue=re.detail;(!ue?.instanceId||ue.instanceId===r)&&kt.showEventStream()},Q=re=>{let ue=re.detail;(!ue?.instanceId||ue.instanceId===r)&&kt.hideEventStream()};window.addEventListener("persona:showEventStream",z),window.addEventListener("persona:hideEventStream",Q),fe.push(()=>{window.removeEventListener("persona:showEventStream",z),window.removeEventListener("persona:hideEventStream",Q)})}let p=z=>{let Q=z.detail;(!Q?.instanceId||Q.instanceId===r)&&kt.showHistory()},f=z=>{let Q=z.detail;(!Q?.instanceId||Q.instanceId===r)&&kt.hideHistory()};window.addEventListener("persona:showHistory",p),window.addEventListener("persona:hideHistory",f),fe.push(()=>{window.removeEventListener("persona:showHistory",p),window.removeEventListener("persona:hideHistory",f)});let h=z=>{let Q=z.detail;(!Q?.instanceId||Q.instanceId===r)&&kt.showArtifacts()},v=z=>{let Q=z.detail;(!Q?.instanceId||Q.instanceId===r)&&kt.hideArtifacts()},B=z=>{let Q=z.detail;Q?.instanceId&&Q.instanceId!==r||Q?.artifact&&kt.upsertArtifact(Q.artifact)},q=z=>{let Q=z.detail;Q?.instanceId&&Q.instanceId!==r||typeof Q?.id=="string"&&kt.selectArtifact(Q.id)},U=z=>{let Q=z.detail;(!Q?.instanceId||Q.instanceId===r)&&kt.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",v),window.addEventListener("persona:upsertArtifact",B),window.addEventListener("persona:selectArtifact",q),window.addEventListener("persona:clearArtifacts",U),fe.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",v),window.removeEventListener("persona:upsertArtifact",B),window.removeEventListener("persona:selectArtifact",q),window.removeEventListener("persona:clearArtifacts",U)})}let Xn=sP(o.persistState);if(Xn&&Ge()){let r=iP(Xn.storage),a=`${Xn.keyPrefix}widget-open`,p=`${Xn.keyPrefix}widget-voice`,f=`${Xn.keyPrefix}widget-voice-mode`;if(r){let h=Xn.persist?.openState&&r.getItem(a)==="true",v=Xn.persist?.voiceState&&r.getItem(p)==="true",B=Xn.persist?.voiceState&&r.getItem(f)==="true";if(h&&(Pt?.setPanelOpen(!0,"auto"),setTimeout(()=>{kt.open(),setTimeout(()=>{if(v||B)kt.startVoiceRecognition();else if(Xn.persist?.focusInput){let q=t.querySelector("textarea");q&&q.focus()}},100)},0)),Xn.persist?.openState&&(ne.on("widget:opened",()=>{r.setItem(a,"true")}),ne.on("widget:closed",()=>{r.setItem(a,"false")})),Xn.persist?.voiceState&&(ne.on("voice:state",q=>{r.setItem(p,q.active?"true":"false")}),ne.on("user:message",q=>{r.setItem(f,q.viaVoice?"true":"false")})),Xn.clearOnChatClear){let q=()=>{r.removeItem(a),r.removeItem(p),r.removeItem(f)},U=()=>q();window.addEventListener("persona:clear-chat",U),fe.push(()=>{window.removeEventListener("persona:clear-chat",U)})}}}if(pe&&Ge()&&(Pt?.setPanelOpen(!0,"auto"),setTimeout(()=>{kt.open()},0)),Zs(),!Hx){let r=xc(()=>{A&&(rs++,Dt.clear(),zn(ye,A.getMessages(),O))});fe.push(r)}N=()=>{A&&(rs++,Dt.clear(),zn(ye,A.getMessages(),O))},A.getMessages().length>0&&Nl(),K=()=>{A&&(rs++,Dt.clear(),zn(ye,A.getMessages(),O))};let wA=Ry(()=>{A&&(rs++,Dt.clear(),zn(ye,A.getMessages(),O))});fe.push(wA);let xA=ff(()=>{A&&(rs++,Dt.clear(),zn(ye,A.getMessages(),O),ar()?.updateInlineArtifactBlocks(ye,qn.artifacts,{suppressTransition:!0}),ao())});return fe.push(xA),kt};var Yw=(t,e)=>{let n=t.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(n);return s?Math.max(0,e*parseFloat(s[1])/100):420},cP=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},dP=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},pP=(t,e)=>{let n=t.parentElement;if(!n)return;let o=t.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let s=o.offsetHeight>0;o.style.height="100%";let i=o.offsetHeight>0;o.remove(),!(!s||i)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(e.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 ${e.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.")},Xw=(t,e)=>{let n=e?.launcher?.enabled??!0;t.className="persona-host",t.style.height=n?"":"100%",t.style.display=n?"":"flex",t.style.flexDirection=n?"":"column",t.style.flex=n?"":"1 1 auto",t.style.minHeight=n?"":"0",t.style.minWidth=n?"":"0"},Rf=t=>{t.style.position="",t.style.top="",t.style.bottom="",t.style.left="",t.style.right="",t.style.zIndex="",t.style.transform="",t.style.pointerEvents=""},Jw=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",Rf(t)},Lf=t=>{t.style.transition=""},If=t=>{t.style.display="",t.style.flexDirection="",t.style.flex="",t.style.minHeight="",t.style.minWidth="",t.style.width="",t.style.height="",t.style.alignItems="",t.style.transition="",t.style.transform="",t.style.marginLeft=""},Hf=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},Fd=(t,e)=>{t.style.width="",t.style.minWidth="0",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},uP=(t,e,n,o,s)=>{s?n.parentElement!==e&&(t.replaceChildren(),e.replaceChildren(n,o),t.appendChild(e)):n.parentElement===e&&(e.replaceChildren(),t.appendChild(n),t.appendChild(o))},gP=(t,e,n,o,s,i)=>{let l=i?e:t;s==="left"?l.firstElementChild!==o&&l.replaceChildren(o,n):l.lastElementChild!==o&&l.replaceChildren(n,o)},fP=t=>{let e=ir(t),n=e.components?.panel,o=(s,i)=>s==null||s===""?i:on(e,s)??s;return{inset:o(n?.inset,bd),canvasBackground:o(n?.canvasBackground,vd)}},Zw=(t,e,n,o)=>{if(!e){t.style.padding="",t.style.background="",t.style.boxSizing="";return}t.style.boxSizing="border-box",t.style.padding=n,t.style.background=o},mP=(t,e,n,o,s,i,l,c)=>{let d=oo(i),g=d.reveal==="push",u=c!=null,m=c?.inset??"",y=c?.canvasBackground??"";uP(t,e,n,o,g),gP(t,e,n,o,d.side,g),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=d.side,t.dataset.personaDockOpen=l?"true":"false",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0",t.style.height="100%",t.style.minHeight="0",t.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.minWidth="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let b=t.ownerDocument.defaultView,C=i?.launcher?.mobileFullscreen??!0,S=i?.launcher?.mobileBreakpoint??640,E=b!=null?b.innerWidth<=S:!1;if(C&&E&&l){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),If(e),Lf(o),Jw(o),Hf(n),Fd(s,o),Zw(o,!1,"",""),t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="stretch",t.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(i?.launcher?.zIndex??ln),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",g&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(t.removeAttribute("data-persona-dock-mobile-fullscreen"),Jw(o),cP(o,d.maxHeight),Zw(o,u&&l,m,y),d.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",If(e),Lf(o),Hf(n),Fd(s,o);let I=d.animate?"transform 180ms ease":"none",N=d.side==="right"?"translateX(100%)":"translateX(-100%)",x=l?"translateX(0)":N;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=d.width,o.style.maxWidth=d.width,o.style.minWidth=d.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=I,o.style.transform=x,o.style.pointerEvents=l?"auto":"none",o.style.zIndex="2",d.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(d.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",Lf(o),Rf(o),Fd(s,o);let I=Yw(d.width,t.clientWidth),N=Math.max(0,t.clientWidth),x=d.animate?"margin-left 180ms ease":"none",D=d.side==="right"?l?-I:0:l?0:-I;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${N+I}px`,e.style.transition=x,e.style.marginLeft=`${D}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${N}px`,n.style.maxWidth=`${N}px`,n.style.minWidth=`${N}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=d.width,o.style.minWidth=d.width,o.style.maxWidth=d.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=l?"auto":"none"}else{t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="",If(e),Rf(o),Hf(n),Fd(s,o);let I=d.reveal==="emerge";I?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let N=l?d.width:"0px",x=d.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?", padding 180ms ease":""}`:"none",D=!l;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${N}`,o.style.width=N,o.style.maxWidth=N,o.style.minWidth=N,o.style.minHeight="0",dP(o,d.maxHeight),o.style.overflow=I||D?"hidden":"visible",o.style.transition=x,I){o.style.alignItems=d.side==="right"?"flex-start":"flex-end";let L=u?`calc(${Yw(d.width,t.clientWidth)}px - (2 * ${m}))`:d.width;s.style.width=L,s.style.minWidth=L,s.style.maxWidth=L,s.style.boxSizing="border-box"}}},hP=(t,e)=>{let n=t.ownerDocument.createElement("div");return Xw(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Xw(n,o)},destroy(){n.remove()}}},yP=(t,e)=>{let{ownerDocument:n}=t,o=t.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let s=t.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let i=t.nextSibling,l=n.createElement("div"),c=n.createElement("div"),d=n.createElement("div"),g=n.createElement("aside"),u=n.createElement("div"),m=e?.launcher?.enabled??!0?e?.launcher?.autoExpand??!1:!0;c.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",g.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",g.appendChild(u),o.insertBefore(l,t),d.appendChild(t);let y=null,b=()=>{y?.disconnect(),y=null},C=null,S=()=>{C=e?.launcher?.detachedPanel===!0?fP(e):null};S();let E=()=>{mP(l,c,d,g,u,e,m,C)},H=null,I=()=>{H?.(),H=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(H=Cd(()=>{S(),E()}))},N=()=>{b(),oo(e).reveal==="push"&&(typeof ResizeObserver>"u"||(y=new ResizeObserver(()=>{E()}),y.observe(l)))},x=!1,D=()=>{E(),N(),m&&!x&&l.dataset.personaDockMobileFullscreen!=="true"&&(x=!0,pP(l,oo(e)))},L=l.ownerDocument.defaultView,$=()=>{D()};return L?.addEventListener("resize",$),oo(e).reveal==="push"?(c.appendChild(d),c.appendChild(g),l.appendChild(c)):(l.appendChild(d),l.appendChild(g)),D(),I(),{mode:"docked",host:u,shell:l,syncWidgetState(K){let se=K.launcherEnabled?K.open:!0;m!==se&&(m=se,D())},updateConfig(K){e=K,(e?.launcher?.enabled??!0)===!1&&(m=!0),S(),D(),I()},destroy(){L?.removeEventListener("resize",$),H?.(),H=null,b(),o.isConnected&&(i&&i.parentNode===o?o.insertBefore(t,i):o.appendChild(t)),l.remove()}}},ex=(t,e)=>xt(e)?yP(t,e):hP(t,e);var cl={desktop:{w:1280,h:800},mobile:{w:390,h:844}},tx=.15,nx=1.5,Wf="persona-preview-shell-theme",bP={load:()=>null,save:()=>{},clear:()=>{}},vP=["How do I get started?","Pricing & plans","Talk to support"];function Bf(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function CP(t){return t==="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 ox(t){let e=CP(t);return`* { box-sizing: border-box; }
123
+ ${Ye?"background: transparent !important;":""}
124
+ `)}if(!f&&!a){let ge="max-height: -moz-available !important; max-height: stretch !important;",we=d?"":"padding-top: 1.25em !important;",be=d?"":`z-index: ${o.launcher?.zIndex??Dt} !important;`;Pe.style.cssText+=ge+we+be}rc(),bn()},Cc=()=>{t.style.setProperty("--persona-content-max-width",Ko(o,Ae()))},Fu=!1;function Nu(){o.layout?.topFade&&j.scrollTop>1?j.setAttribute("data-persona-top-fade","true"):j.removeAttribute("data-persona-top-fade")}let wc=()=>{Nu();let r=sp(o,Ae());Ae()&&o.composer?.placement&&o.debug===!0&&!Fu&&(Fu=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let a=Xo();t.setAttribute("data-persona-composer-placement",r),t.setAttribute("data-persona-conversation-state",Qi),t.setAttribute("data-persona-welcome-anchor",a.anchor??"bottom"),t.style.setProperty("--persona-composer-anchor-gap",a.composerGap??Hl),Ji()},Vu=()=>{if(Ae())return;let r=rt(o),a=o.launcher?.sidebarMode??!1;if(r||a||(o.launcher?.fullHeight??!1)||!de)return;let m=t.ownerDocument.defaultView??window,f=o.launcher?.mobileFullscreen??!0,b=o.launcher?.mobileBreakpoint??640;if(f&&m.innerWidth<=b)return;let D=Pr(o);le.style.height=D.height,le.style.maxHeight=D.maxHeight};vc(),Ti(t,o),Oi(t,o),_i(t,o),Cc(),wc(),er=()=>{vc(),Vu(),Ti(t,o),Oi(t,o),_i(t,o),Cc(),wc(),ta?t.style.setProperty("--persona-artifact-welded-outer-radius",ta):t.style.removeProperty("--persona-artifact-welded-outer-radius"),ji(),qi()};let oe=[];oe.push(()=>{Iu=!0}),oe.push(()=>{h.forEach(r=>r()),y.destroy()}),oe.push(()=>{document.removeEventListener("keydown",Bu)}),oe.push(()=>{Fs!==null&&clearTimeout(Fs)});let Bn=null,Dn=null;oe.push(()=>{Bn?.(),Bn=null,Dn?.(),Dn=null}),Us&&oe.push(()=>{Us?.disconnect(),Us=null}),oe.push(()=>{Gs?.(),Gs=null,bc(),ot&&(ot.remove(),ot=null),Ee?.element.style.removeProperty("width"),Ee?.element.style.removeProperty("maxWidth"),Ee?.destroy()}),Jt&&oe.push(()=>{ru=!0,Yn=null,Co!==null&&(cancelAnimationFrame(Co),Co=null),Ot?.destroy(),Ot=null,Lt?.destroy(),Lt=null,Rr=null});let tr=null,$u=()=>{tr&&(tr(),tr=null),o.colorScheme==="auto"&&(tr=Il(()=>{Ti(t,o)}))};$u(),oe.push(()=>{tr&&(tr(),tr=null)}),oe.push(()=>{k=!0,L?.()}),oe.push(()=>{V=!0});let zu=!1;oe.push(()=>{zu=!0});let Sc=(r,a)=>{let d=mi(r,a);return d||!Hf.includes(r)?d:(iy().then(m=>{if(zu)return;Rd(m.wipe),Rd(m.glyphCycle);let f=mi(r,a);f&&yi(f,t)}).catch(()=>{}),null)},da=o.features?.streamAnimation;if(da?.type&&da.type!=="none"){let r=Sc(da.type,da.plugins);r&&yi(r,t),oe.push(()=>Rf(t))}let eo=Hi(wo),Uu=Hi(Zl),qu=Hi(Bs),nr=[eo,Uu,qu];oe.push(()=>{nr.forEach(r=>r.destroy())});let or=null,S,rr=null,ju=!1,Ku=0,Gu=null,Yu=r=>r.reduce((a,d)=>d.role==="user"?a+1:a,0),Qu=r=>{for(let a=r.length-1;a>=0;a--)if(Ja(r[a]))return r[a].id??null;return null},Xu=!1,rv=()=>{Xu||o.debug!==!0||(Xu=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".'))},Ju=!1,Zu=!1,eg=(r,a)=>{Ju||o.debug!==!0||!a.enabled||a.expose||ju||Zu&&(S.isStreaming()||r.some(Ja)||(Ju=!0,console.info("[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.")))},sr=r=>{if(!S)return;let a=r??S.getMessages(),d=X=>{X.render([],S,Z,a)},m=X=>{nr.forEach(ae=>{ae!==X&&d(ae)})};rr&&(Yu(a)>Ku||Qu(a)!==Gu)&&(rr=null);let f=ds(o);eg(a,f);let b=f.enabled?ef(a):null,D=rr??b,$=rr?"host":"agent";if(D){let X=o.suggestions?.followUps,ae=X?.placement??(X?"auto":"composer"),Fe=(ae==="auto"?Ae()?"composer":"after-message":ae)==="after-message"?qu:eo;m(Fe),Fe.render(D,S,Z,a,o.suggestionChipsConfig,{source:$,surface:"followUp",variant:X?.variant??"chip",behavior:X?.behavior??"send",overflow:X?.overflow??"wrap",maxItems:X?.maxItems??4,config:o,plugins:g,submitPrompt:Ra});return}if(a.some(X=>X.role==="user")){nr.forEach(d);return}let F=o.future?.v5Defaults===!0,q=Vs(),K=o.suggestions?.starters??(F?{}:void 0);if(K){let X=Ss(Xo(),a),ae=K.placement??"auto",He=ae==="auto"?X?"welcome":"composer":ae;if(He==="welcome"&&!X){rv(),nr.forEach(d);return}let Fe=He==="welcome"?Uu:eo;m(Fe),Fe.render(K.items??o.suggestionChips,S,Z,a,o.suggestionChipsConfig,{surface:"starter",variant:K.variant??(F&&!q?"chip":"card"),behavior:K.behavior??"send",overflow:K.overflow??"wrap",maxItems:K.maxItems??(F&&!q?3:4),config:o,plugins:g,submitPrompt:Ra});return}m(eo),eo.render(o.suggestionChips,S,Z,a,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:o,plugins:g,submitPrompt:Ra})},tg=()=>{rr&&(rr=null,sr())},sv=r=>{let a=Array.isArray(r)?[...r]:[];if(!a.length){tg();return}let d=S?S.getMessages():[];rr=a,ju=!0,Ku=Yu(d),Gu=Qu(d),sr(d)},on=!1,It=ny(),Vr=new Map,ir=new Map,To=new Map,ar=null,ko=null;function lr(){if(!ar)return;let r=ar;ar=null,ko?.destroy(),ko=null,It.delete(r),re.querySelector(`#wrapper-${r}`)?.removeAttribute("data-preserve-runtime"),S&&un(ce,S.getMessages(),Xt)}let cr=0,iv=is()!==null,rn=Tf(),sn=0,Po=null,Kt=!1,pa=!1,Lo=0,vt=null,dr=null,xc=!1,$r=!1,pr=null,Ys=!0,ua=!1,zr=null,ga=!1,Io=()=>{ga=!0,dv()},Ac=null,av=4,to=24,lv=80,cv=1e3,no=null,ng=()=>{t.setAttribute("data-persona-scrollbar",tc()),tc()!=="on-scroll"&&(no!==null&&clearTimeout(no),no=null,j.removeAttribute("data-persona-scrollbar-visible"))},dv=()=>{tc()==="on-scroll"&&(j.setAttribute("data-persona-scrollbar-visible",""),no!==null&&clearTimeout(no),no=setTimeout(()=>{no=null,Er(j,to)&&j.removeAttribute("data-persona-scrollbar-visible")},cv))};ng(),oe.push(()=>{no!==null&&clearTimeout(no)});let Mc=new Map,Ec=!1,ma=null,Ie={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};An();let og=o.voiceRecognition?.autoResume??!1,oo=r=>{G.emit("voice:state",{active:Ie.active,source:r,timestamp:Date.now()})},Tn=()=>{$e(r=>({...r,voiceState:{active:Ie.active,timestamp:Date.now(),manuallyDeactivated:Ie.manuallyDeactivated}}))},pv=()=>{if(o.voiceRecognition?.enabled===!1)return;let r=jp(x.voiceState),a=!!r.active,d=Number(r.timestamp??0);Ie.manuallyDeactivated=!!r.manuallyDeactivated,a&&Date.now()-d<Yx&&setTimeout(()=>{Ie.active||(Ie.manuallyDeactivated=!1,Nt(o.voiceRecognition?.provider)?S.toggleVoice().then(()=>{Ie.active=S.isVoiceActive(),oo("restore"),S.isVoiceActive()&&ns()}):Oa("restore"))},1e3)},uv=()=>S?bb(S.getMessages()).filter(r=>!r.__skipPersist):[],fa=null,rg=(r,a)=>{typeof console<"u"&&console.error(r,a)},ha=(r,a)=>{let d=()=>{try{let D=r();return!D||typeof D.then!="function"?null:Promise.resolve(D).catch($=>{rg(a,$)})}catch(D){return rg(a,D),null}},m=fa,f=m?m.then(()=>d()??void 0):d();if(!f)return;let b=f.finally(()=>{fa===b&&(fa=null)});fa=b};function Ur(r){if(!v?.save)return;let a=r?bb(r):S?uv():[],d=T&&S?.getResumableHandle();d&&(x={...x,durableResume:{executionId:d.executionId,after:d.lastEventId}});let m={messages:a,metadata:x,artifacts:dn.artifacts,selectedArtifactId:dn.selectedId,...ur?{draft:ur}:{}};ha(()=>v.save(m),"[AgentWidget] Failed to persist state:")}let ur,ya=()=>!v?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,Qs=Fh({write:()=>{if(!ya())return;let r=ie.getState(),a=Oh({text:r.text,mentionRefs:r.mentionRefs,contentSegments:od(),selectedModelId:r.selectedModelId,activeModeIds:r.activeModeIds,quote:r.quote});JSON.stringify(a)!==JSON.stringify(ur)&&(ur=a,Ur())}});function sg(){ya()&&Qs.schedule()}function Tc(){Qs.flush()}function ig(r){if(!ya())return;let a=_h(r,{mentionSourceIds:(o.contextMentions?.sources??[]).map(d=>d.id),modelIds:(o.composer?.models??[]).map(d=>d.id),modes:o.composer?.modes??[]});a&&(ur=r,Z&&!Z.value&&(Z.value=a.text,Z.dispatchEvent(new Event("input",{bubbles:!0})),Rn()),a.selectedModelId&&(ie.setSelectedModelId(a.selectedModelId),Ao?.repaint()),Zi(a.activeModeIds??[]),a.quote&&Wn(a.quote),Qs.cancel())}function ba(){Qs.cancel(),ur&&(ur=void 0,ya()&&Ur())}let qr=null,ag=()=>Pe.querySelector("#persona-scroll-container")||j,jr=()=>{qr!==null&&(cancelAnimationFrame(qr),qr=null),Kt=!1},lg=()=>{Po!==null&&(cancelAnimationFrame(Po),Po=null),pa=!1,jr()},gv=()=>on&&Pc()&&(nn()!=="anchor-top"||du()),kc=()=>{let r=Ds()||"Jump to latest",a=gv();ft.toggleAttribute("data-persona-scroll-to-bottom-streaming",a),Lo>0?(Qo.textContent=String(Lo),Qo.style.display="",ft.setAttribute("aria-label",`${r} (${Lo} new)`)):(Qo.textContent="",Qo.style.display="none",ft.setAttribute("aria-label",a?`${r} (response streaming below)`:r))},cg=()=>{Lo!==0&&(Lo=0,kc())},mv=()=>{let r=vt?.spacerHeight??0;return r<=0?Er(j,to):wa(r)-j.scrollTop-j.clientHeight<=to},Pc=()=>xo()?!rn.isFollowing():!mv(),Lc=()=>!!S&&S.getMessages().length>0,Ht=()=>{if(!$b()||Wb()){ft.parentNode&&ft.remove(),ft.style.display="none";return}ft.parentNode!==re&&re.appendChild(ft),Jo();let a=uo(j)>0&&Pc()&&Lc();a?kc():cg(),ft.style.display=a?"":"none"},Kr=()=>{rn.pause()&&(lg(),Ht())},On=()=>{rn.resume(),cg(),Ht()},Ho=(r=!1)=>{xo()&&Lc()&&rn.isFollowing()&&(!r&&!on||(Po!==null&&(cancelAnimationFrame(Po),Po=null),pa=!0,Po=requestAnimationFrame(()=>{Po=null,pa=!1,rn.isFollowing()&&fv(ag(),r?220:140)})))},dg=(r,a,d,m=()=>!0)=>{let f=r.scrollTop,b=a(),D=b-f;if(jr(),Math.abs(D)<1){Kt=!0,r.scrollTop=b,sn=r.scrollTop,Kt=!1;return}let $=performance.now();Kt=!0;let F=K=>1-Math.pow(1-K,3),q=K=>{if(!m()){jr();return}let X=a();X!==b&&(b=X,D=b-f);let ae=K-$,He=Math.min(ae/d,1),Fe=F(He),De=f+D*Fe;r.scrollTop=De,sn=r.scrollTop,He<1?qr=requestAnimationFrame(q):(r.scrollTop=b,sn=r.scrollTop,qr=null,Kt=!1)};qr=requestAnimationFrame(q)},fv=(r,a=500)=>{let d=uo(r)-r.scrollTop;if(Math.abs(d)<1){sn=r.scrollTop;return}if(Math.abs(d)>=lv){jr(),Kt=!0,r.scrollTop=uo(r),sn=r.scrollTop,Kt=!1;return}dg(r,()=>uo(r),a,()=>rn.isFollowing())},Ic=()=>{if(!Lc()){Ht();return}let r=ag();Kt=!0,r.scrollTop=uo(r),sn=r.scrollTop,Kt=!1,Ht()},gr=r=>{let a=0,d=r;for(;d&&d!==j;)a+=d.offsetTop,d=d.offsetParent;return a},hv=()=>{let r=j.getRootNode();return(typeof r.getSelection=="function"?r.getSelection():null)??j.ownerDocument.getSelection()},va=()=>Lf(hv(),j),Hc=()=>{if(zb()!=="last-user-turn")return!1;let r=S?.getMessages()??[];if(r.length<2)return!1;let a=[...r].reverse().find(b=>b.role==="user");if(!a)return!1;let d=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(a.id):a.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),m=j.querySelector(`[data-message-id="${d}"]`);if(!m)return!1;let f=Math.min(Math.max(0,gr(m)-Os()),uo(j));return Kt=!0,j.scrollTop=f,sn=j.scrollTop,Kt=!1,nn()==="follow"&&!Er(j,to)&&rn.pause(),Ht(),!0},Ca=r=>{let a=Math.max(0,Math.round(r));cn.style.height=`${a}px`,cn.style.display=a>0?"":"none",vt&&(vt.spacerHeight=Math.max(0,r))},wa=r=>{let a=parseFloat(getComputedStyle(j).paddingBottom)||0,d=0;for(let f of Array.from(j.children)){if(f===cn||f.offsetHeight===0)continue;let b=gr(f)+f.offsetHeight;b>d&&(d=b)}let m=j.scrollHeight-r;return d>0?Math.min(d+a,m):m},yv=()=>{if(!vt||vt.spacerHeight<=0)return;let r=wa(vt.spacerHeight),a=Math.max(0,Math.round(j.scrollTop)+j.clientHeight-r+to);a<vt.spacerHeight&&(Ca(a),Ht())},mr=()=>{dr!==null&&(cancelAnimationFrame(dr),dr=null),jr(),vt=null,cn.style.height="0px",cn.style.display="none"},pg=r=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Rc=r=>j.querySelector(`[data-message-id="${pg(r)}"]`),ug=r=>{dr!==null&&cancelAnimationFrame(dr),dr=requestAnimationFrame(()=>{dr=null;let a=pg(r),d=j.querySelector(`[data-message-id="${a}"]`);if(!d)return;let m=gr(d),f=vt?.spacerHeight??0,b=wa(f),{targetScrollTop:D,spacerHeight:$}=Hd({anchorOffsetTop:m,topOffset:Os(),viewportHeight:j.clientHeight,contentHeight:b,slack:to});vt={initialSpacerHeight:$,contentHeightAtAnchor:b,spacerHeight:$},Ca($),dg(j,()=>d.isConnected?Math.max(0,gr(d)-Os()):D,220)})},Gr=()=>{if(nn()!=="anchor-top"||!vt||!zr)return;let r=Rc(zr);if(!r)return;jr();let a=vt.spacerHeight,d=wa(a),{targetScrollTop:m,spacerHeight:f}=Hd({anchorOffsetTop:gr(r),topOffset:Os(),viewportHeight:j.clientHeight,contentHeight:d,slack:to});vt={initialSpacerHeight:f,contentHeightAtAnchor:d,spacerHeight:f},Ca(f),Kt=!0,j.scrollTop=m,sn=j.scrollTop,Kt=!1,Ht()},bv=()=>{if(xo()){if(!rn.isFollowing()||Er(j,1))return;Ho(!on);return}if(vt&&vt.initialSpacerHeight>0){let r=j.scrollHeight-vt.spacerHeight,a=If({initialSpacerHeight:vt.initialSpacerHeight,contentHeightAtAnchor:vt.contentHeightAtAnchor,currentContentHeight:r});a!==vt.spacerHeight&&Ca(a)}Ht()},vv=r=>{let a=nn();a==="follow"?(On(),Ho(!0)):a==="anchor-top"&&(Ys=!1,ua=!0,ga=!1,zr=r,ug(r))},Cv=()=>{if(nn()==="anchor-top"){if(ua){Ys=!1;return}Ys=!0,mr(),On(),Ho(!0)}},wv=96,Sv=r=>{if(pr===null)return!0;let a=Rc(pr),d=Rc(r);if(!a||!d)return!0;let m=gr(d)-gr(a);return Os()+m>j.clientHeight-wv},xv=r=>{if(nn()!=="anchor-top"||!ua||ga||va())return;let a=pr===null;for(let d of r){if(!a){d.id===pr&&(a=!0);continue}if(Ef(d)){if(d.id===zr||!Sv(d.id))return;zr=d.id,ug(d.id);return}}},Av=r=>{let a=new Map;r.forEach(d=>{let m=Mc.get(d.id);a.set(d.id,{streaming:d.streaming,role:d.role}),!m&&d.role==="assistant"&&(G.emit("assistant:message",d),!$r&&(nn()!=="anchor-top"||du())&&Pc()&&(Lo+=1,kc(),Ht(),Ns(Lo===1?"1 new message below.":`${Lo} new messages below.`))),d.role==="assistant"&&m?.streaming&&d.streaming===!1&&G.emit("assistant:complete",d),d.variant==="approval"&&d.approval&&(m?d.approval.status!=="pending"&&G.emit("approval:resolved",{approval:d.approval,decision:d.approval.status}):G.emit("approval:requested",{approval:d.approval,message:d}))}),Mc.clear(),a.forEach((d,m)=>{Mc.set(m,d)})},Xs=(r,a)=>{let d=a==="user"?"user":"assistant",m=o.layout?.messages?.[d],f=m?.width??"content",b=m?.maxWidth??(f==="full"?`var(--persona-message-${d}-max-width, 100%)`:void 0);r.classList.add("persona-message-row"),r.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),r.classList.add(`persona-message-row-${a}`,`persona-message-width-${f}`),r.classList.toggle("persona-justify-end",a==="user"),r.setAttribute("data-message-role",a),r.setAttribute("data-message-width",f),b?r.style.setProperty("--persona-message-row-max-width",b):r.style.removeProperty("--persona-message-row-max-width")},ro=(r,a)=>{let d=document.createElement("div");return d.className="persona-flex",d.id=`wrapper-${r}`,d.setAttribute("data-wrapper-id",r),Xs(d,a),d},Mv=(r,a,d)=>{let m=new Set;for(let M of a){let me=M.variant==="tool"?"tool":M.variant==="reasoning"?"reasoning":null;if(!me||qo(o,me)!=="row")continue;let fe=me==="tool"?o.features?.toolCallDisplay:o.features?.reasoningDisplay;fe?.expandable!==!1&&(m.add(M.id),l.observe(M,me,me==="tool"?s:i,fe))}let f=document.createElement("div"),D=(()=>{let M=g.find(me=>me.renderLoadingIndicator);if(M?.renderLoadingIndicator)return M.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),$=(M,me)=>me==null?!1:typeof me=="string"?(M.textContent=me,!0):(M.appendChild(me),!0),F=new Set,q=new Map,K=new Set,X=g.some(M=>M.renderAskUserQuestion),ae=[],He=[],Fe=o.enableComponentStreaming!==!1,De=o.approval!==!1,Gt=[],nt=o.messageActions,it=nt?.showRegenerate===!0&&nt.enabled!==!1&&pn.current?.isStreaming()!==!0?ih(a):null,Ft=nt?.showEdit===!0&&nt.enabled!==!1,pt=nt?.showQuote===!0&&nt.enabled!==!1,ze=null,Vn=o.features?.reasoningDisplay?.completedVisibility,$n=M=>Vn==="removed"?!0:Vn==="removed-when-short"?qm(M,o.features?.reasoningDisplay?.shortThinkThreshold):!1,hn=o.features?.toolCallDisplay?.completedVisibility==="removed",yn=M=>M.variant==="reasoning"&&M.reasoning?.status==="complete"?$n(M.reasoning):hn&&M.variant==="tool"&&M.toolCall?.status==="complete";if(a.forEach(M=>{if(yn(M))return;if(F.add(M.id),q.set(M.id,M.role),ar===M.id&&ko){let ye=ro(M.id,M.role);ye.setAttribute("data-persona-message-edit-stub","true"),ye.setAttribute("data-preserve-runtime","true"),f.appendChild(ye),ze={messageId:M.id,element:ko.element};return}let me=X&&cs(M),fe=De&&M.variant==="approval"&&!!M.approval,U=!me&&M.role==="assistant"&&!M.variant&&Fe&&qp(M);!fe&&To.has(M.id)&&(r.querySelector(`#wrapper-${M.id}`)?.removeAttribute("data-preserve-runtime"),To.delete(M.id)),!U&&ir.has(M.id)&&(r.querySelector(`#wrapper-${M.id}`)?.removeAttribute("data-preserve-runtime"),ir.delete(M.id));let Ue=cs(M)?`:${M.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${M.agentMetadata?.askUserQuestionAnswers?Object.keys(M.agentMetadata.askUserQuestionAnswers).length:0}`:"",mt={canRegenerate:it===M.id,canEdit:Ft&&$d(M),canQuote:pt&&!M.variant&&(M.content?.trim().length??0)>0},Bt=`${mt.canRegenerate?"r":""}${mt.canEdit?"e":""}${mt.canQuote?"q":""}`,At=ty(M,cr)+Ue+`:${Bt}`,Ye=me||fe||U?null:oy(It,M.id,At);if(Ye){f.appendChild(Ye.cloneNode(!0)),cs(M)&&M.toolCall?.id&&M.agentMetadata?.awaitingLocalTool===!0&&!M.agentMetadata?.askUserQuestionAnswered&&(K.add(M.toolCall.id),yc(M));return}let ut=null,Ct=g.find(ye=>!!(M.variant==="reasoning"&&ye.renderReasoning||M.variant==="tool"&&ye.renderToolCall||!M.variant&&ye.renderMessage)),ue=o.layout?.messages;if(cs(M)&&M.agentMetadata?.askUserQuestionAnswered===!0){Vr.delete(M.id),r.querySelector(`#wrapper-${M.id}`)?.removeAttribute("data-preserve-runtime");return}if(Ja(M)&&ds(o).enabled)return;if(cs(M)&&o.features?.askUserQuestion?.enabled!==!1){let ye=g.find(wt=>typeof wt.renderAskUserQuestion=="function");if(ye&&pn.current){let wt=Vr.get(M.id),bn=wt!==At,Mt=null;if(bn){let{payload:we,complete:be}=Jm(M),Vo=M.id,ht=()=>pn.current?.getMessages().find(Yt=>Yt.id===Vo);Mt=ye.renderAskUserQuestion({message:M,payload:we,complete:be,resolve:Yt=>{let co=ht();co&&pn.current?.resolveAskUserQuestion(co,Yt)},dismiss:()=>{let Yt=ht();Yt?.agentMetadata?.awaitingLocalTool&&(pn.current?.markAskUserQuestionResolved(Yt),pn.current?.resolveAskUserQuestion(Yt,"(dismissed)"))},config:o})}let qe=wt!=null;if(bn&&Mt===null&&!qe){M.agentMetadata?.awaitingLocalTool===!0&&!M.agentMetadata?.askUserQuestionAnswered&&(K.add(M.toolCall.id),yc(M));return}let ge=ro(M.id,M.role);ge.setAttribute("data-ask-plugin-stub","true"),ge.setAttribute("data-preserve-runtime","true"),f.appendChild(ge),ae.push({messageId:M.id,fingerprint:At,bubble:Mt});return}else{M.agentMetadata?.awaitingLocalTool===!0&&!M.agentMetadata?.askUserQuestionAnswered&&(K.add(M.toolCall.id),yc(M));return}}else if(fe){let ye=O();if(!ye){f.appendChild(ro(M.id,M.role));return}let wt=g.find(ge=>typeof ge.renderApproval=="function")??I,Mt=To.get(M.id)!==At,qe=null;if(Mt&&wt?.renderApproval){let ge=M.id,we=(be,Vo)=>{let ht=pn.current?.getMessages().find(Yt=>Yt.id===ge);ht?.approval&&(ht.approval.toolType==="webmcp"?pn.current?.resolveWebMcpApproval(ht.id,be):pn.current?.resolveApproval(ht.approval,be,Vo))};qe=wt.renderApproval({message:M,defaultRenderer:()=>ye.createApprovalBubble(M,o,c),config:o,approve:be=>we("approved",be),deny:be=>we("denied",be)})}if(Mt&&qe===null)r.querySelector(`#wrapper-${M.id}`)?.removeAttribute("data-preserve-runtime"),To.delete(M.id),ut=ye.createApprovalBubble(M,o,c);else{let ge=ro(M.id,M.role);ge.setAttribute("data-approval-plugin-stub","true"),ge.setAttribute("data-preserve-runtime","true"),f.appendChild(ge),Gt.push({messageId:M.id,fingerprint:At,bubble:qe});return}}else if(Ct)if(M.variant==="reasoning"&&M.reasoning&&Ct.renderReasoning){if(!Is)return;ut=Ct.renderReasoning({message:M,defaultRenderer:()=>Tp(M,o,i),config:o})}else if(M.variant==="tool"&&M.toolCall&&Ct.renderToolCall){if(!Hs)return;ut=Ct.renderToolCall({message:M,defaultRenderer:()=>Ip(M,o,s),config:o})}else Ct.renderMessage&&(ut=Ct.renderMessage({message:M,defaultRenderer:()=>{let ye=hp(M,d,ue,o.messageActions,Wr,{loadingIndicatorRenderer:D,widgetConfig:o,actionEligibility:mt});return M.role!=="user"&&Q(ye,M,o,S),ye},config:o}));if(!ut&&U){let ye=ub(M);if(ye){let wt=ir.get(M.id),bn=wt!==At,Mt=o.wrapComponentDirectiveInBubble!==!1&&go.getOptions(ye.component)?.bubbleChrome!==!1,qe=null;if(bn){let ge=db(ye,{config:o,message:M,transform:d});if(ge&&ye.component==="PersonaArtifactInline"){let we=ge.hasAttribute("data-artifact-inline")?ge:ge.querySelector("[data-artifact-inline]"),be=we?.getAttribute("data-artifact-inline")??"",Vo=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(be):be,ht=be?r.querySelector(`#wrapper-${M.id}`)?.querySelector(`[data-artifact-inline="${Vo}"]`)??null:null;we&&ht&&ht!==we&&yo()?.hasLiveInlineArtifactBlock(ht)&&(we===ge?ge=ht:we.replaceWith(ht))}if(ge)if(Mt){let we=document.createElement("div");if(we.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),we.id=`bubble-${M.id}`,we.setAttribute("data-message-id",M.id),M.content&&M.content.trim()){let be=document.createElement("div");be.className="persona-mb-3 persona-text-sm persona-leading-relaxed",be.innerHTML=d({text:M.content,message:M,streaming:!!M.streaming,raw:M.rawContent}),we.appendChild(be)}we.appendChild(ge),qe=we}else{let we=document.createElement("div");if(we.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",we.id=`bubble-${M.id}`,we.setAttribute("data-message-id",M.id),we.setAttribute("data-persona-component-directive","true"),M.content&&M.content.trim()){let be=document.createElement("div");be.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",be.innerHTML=d({text:M.content,message:M,streaming:!!M.streaming,raw:M.rawContent}),we.appendChild(be)}we.appendChild(ge),qe=we}}if(qe||wt!=null){let ge=ro(M.id,M.role);ge.setAttribute("data-component-directive-stub","true"),ge.setAttribute("data-preserve-runtime","true"),f.appendChild(ge),He.push({messageId:M.id,fingerprint:At,bubble:qe});return}}}if(!ut)if(M.variant==="reasoning"&&M.reasoning){if(!Is)return;ut=Tp(M,o,i)}else if(M.variant==="tool"&&M.toolCall){if(!Hs)return;ut=Ip(M,o,s)}else if(M.variant==="approval"&&M.approval){if(o.approval===!1)return;let ye=O();if(!ye)return;ut=ye.createApprovalBubble(M,o,c)}else{let ye=o.layout?.messages;ye?.renderUserMessage&&M.role==="user"?ut=ye.renderUserMessage({message:M,config:o,streaming:!!M.streaming}):ye?.renderAssistantMessage&&M.role==="assistant"?ut=ye.renderAssistantMessage({message:M,config:o,streaming:!!M.streaming}):ut=hp(M,d,ye,o.messageActions,Wr,{loadingIndicatorRenderer:D,widgetConfig:o,actionEligibility:mt}),M.role!=="user"&&ut&&Q(ut,M,o,S)}let Qe=ro(M.id,M.role);Qe.appendChild(ut),ry(It,M.id,At,Qe),f.appendChild(Qe)}),Re.composerOverlay&&Re.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(me=>{let fe=me.getAttribute("data-persona-ask-sheet-for");fe&&!K.has(fe)&&xd(Re.composerOverlay,fe)}),o.features?.toolCallDisplay?.grouped){let M=[],me=[],fe=o.features.toolCallDisplay.groupedMode==="summary";a.forEach(U=>{if(U.variant==="tool"&&U.toolCall&&Hs){if(hn&&U.toolCall.status==="complete")return;me.push(U);return}U.variant==="reasoning"&&(!Is||U.reasoning?.status==="complete"&&$n(U.reasoning))||((me.length>1||fe&&me.length>0)&&M.push(me),me=[])}),(me.length>1||fe&&me.length>0)&&M.push(me),M.forEach(U=>{let Ue=U.map(ue=>Array.from(f.children).find(Qe=>Qe instanceof HTMLElement&&Qe.getAttribute("data-wrapper-id")===ue.id)).filter(ue=>!!ue);if(Ue.length<(fe?1:2))return;let mt=ro(`tool-group-${U[0].id}`,"assistant");if(mt.setAttribute("data-persona-tool-group-row","true"),o.features?.toolCallDisplay?.groupedMode==="collapsible"){let ue=`tool-group-${U[0].id}`,Qe=U.some(qe=>qe.toolCall?.status!=="complete"),ye={...U[0],id:ue,toolCall:{id:ue,name:`${U.length} tools`,status:Qe?"running":"complete",chunks:U.flatMap(qe=>qe.toolCall?.chunks??[]),success:!U.some(qe=>qe.toolCall?.success===!1)}};m.add(ue),l.observe(ye,"tool",s,o.features.toolCallDisplay);let wt=`${Qe?"Using":"Used"} ${U.length} tools`,bn=o.toolCall?.renderGroupedSummary?.({messages:U,toolCalls:U.map(qe=>qe.toolCall),defaultSummary:wt,config:o}),Mt=_f(ye,o,s.has(ue),bn??wt);Mt.bubble.classList.add("persona-tool-group"),Mt.body.dataset.personaToolGroupStack="true",Ue[0].before(mt),mt.appendChild(Mt.bubble),Ue.forEach((qe,ge)=>{qe.style.setProperty("--persona-message-row-max-width","100%"),qe.style.setProperty("--persona-activity-stagger",`${ge*40}ms`),qe.classList.add("persona-activity-group-child"),Mt.body.appendChild(qe)});return}let Bt=document.createElement("div");Bt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Bt.setAttribute("data-persona-tool-group","true");let At=document.createElement("div");At.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",At.id=`tool-group-summary-${U[0].id}`;let Ye=`Called ${U.length} ${U.length===1?"tool":"tools"}`,ut=o.toolCall?.renderGroupedSummary?.({messages:U,toolCalls:U.map(ue=>ue.toolCall).filter(ue=>!!ue),defaultSummary:Ye,config:o});$(At,ut)||(At.textContent=Ye);let Ct=document.createElement("div");Ct.className="persona-tool-group-stack persona-flex persona-flex-col",Ct.id=`tool-group-stack-${U[0].id}`,Ct.setAttribute("data-persona-tool-group-stack","true"),Bt.appendChild(At),fe||Bt.appendChild(Ct),mt.appendChild(Bt),Ue[0].before(mt),Ue.forEach((ue,Qe)=>{if(fe){ue.remove();return}ue.style.setProperty("--persona-message-row-max-width","100%");let ye=document.createElement("div");ye.className="persona-tool-group-item persona-relative",ye.setAttribute("data-persona-tool-group-item","true"),Qe<Ue.length-1&&ye.setAttribute("data-persona-tool-group-connector","true"),ye.appendChild(ue),Ct.appendChild(ye)})})}l.prune(m),sy(It,F);let Fo=M=>M.variant==="tool"&&!Hs||M.variant==="reasoning"&&!Is||yn(M),zn=a.some(M=>M.role==="assistant"&&M.streaming&&!Fo(M)),kn=a.length-1;for(;kn>=0&&Fo(a[kn]);)kn--;let No=kn>=0?a[kn]:void 0,pi=kn<a.length-1,vr=No?.role==="assistant"&&!No.streaming&&No.variant!=="approval"&&!pi;if(on&&a.some(M=>M.role==="user")&&!zn&&!vr){let M={config:o,streaming:!0,location:"standalone",defaultRenderer:Bi},me=g.find(U=>U.renderLoadingIndicator),fe=null;if(me?.renderLoadingIndicator&&(fe=me.renderLoadingIndicator(M)),fe===null&&o.loadingIndicator?.render&&(fe=o.loadingIndicator.render(M)),fe===null&&(fe=Bi()),fe){let U=document.createElement("div"),Ue=o.loadingIndicator?.showBubble!==!1,mt=o.layout?.messages?.layout??"bubble";U.className=Ue?Di("assistant",mt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),U.setAttribute("data-typing-indicator","true"),Ue&&(U.style.color="var(--persona-message-assistant-text, var(--persona-text))",mt!=="flat"&&(U.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",U.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),U.appendChild(fe);let Bt=ro("typing-indicator","assistant");Bt.appendChild(U),f.appendChild(Bt)}}if(!on&&a.length>0){let M=a[a.length-1],me={config:o,lastMessage:M,messageCount:a.length},fe=g.find(Ue=>Ue.renderIdleIndicator),U=null;if(fe?.renderIdleIndicator&&(U=fe.renderIdleIndicator(me)),U===null&&o.loadingIndicator?.renderIdle&&(U=o.loadingIndicator.renderIdle(me)),U){let Ue=document.createElement("div"),mt=o.loadingIndicator?.showBubble!==!1;Ue.className=mt?["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-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ue.setAttribute("data-idle-indicator","true"),Ue.appendChild(U);let Bt=ro("idle-indicator","assistant");Bt.appendChild(Ue),f.appendChild(Bt)}}if(Gf(f),Rl(r,f),Bd(r),ze){let{messageId:M,element:me}=ze,fe=r.querySelector(`#wrapper-${M}`);fe&&me.parentElement!==fe&&(Xs(fe,q.get(M)??"user"),fe.replaceChildren(me))}if(ae.length>0)for(let{messageId:M,fingerprint:me,bubble:fe}of ae){let U=r.querySelector(`#wrapper-${M}`);U&&(Xs(U,q.get(M)??"assistant"),fe!==null&&(U.replaceChildren(fe),U.setAttribute("data-bubble-fp",me),Vr.set(M,me)))}if(Vr.size>0)for(let M of Vr.keys())F.has(M)||Vr.delete(M);if(He.length>0)for(let{messageId:M,fingerprint:me,bubble:fe}of He){let U=r.querySelector(`#wrapper-${M}`);U&&(Xs(U,q.get(M)??"assistant"),fe!==null&&(U.replaceChildren(fe),U.setAttribute("data-bubble-fp",me),ir.set(M,me)))}if(ir.size>0)for(let M of ir.keys())F.has(M)||ir.delete(M);if(Gt.length>0)for(let{messageId:M,fingerprint:me,bubble:fe}of Gt){let U=r.querySelector(`#wrapper-${M}`);U&&(Xs(U,q.get(M)??"assistant"),fe!==null&&(U.replaceChildren(fe),U.setAttribute("data-bubble-fp",me),To.set(M,me)))}if(To.size>0)for(let M of To.keys())F.has(M)||To.delete(M)},Wc=!1,Sa=()=>{Wc||(Wc=!0,Tr().catch(()=>{}),Om().catch(()=>{Wc=!1}))},un=(r,a,d)=>{a.length>0&&Sa(),Mv(r,a,d),Lu()},Js=null,Ev=()=>{if(Js)return;let r=d=>{let m=d.composedPath();m.includes(Pe)||St&&m.includes(St)||Ge(!1,"user")};Js=r,(t.ownerDocument??document).addEventListener("pointerdown",r,!0)},gg=()=>{if(!Js)return;(t.ownerDocument??document).removeEventListener("pointerdown",Js,!0),Js=null};oe.push(()=>gg());let Zs=null,Tv=()=>{if(Zs)return;let r=d=>{d.key==="Escape"&&(d.isComposing||Ge(!1,"user"))};Zs=r,(t.ownerDocument??document).addEventListener("keydown",r,!0)},mg=()=>{if(!Zs)return;(t.ownerDocument??document).removeEventListener("keydown",Zs,!0),Zs=null};oe.push(()=>mg());let ei=!1,fg=new Set,kv=()=>{let r=o.launcher?.composerBar?.peek?.streamAnimation;return r||o.features?.streamAnimation},Yr=()=>{if(!Ae())return;let r=Re.peekBanner,a=Re.peekTextNode;if(!r||!a)return;if(Se){r.classList.remove("persona-pill-peek--visible");return}let d=S?.getMessages()??[],m;for(let nt=d.length-1;nt>=0;nt--){let it=d[nt];if(it.role==="assistant"&&it.content){m=it;break}}if(!m){r.classList.remove("persona-pill-peek--visible");return}let f=m.content,b=!!m.streaming,D=kv(),$=cl(D),F=$.type!=="none"?Sc($.type,D?.plugins):null,q=F?.isAnimating?.(m)===!0,K=F!==null&&(b||q);K&&F&&!fg.has(F.name)&&(yi(F,t),fg.add(F.name));let X=K&&F?.containerClass?F.containerClass:null,ae=a.dataset.personaPeekStreamClass??null;ae&&ae!==X&&(a.classList.remove(ae),delete a.dataset.personaPeekStreamClass),X&&ae!==X&&(a.classList.add(X),a.dataset.personaPeekStreamClass=X),K?(a.style.setProperty("--persona-stream-step",`${$.speed}ms`),a.style.setProperty("--persona-stream-duration",`${$.duration}ms`)):(a.style.removeProperty("--persona-stream-step"),a.style.removeProperty("--persona-stream-duration"));let He=K?dl(f,$.buffer,F,m,b):f;if(K&&$.placeholder==="skeleton"&&b&&(!He||!He.trim())){let nt=document.createElement("div"),it=hi();it.classList.add("persona-pill-peek__skeleton"),nt.appendChild(it),Rl(a,nt)}else{let nt=Math.max(0,He.length-100),it=He.length>100?He.slice(-100):He,Ft=ja(it);if(!K||!F){let pt=He.length>100?`\u2026${it}`:it;a.textContent!==pt&&(a.textContent=pt)}else{let pt=Ft;(F.wrap==="char"||F.wrap==="word")&&(pt=fi(Ft,F.wrap,`peek-${m.id}`,{skipTags:F.skipTags,startIndex:nt}));let ze=document.createElement("div");if(ze.innerHTML=pt,F.useCaret&&it.length>0){let Vn=pl(),$n=ze.querySelectorAll(".persona-stream-char, .persona-stream-word"),hn=$n[$n.length-1];hn?.parentNode?hn.parentNode.insertBefore(Vn,hn.nextSibling):ze.appendChild(Vn)}Rl(a,ze),F.onAfterRender?.({container:a,bubble:r,messageId:m.id,message:m,speed:$.speed,duration:$.duration})}}let Gt=on||ei;r.classList.toggle("persona-pill-peek--visible",Gt)};if(Ae()){let r=Re.peekBanner;if(r){let m=f=>{f.preventDefault(),f.stopPropagation(),Ge(!0,"user")};r.addEventListener("pointerdown",m),oe.push(()=>{r.removeEventListener("pointerdown",m)})}let a=()=>{ei||(ei=!0,Yr())},d=()=>{ei&&(ei=!1,Yr())};le.addEventListener("pointerenter",a),le.addEventListener("pointerleave",d),oe.push(()=>{le.removeEventListener("pointerenter",a),le.removeEventListener("pointerleave",d)}),St&&(St.addEventListener("pointerenter",a),St.addEventListener("pointerleave",d),oe.push(()=>{St.removeEventListener("pointerenter",a),St.removeEventListener("pointerleave",d)}))}let Pv=r=>{let a=o.launcher?.composerBar??{},d=a.expandedSize??"anchored",m=a.bottomOffset??"16px",f=a.collapsedMaxWidth,b=a.expandedMaxWidth??"880px",D=a.expandedTopOffset??"5vh",$=a.modalMaxWidth??"880px",F=a.modalMaxHeight??"min(90vh, 800px)",q="calc(100vw - 32px)",K="var(--persona-pill-area-height, 80px)",X=Pe.style;if(X.left="",X.right="",X.top="",X.bottom="",X.transform="",X.width="",X.maxWidth="",X.height="",X.maxHeight="",St){let ae=St.style;ae.bottom=m,ae.width=f??""}if(r&&d!=="fullscreen"){if(d==="modal"){X.top="50%",X.left="50%",X.transform="translate(-50%, -50%)",X.bottom="auto",X.right="auto",X.width=$,X.maxWidth=q,X.maxHeight=F,X.height=F;return}X.left="50%",X.transform="translateX(-50%)",X.bottom=`calc(${m} + ${K})`,X.top=D,X.width=b,X.maxWidth=q}},ti=()=>{if(Se&&Sa(),!Ve())return;if(Ae()){let q=(o.launcher?.composerBar??{}).expandedSize??"anchored",K=Se?"expanded":"collapsed";Pe.dataset.state=K,Pe.dataset.expandedSize=q,St&&(St.dataset.state=K,St.dataset.expandedSize=q),Pe.style.removeProperty("display"),Pe.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Pv(Se),re.style.display=Se?"flex":"none",er(),Se?(Ev(),Tv()):(gg(),mg()),Yr();return}let r=rt(o),a=t.ownerDocument.defaultView??window,d=o.launcher?.mobileBreakpoint??640,m=o.launcher?.mobileFullscreen??!0,f=a.innerWidth<=d,b=m&&f&&de,D=Cn(o).reveal;Se?(Pe.style.removeProperty("display"),Pe.style.display=r?"flex":"",Pe.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-95","persona-opacity-0"),le.classList.add("persona-scale-100","persona-opacity-100"),ct?(ct.setPanelOpen(!0),ct.element.style.display="none"):_t&&(_t.style.display="none")):(r?r&&(D==="overlay"||D==="push")&&!b?(Pe.style.removeProperty("display"),Pe.style.display="flex",Pe.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Pe.style.setProperty("display","none","important"),Pe.classList.remove("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Pe.style.display="",Pe.classList.add("persona-pointer-events-none","persona-opacity-0"),le.classList.remove("persona-scale-100","persona-opacity-100"),le.classList.add("persona-scale-95","persona-opacity-0")),ct?(ct.setPanelOpen(!1),ct.element.style.display=r?"none":""):_t&&(_t.style.display=r?"none":""))},Ge=(r,a="user")=>{if(!Ve()||Se===r)return;let d=Se;Se=r,ti();let m=(()=>{let b=o.launcher?.sidebarMode??!1,D=t.ownerDocument.defaultView??window,$=o.launcher?.mobileFullscreen??!0,F=o.launcher?.mobileBreakpoint??640,q=D.innerWidth<=F,K=rt(o)&&$&&q,X=Ae()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return b||$&&q&&de||K||X})();if(Se&&m){if(!Bn){let b=t.getRootNode(),D=b instanceof ShadowRoot?b.host:t.closest(".persona-host");D&&(Bn=ap(D,o.launcher?.zIndex??Dt))}Dn||(Dn=lp(t.ownerDocument))}else Se||(Bn?.(),Bn=null,Dn?.(),Dn=null);Se&&(li(),Hc()||(nn()==="follow"?Ho(!0):Ic()));let f={open:Se,source:a,timestamp:Date.now()};Se&&!d?G.emit("widget:opened",f):!Se&&d&&G.emit("widget:closed",f),G.emit("widget:state",{open:Se,launcherEnabled:de,voiceActive:Ie.active,streaming:S.isStreaming()})},Ro={inputDisabled:!1,sendDisabled:!1},_n=()=>Ro.inputDisabled,Bc=()=>Nt(o.voiceRecognition?.provider)&&!!S&&(S.isBargeInActive()||["listening","processing","speaking"].includes(S.getVoiceStatus())),fr=()=>Ro.inputDisabled||Ro.sendDisabled,Lv=()=>(Ro.inputDisabled?Ro.inputReason:void 0)??(Ro.sendDisabled?Ro.sendReason:void 0);function Dc(){if(!pe)return;if(ie.getState().phase==="streaming"){pe.disabled=!1;return}let r=_e?!_e.isReady():!1;pe.disabled=fr()||r}function xa(){if(!Hn)return;let r=ie.getState(),a=o.sendButton?.visibility==="when-text"&&r.phase!=="streaming"&&r.text.trim().length===0&&r.attachments.length===0;Hn.toggleAttribute("data-persona-send-hidden",a)}function Iv(){let r=Lv();if(Ae()){let a=Ut??Le;r?a.setAttribute("title",r):a.removeAttribute("title"),Le.toggleAttribute(Ts,!!r);return}if(r){We.setAttribute("role","status"),We.setAttribute("aria-live","polite"),We.setAttribute(Ts,""),We.textContent=r,ui(We,o.statusIndicator??{},"idle");return}if(We.hasAttribute(Ts)&&(We.removeAttribute("role"),We.removeAttribute("aria-live"),We.removeAttribute(Ts),C)){let a=S.getStatus();Ws(We,Jl(a),o.statusIndicator??{},a)}}function Oc(){let r=Pd(o.composer?.inputDisabled),a=Pd(o.composer?.sendDisabled);Ro={inputDisabled:r.disabled,inputReason:r.reason,sendDisabled:a.disabled,sendReason:a.reason},ie.setInputDisabled(r.disabled),ie.setSendDisabled(a.disabled);let d=ie.getState().phase==="streaming",m=r.disabled,f=d||m;Z&&(Z instanceof HTMLTextAreaElement?Z.disabled=m:Z.setAttribute("contenteditable",m?"false":"true"),Z.setAttribute("aria-disabled",m?"true":"false")),st&&(st.disabled=m),et&&(et.disabled=m);for(let b of lt?.affordanceButtons??[])b.querySelectorAll("button").forEach(D=>{D.disabled=m});te&&(te.disabled=m||d&&!Bc()),nr.forEach(b=>{b.elements.forEach(D=>{D.toggleAttribute("data-disabled",f),D instanceof HTMLButtonElement||D.setAttribute("aria-disabled",f?"true":"false")}),b.buttons.forEach(D=>{D.disabled=f})}),zc.forEach(b=>{b.toggleAttribute("data-disabled",f),b instanceof HTMLButtonElement?b.disabled=f:b.setAttribute("aria-disabled",f?"true":"false"),b.querySelectorAll("button").forEach(D=>{D.disabled=f})}),Le.dataset.personaComposerStreaming=d?"true":"false",Le.dataset.personaComposerInputDisabled=m?"true":"false",Le.dataset.personaComposerSendDisabled=fr()?"true":"false",Le.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(b=>{(b instanceof HTMLButtonElement||b instanceof HTMLInputElement||b instanceof HTMLTextAreaElement||b instanceof HTMLSelectElement)&&(b.disabled=d)}),Dc(),Iv()}let ni=r=>{ie.setStreaming(r),lu(r?"stop":"send"),Oc()},Aa=()=>{Ie.active||Z&&Z.focus()};G.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Aa(),200)});let hg=null,_c=!1,Fc=!xt.hidden,Wo=null,Nc=!z,Ma=null;oe.push(()=>{Ma?.cancel(),Ma=null});let Hv=r=>{let a=Ay(r);if(a===Qi)return;Qi=a,t.setAttribute("data-persona-conversation-state",a);let d=oc();Ji(),Nc&&(Ma?.cancel(),Ma=Sy(Le,a==="active"?d:oc(),a==="active"?"drop":"rise",Xo().layout==="centered"?320:260)),Gr()},yg=null,bg,vg=null,Qr=null,Vc=!1,oi=r=>{let a=Xo(),d=`${a.variant}|${a.layout}|${a.dismiss}|${a.anchor??"bottom"}|${a.align??""}|${a.iconPlacement}|${a.kicker??""}|${a.title}|${a.subtitle}`;(d!==yg||a.icon!==bg)&&(yg=d,bg=a.icon,Fl({host:xt,iconHolder:Bb,kicker:Db,title:Ob,subtitle:_b,starterSuggestions:Zl},a));let m=a.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${a.message}`;m!==vg&&(vg=m,Nl(en,a.message,o));let f=r??(S?S.getMessages():o.initialMessages);Hv(f);let b=_c,D=!b&&Ss(a,f),$=D!==Fc;if(Fc=D,Qr){Wo?.cancel(),Wo=null,b!==Vc&&(Vc=b,b?vp(j,xt,null):bp(j,xt,Qr)),ws(j,xt,!b);return}if($&&!D&&!b&&a.dismiss==="on-first-message"&&Nc){Wo=wy(xt,q=>{Wo===q&&(Wo=null),!Fc&&!Qr&&(ws(j,xt,!1),Gr()),q?.cancel()});return}if(Wo){if(!D&&!b)return;Wo.cancel(),Wo=null}let F=!xt.hidden;ws(j,xt,D),!D&&F&&Gr()},$c=[],zc=[],Uc=!1,Cg=null,wg,Sg=()=>{zc.length=0;let r=$c.splice(0,$c.length);for(let a of r)try{a()}catch(d){console.warn("[persona] renderWelcome cleanup threw",d)}};oe.push(Sg);let Rv=(r,a)=>{let d=dp(r,a);if(!d)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),P("span");let m=o.suggestions?.starters,f=pp({item:{...d,behavior:d.behavior??m?.behavior??"send"},index:a,surface:"starter",source:"config",variant:m?.variant??"card",streaming:C?S.isStreaming():!1,config:o,plugins:g,chipsConfig:o.suggestionChipsConfig,session:S,getTextarea:()=>Z,eventTarget:xt,submitPrompt:Ra});return zc.push(f),f},qc=()=>{if(Uc)return;Uc=!0;let r=Xo();Cg=`${r.variant}|${r.layout}|${r.dismiss}|${r.title}|${r.subtitle}|${r.message??""}`,wg=r.icon;try{Sg(),vp(j,xt,Qr),Qr=null,Vc=!1;let a=S?S.getMessages():o.initialMessages,d=Ss(r,a),m=0,f=null;for(let b of g)if(b.renderWelcome&&(f=b.renderWelcome({config:r,variant:r.variant,visible:d,defaultRenderer:()=>xt,sendMessage:D=>{if(!S||S.isStreaming())return;let $=D.trim();$&&S.sendMessage($)},requestRender:()=>qc(),renderStarter:D=>Rv(D,m++),storage:E(b.id),onCleanup:D=>{$c.push(D)}}),f))break;f&&f!==xt&&(Qr=f,bp(j,xt,f))}finally{Uc=!1}oi()},Wv=()=>{let r=Xo();`${r.variant}|${r.layout}|${r.dismiss}|${r.title}|${r.subtitle}|${r.message??""}`===Cg&&r.icon===wg||qc()},Ea=()=>{oi(),Fr||(Z.placeholder=Hh(ie.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!S?.isStreaming()&&(pe.textContent=o.copy?.sendButtonLabel??"Send")),Z.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Z.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},Bv=!!o.setStoredConversationId,Xr=r=>$e(a=>{let d={...a};return delete d[r],d}),Ta=r=>{let a=x[r];return typeof a=="string"?a:null},xg=()=>{let r=x.durableResume;if(!r||typeof r!="object")return null;let a=r;return typeof a.executionId=="string"&&a.executionId.length>0&&typeof a.after=="string"&&a.after.length>0?{executionId:a.executionId,after:a.after}:null};o.clientToken&&(o={...o,getStoredSessionId:()=>Ta("sessionId"),setStoredSessionId:r=>{$e(a=>({...a,sessionId:r}))},clearStoredSessionId:o.clearStoredSessionId??(()=>Xr("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>Ta("conversationId")),setStoredConversationId:o.setStoredConversationId??(r=>{$e(a=>({...a,conversationId:r}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>Xr("conversationId"))});let Ag=()=>o.clientToken??null,Mg=r=>ib(r,$i(),o.persistState===!1),Eg=Ag(),gn=Eg?Mg(Eg):null,Dv=()=>{let r=x.pendingDisplayProjections;if(!r||typeof r!="object")return null;let a=r;return typeof a.conversationId!="string"||!Array.isArray(a.messageIds)?null:{conversationId:a.conversationId,messageIds:a.messageIds.filter(d=>typeof d=="string")}},Bo={...gn?{visitorStore:gn}:{},historyBootstrapReady:o.features?.history?.enabled===!0&&!jl()?Promise.all([ee,he]).then(()=>{}):ee,getStoredMessageCursor:()=>Ta("historyMessageCursor"),setStoredMessageCursor:r=>{if(r===null){Xr("historyMessageCursor");return}$e(a=>({...a,historyMessageCursor:r}))},getPendingDisplayProjections:Dv,setPendingDisplayProjections:r=>{if(!r){Xr("pendingDisplayProjections");return}$e(a=>({...a,pendingDisplayProjections:r}))},getStoredResumableHandle:xg,setStoredResumableHandle:r=>{if(!r){Xr("durableResume");return}$e(a=>({...a,durableResume:r}))},shouldResumeDurableConversation:()=>T&&xg()!==null,...Bv?{}:{getStoredConversationRevision:()=>Ta("conversationRevision"),setStoredConversationRevision:r=>{if(r===null){Xr("conversationRevision");return}$e(a=>({...a,conversationRevision:r}))}}};if(T){let r=o.onExecutionState,a=t.ownerDocument.defaultView,d=!1,m=()=>d=!0,f=()=>d=!1;a?.addEventListener("pagehide",m),a?.addEventListener("pageshow",f),oe.push(()=>{a?.removeEventListener("pagehide",m),a?.removeEventListener("pageshow",f)}),o={...o,reconnectStream:o.reconnectStream??(b=>S.getClient().reconnectClientTokenStream(b)),onExecutionState:b=>{(b||!d)&&Bo.setStoredResumableHandle?.(b?{executionId:b.executionId,after:b.lastEventId}:null),r?.(b)}}}let Ov=()=>{let r=Ag();if(r&&gn?.matches(r,$i(),o.persistState===!1)||!r&&!gn)return;gn?.destroy(),gn=r?Mg(r):null;let a={...Bo};gn?a.visitorStore=gn:delete a.visitorStore,Bo=a,S.setHistoryInternals(Bo)},hr=null,_v=()=>{hr==null&&(hr=setInterval(()=>{let r=ce.querySelectorAll("[data-tool-elapsed]");if(r.length===0){clearInterval(hr),hr=null;return}let a=Date.now();r.forEach(d=>{let m=Number(d.getAttribute("data-tool-elapsed"));m&&(d.textContent=d.closest(".persona-activity-row")?bi(a-m):Km(a-m))})},100))},jc=(r,a)=>{if(Object.is(r,a))return!0;if(r===null||a===null||typeof r!="object"||typeof a!="object")return!1;if(Array.isArray(r)||Array.isArray(a))return!Array.isArray(r)||!Array.isArray(a)||r.length!==a.length?!1:r.every((D,$)=>jc(D,a[$]));let d=r,m=a,f=Object.keys(d),b=Object.keys(m);return f.length===b.length&&f.every(D=>Object.prototype.hasOwnProperty.call(m,D)&&jc(d[D],m[D]))},Tg=r=>{let{content:a,rawContent:d,llmContent:m,...f}=r;return f},Kc=r=>r.role==="assistant"&&r.streaming===!0&&!r.variant&&!r.toolCall&&!r.tools&&!r.approval&&!r.reasoning&&!r.contentParts&&!r.stopReason&&!qp(r),Fv=(r,a,d)=>{if(r.length!==a.length)return!1;let m=r[d.index],f=a[d.index];return!m||!f||m.id!==d.id||f.id!==d.id?!1:(!Object.is(m.content,f.content)||!Object.is(m.rawContent,f.rawContent)||!Object.is(m.llmContent,f.llmContent))&&Kc(m)&&Kc(f)&&jc(Tg(m),Tg(f))},ka=null,Jr=null,yr=null,so=null,Gc=null,Nv=r=>{if(!T)return Ur(r);Gc=r,queueMicrotask(()=>{Gc===r&&(Gc=null,Ur(r))})},Pa=r=>{ka=r;let a,d;Jr=null;for(let f=r.length-1;f>=0;f-=1){let b=r[f];if(!a&&b.role==="user"&&(a=b),!d&&b.role==="assistant"&&(d=b),!Jr&&Kc(b)&&(Jr={index:f,id:b.id}),a&&d&&Jr)break}un(ce,r,Xt),yo()?.updateInlineArtifactBlocks(ce,dn.artifacts,{suppressTransition:on}),_v(),oi(r),sr(r),Ho(!on),Av(r),r.length===0&&(mr(),Ys=!0,ua=!1,zr=null,ga=!1),!xc||$r?(xc=!0,pr=a?.id??null,Ac=d?.id??null):a&&a.id!==pr?(pr=a.id,vv(a.id)):d&&d.id!==Ac&&Cv(),d&&(Ac=d.id),xv(r);let m=Ie.lastUserMessageId;a&&a.id!==m&&(Ie.lastUserMessageId=a.id,G.emit("user:message",a)),Ie.lastUserMessageWasVoice=!!a?.viaVoice,Nv(r),Yr()},Yc=()=>{so!==null&&(cancelAnimationFrame(so),so=null);let r=yr;yr=null,r&&Pa(r)},kg=()=>{so!==null&&cancelAnimationFrame(so),so=null,yr=null},Vv=r=>{let a=yr??ka;if(on&&a&&Jr&&Fv(a,r,Jr)){yr=r,so===null&&(so=requestAnimationFrame(()=>{so=null;let d=yr;yr=null,d&&Pa(d)}));return}if(r.length===0){kg(),Pa(r);return}Yc(),Pa(r)};S=new Sl(o,{onMessagesChanged(r){Vv(r)},onStatusChanged(r){let a=o.statusIndicator??{};Ws(We,(m=>m==="idle"?a.idleText??gt.idle:m==="connecting"?a.connectingText??gt.connecting:m==="connected"?a.connectedText??gt.connected:m==="error"?a.errorText??gt.error:m==="paused"?a.pausedText??gt.paused:m==="resuming"?a.resumingText??gt.resuming:gt[m])(r),a,r),Ki()},onStreamingChanged(r){r||(S?.getMessages().length===0?kg():Yc()),on=r,ni(r),Ki(),S&&un(ce,S.getMessages(),Xt),r||(Ho(!0),yv(),Zu=!0,S&&eg(S.getMessages(),ds(o))),Ht(),Ns(r?"Responding\u2026":"Response complete."),Yr()},onVoiceStatusChanged(r){if(G.emit("voice:status",{status:r,timestamp:Date.now()}),!(r!=="disconnected"&&!Nt(o.voiceRecognition?.provider)))switch(r){case"listening":if(!Ec){let a=S.getVoiceDisclosure();a&&(Ec=!0,Ae()?(ma=Z.placeholder,Z.placeholder=a,Ns(a)):Fg(a,1e4))}lo(),ns();break;case"processing":lo(),dC();break;case"speaking":lo(),pC();break;default:r==="idle"&&S.isBargeInActive()?(lo(),ns(),te?.setAttribute("aria-label","End voice session")):(Ie.active=!1,Ec=!1,ma!==null&&(Z.placeholder=ma,ma=null),lo(),oo("system"),Tn());break}},onArtifactsState(r){dn=r,r.artifacts.length===0&&(Nr=!1),yo()?.updateInlineArtifactBlocks(ce,r.artifacts,{suppressTransition:on}),En(),Ur()},onHistoryStateChanged(r){iu(r)},onHistoryNotice(r){au(r)},onReconnect(r){let{executionId:a,lastEventId:d}=r.handle;r.phase==="paused"?G.emit("stream:paused",{executionId:a,after:d}):r.phase==="resuming"?G.emit("stream:resuming",{executionId:a,after:d,attempt:r.attempt??1}):G.emit("stream:resumed",{executionId:a,after:d})}},Bo),pn.current=S,oe.push(()=>S.cancel()),oe.push(()=>{S.destroy(),gn?.destroy(),gn=null});let Qc=null;if(S.onReadAloudChange((r,a)=>{ku=r,Pu=a,Lu();let d=r??Qc;r&&(Qc=r);let m=d?S.getMessages().find(f=>f.id===d)??null:null;G.emit("message:read-aloud",{messageId:d,message:m,state:a,timestamp:Date.now()}),a==="idle"&&(Qc=null)}),C=!0,xc=!0,o.voiceRecognition?.enabled===!0&&Nt(o.voiceRecognition.provider))try{S.setupVoice()}catch(r){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",r)}let tt=null,Xc=null,Pg=!1,Lg=S.getHistoryState(),ri=()=>o.features?.history?.enabled===!0,Ig=r=>{r&&(Qn.textContent="",Qn.textContent=r)},Jc=()=>{h.forEach(d=>d()),h=[];let r=tt,a=r?.railCollapseShortcut();r&&a&&h.push(y.register({id:"history-rail-collapse",combo:a.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>Rs&&Ui==="rail"&&r.railCollapsible()||r.railTriggerApplies(),run:()=>r.railOverlayMode()?r.toggleRailPinned():r.toggleRailCollapsed()}));for(let d of o.layout?.header?.trailingActions??[])d.shortcut&&h.push(y.register({id:`header-action-${d.id}`,combo:d.shortcut,run:()=>{let m=t.querySelector(`[data-persona-header-action="${d.id}"]`);m?m.click():o.layout?.header?.onAction?.(d.id)}}));for(let d of g)for(let m of d.shortcuts??[])h.push(y.register({...m,id:`${d.id}:${m.id}`}))};Jc();let La=null,Hg=!1,si=()=>{if(!So)return;let r=o.layout?.header?.titleSource==="conversation",a=r&&La?.trim()||null;So.textContent=a??o.launcher?.title??"Chat Assistant";let d=So.closest(".persona-combo-btn");if(!d)return;let m=!r||S.getActiveConversationId()!==null;d.setAttribute("data-persona-menu-locked",m?"false":"true"),d.setAttribute("aria-haspopup",m?"true":"false"),m||d.setAttribute("aria-expanded","false"),d.style.cursor=m?"pointer":"default";let f=d.querySelector("svg");f&&(f.style.display=m?"":"none")},$v=r=>{r!==La&&(La=r,si())},zv=r=>{Hg=r?.starred===!0,$v(r&&r.title.trim()||null),si()};si(),re.addEventListener("persona:title-menu-builtin",r=>{let a=r.detail?.actionId,d=S.getActiveConversationId();d&&(a==="delete"?Fn(m=>m.requestDeleteConversation(d)):a==="star"&&S.canUpdateConversations()&&Fn(m=>m.updateHistoryConversation(d,{starred:!Hg})).catch(()=>{}))}),iu=r=>{Lg=r,tt?.historySurface?.view.setNewConversationRequired(r.recovery==="new_conversation_required"),ni(r.sendBlocked||on),tt?.syncEarlierMessagesPill()},au=r=>{(r.code==="history_continuity_reset"||r.code==="conversation_deleted_recovered")&&(It.clear(),mr(),On()),Ig(r.message),tt?.historySurface?.view.refresh()};let Uv={get actionManager(){return Me},get activeConversationTitle(){return La},announceHistory:Ig,get applyRailChrome(){return ji},set applyRailChrome(r){ji=r},get artifactSplitRoot(){return Zn},get body(){return j},get config(){return o},get container(){return re},get conversationOpenPendingEl(){return hg},set conversationOpenPendingEl(r){hg=r},get conversationOpenTakeover(){return _c},set conversationOpenTakeover(r){_c=r},currentKeyPrefix:$i,destroyCallbacks:oe,eventBus:G,get footer(){return Le},get header(){return Ke},get historyChromeSync(){return Ki},set historyChromeSync(r){Ki=r},historyFeatureEnabled:ri,get historyInternals(){return Bo},set historyInternals(r){Bo=r},get historyPresentation(){return Ui},set historyPresentation(r){Ui=r},get historySessionState(){return Lg},get historyVisible(){return Rs},set historyVisible(r){Rs=r},get isStreaming(){return on},jumpToBottomInstant:Ic,get lastAppliedMessages(){return ka},set lastAppliedMessages(r){ka=r},get launcherEnabled(){return de},get launcherSurfaceInstance(){return ct},maybeFocusInput:Aa,messageCache:It,get messagesWrapper(){return ce},mount:t,get open(){return Se},panel:le,panelElements:Re,get persistentMetadata(){return x},set persistentMetadata(r){x=r},plugins:g,get reapplyHistoryHostChrome(){return qi},set reapplyHistoryHostChrome(r){qi=r},repinAnchoredMessage:Gr,resetAnchorState:mr,restoreScrollPosition:Hc,resumeAutoScroll:On,runStorageMutation:ha,get session(){return S},setActiveConversationSummary:zv,storageAdapter:v,get suppressScrollSend(){return $r},set suppressScrollSend(r){$r=r},syncScrollToBottomButton:Ht,updateWelcome:oi,getHistoryProviderFactory:cb,historyErrors:{HistoryClientError:bt,HistoryProviderError:el},isDockedMountMode:rt,renderLucideIcon:se,loadHistoryView:ab,createHeaderIconButton:bs,attachTooltip:vn},Zc=r=>(!tt&&!Pg&&(tt=r.createHistoryShell(Uv),tt.railCollapseShortcut()&&Jc()),tt),ed=()=>{if(tt)return Promise.resolve(tt);let r=jl();return r?Promise.resolve(Zc(r)):(Xc??=lb().then(Zc,a=>{throw Xc=null,a}),Xc)},Fn=r=>{let a=jl(),d=tt??(a?Zc(a):null);return d?r(d):ed().then(m=>{if(!m)throw new Error("[AgentWidget] The widget was destroyed");return r(m)})},Ia=()=>{tt?.syncHistoryPresentation()};oe.push(()=>{Pg=!0}),ri()&&ed().catch(()=>{}).finally(ne),o.clientToken&&(o.features?.history?.enabled===!0||o.sessionInit==="mount")&&S.initClientSession().then(()=>{let r=tt;if(r?.historyAvailable())return S.reconcileBootConversation({scope:r.historyScope()})}).then(()=>{tt?.syncEarlierMessagesPill()}).catch(r=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",r)});let td=()=>S.warmClientSession(),Rg=r=>{let a=o.sessionInit??"input",d=Be?.input??Z,m=r.target;d&&(r.type==="input"?(a==="input"||a==="focus")&&m===d&&r.inputType&&d.value.trim():a==="focus"&&(r.type==="keyup"?m===d&&r.key==="Tab":(Be?.form??Ut)?.contains(m)))&&td()},Wg=["input","pointerdown","keyup"];Wg.forEach(r=>t.addEventListener(r,Rg));let Bg,nd,Dg=()=>{let r=nd;nd=void 0;try{typeof r=="function"&&r()}catch{}},Og=()=>{let r=o.clientToken&&typeof o.sessionInit=="function"?o.sessionInit:void 0;if(r!==Bg){Dg(),Bg=r;try{nd=r?.({warm:td,mount:t})}catch{}}};Og(),oe.push(()=>{Wg.forEach(r=>t.removeEventListener(r,Rg)),Dg()}),(Jt||o.onSSEEvent)&&S.setSSEEventCallback((r,a)=>{o.onSSEEvent?.(r,a),Xl(r,a)});let _g=()=>{let r=o.resume??(T?Bo.getStoredResumableHandle?.():null);r&&typeof o.reconnectStream=="function"&&S.resumeFromHandle(r)};z?z.then(r=>{if(r){if(r.metadata&&(x=jp(r.metadata),Me.syncFromMetadata()),r.messages?.length){$r=!0;try{S.hydrateMessages(r.messages)}finally{$r=!1}Sa()}r.artifacts?.length&&S.hydrateArtifacts(r.artifacts,r.selectedArtifactId??null),ig(r.draft)}}).catch(r=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",r)}).finally(()=>{Nc=!0,W(),_g()}):(ig(ve),_g());let qv=()=>{!Ae()||Se||!(o.launcher?.composerBar?.expandOnSubmit??!0)||Ge(!0,"auto")},jv=(r,a)=>r?a?{refs:[...r.refs,...a.refs],finalize:async()=>{let[d,m]=await Promise.allSettled([r.finalize(),a.finalize()]),f=[];return d.status==="fulfilled"?f.push(d.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",d.reason),m.status==="fulfilled"?f.push(m.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",m.reason),nA(f)}}:r:a,od=()=>{let a=Z.getInlineMessageFields?.();return a&&a.contentSegments.some(m=>m.kind==="mention")?a.contentSegments:void 0},io=!1,br=null,Ha=()=>{Z.value="",Z.style.height="auto",Rn(),ai()},rd="data-persona-composer-notice",Zr=null;function Fg(r,a=4e3){Ns(r),!(Ae()||!We)&&(We.hasAttribute(Ts)||(We.setAttribute(rd,""),We.setAttribute("role","status"),We.setAttribute("aria-live","polite"),We.textContent=r,ui(We,o.statusIndicator??{},"idle"),Zr&&clearTimeout(Zr),Zr=setTimeout(()=>{if(Zr=null,!!We?.hasAttribute(rd)&&(We.removeAttribute(rd),We.removeAttribute("role"),We.removeAttribute("aria-live"),C)){let d=S.getStatus();Ws(We,Jl(d),o.statusIndicator??{},d)}},a)))}function Kv(){let r=ie.getState().pendingSubmission;r&&(Or(void 0),Z&&(Z.value=r.text,Z.dispatchEvent(new Event("input",{bubbles:!0})),Rn()),r.options.selectedModelId&&(ie.setSelectedModelId(r.options.selectedModelId),Ao?.repaint()),r.options.activeModeIds?.length&&Zi(r.options.activeModeIds),r.options.quote&&Wn(r.options.quote),Z?.focus())}let Gv=r=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",r)},Ng=(r={})=>{let a=(r.overrideText??Z?.value??"").trim();return r.resolveInlineCommand&&a?(lt?.takeInlineCommand(a)??Promise.resolve(null)).then(d=>Vg(r,a,d)):Vg(r,a,null)},Vg=(r,a,d)=>{if(d?.kind==="action"){Ha(),lt?.clear(),Zo();return}let m=d?.kind==="server"?d.mentions:null,f=d?.kind==="prompt"?d.sendText:a,b=r.pending?.contentParts,D=(_e?.hasAttachments()??!1)||(b?.length??0)>0;if(!Uh({text:f,hasAttachments:D,attachmentsReady:_e?.isReady()??!0,hasMentions:lt?.hasMentions()??!1,hasServerMentions:!!m,inputDisabled:_n(),sendDisabled:fr()}))return;let $=S.isStreaming()?ac():"block";if($==="defer-one"&&!r.pending){if(ie.getState().pendingSubmission){Fg("One message is already queued. Edit or remove it first.");return}Yv({intent:r,sendText:f,serverMentions:m});return}let F={text:f,mentionRefs:[...lt?.getMentionRefs()??[],...m?.refs??[]],contentSegments:d?.kind==="prompt"?void 0:od(),options:{...ie.getState().selectedModelId&&{selectedModelId:ie.getState().selectedModelId},...ie.getState().activeModeIds.length>0&&{activeModeIds:[...ie.getState().activeModeIds]},...ie.getState().quote&&{quote:{...ie.getState().quote}}},viaVoice:r.viaVoice};r.pending&&(F.options={...r.pending.options},F.contentSegments=r.pending.contentSegments,F.mentionRefs=[...r.pending.mentionRefs],F.viaVoice=r.pending.viaVoice);let q=()=>{if(b?.length)return[...b];if(!_e?.hasAttachments())return;let De=[..._e.getContentParts()];return F.text&&De.push(zo(F.text)),De};F.contentParts=q();let K=()=>{lr(),qv();let De=lt?.collectForSubmit()??null,Gt=jv(De,m),nt=q();r.consumeDraft!==!1&&Ha();let it={selectedModelId:F.options.selectedModelId,activeModeIds:F.options.activeModeIds},Ft=$==="interrupt";Ft&&S.cancel(),S.sendMessage(F.text,{contentParts:nt,mentions:Gt??void 0,contentSegments:F.contentSegments,viaVoice:F.viaVoice,composerOptions:it,...F.options.quote&&{quote:F.options.quote},...Ft&&{interrupt:!0}}),_e?.hasAttachments()&&_e.clearAttachments(),De&&lt?.clear(),Zo();let pt=ie.getState().activeModeIds,ze=Ih(pt,o.composer?.modes);ze.length!==pt.length&&Zi(ze),ie.getState().quote&&Wn(void 0),ba(),gc.release(),An()},X=o.composer?.onBeforeSend;if(!X){K();return}let ae=new AbortController;br=ae;let He=De=>{if(br=null,De.status==="error"){Gv(De.error);return}De.status==="proceed"&&K()},Fe=qh(X,F,ae.signal);if(!(Fe instanceof Promise)){He(Fe);return}return ie.setPreparing(!0),Fe.then(He).finally(()=>ie.setPreparing(!1))};function Yv(r){let a=ie.getState(),d=_e?.hasAttachments()??!1,m=d?[..._e.getContentParts()]:[];d&&r.sendText&&m.push(zo(r.sendText));let f=Zd({text:r.sendText,contentParts:m.length?m:void 0,mentionRefs:[...lt?.getMentionRefs()??[],...r.serverMentions?.refs??[]],contentSegments:od(),options:{...a.selectedModelId&&{selectedModelId:a.selectedModelId},...a.activeModeIds.length>0&&{activeModeIds:[...a.activeModeIds]},...a.quote&&{quote:{...a.quote}}},viaVoice:r.intent.viaVoice});Or(f),r.intent.consumeDraft!==!1&&Ha(),d&&_e.clearAttachments(),lt?.clear(),Zo(),a.quote&&Wn(void 0),ba(),gc.release(),An(),Ns("Message queued. It sends when the response finishes.")}function Qv(){let r=ie.getState().pendingSubmission;r&&(Or(void 0),Wa(r.text,{consumeDraft:!1,pending:r}))}function Xv(r){if(o.messageActions?.showEdit!==!0)return;let a=S.getMessages().find(d=>d.id===r);!a||!$d(a)||ar!==r&&(lr(),ar=r,ko=Dh({messageId:r,initialText:a.content,onSave:d=>Jv(r,d),onCancel:()=>lr()}),It.delete(r),un(ce,S.getMessages(),Xt),ko.focus())}function Jv(r,a){let d=ko;if(ar=null,ko=null,d?.destroy(),It.delete(r),!S.resubmitFrom(r,{reason:"edit",replacement:{text:a,mentionRefs:[],options:{}}})){un(ce,S.getMessages(),Xt);return}Gr()}function Zv(r){if(S.isStreaming())return;let a=Vd(S.getMessages(),r);a&&(lr(),S.resubmitFrom(a,{reason:"retry"})&&Gr())}ea={regenerate:Zv,edit:Xv,quote:r=>{let d=S.getMessages().find(m=>m.id===r)?.content?.trim();d&&(Wn({text:d,messageId:r}),Z?.focus())}};let ii=async r=>{if(!io){io=!0;try{await Ng({resolveInlineCommand:!0,...r})}finally{io=!1}}};function Ra(r){fr()||(Ha(),Wa(r,{consumeDraft:!1}))}let Wa=(r,a)=>{if(io)return;io=!0;let d=()=>{io=!1};try{let m=Ng({...a,overrideText:r});m instanceof Promise?m.finally(d):d()}catch(m){throw d(),m}},eC=r=>{if(r.preventDefault(),S.isStreaming()){S.cancel(),wn?.reset(),Ot?.update();return}io||ii()},tC=()=>o.features?.composerHistory!==!1,sd={...ip},id=!1,ai=()=>{sd={...ip}},nC=()=>S.getMessages().filter(r=>r.role==="user").map(r=>r.content??"").filter(r=>r.length>0),oC=r=>{if(!Z)return;id=!0,Z.value=r,Z.dispatchEvent(new Event("input",{bubbles:!0})),id=!1;let a=Z.value.length;Z.setSelectionRange(a,a)},rC=r=>{id||(r.isComposing||lt?.handleInput(r.inputType??void 0),ai())},sC=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:kd(Z)}),iC=r=>{if(Z&&!_n()&&!(!r.isComposing&&lt?.handleKeydown(r))){if(tC()&&(r.key==="ArrowUp"||r.key==="ArrowDown")&&!r.shiftKey&&!r.metaKey&&!r.ctrlKey&&!r.altKey&&!r.isComposing){let a=Z.selectionStart===0&&Z.selectionEnd===0,d=ey({direction:r.key==="ArrowUp"?"up":"down",history:nC(),currentValue:Z.value,atStart:a,state:sd});if(sd=d.state,d.handled){r.preventDefault(),d.value!==void 0&&oC(d.value);return}}if(uf(r,sC())){if(S.isStreaming()){if(r.preventDefault(),ac()==="block"||io||fr())return;ai(),ii();return}if(io){r.preventDefault();return}if(fr()){r.preventDefault();return}ai(),r.preventDefault(),pe.click()}}},$g=r=>{if(!(r.key!=="Escape"||r.isComposing)&&r.composedPath().includes(re)){if(br){br.abort(),br=null,r.preventDefault(),r.stopImmediatePropagation();return}S.isStreaming()&&(S.cancel(),wn?.reset(),Ot?.update(),ai(),r.preventDefault(),r.stopImmediatePropagation())}},aC=async r=>{if(o.attachments?.enabled!==!0||!_e||_n())return;let a=Jx(r.clipboardData);a.length!==0&&(r.preventDefault(),await _e.handleFiles(a))},mn=null,Nn=!1,es=null,ao=null,ad=()=>o.voiceRecognition?.completionBehavior==="review";function Ba(r){te?.setAttribute("data-state",r),r==="recording"?cC():pd()}let zg="--persona-voice-level",ld=.5,ts=null,cd=-1,Da=0,Ug=()=>{let r=[],a=tn??te?.parentElement??null;return a&&r.push(a),Le&&r.push(Le),r},dd=r=>{let a=Math.round(Math.max(0,Math.min(1,r))*100)/100;if(a!==cd){cd=a;for(let d of Ug())d.style.setProperty(zg,String(a))}},lC=()=>{cd=-1,Da=0;for(let r of Ug())r.style.removeProperty(zg)};function cC(){if(ts!==null)return;if(typeof requestAnimationFrame!="function"){dd(C?S.getVoiceLevel()??ld:ld);return}let r=()=>{ts=requestAnimationFrame(r);let a=C?S.getVoiceLevel():null;if(a===null){dd(ld);return}Da+=(a-Da)*.3,dd(Da)};ts=requestAnimationFrame(r)}function pd(){ts!==null&&(cancelAnimationFrame(ts),ts=null),lC()}let qg=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Oa=(r="user")=>{if(Nn||S.isStreaming())return;let a=qg();if(!a)return;mn=new a;let d=o.voiceRecognition??{},m=d.pauseDuration??2e3;mn.continuous=d.provider?.browser?.continuous??!0,mn.interimResults=!0,mn.lang=d.provider?.browser?.language??"en-US";let f=Z.value;mn.onresult=b=>{let D="",$="";for(let q=0;q<b.results.length;q++){let K=b.results[q],X=K[0].transcript;K.isFinal?D+=X+" ":$=X}let F=f+D+$;Z.value=F,Rn(),es&&clearTimeout(es),(D||$)&&(es=window.setTimeout(()=>{if(Z.value.trim()&&mn&&Nn){if(Do(),ad())return;ii({viaVoice:!0})}},m))},mn.onerror=b=>{b.error!=="no-speech"&&Do()},mn.onend=()=>{if(Nn){let b=Z.value.trim();!ad()&&b&&b!==f.trim()&&ii({viaVoice:!0}),Do()}};try{if(mn.start(),Nn=!0,Ie.active=!0,r!=="system"&&(Ie.manuallyDeactivated=!1),oo(r),Tn(),An(),te){let b=o.voiceRecognition??{};ao={backgroundColor:te.style.backgroundColor,color:te.style.color,borderColor:te.style.borderColor,iconName:b.iconName??"mic",iconSize:parseFloat(b.iconSize??"")||qn};let D=b.recordingBackgroundColor,$=b.recordingIconColor,F=b.recordingBorderColor;if(te.classList.add("persona-voice-recording"),Ba("recording"),te.style.backgroundColor=D??"var(--persona-voice-recording-bg, #ef4444)",te.style.color=$??"var(--persona-voice-recording-indicator, #ffffff)",$){let q=te.querySelector("svg");q&&q.setAttribute("stroke",$)}F&&(te.style.borderColor=F),te.setAttribute("aria-label","Stop voice recognition")}}catch{Do("system")}},Do=(r="user")=>{if(Nn){if(Nn=!1,es&&(clearTimeout(es),es=null),mn){try{mn.stop()}catch{}mn=null}if(Ie.active=!1,oo(r),Tn(),An(),te){if(te.classList.remove("persona-voice-recording"),Ba("idle"),ao){te.style.backgroundColor=ao.backgroundColor,te.style.color=ao.color,te.style.borderColor=ao.borderColor;let a=te.querySelector("svg");a&&a.setAttribute("stroke",ao.color||"currentColor"),ao=null}te.setAttribute("aria-label","Start voice recognition")}}},jg=null,_a=r=>{let a=m=>{jg??=m.createMicStateStyles({mic:()=>te,config:()=>o,session:()=>S,get original(){return ao},set original(f){ao=f},setMicState:Ba,renderIcon:se,iconFallbackPx:qn}),r(jg)},d=ah();d?a(d):Si().then(a,()=>{})},ns=()=>_a(r=>r.recording()),dC=()=>_a(r=>r.processing()),pC=()=>_a(r=>r.speaking()),lo=()=>_a(r=>r.reset()),ud=()=>{if(!_n()){if(Nt(o.voiceRecognition?.provider)){let r=S.getVoiceStatus(),a=S.getVoiceInterruptionMode();if(a==="none"&&(r==="processing"||r==="speaking"))return;if(a==="cancel"&&(r==="processing"||r==="speaking")){S.stopVoicePlayback();return}if(S.isBargeInActive()){S.stopVoicePlayback(),S.deactivateBargeIn().then(()=>{Ie.active=!1,Ie.manuallyDeactivated=!0,Tn(),oo("user"),lo()});return}S.toggleVoice().then(()=>{Ie.active=S.isVoiceActive(),Ie.manuallyDeactivated=!S.isVoiceActive(),Tn(),oo("user"),S.isVoiceActive()?ns():lo()});return}if(Nn){let r=Z.value.trim();Ie.manuallyDeactivated=!0,Tn(),Do("user"),r&&!ad()&&ii()}else Ie.manuallyDeactivated=!1,Tn(),Oa("user")}};lc=ud;let Kg=()=>S.prewarmVoice(),Gg=()=>{let r=o.voiceRecognition;return r?.enabled!==!0?!1:r.prewarm??(o.clientToken?"hover":!1)},Yg=r=>{Gg()==="hover"&&te?.contains(r.target)&&Kg()},Qg=["pointerover","pointerdown","focusin"];Qg.forEach(r=>t.addEventListener(r,Yg));let Xg,Jg=null,gd,Zg=()=>{let r=gd;gd=void 0;try{typeof r=="function"&&r()}catch{}},md=()=>{let r=Gg(),a=typeof r=="function"&&te?r:void 0,d=a?te:null;if(!(a===Xg&&d===Jg)&&(Zg(),Xg=a,Jg=d,!(!a||!d)))try{gd=a({warm:Kg,micButton:d,mount:t})}catch{}};md(),oe.push(()=>{Qg.forEach(r=>t.removeEventListener(r,Yg)),Zg()}),te&&oe.push(()=>{Nt(o.voiceRecognition?.provider)?(S.isVoiceActive()&&S.toggleVoice(),lo()):Do("system")});let uC=G.on("assistant:complete",()=>{ie.getState().pendingSubmission&&setTimeout(()=>{S.isStreaming()||Qv()},0)});oe.push(uC);let gC=G.on("assistant:complete",()=>{og&&(Ie.active||Ie.manuallyDeactivated||og==="assistant"&&!Ie.lastUserMessageWasVoice||setTimeout(()=>{!Ie.active&&!Ie.manuallyDeactivated&&(Nt(o.voiceRecognition?.provider)?S.toggleVoice().then(()=>{Ie.active=S.isVoiceActive(),oo("auto"),S.isVoiceActive()&&ns()}):Oa("auto"))},600))});oe.push(gC);let mC=G.on("action:resubmit",()=>{setTimeout(()=>{S&&!S.isStreaming()&&S.continueConversation()},100)});oe.push(mC);let em=()=>{Ge(!Se,"user")},ct=null,_t=null;if(de&&!Ae()){let{instance:r,element:a}=Mp({config:o,plugins:g,onToggle:em});ct=r,r||(_t=a)}ct?t.appendChild(ct.element):_t&&t.appendChild(_t),ti(),sr(),Ea(),qc(),ni(S.isStreaming()),Hc()||(nn()==="follow"?Ho(!0):Ic()),pv(),Ps&&(!de||Ae()?setTimeout(()=>Aa(),0):Se&&setTimeout(()=>Aa(),200));let Oo=null,tm=()=>{Oo&&(Oo.disconnect(),Oo.observe(Le),Oo.observe(re),Oo.observe(xt))},nm=Vs(),li=()=>{if(Ae()){Jo(),ti();return}let r=rt(o),a=o.launcher?.sidebarMode??!1,d=t.ownerDocument.defaultView??window,m=o.launcher?.mobileFullscreen??!0,f=o.launcher?.mobileBreakpoint??640,b=d.innerWidth<=f,D=m&&b&&de;try{if(D){er(),qs=ca();return}let $=!1;Yl&&(Yl=!1,er(),$=!0);let F=ca();if(!$&&F!==qs&&(er(),$=!0),qs=F,$&&sa(),!de&&!r){le.style.height="",le.style.width="";return}if(!a&&!r){let q=Pr(o);le.style.width=q.width,le.style.maxWidth=q.maxWidth}la(),Vu()}finally{Jo(),Ji();let $=Vs();if($!==nm&&(nm=$,oi(),sr()),ti(),Se&&de){let q=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),K=o.launcher?.sidebarMode??!1,X=o.launcher?.mobileFullscreen??!0,ae=rt(o)&&X&&q,He=K||X&&q&&de||ae;if(He&&!Dn){let Fe=t.getRootNode(),De=Fe instanceof ShadowRoot?Fe.host:t.closest(".persona-host");De&&!Bn&&(Bn=ap(De,o.launcher?.zIndex??Dt)),Dn=lp(t.ownerDocument)}else He||(Bn?.(),Bn=null,Dn?.(),Dn=null)}}};li();let Fa=t.ownerDocument.defaultView??window;if(Fa.addEventListener("resize",li),oe.push(()=>Fa.removeEventListener("resize",li)),typeof ResizeObserver<"u"){Oo=new ResizeObserver(()=>{Ji()}),tm(),oe.push(()=>{Oo?.disconnect(),Oo=null});let r=new ResizeObserver(()=>{Ia()});r.observe(re),oe.push(()=>r.disconnect())}Fa.addEventListener("resize",Ia),oe.push(()=>Fa.removeEventListener("resize",Ia)),sn=j.scrollTop;let om=uo(j),rm=()=>{Nu();let r=j.scrollTop,a=uo(j),d=a<om;if(om=a,!xo()){sn=r,Ht();return}let{action:m,nextLastScrollTop:f}=kf({following:rn.isFollowing(),currentScrollTop:r,lastScrollTop:sn,nearBottom:Er(j,to),userScrollThreshold:av,isAutoScrolling:Kt||pa||d,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(sn=f,m==="resume"){va()||On();return}m==="pause"&&Kr()};if(j.addEventListener("scroll",rm,{passive:!0}),oe.push(()=>j.removeEventListener("scroll",rm)),typeof ResizeObserver<"u"){let r=new ResizeObserver(()=>{bv(),Bd(ce)});r.observe(ce),r.observe(j),oe.push(()=>r.disconnect())}let sm=()=>{xo()&&rn.isFollowing()&&va()&&Kr()},im=j.ownerDocument;im.addEventListener("selectionchange",sm),oe.push(()=>{im.removeEventListener("selectionchange",sm)});let fC=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),am=r=>{fC.has(r.key)&&(Io(),cu()&&xo()&&rn.isFollowing()&&Kr())},lm=r=>{r.target?.closest("a, button, [tabindex], input, textarea, select")&&(Io(),cu()&&xo()&&rn.isFollowing()&&Kr())};j.addEventListener("keydown",am),j.addEventListener("focusin",lm),oe.push(()=>{j.removeEventListener("keydown",am),j.removeEventListener("focusin",lm)});let cm=r=>{if(r.deltaY!==0&&Io(),!xo())return;let a=Pf({following:rn.isFollowing(),deltaY:r.deltaY,nearBottom:Er(j,to),resumeWhenNearBottom:!0});a==="pause"?Kr():a==="resume"&&!va()&&On()};j.addEventListener("wheel",cm,{passive:!0}),j.addEventListener("touchmove",Io,{passive:!0}),j.addEventListener("pointerdown",Io,{passive:!0}),oe.push(()=>{j.removeEventListener("touchmove",Io),j.removeEventListener("pointerdown",Io)}),oe.push(()=>j.removeEventListener("wheel",cm)),ft.addEventListener("click",()=>{mr(),j.scrollTop=j.scrollHeight,sn=j.scrollTop,On(),Ho(!0),Ht()}),oe.push(()=>ft.remove()),oe.push(()=>{lg(),mr()});let dm=()=>{xe&&(or&&(xe.removeEventListener("click",or),or=null),Ve()?(xe.style.display="",or=()=>{Ge(!1,"user")},xe.addEventListener("click",or)):xe.style.display="none")};dm(),(()=>{let{clearChatButton:r}=Re;r&&r.addEventListener("click",()=>{let a=tt;if(a?.historyAvailable()){a.startNewConversation({focusComposer:!0}).catch(m=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",m)});return}S.clearMessages(),o.layout?.topFade&&(j.scrollTop=0),j.removeAttribute("data-persona-top-fade"),It.clear(),On(),xd(Re.composerOverlay);try{localStorage.removeItem(Es),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Es}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Es)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let d=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(d),v?.clear&&ha(()=>v.clear(),"[AgentWidget] Failed to clear storage adapter:"),x={},Me.syncFromMetadata(),_e?.clearAttachments(),ba(),Or(void 0),Wn(void 0),lr(),Lt?.clear(),wn?.reset(),Ot?.update()})})();let pm=[["keydown",iC],["input",rC],["input",Rn],["input",Zo],["keyup",Zo],["paste",aC],["focus",Yb]],um=r=>{if(r)for(let[a,d]of pm)Be?.addListener(r,a,d)},hC=r=>{if(r)for(let[a,d]of pm)Be?.removeListener(r,a,d)},gm=()=>{Be&&(Be.addListener(Be.form,"submit",eC),Be.addListener(Be.footer,"click",Zo),um(Z),te&&Be.addListener(te,"click",ud),md())};gm();let mm=()=>{lt?.onComposerSwap((r,a)=>{hC(a),Z=r,Be&&(Be.input=r),um(r),dc(),Oc(),Rn()})};mm();let fd=!1;function fm(){if(!fd){fd=!0;try{let r=Z?.value??"",a=Le.ownerDocument??document,d=Z?a.activeElement===Z:!1;pd(),Be?.destroy(),Be=null,lt?.destroy(),lt=null;let m=null,f=()=>(m=Ae()?Dl({config:o}):Wi({config:o}),m.footer),b=vu(f)??f();Zt.replaceComposer(b),Le=Zt.composer.footer;let D=m!==null&&b===m.footer;Fr=!D,lu=D?m.setSendButtonMode:()=>{},bu(Le),wu(Le),Su(),xu(),pc(),mm(),Au(),uc(),Mu(),gm();let $=nr.indexOf(eo);if(eo.destroy(),eo=Hi(wo),$>=0&&(nr[$]=eo),Z&&(Z.value=r),Rn(),Zo(),Ea(),sr(),ni(S.isStreaming()),o.statusIndicator?.mode==="transient"&&!Ae()){let F=S.getStatus();Ws(We,Jl(F),o.statusIndicator,F)}Ie.active&&Ba("recording"),er(),tm(),Jo(),An(),xa(),d&&Z?.focus()}finally{fd=!1}}}let ci=t.ownerDocument??document;ci.addEventListener("keydown",$g,!0);let hm=()=>{Tc()},ym=()=>{ci.visibilityState==="hidden"&&Tc()};typeof window<"u"&&(window.addEventListener("pagehide",hm),ci.addEventListener("visibilitychange",ym),oe.push(()=>{window.removeEventListener("pagehide",hm),ci.removeEventListener("visibilitychange",ym)}));let bm="persona-attachment-drop-active",di=0,hd=()=>{di=0,re.classList.remove(bm)},os=()=>o.attachments?.enabled===!0&&_e!==null&&!_n(),vm=r=>{!Kl(r.dataTransfer)||!os()||(di++,di===1&&re.classList.add(bm))},Cm=r=>{!Kl(r.dataTransfer)||!os()||(di--,di<=0&&hd())},wm=r=>{!Kl(r.dataTransfer)||!os()||(r.preventDefault(),r.dataTransfer.dropEffect="copy")},Sm=r=>{if(!Kl(r.dataTransfer)||!os())return;r.preventDefault(),r.stopPropagation(),hd();let a=Array.from(r.dataTransfer.files??[]);a.length!==0&&_e.handleFiles(a)},_o=!0;re.addEventListener("dragenter",vm,_o),re.addEventListener("dragleave",Cm,_o),t.addEventListener("dragover",wm,_o),t.addEventListener("drop",Sm,_o);let Na=t.ownerDocument,xm=r=>{os()&&r.preventDefault()},Am=r=>{os()&&r.preventDefault()};Na.addEventListener("dragover",xm),Na.addEventListener("drop",Am),oe.push(()=>{Be?.destroy(),Be=null,pd(),xn?.destroy(),xn=null,Xn?.destroy(),Xn=null,Mo?.destroy(),Mo=null,Eo?.destroy(),Eo=null,Ao=null,ic=null,Tc(),Qs.destroy(),Zr&&clearTimeout(Zr),lr(),br?.abort(),br=null,_e?.destroy(),_e=null,ie.destroy(),ci.removeEventListener("keydown",$g,!0),lt?.destroy()}),oe.push(()=>{re.removeEventListener("dragenter",vm,_o),re.removeEventListener("dragleave",Cm,_o),t.removeEventListener("dragover",wm,_o),t.removeEventListener("drop",Sm,_o),Na.removeEventListener("dragover",xm),Na.removeEventListener("drop",Am),hd()}),oe.push(()=>{S.cancel()}),ct?oe.push(()=>{ct?.destroy()}):_t&&oe.push(()=>{_t?.remove()});let dt={update(r){let a=o.future?.v5Defaults===!0,d=o.toolCall,m=o.messageActions,f=o.layout?.messages,b=o.colorScheme,D=o.loadingIndicator,$=o.iterationDisplay,F=o.features?.showReasoning,q=o.features?.showToolCalls,K=o.features?.toolCallDisplay,X=o.features?.reasoningDisplay,ae=o.features?.streamAnimation?.type,He=o.features?.history?.enabled===!0,Fe=o.features?.history?.provider,De=o.getIdentityProof,Gt=o.clientToken,nt=o.contextMentions;o=tb({...o,features:p},r),p=o.features,o=_p(o),u(),vc(),Ti(t,o),Oi(t,o),_i(t,o),ji(),En(),o.colorScheme!==b&&$u();let it=Vp.getForInstance(o.plugins);g.length=0,g.push(...it),Jc(),de=o.launcher?.enabled??!0,In=o.launcher?.autoExpand??!1,Is=o.features?.showReasoning??!0,Hs=o.features?.showToolCalls??!0,Vi=o.features?.scrollToBottom??{};let Ft=nn();vo=o.features?.scrollBehavior??{},Ft!==nn()&&(mr(),On()),ng(),uu(),Ht();let pt=Jt;if(Jt=o.features?.showEventStreamToggle??!1,Jt&&!pt){if(Lt||(zi(),S.setSSEEventCallback((N,Te)=>{o.onSSEEvent?.(N,Te),Xl(N,Te)})),!Ne&&Ke){let N=o.features?.eventStream?.classNames,Te="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"+(N?.toggleButton?" "+N.toggleButton:"");Ne=P("button",Te),Ne.style.width="28px",Ne.style.height="28px",Ne.style.color=Vt.actionIconColor,Ne.type="button",Ne.setAttribute("aria-label","Event Stream"),Ne.title="Event Stream";let ke=yt(fb,"18px","currentColor",1.5);ke&&Ne.appendChild(ke);let Oe=Re.clearChatButtonWrapper,Ze=Re.closeButtonWrapper,Rt=Oe||Ze;Rt&&Rt.parentNode===Ke?Ke.insertBefore(Ne,Rt):Ke.appendChild(Ne),Ne.addEventListener("click",()=>{Sn?_r():cc()})}}else!Jt&&pt&&(_r(),Ne&&(Ne.remove(),Ne=null),Lt?.clear(),Rr?.destroy(),Lt=null,Rr=null,wn?.reset(),wn=null,Yn=null);if(o.launcher?.enabled===!1&&ct&&(ct.destroy(),ct=null),o.launcher?.enabled===!1&&_t&&(_t.remove(),_t=null),o.launcher?.enabled!==!1&&!ct&&!_t){let{instance:N,element:Te}=Mp({config:o,plugins:g,onToggle:em});ct=N,N||(_t=Te),t.appendChild(Te)}ct&&ct.update(o),si(),Yo&&o.launcher?.subtitle!==void 0&&(Yo.textContent=o.launcher.subtitle);let ze=o.layout?.header;if(ze?.layout!==tu&&Ke){let N=ze?Bl(o,ze,{showClose:Ve(),onClose:()=>Ge(!1,"user")}):kr({config:o,showClose:Ve(),onClose:()=>Ge(!1,"user")});Zt.replaceHeader(N),Ke=Zt.header.element,at=Zt.header.iconHolder,So=Zt.header.headerTitle,Yo=Zt.header.headerSubtitle,xe=Zt.header.closeButton,tu=ze?.layout,si()}else if(ze){if(at&&(at.style.display=ze.showIcon===!1?"none":""),So&&(So.style.display=ze.showTitle===!1?"none":""),Yo&&(Yo.style.display=ze.showSubtitle===!1?"none":""),xe){let N=Ve()&&ze.showCloseButton!==!1;xe.style.display=N?"":"none"}if(Re.clearChatButtonWrapper){let N=ze.showClearChat;if(N!==void 0){Re.clearChatButtonWrapper.style.display=N?"":"none";let{closeButtonWrapper:Te}=Re;Te&&!Te.classList.contains("persona-absolute")&&(N?Te.classList.remove("persona-ml-auto"):Te.classList.add("persona-ml-auto"))}}}let $n=o.layout?.showHeader!==!1;Ke&&(Ke.style.display=$n?"":"none");let hn=o.layout?.showFooter!==!1;Le&&(Le.style.display=hn?"":"none"),Jo(),Ht(),de!==eu?de?Ge(In,"auto"):(Se=!0,ti()):In!==Zp&&Ge(In,"auto"),Zp=In,eu=de,li(),dm();let zn=JSON.stringify(o.toolCall)!==JSON.stringify(d),kn=JSON.stringify(o.messageActions)!==JSON.stringify(m),No=JSON.stringify(o.layout?.messages)!==JSON.stringify(f),pi=o.loadingIndicator?.render!==D?.render||o.loadingIndicator?.renderIdle!==D?.renderIdle||o.loadingIndicator?.showBubble!==D?.showBubble,vr=o.iterationDisplay!==$,M=(o.features?.showReasoning??!0)!==(F??!0)||(o.features?.showToolCalls??!0)!==(q??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(K)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(X);(o.future?.v5Defaults===!0!==a||zn||kn||No||pi||vr||M)&&S&&(cr++,un(ce,S.getMessages(),Xt));let fe=o.features?.streamAnimation?.type;if(fe!==ae&&fe&&fe!=="none"){let N=Sc(fe,o.features?.streamAnimation?.plugins);N&&yi(N,t)}let U=o.launcher??{},Ue=U.headerIconHidden??!1,mt=o.layout?.header?.showIcon,Bt=Ue||mt===!1,At=U.headerIconName,Ye=U.headerIconSize??$a;if(at){let N=Ke,Te=N?.querySelector(".persona-flex-col");if(Bt)at.style.display="none",N&&Te&&!N.contains(Te)&&N.insertBefore(Te,N.firstChild);else{if(at.style.display="",at.style.height=Ye,at.style.width=Ye,N&&Te&&(N.contains(at)?at.nextSibling!==Te&&(at.remove(),N.insertBefore(at,Te)):N.insertBefore(at,Te)),At){let Oe=parseFloat(Ye)||24,Ze=se(At,Oe*.6,"currentColor",1);Ze?(Ze.style.width=`calc(${Oe}px * var(--persona-components-header-iconScale, 0.6))`,Ze.style.height=`calc(${Oe}px * var(--persona-components-header-iconScale, 0.6))`,at.replaceChildren(Ze)):at.textContent=U.agentIconText??"\u{1F4AC}"}else if(U.iconUrl){let Oe=at.querySelector("img");if(Oe)Oe.src=U.iconUrl,Oe.style.height=Ye,Oe.style.width=Ye;else{let Ze=document.createElement("img");Ze.src=U.iconUrl,Ze.alt="",Ze.className="persona-rounded-xl persona-object-cover",Ze.style.height=Ye,Ze.style.width=Ye,at.replaceChildren(Ze)}}else{let Oe=at.querySelector("svg"),Ze=at.querySelector("img");(Oe||Ze)&&at.replaceChildren(),at.textContent=U.agentIconText??"\u{1F4AC}"}let ke=at.querySelector("img");ke&&(ke.style.height=Ye,ke.style.width=Ye)}}let ut=o.layout?.header?.showTitle,Ct=o.layout?.header?.showSubtitle;if(So&&(So.style.display=ut===!1?"none":""),Yo&&(Yo.style.display=Ct===!1?"none":""),xe){let N=Ve()&&o.layout?.header?.showCloseButton!==!1;if(xe.style.display=N?"":"none",!Ae()){let Et=U.closeButtonSize??"";xe.style.height=Et,xe.style.width=Et,xe.style.minWidth=Et,xe.style.minHeight=Et}let Te=U.closeButtonPlacement??"inline",{closeButtonWrapper:ke}=Re,Oe=Te==="top-right",Ze=ke?.classList.contains("persona-absolute");if(ke&&Oe!==Ze)if(ke.remove(),Oe){ke.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Et=tt?.railColumn??re;Et.style.position="relative",Et.appendChild(ke)}else{let Et=U.clearChat?.placement??"inline",Tt=U.clearChat?.enabled??!0;ke.className=Tt&&Et==="inline"?"":"persona-ml-auto",Ke&&Ke.appendChild(ke)}if(xe.style.color=U.closeButtonColor||Vt.actionIconColor,U.closeButtonBackgroundColor?(xe.style.backgroundColor=U.closeButtonBackgroundColor,xe.classList.remove("hover:persona-bg-gray-100")):(xe.style.backgroundColor="",xe.classList.add("hover:persona-bg-gray-100")),U.closeButtonBorderWidth||U.closeButtonBorderColor){let Et=U.closeButtonBorderWidth||"0px",Tt=U.closeButtonBorderColor||"transparent";xe.style.border=`${Et} solid ${Tt}`,xe.classList.remove("persona-border-none")}else xe.style.border="",xe.classList.add("persona-border-none");U.closeButtonBorderRadius?(xe.style.borderRadius=U.closeButtonBorderRadius,xe.classList.remove("persona-rounded-full")):(xe.style.borderRadius="",xe.classList.add("persona-rounded-full")),U.closeButtonPaddingX?(xe.style.paddingLeft=U.closeButtonPaddingX,xe.style.paddingRight=U.closeButtonPaddingX):(xe.style.paddingLeft="",xe.style.paddingRight=""),U.closeButtonPaddingY?(xe.style.paddingTop=U.closeButtonPaddingY,xe.style.paddingBottom=U.closeButtonPaddingY):(xe.style.paddingTop="",xe.style.paddingBottom=""),Wl(xe,U.closeButtonIconName??"x",{iconSize:Ae()?wp:void 0,iconText:U.closeButtonIconText??"\xD7"});let Rt=U.closeButtonTooltipText??"Close chat",Ln=U.closeButtonShowTooltip??!0;xe.setAttribute("aria-label",Rt),ke&&vn({anchor:xe,trigger:ke,text:()=>xe?.getAttribute("aria-label")??Rt,enabled:Ln})}let{clearChatButton:ue,clearChatButtonWrapper:Qe}=Re;if(ue){let N=U.clearChat??{},Te=N.enabled??!0,ke=o.layout?.header?.showClearChat,Oe=ke!==void 0?ke:Te,Ze=N.placement??"inline";if(Qe){Qe.style.display=Oe?"":"none";let{closeButtonWrapper:Rt}=Re;!Ae()&&Rt&&!Rt.classList.contains("persona-absolute")&&(Oe?Rt.classList.remove("persona-ml-auto"):Rt.classList.add("persona-ml-auto"));let Ln=Ze==="top-right",Et=Qe.classList.contains("persona-absolute");if(!Ae()&&Ln!==Et&&Oe){if(Qe.remove(),Ln){Qe.className="persona-absolute persona-top-4 persona-z-50",Qe.style.right="48px";let Un=tt?.railColumn??re;Un.style.position="relative",Un.appendChild(Qe)}else{Qe.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Qe.style.right="";let Un=Re.closeButtonWrapper;Ke&&Un&&Un.parentElement===Ke?Ke.insertBefore(Qe,Un):Ke&&Ke.appendChild(Qe)}let Tt=Re.closeButtonWrapper;Tt&&!Tt.classList.contains("persona-absolute")&&(Ln?Tt.classList.add("persona-ml-auto"):Tt.classList.remove("persona-ml-auto"))}}if(Oe){if(!Ae()){let Tt=N.size??"";ue.style.height=Tt,ue.style.width=Tt,ue.style.minWidth=Tt,ue.style.minHeight=Tt}let Rt=N.iconColor??"";if(ue.style.color=Rt||Vt.actionIconColor,Wl(ue,N.iconName??"refresh-cw",{iconSize:Ae()?Sp:void 0}),N.backgroundColor?(ue.style.backgroundColor=N.backgroundColor,ue.classList.remove("hover:persona-bg-gray-100")):(ue.style.backgroundColor="",ue.classList.add("hover:persona-bg-gray-100")),N.borderWidth||N.borderColor){let Tt=N.borderWidth||"0px",Un=N.borderColor||"transparent";ue.style.border=`${Tt} solid ${Un}`,ue.classList.remove("persona-border-none")}else ue.style.border="",ue.classList.add("persona-border-none");N.borderRadius?(ue.style.borderRadius=N.borderRadius,ue.classList.remove("persona-rounded-full")):(ue.style.borderRadius="",ue.classList.add("persona-rounded-full")),N.paddingX?(ue.style.paddingLeft=N.paddingX,ue.style.paddingRight=N.paddingX):(ue.style.paddingLeft="",ue.style.paddingRight=""),N.paddingY?(ue.style.paddingTop=N.paddingY,ue.style.paddingBottom=N.paddingY):(ue.style.paddingTop="",ue.style.paddingBottom="");let Ln=N.tooltipText??"Clear chat",Et=N.showTooltip??!0;ue.setAttribute("aria-label",Ln),Qe&&vn({anchor:ue,trigger:Qe,text:()=>ue?.getAttribute("aria-label")??Ln,enabled:Et})}}let ye=o.actionParsers&&o.actionParsers.length?o.actionParsers:[zp],wt=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Fi.message,Fi.messageAndClick];Me=Up({parsers:ye,handlers:wt,getSessionMetadata:Wt,updateSessionMetadata:$e,emit:G.emit,documentRef:typeof document<"u"?document:null}),Xt=vb(o,Me,nu),Ov(),S.updateConfig(o),Og(),(o.features?.history?.enabled===!0!==He||o.features?.history?.provider!==Fe||o.getIdentityProof!==De||o.clientToken!==Gt)&&(tt?.closeHistory({restoreFocus:!1}),tt?.installHistoryProvider()),tt?.syncHistoryChromeImpl(),Ia(),ri()&&!tt&&ed().catch(()=>{}),un(ce,S.getMessages(),Xt),sr(),Ea(),Wv(),ni(S.isStreaming()),nt!==o.contextMentions&&fm();let bn=o.voiceRecognition?.enabled===!0,Mt=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),qe=Nt(o.voiceRecognition?.provider);if(bn&&(Mt||qe))if(!te||!tn){let N=gs(o);if(N){te=N.button,tn=N.wrapper;let Te=Hn&&Hn.parentElement===Gi?Hn:null;Gi?Gi.insertBefore(tn,Te):Ut?.appendChild(tn),Be&&(Be.micButton=te),Be?.addListener(te,"click",ud),te.disabled=_n()||S.isStreaming()&&!Bc()}}else{let N=o.voiceRecognition??{},Te=o.sendButton??{},ke=N.iconName??"mic",Oe=N.iconSize,Ze=parseFloat(Oe??"")||qn;te.classList.add(Uo),te.classList.toggle(Mr,!Oe),te.style.width=Oe??"",te.style.height=Oe??"",te.style.minWidth=Oe??"",te.style.minHeight=Oe??"";let Rt=N.iconColor??Te.textColor;te.innerHTML="";let Ln=se(ke,Ze,Rt||"currentColor",1.5);Ln?te.appendChild(Ln):te.textContent="\u{1F3A4}";let Et=N.backgroundColor??Te.backgroundColor;Et?te.style.backgroundColor=Et:te.style.backgroundColor="",Rt?te.style.color=Rt:te.style.color="var(--persona-text, #111827)",N.borderWidth?(te.style.borderWidth=N.borderWidth,te.style.borderStyle="solid"):(te.style.borderWidth="",te.style.borderStyle=""),N.borderColor?te.style.borderColor=N.borderColor:te.style.borderColor="",N.paddingX?(te.style.paddingLeft=N.paddingX,te.style.paddingRight=N.paddingX):(te.style.paddingLeft="",te.style.paddingRight=""),N.paddingY?(te.style.paddingTop=N.paddingY,te.style.paddingBottom=N.paddingY):(te.style.paddingTop="",te.style.paddingBottom="");let Tt=N.tooltipText??"Start voice recognition",Un=N.showTooltip??!1;te.setAttribute("aria-label",Tt),tn&&vn({anchor:te,trigger:tn,text:()=>te?.getAttribute("aria-label")??Tt,enabled:Un}),tn.style.display="",te.disabled=_n()||S.isStreaming()&&!Bc()}else te&&tn&&(tn.style.display="none",Nt(o.voiceRecognition?.provider)?S.isVoiceActive()&&S.toggleVoice():Nn&&Do());if(md(),o.attachments?.enabled===!0){if(!qt||!st){let N=o.attachments??{};jt||(jt=P("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),jt.style.display="none",(Z.parentElement??Ut).insertBefore(jt,Z)),et||(et=document.createElement("input"),et.type="file",et.accept=(N.allowedTypes??us).join(","),et.multiple=(N.maxFiles??4)>1,et.style.display="none",et.setAttribute("aria-label","Attach files"),(Z.parentElement??Ut).insertBefore(et,Z)),qt=P("div","persona-send-button-wrapper"),st=P("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Uo} ${Mr}`),st.type="button",st.setAttribute("aria-label",N.buttonTooltipText??"Attach file");let Te=N.buttonIconName??"paperclip";st.style.fontSize="18px",st.style.lineHeight="1";let ke=se(Te,qn,"currentColor",1.5);ke?st.appendChild(ke):st.textContent="\u{1F4CE}",st.addEventListener("click",Ze=>{Ze.preventDefault(),et?.click()}),qt.appendChild(st);let Oe=N.buttonTooltipText??"Attach file";vn({anchor:st,trigger:qt,text:()=>st?.getAttribute("aria-label")??Oe}),ec?ec.append(qt):Ut.appendChild(qt),Be&&(Be.attachmentButton=st,Be.attachmentInput=et??void 0,Be.attachmentPreviews=jt??void 0),!_e&&et&&jt&&(_e=xi.fromConfig(N,gu),_e.setPreviewsContainer(jt),Be?.addListener(et,"change",async()=>{_e&&et?.files&&(await _e.handleFileSelect(et.files),et.value="")}))}else{qt.style.display="";let N=o.attachments??{};et&&(et.accept=(N.allowedTypes??us).join(","),et.multiple=(N.maxFiles??4)>1),_e&&_e.updateConfig({allowedTypes:N.allowedTypes,maxFileSize:N.maxFileSize,maxFiles:N.maxFiles,adapter:N.adapter})}if(re.querySelector(".persona-attachment-drop-overlay")?.remove(),re.appendChild(Cb(o.attachments?.dropOverlay)),st){let N=o.attachments??{},Te=N.buttonTooltipText??"Attach file";st.setAttribute("aria-label",Te),st.textContent="";let ke=se(N.buttonIconName??"paperclip",qn,"currentColor",1.5);ke?st.appendChild(ke):st.textContent="\u{1F4CE}",qt&&vn({anchor:st,trigger:qt,text:()=>st?.getAttribute("aria-label")??Te})}}else qt&&(qt.style.display="none"),_e&&_e.clearAttachments(),re.querySelector(".persona-attachment-drop-overlay")?.remove();let be=o.sendButton??{},Vo=be.useIcon??!1,ht=be.iconText??"\u2191",Yt=be.iconName,co=be.tooltipText??"Send message",yd=be.showTooltip??!1,Cr=be.size,bd=parseFloat(Cr??"")||ff,po=be.backgroundColor,wr=be.textColor;if(Vo){if(pe.style.width=Cr??"",pe.style.height=Cr??"",pe.style.minWidth=Cr??"",pe.style.minHeight=Cr??"",pe.style.fontSize="18px",pe.style.lineHeight="1",wr?pe.style.color=wr:pe.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!S.isStreaming())if(pe.innerHTML="",Yt){let N=parseFloat(be.iconSize??"")||Math.round(bd*.5),Te=wr?.trim()||"currentColor",ke=be.iconStrokeWidth??2,Oe=se(Yt,N,Te,ke),Ze=se(be.stopIconName??"square",N,Te,ke);Oe&&Ze?pe.appendChild(hf(Oe,Ze)):Oe?pe.appendChild(Oe):pe.textContent=ht}else pe.textContent=ht;pe.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Uo}`,po?(pe.style.backgroundColor=po,pe.classList.remove("persona-bg-persona-primary")):(pe.style.backgroundColor="",pe.classList.add("persona-bg-persona-primary"))}else pe.textContent=o.copy?.sendButtonLabel??"Send",pe.style.width="",pe.style.height="",pe.style.minWidth="",pe.style.minHeight="",pe.style.fontSize="",pe.style.lineHeight="",pe.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",po?(pe.style.backgroundColor=po,pe.classList.remove("persona-bg-persona-accent")):pe.classList.add("persona-bg-persona-accent"),wr?pe.style.color=wr:pe.classList.add("persona-text-white");be.borderWidth?(pe.style.borderWidth=be.borderWidth,pe.style.borderStyle="solid"):(pe.style.borderWidth="",pe.style.borderStyle=""),be.borderColor?pe.style.borderColor=be.borderColor:pe.style.borderColor="",be.paddingX?(pe.style.paddingLeft=be.paddingX,pe.style.paddingRight=be.paddingX):(pe.style.paddingLeft="",pe.style.paddingRight=""),be.paddingY?(pe.style.paddingTop=be.paddingY,pe.style.paddingBottom=be.paddingY):(pe.style.paddingTop="",pe.style.paddingBottom=""),S.isStreaming()||pe.setAttribute("aria-label",co),xa(),Hn&&vn({anchor:pe,trigger:Hn,text:()=>pe.getAttribute("aria-label")??co,enabled:yd}),Eu(),wc();let Mm=Ml(ie.getState().activeModeIds,o.composer?.modes);ie.setActiveModeIds(Mm),Br().length>0!==!!Xn&&uc(),Xn?.render(Mm,Br());for(let N of[...Dr.keys()])Al(N,o.composer?.modeGroups)||Dr.delete(N);Dr.forEach(N=>N.repaint()),Ao?.repaint(),xn?.resolve();let Va=Ko(o,Ae());if(Cc(),Va){ce.style.maxWidth=Va,ce.style.marginLeft="auto",ce.style.marginRight="auto",ce.style.width="100%",en.style.maxWidth=Va,en.style.marginLeft="auto",en.style.marginRight="auto",en.style.width="100%";for(let N of[Ut,wo,jt,We])N&&(N.style.maxWidth=Va,N.style.marginLeft="auto",N.style.marginRight="auto",N.style.width="100%")}else{ce.style.maxWidth="",ce.style.marginLeft="",ce.style.marginRight="",ce.style.width="",en.style.maxWidth="",en.style.marginLeft="",en.style.marginRight="",en.style.width="";for(let N of[Ut,wo,jt,We])N&&(N.style.maxWidth="",N.style.marginLeft="",N.style.marginRight="",N.style.width="")}let Pn=o.statusIndicator??{};if(vd(We,Ut,Pn),ui(We,Pn,S?.getStatus()??"idle"),S){let N=S.getStatus();Ws(We,(ke=>ke==="idle"?Pn.idleText??gt.idle:ke==="connecting"?Pn.connectingText??gt.connecting:ke==="connected"?Pn.connectedText??gt.connected:ke==="error"?Pn.errorText??gt.error:ke==="paused"?Pn.pausedText??gt.paused:ke==="resuming"?Pn.resumingText??gt.resuming:gt[ke])(N),Pn,N)}We.classList.remove("persona-text-left","persona-text-center","persona-text-right");let vC=Pn.align==="left"?"persona-text-left":Pn.align==="center"?"persona-text-center":"persona-text-right";We.classList.add(vC),dc(),Oc(),An(),qi()},open(){Ve()&&Ge(!0,"api")},close(){Ve()&&Ge(!1,"api")},toggle(){Ve()&&Ge(!Se,"api")},reconnect(){S.reconnectNow()},clearChat(){Jn=!1,l.clear(),s.clear(),i.clear(),c.clear(),S.clearMessages(),o.layout?.topFade&&(j.scrollTop=0),j.removeAttribute("data-persona-top-fade"),It.clear(),On();try{localStorage.removeItem(Es),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Es}`)}catch(a){console.error("[AgentWidget] Failed to clear default localStorage:",a)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Es)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(a){console.error("[AgentWidget] Failed to clear custom localStorage:",a)}let r=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(r),v?.clear&&ha(()=>v.clear(),"[AgentWidget] Failed to clear storage adapter:"),x={},Me.syncFromMetadata(),_e?.clearAttachments(),ba(),Or(void 0),Wn(void 0),lr(),Lt?.clear(),wn?.reset(),Ot?.update()},setMessage(r){return!Z||S.isStreaming()||_n()?!1:(!Se&&Ve()&&Ge(!0,"system"),Z.value=r,Z.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(r){if(S.isStreaming()||fr())return!1;let a=r?.trim()||Z.value.trim();return a?(!Se&&Ve()&&Ge(!0,"system"),Z.value="",Z.style.height="auto",Rn(),Wa(a,{consumeDraft:!1}),!0):!1},getComposerState(){return ie.getState()},setQuote(r){let a=r?.text?.trim();a&&Wn({...r,text:a})},clearQuote(){Wn(void 0)},startVoiceRecognition(){return S.isStreaming()?!1:Nt(o.voiceRecognition?.provider)?(S.isVoiceActive()||S.isBargeInActive()||(!Se&&Ve()&&Ge(!0,"system"),Ie.manuallyDeactivated=!1,Tn(),S.toggleVoice().then(()=>{Ie.active=S.isVoiceActive(),oo("user"),S.isVoiceActive()&&ns()})),!0):Nn?!0:qg()?(!Se&&Ve()&&Ge(!0,"system"),Ie.manuallyDeactivated=!1,Tn(),Oa("user"),!0):!1},stopVoiceRecognition(){return Nt(o.voiceRecognition?.provider)?!S.isVoiceActive()&&!S.isBargeInActive()?!1:((S.isBargeInActive()?S.deactivateBargeIn():S.toggleVoice()).then(()=>{Ie.active=!1,Ie.manuallyDeactivated=!0,Tn(),oo("user"),lo()}),!0):Nn?(Ie.manuallyDeactivated=!0,Tn(),Do("user"),!0):!1},injectMessage(r){return!Se&&Ve()&&Ge(!0,"system"),S.injectMessage(r)},injectAssistantMessage(r){!Se&&Ve()&&Ge(!0,"system");let a=S.injectAssistantMessage(r);return Ls&&(Ls=!1,Hr&&(clearTimeout(Hr),Hr=null),setTimeout(()=>{S&&!S.isStreaming()&&S.continueConversation()},100)),a},injectUserMessage(r){return!Se&&Ve()&&Ge(!0,"system"),S.injectUserMessage(r)},injectSystemMessage(r){return!Se&&Ve()&&Ge(!0,"system"),S.injectSystemMessage(r)},injectMessageBatch(r){return!Se&&Ve()&&Ge(!0,"system"),S.injectMessageBatch(r)},injectComponentDirective(r){return!Se&&Ve()&&Ge(!0,"system"),S.injectComponentDirective(r)},injectTestMessage(r){!Se&&Ve()&&Ge(!0,"system"),S.injectTestEvent(r)},async connectStream(r,a){return S.connectStream(r,a)},__pushEventStreamEvent(r){Jt&&(zi(),Xl(r.type,r.payload))},showEventStream(){Jt&&cc()},hideEventStream(){Sn&&_r()},isEventStreamVisible(){return Sn},listConversations(r){return S.listConversations(r)},getActiveConversationId(){return S.getActiveConversationId()},openConversation(r,a){return Fn(d=>d.openHistoryConversation(r,{focusComposer:a?.focus===!0}))},startNewConversation(r){return Fn(a=>a.startNewConversation({focusComposer:r?.focus===!0}))},warmSession(){td()},deleteConversation(r){return Fn(a=>a.deleteHistoryConversation(r))},renameConversation(r,a){return Fn(d=>d.updateHistoryConversation(r,{title:a}))},setConversationStarred(r,a){return Fn(d=>d.updateHistoryConversation(r,{starred:a}))},clearConversationHistory(r){return Fn(a=>a.clearConversationHistory(r))},resetHistoryIdentity(){return Fn(r=>r.resetHistoryIdentity())},async getVisitorToken(){let r=gn;if(!r)return null;let a=await r.get();return r===gn?a:null},getHistoryIdentityStatus(){let r=tt?.historyProvider;return r?r.getIdentityStatus():ri()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(r){return ri()?Fn(a=>a.openHistory({...r?.returnSurface?{returnSurface:r.returnSurface}:{},...r?.focus!==void 0?{focus:r.focus}:{}})):Promise.resolve()},hideHistory(r){tt?.closeHistory(r?.restoreFocus!==void 0?{restoreFocus:r.restoreFocus}:void 0)},isHistoryVisible(){return Rs},showArtifacts(){zt(o)&&(Jn=!1,Nr=!0,En(),Ee?.setMobileOpen(!0))},hideArtifacts(){zt(o)&&(Jn=!0,En())},upsertArtifact(r){return zt(o)?(as(o.features?.artifacts,{artifactType:r.artifactType,...r.artifactType==="markdown"&&r.file?{file:r.file}:{},...r.presentation?{presentation:r.presentation}:{}})==="panel"&&(Jn=!1,Nr=!0),S.upsertArtifact(r)):null},selectArtifact(r){zt(o)&&S.selectArtifact(r)},clearArtifacts(){zt(o)&&S.clearArtifacts()},getArtifacts(){return S?.getArtifacts()??[]},getSelectedArtifactId(){return S?.getSelectedArtifactId()??null},focusInput(){return de&&!Se&&!Ae()||!Z?!1:(Z.focus(),!0)},async resolveApproval(r,a,d){let f=S.getMessages().find(b=>b.variant==="approval"&&b.approval?.id===r);if(!f?.approval)throw new Error(`Approval not found: ${r}`);if(f.approval.toolType==="webmcp"){S.resolveWebMcpApproval(f.id,a);return}return S.resolveApproval(f.approval,a,d)},setFollowUpSuggestions(r){sv(r)},clearFollowUpSuggestions(){tg()},getMessages(){return S.getMessages()},getStatus(){return S.getStatus()},getPersistentMetadata(){return{...x}},updatePersistentMetadata(r){$e(r)},on(r,a){return G.on(r,a)},off(r,a){G.off(r,a)},isOpen(){return Ve()&&Se},isVoiceActive(){return Ie.active},toggleReadAloud(r){S.toggleReadAloud(r)},stopReadAloud(){S.stopSpeaking()},getReadAloudState(r){return S.getReadAloudState(r)},onReadAloudChange(r){return S.onReadAloudChange(r)},getState(){return{open:Ve()&&Se,launcherEnabled:de,voiceActive:Ie.active,streaming:S.isStreaming()}},showCSATFeedback(r){!Se&&Ve()&&Ge(!0,"system");let a=ce.querySelector(".persona-feedback-container");a&&a.remove();let d=gb({onSubmit:async(m,f)=>{S.isClientTokenMode()&&await S.submitCSATFeedback(m,f),r?.onSubmit?.(m,f)},onDismiss:r?.onDismiss,...r});ce.appendChild(d),d.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(r){!Se&&Ve()&&Ge(!0,"system");let a=ce.querySelector(".persona-feedback-container");a&&a.remove();let d=mb({onSubmit:async(m,f)=>{S.isClientTokenMode()&&await S.submitNPSFeedback(m,f),r?.onSubmit?.(m,f)},onDismiss:r?.onDismiss,...r});ce.appendChild(d),d.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(r,a){return S.submitCSATFeedback(r,a)},async submitNPSFeedback(r,a){return S.submitNPSFeedback(r,a)},destroy(){Yc(),hr!=null&&(clearInterval(hr),hr=null),l.clear(),s.clear(),i.clear(),c.clear(),oe.forEach(r=>r()),Pe.remove(),St?.remove(),ct?.destroy(),_t?.remove(),or&&xe.removeEventListener("click",or)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let r=window.AgentWidgetBrowser,a={controller:dt,getMessages:dt.getMessages,getStatus:dt.getStatus,getMetadata:dt.getPersistentMetadata,updateMetadata:dt.updatePersistentMetadata,clearHistory:()=>dt.clearChat(),setVoiceActive:d=>d?dt.startVoiceRecognition():dt.stopVoiceRecognition()};window.AgentWidgetBrowser=a,oe.push(()=>{window.AgentWidgetBrowser===a&&(window.AgentWidgetBrowser=r)})}if(typeof window<"u"){let r=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),a=q=>{let K=q.detail;(!K?.instanceId||K.instanceId===r)&&dt.focusInput()};if(window.addEventListener("persona:focusInput",a),oe.push(()=>{window.removeEventListener("persona:focusInput",a)}),Jt){let q=X=>{let ae=X.detail;(!ae?.instanceId||ae.instanceId===r)&&dt.showEventStream()},K=X=>{let ae=X.detail;(!ae?.instanceId||ae.instanceId===r)&&dt.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",K),oe.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",K)})}let d=q=>{let K=q.detail;(!K?.instanceId||K.instanceId===r)&&dt.showHistory()},m=q=>{let K=q.detail;(!K?.instanceId||K.instanceId===r)&&dt.hideHistory()};window.addEventListener("persona:showHistory",d),window.addEventListener("persona:hideHistory",m),oe.push(()=>{window.removeEventListener("persona:showHistory",d),window.removeEventListener("persona:hideHistory",m)});let f=q=>{let K=q.detail;(!K?.instanceId||K.instanceId===r)&&dt.showArtifacts()},b=q=>{let K=q.detail;(!K?.instanceId||K.instanceId===r)&&dt.hideArtifacts()},D=q=>{let K=q.detail;K?.instanceId&&K.instanceId!==r||K?.artifact&&dt.upsertArtifact(K.artifact)},$=q=>{let K=q.detail;K?.instanceId&&K.instanceId!==r||typeof K?.id=="string"&&dt.selectArtifact(K.id)},F=q=>{let K=q.detail;(!K?.instanceId||K.instanceId===r)&&dt.clearArtifacts()};window.addEventListener("persona:showArtifacts",f),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",D),window.addEventListener("persona:selectArtifact",$),window.addEventListener("persona:clearArtifacts",F),oe.push(()=>{window.removeEventListener("persona:showArtifacts",f),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",D),window.removeEventListener("persona:selectArtifact",$),window.removeEventListener("persona:clearArtifacts",F)})}let fn=Zx(o.persistState);if(fn&&Ve()){let r=eA(fn.storage),a=`${fn.keyPrefix}widget-open`,d=`${fn.keyPrefix}widget-voice`,m=`${fn.keyPrefix}widget-voice-mode`;if(r){let f=fn.persist?.openState&&r.getItem(a)==="true",b=fn.persist?.voiceState&&r.getItem(d)==="true",D=fn.persist?.voiceState&&r.getItem(m)==="true";if(f&&(ct?.setPanelOpen(!0,"auto"),setTimeout(()=>{dt.open(),setTimeout(()=>{if(b||D)dt.startVoiceRecognition();else if(fn.persist?.focusInput){let $=t.querySelector("textarea");$&&$.focus()}},100)},0)),fn.persist?.openState&&(G.on("widget:opened",()=>{r.setItem(a,"true")}),G.on("widget:closed",()=>{r.setItem(a,"false")})),fn.persist?.voiceState&&(G.on("voice:state",$=>{r.setItem(d,$.active?"true":"false")}),G.on("user:message",$=>{r.setItem(m,$.viaVoice?"true":"false")})),fn.clearOnChatClear){let $=()=>{r.removeItem(a),r.removeItem(d),r.removeItem(m)},F=()=>$();window.addEventListener("persona:clear-chat",F),oe.push(()=>{window.removeEventListener("persona:clear-chat",F)})}}}if(Xe&&Ve()&&(ct?.setPanelOpen(!0,"auto"),setTimeout(()=>{dt.open()},0)),Yr(),!iv){let r=qa(()=>{S&&(cr++,It.clear(),un(ce,S.getMessages(),Xt))});oe.push(r)}R=()=>{S&&(cr++,It.clear(),un(ce,S.getMessages(),Xt))},S.getMessages().length>0&&Sa(),_=()=>{S&&(cr++,It.clear(),un(ce,S.getMessages(),Xt))};let yC=Dm(()=>{S&&(cr++,It.clear(),un(ce,S.getMessages(),Xt))});oe.push(yC);let bC=Wp(()=>{S&&(cr++,It.clear(),un(ce,S.getMessages(),Xt),yo()?.updateInlineArtifactBlocks(ce,dn.artifacts,{suppressTransition:!0}),En())});return oe.push(bC),dt};var Sb=(t,e)=>{let n=t.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(n);return s?Math.max(0,e*parseFloat(s[1])/100):420},oA=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},rA=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},sA=(t,e)=>{let n=t.parentElement;if(!n)return;let o=t.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let s=o.offsetHeight>0;o.style.height="100%";let i=o.offsetHeight>0;o.remove(),!(!s||i)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(e.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 ${e.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.")},xb=(t,e)=>{let n=e?.launcher?.enabled??!0;t.className="persona-host",t.style.height=n?"":"100%",t.style.display=n?"":"flex",t.style.flexDirection=n?"":"column",t.style.flex=n?"":"1 1 auto",t.style.minHeight=n?"":"0",t.style.minWidth=n?"":"0"},Qp=t=>{t.style.position="",t.style.top="",t.style.bottom="",t.style.left="",t.style.right="",t.style.zIndex="",t.style.transform="",t.style.pointerEvents=""},Ab=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",Qp(t)},Kp=t=>{t.style.transition=""},Gp=t=>{t.style.display="",t.style.flexDirection="",t.style.flex="",t.style.minHeight="",t.style.minWidth="",t.style.width="",t.style.height="",t.style.alignItems="",t.style.transition="",t.style.transform="",t.style.marginLeft=""},Yp=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},Gl=(t,e)=>{t.style.width="",t.style.minWidth="0",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},iA=(t,e,n,o,s)=>{s?n.parentElement!==e&&(t.replaceChildren(),e.replaceChildren(n,o),t.appendChild(e)):n.parentElement===e&&(e.replaceChildren(),t.appendChild(n),t.appendChild(o))},aA=(t,e,n,o,s,i)=>{let l=i?e:t;s==="left"?l.firstElementChild!==o&&l.replaceChildren(o,n):l.lastElementChild!==o&&l.replaceChildren(n,o)},lA=t=>{let e=ho(t),n=e.components?.panel,o=(s,i)=>s==null||s===""?i:Pt(e,s)??s;return{inset:o(n?.inset,Pl),canvasBackground:o(n?.canvasBackground,Ll)}},Mb=(t,e,n,o)=>{if(!e){t.style.padding="",t.style.background="",t.style.boxSizing="";return}t.style.boxSizing="border-box",t.style.padding=n,t.style.background=o},cA=(t,e,n,o,s,i,l,c)=>{let u=Cn(i),p=u.reveal==="push",g=c!=null,y=c?.inset??"",h=c?.canvasBackground??"";iA(t,e,n,o,p),aA(t,e,n,o,u.side,p),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=u.side,t.dataset.personaDockOpen=l?"true":"false",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0",t.style.height="100%",t.style.minHeight="0",t.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.minWidth="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let C=t.ownerDocument.defaultView,E=i?.launcher?.mobileFullscreen??!0,A=i?.launcher?.mobileBreakpoint??640,I=C!=null?C.innerWidth<=A:!1;if(E&&I&&l){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),Gp(e),Kp(o),Ab(o),Yp(n),Gl(s,o),Mb(o,!1,"",""),t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="stretch",t.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(i?.launcher?.zIndex??Dt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",p&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(t.removeAttribute("data-persona-dock-mobile-fullscreen"),Ab(o),oA(o,u.maxHeight),Mb(o,g&&l,y,h),u.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",Gp(e),Kp(o),Yp(n),Gl(s,o);let k=u.animate?"transform 180ms ease":"none",R=u.side==="right"?"translateX(100%)":"translateX(-100%)",B=l?"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=u.width,o.style.maxWidth=u.width,o.style.minWidth=u.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=k,o.style.transform=B,o.style.pointerEvents=l?"auto":"none",o.style.zIndex="2",u.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(u.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",Kp(o),Qp(o),Gl(s,o);let k=Sb(u.width,t.clientWidth),R=Math.max(0,t.clientWidth),B=u.animate?"margin-left 180ms ease":"none",O=u.side==="right"?l?-k:0:l?0:-k;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${R+k}px`,e.style.transition=B,e.style.marginLeft=`${O}px`,e.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=u.width,o.style.minWidth=u.width,o.style.maxWidth=u.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=l?"auto":"none"}else{t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="",Gp(e),Qp(o),Yp(n),Gl(s,o);let k=u.reveal==="emerge";k?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let R=l?u.width:"0px",B=u.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${g?", padding 180ms ease":""}`:"none",O=!l;if(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",rA(o,u.maxHeight),o.style.overflow=k||O?"hidden":"visible",o.style.transition=B,k){o.style.alignItems=u.side==="right"?"flex-start":"flex-end";let V=g?`calc(${Sb(u.width,t.clientWidth)}px - (2 * ${y}))`:u.width;s.style.width=V,s.style.minWidth=V,s.style.maxWidth=V,s.style.boxSizing="border-box"}}},dA=(t,e)=>{let n=t.ownerDocument.createElement("div");return xb(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){xb(n,o)},destroy(){n.remove()}}},pA=(t,e)=>{let{ownerDocument:n}=t,o=t.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let s=t.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let i=t.nextSibling,l=n.createElement("div"),c=n.createElement("div"),u=n.createElement("div"),p=n.createElement("aside"),g=n.createElement("div"),y=e?.launcher?.enabled??!0?e?.launcher?.autoExpand??!1:!0;c.dataset.personaDockRole="push-track",u.dataset.personaDockRole="content",p.dataset.personaDockRole="panel",g.dataset.personaDockRole="host",p.appendChild(g),o.insertBefore(l,t),u.appendChild(t);let h=null,C=()=>{h?.disconnect(),h=null},E=null,A=()=>{E=e?.launcher?.detachedPanel===!0?lA(e):null};A();let I=()=>{cA(l,c,u,p,g,e,y,E)},L=null,k=()=>{L?.(),L=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(L=Il(()=>{A(),I()}))},R=()=>{C(),Cn(e).reveal==="push"&&(typeof ResizeObserver>"u"||(h=new ResizeObserver(()=>{I()}),h.observe(l)))},B=!1,O=()=>{I(),R(),y&&!B&&l.dataset.personaDockMobileFullscreen!=="true"&&(B=!0,sA(l,Cn(e)))},V=l.ownerDocument.defaultView,J=()=>{O()};return V?.addEventListener("resize",J),Cn(e).reveal==="push"?(c.appendChild(u),c.appendChild(p),l.appendChild(c)):(l.appendChild(u),l.appendChild(p)),O(),k(),{mode:"docked",host:g,shell:l,syncWidgetState(_){let Q=_.launcherEnabled?_.open:!0;y!==Q&&(y=Q,O())},updateConfig(_){e=_,(e?.launcher?.enabled??!0)===!1&&(y=!0),A(),O(),k()},destroy(){V?.removeEventListener("resize",J),L?.(),L=null,C(),o.isConnected&&(i&&i.parentNode===o?o.insertBefore(t,i):o.appendChild(t)),l.remove()}}},Eb=(t,e)=>rt(e)?pA(t,e):dA(t,e);var Ni={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Tb=.15,kb=1.5,Xp="persona-preview-shell-theme",uA={load:()=>null,save:()=>{},clear:()=>{}},gA=["How do I get started?","Pricing & plans","Talk to support"];function Jp(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function mA(t){return t==="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 Pb(t){let e=mA(t);return`* { box-sizing: border-box; }
130
125
  html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
131
126
  html { color-scheme: ${t}; }
132
127
  body { font-family: system-ui, sans-serif; background: ${e.pageBg}; }
@@ -150,7 +145,7 @@ _Details: ${n.message}_`:o}var mg=t=>({isError:!0,content:[{type:"text",text:t}]
150
145
  .preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
151
146
  .preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
152
147
  .preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
153
- .preview-workspace-card.short { height: 96px; }`}function rx(t,e){let n=t.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(Wf);o||(o=n.createElement("style"),o.id=Wf,n.head.appendChild(o)),o.textContent=ox(e)}var wP=`
148
+ .preview-workspace-card.short { height: 96px; }`}function Lb(t,e){let n=t.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(Xp);o||(o=n.createElement("style"),o.id=Xp,n.head.appendChild(o)),o.textContent=Pb(e)}var fA=`
154
149
  <div class="preview-iframe-mock" aria-hidden="true">
155
150
  <div class="preview-iframe-chrome">
156
151
  <span class="preview-iframe-dot"></span>
@@ -169,7 +164,7 @@ _Details: ${n.message}_`:o}var mg=t=>({isError:!0,content:[{type:"text",text:t}]
169
164
  <div class="preview-iframe-line body"></div>
170
165
  <div class="preview-iframe-line body"></div>
171
166
  </div>
172
- </div>`,xP=`
167
+ </div>`,hA=`
173
168
  <div class="preview-workspace-content-shell" aria-hidden="true">
174
169
  <div class="preview-iframe-line hero"></div>
175
170
  <div class="preview-iframe-line body"></div>
@@ -182,8 +177,8 @@ _Details: ${n.message}_`:o}var mg=t=>({isError:!0,content:[{type:"text",text:t}]
182
177
  <div class="preview-workspace-card short"></div>
183
178
  <div class="preview-workspace-card short"></div>
184
179
  </div>
185
- </div>`;function sx(t,e,n,o){let s=`
186
- ${wP}
180
+ </div>`;function Ib(t,e,n,o){let s=`
181
+ ${fA}
187
182
  <div style="position:fixed;inset:0;z-index:9999;"><div id="${t}" data-mount-id="${t}"></div></div>`,i=`
188
183
  <div class="preview-workspace-shell">
189
184
  <div class="preview-workspace-topbar">
@@ -195,7 +190,7 @@ _Details: ${n.message}_`:o}var mg=t=>({isError:!0,content:[{type:"text",text:t}]
195
190
  </div>
196
191
  <div class="preview-workspace-body">
197
192
  <div id="preview-content-${t}" class="preview-workspace-content" data-mount-id="${t}">
198
- ${xP}
193
+ ${hA}
199
194
  </div>
200
195
  </div>
201
196
  </div>`;return`<!DOCTYPE html>
@@ -203,16 +198,16 @@ _Details: ${n.message}_`:o}var mg=t=>({isError:!0,content:[{type:"text",text:t}]
203
198
  <head>
204
199
  <meta charset="UTF-8">
205
200
  <meta name="viewport" content="width=device-width, initial-scale=1">
206
- <link rel="stylesheet" href="${Bf(o)}">
207
- <style id="${Wf}">${ox(e)}</style>
201
+ <link rel="stylesheet" href="${Jp(o)}">
202
+ <style id="${Xp}">${Pb(e)}</style>
208
203
  </head>
209
204
  <body>
210
205
  ${n?i:s}
211
206
  </body>
212
- </html>`}var SP=()=>[{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()}],AP=t=>!!(t?.features?.toolCallDisplay?.activePreview||t?.features?.toolCallDisplay?.grouped||t?.features?.toolCallDisplay?.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||t?.features?.reasoningDisplay?.activePreview);function MP(t,e,n=[]){if(t==="follow-ups"){let o=Date.now();return[{id:"preview-follow-up-user",role:"user",content:"What can Persona help me build?",createdAt:new Date(o-12e4).toISOString()},{id:"preview-follow-up-assistant",role:"assistant",content:"Persona gives you a themeable streaming chat interface with flexible integrations and interaction patterns. Where would you like to go next?",createdAt:new Date(o-6e4).toISOString()},{id:"preview-follow-up-suggestions",role:"assistant",content:"",createdAt:new Date(o-59e3).toISOString(),streaming:!1,variant:"tool",toolCall:{id:"preview-follow-up-suggestions",name:"suggest_replies",status:"complete",args:{suggestions:[{id:"preview-implementation",label:"Show me an implementation",prompt:"Show me a practical implementation",description:"See a complete integration example",icon:"code-2",emphasis:"primary"},{id:"preview-theming",label:"Explore theming",prompt:"Tell me how theming works",description:"Customize colors, type, and component styles",icon:"palette"},{id:"preview-security",label:"Review security",prompt:"Explain the security model",description:"Learn about isolation and safe rendering",icon:"shield-check"},{id:"preview-support",label:"Talk to support",prompt:"Help me contact support",description:"Get help choosing the right approach",icon:"messages-square"}]},chunks:[]}},...n]}return t==="home"?[]:t==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:t==="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()}]:t==="conversation"&&AP(e)?[...SP(),...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 TP(t,e,n=[]){let o={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},s={...t,launcher:o,suggestionChips:e==="home"?t.suggestionChips?.length?t.suggestionChips:vP:t.suggestionChips,initialMessages:MP(e,t,n),storageAdapter:bP};return e==="artifact"&&(s.features={...s.features,artifacts:{...s.features?.artifacts,enabled:!0}}),e==="messages"&&(s.features={...s.features,history:{presentation:"panel",...s.features?.history,enabled:!0}}),s}function EP(t,e){let n=Dc(t.config),o=t.config?.future,s=t.theme?ki(t.theme,{validate:!1,future:o}):ki(void 0,{future:o});return{...n,...t.config,theme:s,darkTheme:t.darkTheme,colorScheme:e??t.config?.colorScheme??"light"}}function Ni(t,e){let n=t.scene??"conversation";return TP(EP(t,e),n,t.appendedMessages??[])}function ix(t){let e=t.compareMode??"off",n=t.shellMode??"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:Ni(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Ni(t,"dark"),shellMode:"dark"}];if(e==="baseline"&&(t.baselineConfig||t.baselineTheme)){let o={...t,config:t.baselineConfig??t.config,theme:t.baselineTheme??t.theme,darkTheme:t.baselineDarkTheme??t.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:Ni(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Ni(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Ni(t,n),shellMode:n}]}function PP(t,e){let n={...e},o=[],s=[],i=null,l=!1,c=1,d=1,g=0;function u(){return n.device??"desktop"}function m(){return n.zoom??c}function y(){let I=getComputedStyle(t),N=parseFloat(I.paddingLeft)+parseFloat(I.paddingRight),x=parseFloat(I.paddingTop)+parseFloat(I.paddingBottom),D=40,L=(n.compareMode??"off")!=="off",$=(t.clientWidth-N-D)/(L?2:1),K=t.clientHeight-x-D;if($<=0||K<=0)return 1;let se=cl[u()]??cl.desktop;return Math.min($/se.w,K/se.h,1)}function b(){c=y();let I=Math.max(tx,Math.min(nx,m()));d=I;let N=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let x of N){let D=x.dataset.device??"desktop",L=cl[D]??cl.desktop;x.style.width=`${L.w*I}px`,x.style.height=`${L.h*I}px`,D==="mobile"&&(x.style.borderRadius=`${32*I}px`);let $=x.querySelector("iframe");$&&($.style.width=`${L.w}px`,$.style.height=`${L.h}px`,$.style.transformOrigin="top left",$.style.transition="none",$.style.transform=`scale(${I})`)}n.onScaleChange?.(I)}function C(){n.onBeforeDestroy?.();for(let I of o)I.destroy();for(let I of s)I();o=[],s=[]}function S(){return Array.from(t.querySelectorAll("iframe[data-mount-id]"))}function E(){if(l)return;C();let I=++g,N=ix(n),x=u(),D=(n.compareMode??"off")!=="off",L=(n.scene??"conversation")==="minimized",$=n.widgetCssPath??"/widget-dist/widget.css",K=n.buildSrcdoc??sx,se=x==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",ne=F=>`<div class="${se}" data-mount-id="${F.mountId}" data-device="${x}" data-shell-mode="${F.shellMode}">
213
- ${D?`<div class="preview-frame-meta"><span class="preview-frame-label">${Bf(F.label)}</span></div>`:""}
214
- <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${F.mountId}"></iframe>
215
- </div>`,M=D?`<div class="preview-compare-grid">${N.map(F=>`<div class="preview-compare-cell">${ne(F)}</div>`).join("")}</div>`:`<div class="preview-single">${ne(N[0])}</div>`;n.morphContainer?n.morphContainer(t,M):t.innerHTML=M,b();let T=S(),_=0,k=T.length,Z=()=>{if(l||I!==g)return;for(let ie of T){let le=ie.dataset.mountId;if(!le||!ie.contentDocument)continue;let pe=N.find(st=>st.mountId===le);if(!pe)continue;let ve=()=>{},Ce=xt(pe.config),me=Ce?(()=>{let st=ie.contentDocument?.getElementById(`preview-content-${le}`);if(!st)return null;let he=ex(st,pe.config),W=ie.contentDocument.createElement("div");W.id=le,W.style.height="100%",W.style.display="flex",W.style.flexDirection="column",W.style.flex="1",W.style.minHeight="0",he.host.appendChild(W);let We=()=>he.syncWidgetState(vt.getState()),Fe=ve;return ve=()=>{he.destroy(),Fe()},W.__syncDock=We,W.__hostLayout=he,W})():ie.contentDocument.getElementById(le);if(!me)continue;let vt=Qw(me,pe.config);if(o.push(vt),Ce&&me.__syncDock){let st=me.__syncDock,he=vt.on("widget:opened",st),W=vt.on("widget:closed",st),We=ve;ve=()=>{he(),W(),We()},st()}s.push(ve),L&&vt.close()}let F=n.scene??"conversation";if(F==="messages")for(let ie of o)ie.showHistory({focus:!1});if(F==="artifact"||n.config?.features?.artifacts?.enabled)for(let ie of o)ie.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
207
+ </html>`}var yA=()=>[{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()}],bA=t=>!!(t?.features?.toolCallDisplay?.activePreview||t?.features?.toolCallDisplay?.grouped||t?.features?.toolCallDisplay?.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||t?.features?.reasoningDisplay?.activePreview);function vA(t,e,n=[]){if(t==="follow-ups"){let o=Date.now();return[{id:"preview-follow-up-user",role:"user",content:"What can Persona help me build?",createdAt:new Date(o-12e4).toISOString()},{id:"preview-follow-up-assistant",role:"assistant",content:"Persona gives you a themeable streaming chat interface with flexible integrations and interaction patterns. Where would you like to go next?",createdAt:new Date(o-6e4).toISOString()},{id:"preview-follow-up-suggestions",role:"assistant",content:"",createdAt:new Date(o-59e3).toISOString(),streaming:!1,variant:"tool",toolCall:{id:"preview-follow-up-suggestions",name:"suggest_replies",status:"complete",args:{suggestions:[{id:"preview-implementation",label:"Show me an implementation",prompt:"Show me a practical implementation",description:"See a complete integration example",icon:"code-2",emphasis:"primary"},{id:"preview-theming",label:"Explore theming",prompt:"Tell me how theming works",description:"Customize colors, type, and component styles",icon:"palette"},{id:"preview-security",label:"Review security",prompt:"Explain the security model",description:"Learn about isolation and safe rendering",icon:"shield-check"},{id:"preview-support",label:"Talk to support",prompt:"Help me contact support",description:"Get help choosing the right approach",icon:"messages-square"}]},chunks:[]}},...n]}return t==="home"?[]:t==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:t==="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()}]:t==="conversation"&&bA(e)?[...yA(),...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 CA(t,e,n=[]){let o={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},s={...t,launcher:o,suggestionChips:e==="home"?t.suggestionChips?.length?t.suggestionChips:gA:t.suggestionChips,initialMessages:vA(e,t,n),storageAdapter:uA};return e==="artifact"&&(s.features={...s.features,artifacts:{...s.features?.artifacts,enabled:!0}}),e==="messages"&&(s.features={...s.features,history:{presentation:"panel",...s.features?.history,enabled:!0}}),s}function wA(t,e){let n=Wm(t.config),o=t.config?.future,s=t.theme?ys(t.theme,{validate:!1,future:o}):ys(void 0,{future:o});return{...n,...t.config,theme:s,darkTheme:t.darkTheme,colorScheme:e??t.config?.colorScheme??"light"}}function ks(t,e){let n=t.scene??"conversation";return CA(wA(t,e),n,t.appendedMessages??[])}function Hb(t){let e=t.compareMode??"off",n=t.shellMode??"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:ks(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:ks(t,"dark"),shellMode:"dark"}];if(e==="baseline"&&(t.baselineConfig||t.baselineTheme)){let o={...t,config:t.baselineConfig??t.config,theme:t.baselineTheme??t.theme,darkTheme:t.baselineDarkTheme??t.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:ks(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:ks(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:ks(t,n),shellMode:n}]}function SA(t,e){let n={...e},o=[],s=[],i=null,l=!1,c=1,u=1,p=0;function g(){return n.device??"desktop"}function y(){return n.zoom??c}function h(){let k=getComputedStyle(t),R=parseFloat(k.paddingLeft)+parseFloat(k.paddingRight),B=parseFloat(k.paddingTop)+parseFloat(k.paddingBottom),O=40,V=(n.compareMode??"off")!=="off",J=(t.clientWidth-R-O)/(V?2:1),_=t.clientHeight-B-O;if(J<=0||_<=0)return 1;let Q=Ni[g()]??Ni.desktop;return Math.min(J/Q.w,_/Q.h,1)}function C(){c=h();let k=Math.max(Tb,Math.min(kb,y()));u=k;let R=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let B of R){let O=B.dataset.device??"desktop",V=Ni[O]??Ni.desktop;B.style.width=`${V.w*k}px`,B.style.height=`${V.h*k}px`,O==="mobile"&&(B.style.borderRadius=`${32*k}px`);let J=B.querySelector("iframe");J&&(J.style.width=`${V.w}px`,J.style.height=`${V.h}px`,J.style.transformOrigin="top left",J.style.transition="none",J.style.transform=`scale(${k})`)}n.onScaleChange?.(k)}function E(){n.onBeforeDestroy?.();for(let k of o)k.destroy();for(let k of s)k();o=[],s=[]}function A(){return Array.from(t.querySelectorAll("iframe[data-mount-id]"))}function I(){if(l)return;E();let k=++p,R=Hb(n),B=g(),O=(n.compareMode??"off")!=="off",V=(n.scene??"conversation")==="minimized",J=n.widgetCssPath??"/widget-dist/widget.css",_=n.buildSrcdoc??Ib,Q=B==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",G=W=>`<div class="${Q}" data-mount-id="${W.mountId}" data-device="${B}" data-shell-mode="${W.shellMode}">
208
+ ${O?`<div class="preview-frame-meta"><span class="preview-frame-label">${Jp(W.label)}</span></div>`:""}
209
+ <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${W.mountId}"></iframe>
210
+ </div>`,w=O?`<div class="preview-compare-grid">${R.map(W=>`<div class="preview-compare-cell">${G(W)}</div>`).join("")}</div>`:`<div class="preview-single">${G(R[0])}</div>`;n.morphContainer?n.morphContainer(t,w):t.innerHTML=w,C();let v=A(),T=0,x=v.length,z=()=>{if(l||k!==p)return;for(let ee of v){let ne=ee.dataset.mountId;if(!ne||!ee.contentDocument)continue;let he=R.find($e=>$e.mountId===ne);if(!he)continue;let ve=()=>{},Xe=rt(he.config),Je=Xe?(()=>{let $e=ee.contentDocument?.getElementById(`preview-content-${ne}`);if(!$e)return null;let Ce=Eb($e,he.config),H=ee.contentDocument.createElement("div");H.id=ne,H.style.height="100%",H.style.display="flex",H.style.flexDirection="column",H.style.flex="1",H.style.minHeight="0",Ce.host.appendChild(H);let Me=()=>Ce.syncWidgetState(Wt.getState()),de=ve;return ve=()=>{Ce.destroy(),de()},H.__syncDock=Me,H.__hostLayout=Ce,H})():ee.contentDocument.getElementById(ne);if(!Je)continue;let Wt=wb(Je,he.config);if(o.push(Wt),Xe&&Je.__syncDock){let $e=Je.__syncDock,Ce=Wt.on("widget:opened",$e),H=Wt.on("widget:closed",$e),Me=ve;ve=()=>{Ce(),H(),Me()},$e()}s.push(ve),V&&Wt.close()}let W=n.scene??"conversation";if(W==="messages")for(let ee of o)ee.showHistory({focus:!1});if(W==="artifact"||n.config?.features?.artifacts?.enabled)for(let ee of o)ee.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
216
211
 
217
212
  This is a preview of the artifact sidebar.
218
213
 
@@ -220,4 +215,4 @@ This is a preview of the artifact sidebar.
220
215
 
221
216
  - Markdown rendering
222
217
  - Document toolbar
223
- - Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:T,controllers:[...o]})};for(let F of T){let ie=F.dataset.mountId;if(!ie)continue;let le=N.find(pe=>pe.mountId===ie);le&&(F.addEventListener("load",()=>{_++,_>=k&&Z()},{once:!0}),F.srcdoc=K(ie,le.shellMode,xt(le.config),$))}k===0&&Z()}function H(){if(l)return;let I=ix(n);if(o.length!==I.length){E();return}if(I.some(x=>{let D=t.querySelector(`.preview-iframe-wrapper[data-mount-id="${x.mountId}"]`);return!D||D.dataset.shellMode!==x.shellMode})){E();return}o.forEach((x,D)=>{x.update(I[D].config),(n.scene??"conversation")==="minimized"&&x.close()});for(let x of I){let D=t.querySelector(`iframe[data-mount-id="${x.mountId}"]`);D&&rx(D,x.shellMode)}n.onAfterUpdate?.({iframes:S(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(i=new ResizeObserver(()=>{l||b()}),i.observe(t)),E(),{update(I){if(l)return;let N=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},N?E():H()},destroy(){l||(l=!0,C(),i?.disconnect(),t.innerHTML="")},getControllers(){return[...o]},fitToContainer(){l||(n={...n,zoom:void 0},b())},getIframes(){return S()},getScale(){return d},setZoom(I){l||(n={...n,zoom:I},b())}}}export{PP as createThemePreview};
218
+ - Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:v,controllers:[...o]})};for(let W of v){let ee=W.dataset.mountId;if(!ee)continue;let ne=R.find(he=>he.mountId===ee);ne&&(W.addEventListener("load",()=>{T++,T>=x&&z()},{once:!0}),W.srcdoc=_(ee,ne.shellMode,rt(ne.config),J))}x===0&&z()}function L(){if(l)return;let k=Hb(n);if(o.length!==k.length){I();return}if(k.some(B=>{let O=t.querySelector(`.preview-iframe-wrapper[data-mount-id="${B.mountId}"]`);return!O||O.dataset.shellMode!==B.shellMode})){I();return}o.forEach((B,O)=>{B.update(k[O].config),(n.scene??"conversation")==="minimized"&&B.close()});for(let B of k){let O=t.querySelector(`iframe[data-mount-id="${B.mountId}"]`);O&&Lb(O,B.shellMode)}n.onAfterUpdate?.({iframes:A(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(i=new ResizeObserver(()=>{l||C()}),i.observe(t)),I(),{update(k){if(l)return;let R=k.device!==void 0&&k.device!==n.device||k.scene!==void 0&&k.scene!==n.scene||k.compareMode!==void 0&&k.compareMode!==n.compareMode||k.widgetCssPath!==void 0&&k.widgetCssPath!==n.widgetCssPath;n={...n,...k},R?I():L()},destroy(){l||(l=!0,E(),i?.disconnect(),t.innerHTML="")},getControllers(){return[...o]},fitToContainer(){l||(n={...n,zoom:void 0},C())},getIframes(){return A()},getScale(){return u},setZoom(k){l||(n={...n,zoom:k},C())}}}export{SA as createThemePreview};