@runtypelabs/persona 3.34.0 → 3.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) hide show
  1. package/README.md +11 -11
  2. package/dist/animations/glyph-cycle.d.cts +1 -1
  3. package/dist/animations/glyph-cycle.d.ts +1 -1
  4. package/dist/animations/{types-CthJFfNx.d.cts → types-DgYsuwXL.d.cts} +15 -14
  5. package/dist/animations/{types-CthJFfNx.d.ts → types-DgYsuwXL.d.ts} +15 -14
  6. package/dist/animations/wipe.d.cts +1 -1
  7. package/dist/animations/wipe.d.ts +1 -1
  8. package/dist/codegen.cjs +11 -11
  9. package/dist/codegen.js +10 -10
  10. package/dist/index.cjs +46 -44
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +514 -158
  13. package/dist/index.d.ts +514 -158
  14. package/dist/index.global.js +41 -89
  15. package/dist/index.global.js.map +1 -1
  16. package/dist/index.js +46 -44
  17. package/dist/index.js.map +1 -1
  18. package/dist/install.global.js +1 -1
  19. package/dist/install.global.js.map +1 -1
  20. package/dist/launcher.global.js +2 -2
  21. package/dist/launcher.global.js.map +1 -1
  22. package/dist/markdown-parsers.js +53 -0
  23. package/dist/plugin-kit.d.cts +4 -4
  24. package/dist/plugin-kit.d.ts +4 -4
  25. package/dist/runtype-tts.js +1 -0
  26. package/dist/smart-dom-reader.cjs +1 -1
  27. package/dist/smart-dom-reader.d.cts +352 -103
  28. package/dist/smart-dom-reader.d.ts +352 -103
  29. package/dist/smart-dom-reader.js +1 -1
  30. package/dist/theme-editor-preview.cjs +203 -0
  31. package/dist/theme-editor-preview.d.cts +5748 -0
  32. package/dist/theme-editor-preview.d.ts +5748 -0
  33. package/dist/theme-editor-preview.js +203 -0
  34. package/dist/theme-editor.cjs +14 -131
  35. package/dist/theme-editor.d.cts +362 -574
  36. package/dist/theme-editor.d.ts +362 -574
  37. package/dist/theme-editor.js +14 -131
  38. package/dist/theme-reference.cjs +1 -1
  39. package/dist/theme-reference.d.cts +1 -1
  40. package/dist/theme-reference.d.ts +1 -1
  41. package/dist/theme-reference.js +1 -1
  42. package/dist/voice-worklet-player.cjs +80 -0
  43. package/dist/voice-worklet-player.d.cts +215 -0
  44. package/dist/voice-worklet-player.d.ts +215 -0
  45. package/dist/voice-worklet-player.js +80 -0
  46. package/dist/widget.css +54 -36
  47. package/package.json +16 -2
  48. package/src/animations/glyph-cycle.ts +11 -14
  49. package/src/animations/wipe.ts +1 -1
  50. package/src/ask-user-question-tool.test.ts +1 -1
  51. package/src/ask-user-question-tool.ts +6 -8
  52. package/src/client.test.ts +67 -12
  53. package/src/client.ts +40 -32
  54. package/src/codegen.test.ts +1 -1
  55. package/src/codegen.ts +1 -1
  56. package/src/components/approval-bubble.test.ts +1 -1
  57. package/src/components/approval-bubble.ts +3 -3
  58. package/src/components/artifact-pane.ts +3 -3
  59. package/src/components/ask-user-question-bubble.test.ts +14 -14
  60. package/src/components/ask-user-question-bubble.ts +10 -10
  61. package/src/components/composer-builder.ts +17 -16
  62. package/src/components/composer-parts.test.ts +54 -0
  63. package/src/components/composer-parts.ts +95 -126
  64. package/src/components/demo-carousel.ts +1 -1
  65. package/src/components/event-stream-view.test.ts +7 -7
  66. package/src/components/event-stream-view.ts +5 -5
  67. package/src/components/header-builder.ts +33 -27
  68. package/src/components/header-layouts.ts +1 -1
  69. package/src/components/header-parts.test.ts +90 -0
  70. package/src/components/header-parts.ts +62 -93
  71. package/src/components/launcher.test.ts +11 -0
  72. package/src/components/launcher.ts +1 -1
  73. package/src/components/message-bubble.test.ts +74 -2
  74. package/src/components/message-bubble.ts +25 -11
  75. package/src/components/messages.ts +2 -2
  76. package/src/components/panel.test.ts +1 -1
  77. package/src/components/panel.ts +92 -97
  78. package/src/components/pill-composer-builder.ts +28 -24
  79. package/src/components/reasoning-bubble.ts +2 -2
  80. package/src/components/suggestions.ts +1 -1
  81. package/src/components/tool-bubble.ts +1 -1
  82. package/src/components/widget-view.test.ts +181 -0
  83. package/src/components/widget-view.ts +234 -0
  84. package/src/defaults.ts +54 -51
  85. package/src/generated/runtype-openapi-contract.ts +5 -0
  86. package/src/index-core.ts +30 -4
  87. package/src/index-global.ts +73 -6
  88. package/src/index.ts +7 -1
  89. package/src/install.test.ts +11 -11
  90. package/src/install.ts +28 -18
  91. package/src/launcher-global.ts +25 -14
  92. package/src/markdown-parsers-eager.ts +20 -0
  93. package/src/markdown-parsers-entry.ts +4 -0
  94. package/src/markdown-parsers-loader.ts +49 -0
  95. package/src/plugin-kit.test.ts +1 -1
  96. package/src/plugin-kit.ts +7 -7
  97. package/src/plugins/types.ts +5 -5
  98. package/src/postprocessors.ts +27 -14
  99. package/src/runtime/host-layout.test.ts +1 -1
  100. package/src/runtime/host-layout.ts +4 -5
  101. package/src/runtime/init.ts +2 -2
  102. package/src/session.test.ts +5 -6
  103. package/src/session.ts +333 -227
  104. package/src/session.voice.test.ts +146 -0
  105. package/src/session.webmcp.test.ts +24 -25
  106. package/src/smart-dom-reader.ts +3 -4
  107. package/src/styles/widget.css +54 -36
  108. package/src/suggest-replies-tool.test.ts +3 -3
  109. package/src/suggest-replies-tool.ts +5 -5
  110. package/src/testing/index.ts +1 -1
  111. package/src/theme-editor/color-utils.ts +2 -2
  112. package/src/theme-editor/index.ts +4 -13
  113. package/src/theme-editor/presets.ts +1 -1
  114. package/src/theme-editor/preview-utils.ts +22 -20
  115. package/src/theme-editor/preview.ts +4 -1
  116. package/src/theme-editor/role-mappings.ts +3 -3
  117. package/src/theme-editor/sections.ts +21 -20
  118. package/src/theme-editor/types.ts +1 -1
  119. package/src/theme-editor/webmcp/index.ts +1 -1
  120. package/src/theme-editor/webmcp/summary.ts +1 -2
  121. package/src/theme-editor/webmcp/tools.ts +30 -30
  122. package/src/theme-editor/webmcp/types.ts +2 -2
  123. package/src/theme-editor-preview.ts +10 -0
  124. package/src/theme-reference.ts +26 -26
  125. package/src/types.ts +368 -99
  126. package/src/ui.approval-plugin.test.ts +3 -3
  127. package/src/ui.ask-user-question-plugin.test.ts +9 -9
  128. package/src/ui.component-directive.test.ts +4 -4
  129. package/src/ui.composer-bar.test.ts +10 -11
  130. package/src/ui.composer-keyboard.test.ts +5 -5
  131. package/src/ui.header-icon-color.test.ts +59 -0
  132. package/src/ui.scroll.test.ts +5 -6
  133. package/src/ui.stop-button.test.ts +3 -4
  134. package/src/ui.suggest-replies.test.ts +2 -2
  135. package/src/ui.ts +292 -131
  136. package/src/utils/buttons.ts +1 -1
  137. package/src/utils/code-generators.ts +1 -1
  138. package/src/utils/composer-history.ts +3 -3
  139. package/src/utils/dom-context.test.ts +2 -2
  140. package/src/utils/dom-context.ts +7 -7
  141. package/src/utils/dom.test.ts +67 -0
  142. package/src/utils/dom.ts +75 -0
  143. package/src/utils/dropdown.ts +2 -2
  144. package/src/utils/event-stream-buffer.test.ts +2 -2
  145. package/src/utils/message-fingerprint.test.ts +9 -0
  146. package/src/utils/message-fingerprint.ts +5 -0
  147. package/src/utils/morph.ts +1 -1
  148. package/src/utils/sanitize.ts +32 -16
  149. package/src/utils/sequence-buffer.test.ts +8 -8
  150. package/src/utils/sequence-buffer.ts +4 -4
  151. package/src/utils/smart-dom-adapter.test.ts +1 -1
  152. package/src/utils/smart-dom-adapter.ts +4 -5
  153. package/src/utils/speech-text.test.ts +122 -0
  154. package/src/utils/speech-text.ts +101 -0
  155. package/src/utils/stream-animation.test.ts +3 -3
  156. package/src/utils/stream-animation.ts +6 -6
  157. package/src/utils/theme.test.ts +1 -1
  158. package/src/utils/throughput-tracker.test.ts +11 -11
  159. package/src/utils/throughput-tracker.ts +9 -9
  160. package/src/utils/tokens.ts +13 -13
  161. package/src/utils/virtual-scroller.ts +1 -1
  162. package/src/vendor/smart-dom-reader/README.md +4 -4
  163. package/src/vendor/smart-dom-reader/index.d.ts +1 -1
  164. package/src/vendor/smart-dom-reader/index.js +2 -2
  165. package/src/version.ts +1 -1
  166. package/src/voice/audio-playback-manager.test.ts +159 -0
  167. package/src/voice/audio-playback-manager.ts +145 -30
  168. package/src/voice/browser-speech-engine.ts +130 -0
  169. package/src/voice/fallback-speech-engine.ts +89 -0
  170. package/src/voice/index.ts +21 -0
  171. package/src/voice/read-aloud-controller.test.ts +143 -0
  172. package/src/voice/read-aloud-controller.ts +136 -0
  173. package/src/voice/runtype-speech-engine.test.ts +280 -0
  174. package/src/voice/runtype-speech-engine.ts +211 -0
  175. package/src/voice/runtype-tts-entry.ts +10 -0
  176. package/src/voice/runtype-tts-loader.test.ts +47 -0
  177. package/src/voice/runtype-tts-loader.ts +42 -0
  178. package/src/voice/runtype-voice-provider.ts +332 -537
  179. package/src/voice/voice-factory.ts +26 -4
  180. package/src/voice/voice.test.ts +321 -7
  181. package/src/voice/worklet-playback-engine.ts +272 -0
  182. package/src/voice-worklet-player.ts +39 -0
  183. package/src/webmcp-bridge.test.ts +6 -6
  184. package/src/webmcp-bridge.ts +24 -25
  185. package/src/webmcp-polyfill.ts +1 -1
  186. package/src/voice/voice-activity-detector.ts +0 -90
@@ -0,0 +1,203 @@
1
+ "use strict";var gg=Object.create;var Na=Object.defineProperty;var fg=Object.getOwnPropertyDescriptor;var hg=Object.getOwnPropertyNames;var yg=Object.getPrototypeOf,bg=Object.prototype.hasOwnProperty;var Vs=(n,e)=>()=>(n&&(e=n(n=0)),e);var Hi=(n,e)=>{for(var t in e)Na(n,t,{get:e[t],enumerable:!0})},Vp=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of hg(e))!bg.call(n,o)&&o!==t&&Na(n,o,{get:()=>e[o],enumerable:!(r=fg(e,o))||r.enumerable});return n};var jp=(n,e,t)=>(t=n!=null?gg(yg(n)):{},Vp(e||!n||!n.__esModule?Na(t,"default",{value:n,enumerable:!0}):t,n)),vg=n=>Vp(Na({},"__esModule",{value:!0}),n);var Qp={};Hi(Qp,{DOMPurify:()=>Gp.default,Marked:()=>Kp.Marked});var Kp,Gp,Xp=Vs(()=>{"use strict";Kp=require("marked"),Gp=jp(require("dompurify"),1)});var hs,Ji=Vs(()=>{"use strict";hs=class{constructor(e=24e3,t={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;var o;this.sampleRate=e;let r=Math.max(0,(o=t.prebufferMs)!=null?o:0);this.waterlineSamples=Math.round(e*r/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let r=t.AudioContext||t.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let e=this.ctx;return e.state==="suspended"&&!this.userPaused&&e.resume(),e}enqueue(e){if(e.length===0)return;let t=e;if(this.remainder){let o=new Uint8Array(this.remainder.length+e.length);o.set(this.remainder),o.set(e,this.remainder.length),t=o,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let r=this.pcmToFloat32(t);r.length!==0&&(this.buffering?(this.pendingBuffers.push(r),this.pendingSamples+=r.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(r))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let e of this.activeSources)try{e.stop(),e.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(e){this.finishedCallbacks.push(e)}onStarted(e){this.startedCallbacks.push(e)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let e=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let t of e)this.scheduleSamples(t)}scheduleSamples(e){if(e.length===0)return;let t=this.ensureContext(),r=t.createBuffer(1,e.length,this.sampleRate);r.getChannelData(0).set(e);let o=t.createBufferSource();o.buffer=r,o.connect(t.destination);let s=t.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),o.start(this.nextStartTime),this.nextStartTime+=r.duration,this.activeSources.push(o),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}o.onended=()=>{let a=this.activeSources.indexOf(o);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let e=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of e)t()}}pcmToFloat32(e){let t=Math.floor(e.length/2),r=new Float32Array(t),o=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let s=0;s<t;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}}});function wf(n){return n.replace(/\/+$/,"")}async function Cf(n){var e,t;try{let r=await n.json();return r.detail?`${(e=r.error)!=null?e:`Runtype TTS ${n.status}`}: ${r.detail}`:(t=r.error)!=null?t:`Runtype TTS request failed (${n.status})`}catch{return`Runtype TTS request failed (${n.status})`}}var ei,Ru=Vs(()=>{"use strict";Ji();ei=class{constructor(e){this.opts=e;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){var e,t;return(t=this.playerPromise)!=null?t:this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new hs(24e3,{prebufferMs:(e=this.opts.prebufferMs)!=null?e:200})).then(r=>this.player=r)}speak(e,t){let r=++this.generation;this.run(r,e,t)}async run(e,t,r){var o,s,a,i;try{let d=await this.ensurePlayer();if(e!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var u;e===this.generation&&((u=r.onStart)==null||u.call(r))}),d.onFinished(()=>{var u;e===this.generation&&((u=r.onEnd)==null||u.call(r))});let c=`${wf(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,g=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:t.text,voice:(o=t.voice)!=null?o:this.opts.voice,format:"pcm"})});if(e!==this.generation)return;if(!g.ok||!g.body)throw new Error(await Cf(g));let f=g.body.getReader();for(;;){let{done:u,value:m}=await f.read();if(e!==this.generation){await f.cancel().catch(()=>{});return}if(u)break;m&&m.byteLength>0&&d.enqueue(m)}d.markStreamEnd()}catch(d){if(e!==this.generation)return;let c=d instanceof Error?d:new Error(String(d));(a=(s=this.opts).onError)==null||a.call(s,c),(i=r.onError)==null||i.call(r,c)}}pause(){var e;(e=this.player)==null||e.pause()}resume(){var e;(e=this.player)==null||e.resume()}stop(){var e;this.generation++,(e=this.player)==null||e.flush()}destroy(){var e;this.generation++,(e=this.player)==null||e.destroy(),this.player=null,this.playerPromise=null}}});var ti,Hu=Vs(()=>{"use strict";ti=class{constructor(e,t,r={}){this.primary=e;this.fallback=t;this.options=r;this.id="fallback";this.active=e}get supportsPause(){return this.active.supportsPause}speak(e,t){this.active=this.primary;let r=!1;this.primary.speak(e,{onStart:()=>{var o;r=!0,(o=t.onStart)==null||o.call(t)},onEnd:()=>{var o;return(o=t.onEnd)==null?void 0:o.call(t)},onError:o=>{var s,a,i;if(r){(s=t.onError)==null||s.call(t,o);return}(i=(a=this.options).onFallback)==null||i.call(a,o),this.active=this.fallback,this.fallback.speak(e,t)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){var e,t,r,o;(t=(e=this.primary).destroy)==null||t.call(e),(o=(r=this.fallback).destroy)==null||o.call(r)}}});var Bu={};Hi(Bu,{FallbackSpeechEngine:()=>ti,RuntypeSpeechEngine:()=>ei});var Du=Vs(()=>{"use strict";Ru();Hu()});var Ly={};Hi(Ly,{createThemePreview:()=>ig});module.exports=vg(Ly);var Jp=null,js=null,ls=null;var Yp=()=>js?Promise.resolve(js):ls||(Jp?(ls=Jp().then(n=>(js=n,n)),ls):(ls=Promise.resolve().then(()=>(Xp(),Qp)).then(n=>(js=n,n)),ls)),cs=()=>js;var xg=n=>{if(n)return n},Bi=n=>{let e=null;return t=>{var o,s;let r=cs();if(!r)return ho(t);if(!e){let{Marked:a}=r,i=n==null?void 0:n.markedOptions;e=new a({gfm:(o=i==null?void 0:i.gfm)!=null?o:!0,breaks:(s=i==null?void 0:i.breaks)!=null?s:!0,pedantic:i==null?void 0:i.pedantic,silent:i==null?void 0:i.silent});let d=xg(n==null?void 0:n.renderer);d&&e.use({renderer:d})}return e.parse(t)}},Fa=n=>n?Bi({markedOptions:n.options,renderer:n.renderer}):Bi(),By=Bi();var ho=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var wg={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},Cg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ag=()=>{let n=null;return e=>{let t=cs();if(!t)return ho(e);if(!n){let{DOMPurify:r}=t;n=r(typeof window!="undefined"?window:void 0),n.addHook("uponSanitizeAttribute",(o,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!Cg.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return n.sanitize(e,wg)}},Oa=n=>n===!1?null:typeof n=="function"?n:Ag();var No="webmcp:",Di=new Map,Zp=n=>{var e;Di.clear();for(let t of n){let r=(e=t.title)==null?void 0:e.trim();r&&Di.set(t.name,r)}},Ni=n=>Di.get(ru(n)),_a={warn(n,...e){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${n}`,...e)}},eu=null;function nu(n){if(n.length===0)return"0:empty";let e=n.map(t=>{var r,o;return[t.name,(r=t.description)!=null?r:"",t.parametersSchema?JSON.stringify(t.parametersSchema):"",(o=t.origin)!=null?o:"",t.annotations?JSON.stringify(t.annotations):""].join("")}).sort();return`${n.length}:${Sg(e.join(""))}`}function tu(n,e){let t=3735928559^e,r=1103547991^e;for(let o=0;o<n.length;o++){let s=n.charCodeAt(o);t=Math.imul(t^s,2654435761),r=Math.imul(r^s,1597334677)}return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(t^t>>>13,3266489909),4294967296*(2097151&r)+(t>>>0)}function Sg(n){let e=tu(n,0).toString(36),t=tu(n,2654435761).toString(36);return`${e}.${t}`}var $a=class{constructor(e){this.config=e;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var t;this.confirmHandler=(t=e.onConfirm)!=null?t:null,this.timeoutMs=3e4}setConfirmHandler(e){this.confirmHandler=e}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let e=this.getModelContext();if(!e)return[];let t;try{t=await e.getTools()}catch(o){return _a.warn("getTools() threw: shipping an empty WebMCP snapshot.",o),[]}Zp(t);let r=typeof location!="undefined"?location.origin:"";return t.filter(o=>this.passesClientAllowlist(o.name)).map(o=>{let s={name:o.name,description:o.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=Mg(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(e,t,r){if(await this.ensureReady(),this.config.enabled!==!0)return vr("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let v=typeof document!="undefined"&&!!document.modelContext;return vr(v?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=ru(e),a;try{a=await o.getTools()}catch(v){let x=v instanceof Error?v.message:String(v);return vr(`Failed to read WebMCP registry: ${x}`)}Zp(a);let i=a.find(v=>v.name===s);if(!i)return vr(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return vr(`WebMCP tool not allowed by client allowlist: ${s}`);if(r!=null&&r.aborted)return vr("Aborted by cancel()");let d=Ni(s),c={toolName:s,args:t,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(c))return vr("User declined the tool call.");if(r!=null&&r.aborted)return vr("Aborted by cancel()");let g=new AbortController,f=!1,u=setTimeout(()=>{f=!0,g.abort()},this.timeoutMs),m=()=>g.abort();r&&(r.aborted?g.abort():r.addEventListener("abort",m,{once:!0}));try{let v=await o.executeTool(i,Pg(t),{signal:g.signal});return Eg(v)}catch(v){if(f)return vr(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return vr("Aborted by cancel()");let x=v instanceof Error?v.message:String(v);return vr(x)}finally{clearTimeout(u),r&&r.removeEventListener("abort",m)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(eu?await eu():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(e){_a.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let t=e;return typeof t.getTools!="function"||typeof t.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,_a.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):e}async requestConfirm(e){var r;let t=(r=this.confirmHandler)!=null?r:kg;try{return await t(e)}catch(o){return _a.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,o),!1}}passesClientAllowlist(e){let t=this.config.allowlist;return!t||t.length===0?!0:t.some(r=>Tg(e,r))}},ru=n=>n.startsWith(No)?n.slice(No.length):n,Ks=n=>n.startsWith(No),Tg=(n,e)=>{if(e==="*")return!0;let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(n)},Mg=n=>{if(!(n===void 0||n===""))try{let e=JSON.parse(n);return e!==null&&typeof e=="object"?e:void 0}catch{return}},Eg=n=>{if(n==null)return{content:[{type:"text",text:""}]};let e;try{e=JSON.parse(n)}catch{return{content:[{type:"text",text:n}]}}return e!==null&&typeof e=="object"&&Array.isArray(e.content)?e:{content:[{type:"text",text:typeof e=="string"?e:Ig(e)}]}},vr=n=>({isError:!0,content:[{type:"text",text:n}]}),kg=async n=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let e=Lg(n.args),t=`Allow the AI to call ${n.toolName}`+(e?`
2
+
3
+ Arguments:
4
+ ${e}`:"")+(n.description?`
5
+
6
+ ${n.description}`:"");return window.confirm(t)},Lg=n=>{if(n==null)return"";try{let e=JSON.stringify(n,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(n)}},Pg=n=>{if(n===void 0)return"{}";try{let e=JSON.stringify(n);return e===void 0?"{}":e}catch{return"{}"}},Ig=n=>{if(n===void 0)return"";try{return JSON.stringify(n)}catch{return String(n)}};var yo=require("partial-json");var b=(n,e)=>{let t=document.createElement(n);return e&&(t.className=e),t},Nr=(n,e,t)=>{let r=n.createElement(e);return t&&(r.className=t),r};var Lt=(n,e={},...t)=>{let r=document.createElement(n);if(e.className&&(r.className=e.className),e.text!==void 0&&(r.textContent=e.text),e.attrs)for(let[s,a]of Object.entries(e.attrs))r.setAttribute(s,a);if(e.style){let s=r.style,a=e.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(s[i]=d)}}let o=t.filter(s=>s!=null);return o.length>0&&r.append(...o),r},Gs=(...n)=>n.filter(Boolean).join(" ");var Fi="ask_user_question",Qs=8,ds="data-persona-ask-sheet-for",Wg="Other",Rg="Other\u2026",su="Type your own answer here",au="Send",Hg="Next",Bg="Back",Dg="Submit all",Ng="Skip",Fg=3,Oi="data-ask-current-index",_i="data-ask-question-count",iu="data-ask-answers",$i="data-ask-grouped",lu="data-ask-layout",Og=n=>n.layout==="pills"?"pills":"rows",_g=n=>n.getAttribute(lu)==="pills"?"pills":"rows",ou=!1,cu=n=>n.replace(/["\\]/g,"\\$&"),Fo=n=>n.variant==="tool"&&!!n.toolCall&&n.toolCall.name===Fi,Ui=n=>{var e,t;return(t=(e=n==null?void 0:n.features)==null?void 0:e.askUserQuestion)!=null?t:{}},ps=n=>{let e=n.toolCall;if(!e)return{payload:null,complete:!1};let t=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:t};let r=e.chunks;if(!r||r.length===0)return{payload:null,complete:t};try{let o=r.join(""),s=(0,yo.parse)(o,yo.STR|yo.OBJ|yo.ARR);if(s&&typeof s=="object")return{payload:s,complete:t}}catch{}return{payload:null,complete:t}},Xs=n=>{let e=Array.isArray(n==null?void 0:n.questions)?n.questions:[];return e.length>Qs&&!ou&&(ou=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Qs}.`)),e.slice(0,Qs)},$g=n=>{var e;return(e=Xs(n)[0])!=null?e:null},Ug=(n,e)=>{var t;return(t=Xs(n)[e])!=null?t:null},qg=(n,e)=>{let t=e.styles;t&&(t.sheetBackground&&n.style.setProperty("--persona-ask-sheet-bg",t.sheetBackground),t.sheetBorder&&n.style.setProperty("--persona-ask-sheet-border",t.sheetBorder),t.sheetShadow&&n.style.setProperty("--persona-ask-sheet-shadow",t.sheetShadow),t.pillBackground&&n.style.setProperty("--persona-ask-pill-bg",t.pillBackground),t.pillBackgroundSelected&&n.style.setProperty("--persona-ask-pill-bg-selected",t.pillBackgroundSelected),t.pillTextColor&&n.style.setProperty("--persona-ask-pill-fg",t.pillTextColor),t.pillTextColorSelected&&n.style.setProperty("--persona-ask-pill-fg-selected",t.pillTextColorSelected),t.pillBorderRadius&&n.style.setProperty("--persona-ask-pill-radius",t.pillBorderRadius),t.customInputBackground&&n.style.setProperty("--persona-ask-input-bg",t.customInputBackground))},du=(n,e,t)=>{if(n!=="rows")return null;let r=b("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),e){let o=b("span","persona-ask-row-check");r.appendChild(o)}else{let o=b("span","persona-ask-row-badge");o.textContent=String(t+1),r.appendChild(o)}return r},zg=(n,e,t,r)=>{let s=b("button",t==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",r?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(e)),s.setAttribute("data-option-label",n.label),t==="rows"){let a=b("span","persona-ask-row-content"),i=b("span","persona-ask-row-label");if(i.textContent=n.label,a.appendChild(i),n.description){let c=b("span","persona-ask-row-description");c.textContent=n.description,a.appendChild(c)}s.appendChild(a);let d=du(t,r,e);d&&s.appendChild(d)}else s.textContent=n.label,n.description&&(s.title=n.description);return s},Vg=n=>{let t=b("span",n==="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 t.setAttribute("aria-hidden","true"),t},jg=(n,e,t,r)=>{var g,f,u;let s=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(n!=null&&n.multiSelect),d=(Array.isArray(n==null?void 0:n.options)?n.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!t){for(let m=0;m<Fg;m++)s.appendChild(Vg(r));return s}if(d.forEach((m,v)=>{s.appendChild(zg(m,v,r,a))}),(n==null?void 0:n.allowFreeText)!==!1){let m=r==="rows"?Wg:Rg;if(r==="rows"){let v=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");v.setAttribute("data-ask-user-action","focus-free-text"),v.setAttribute("data-option-index",String(d.length)),v.setAttribute("data-ask-other-row","true");let x=b("span","persona-ask-row-content"),E=document.createElement("input");E.type="text",E.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",E.placeholder=(g=e.freeTextPlaceholder)!=null?g:su,E.setAttribute("data-ask-free-text-input","true"),E.setAttribute("aria-label",(f=e.freeTextLabel)!=null?f:m),x.appendChild(E),v.appendChild(x);let k=du(r,a,d.length);k&&v.appendChild(k),s.appendChild(v)}else{let v=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(u=e.freeTextLabel)!=null?u:m,s.appendChild(v)}}return s},pu=(n,e)=>{var s,a;let r=b("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");r.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=n.freeTextPlaceholder)!=null?s:su,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),e!=="rows"){let i=b("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=n.submitLabel)!=null?a:au,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Kg=n=>{var r;let e=b("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let t=b("button","persona-ask-multi-submit persona-pointer-events-auto");return t.type="button",t.textContent=(r=n.submitLabel)!=null?r:au,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,e.appendChild(t),e},Gg=(n,e,t)=>{var c,g,f,u;let r=b("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=b("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(c=t.backLabel)!=null?c:Bg,o.setAttribute("data-ask-user-action","back"),o.disabled=n===0,r.appendChild(o);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(g=t.skipLabel)!=null?g:Ng,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=b("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=n===e-1;return i.textContent=d?(f=t.submitAllLabel)!=null?f:Dg:(u=t.nextLabel)!=null?u:Hg,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Oo=n=>{let e=n.getAttribute(iu);if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},uu=(n,e)=>{n.setAttribute(iu,JSON.stringify(e))},pr=n=>{var t;let e=Number((t=n.getAttribute(Oi))!=null?t:"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},Qg=(n,e)=>{n.setAttribute(Oi,String(Math.max(0,Math.floor(e))))},us=n=>{var t;let e=Number((t=n.getAttribute(_i))!=null?t:"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},bo=n=>n.getAttribute($i)==="true",Xg=(n,e)=>{var o;let t=(o=n.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let r={};return e.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let d=t[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Jg=(n,e)=>{var r;let t=(r=n.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.min(e-1,Math.floor(t)))},Ua=(n,e)=>{let{payload:t}=ps(e),r=Xs(t),o=Oo(n),s={},a=new Set;return r.forEach((i,d)=>{let c=typeof(i==null?void 0:i.question)=="string"?i.question:"";c&&(a.has(c)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),a.add(c),Object.prototype.hasOwnProperty.call(o,d)&&(s[c]=o[d]))}),s},mu=n=>{let e=Oo(n),t=pr(n),r=e[t],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=n.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var f;let c=(f=d.getAttribute("data-option-label"))!=null?f:"",g=o.has(c);d.setAttribute("aria-pressed",g?"true":"false"),d.classList.toggle("persona-ask-pill-selected",g)});let a=new Set(Array.from(s).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),i=n.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},gu=n=>{if(!bo(n))return;let e=Oo(n),t=pr(n),r=e[t],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=n.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=n.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(n.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},qi=(n,e,t)=>{let r=Ui(t),o=_g(n),{payload:s,complete:a}=ps(e),i=bo(n),d=pr(n),c=us(n),g=i?Ug(s,d):$g(s),f=!!(g!=null&&g.multiSelect),u=n.querySelector('[data-ask-step-inline="true"]');u&&(u.textContent=i?`${d+1}/${c}`:"");let m=n.querySelector('[data-ask-stepper="true"]');m&&m.remove();let v=n.querySelector('[data-ask-question="true"]');if(v){let L=typeof(g==null?void 0:g.question)=="string"?g.question:"";v.textContent=L,v.classList.toggle("persona-ask-question-skeleton",!L&&!a)}let x=n.querySelector('[data-ask-pill-list="true"]');if(x){let L=jg(g,r,a,o);x.replaceWith(L)}if(o!=="rows"){let L=n.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(pu(r,o))}let E=n.querySelector('[data-ask-multi-actions="true"]');!i&&f&&!E?n.appendChild(Kg(r)):(!f||i)&&E&&E.remove(),n.setAttribute("data-multi-select",f?"true":"false");let k=n.querySelector('[data-ask-nav-row="true"]');if(i){let L=Gg(d,c,r);k?k.replaceWith(L):n.appendChild(L)}else k&&k.remove();mu(n),gu(n)},Yg=(n,e,t)=>{let r=Ui(e),o=Og(r),s=n.toolCall.id,a=Xs(t),i=Math.max(1,a.length),d=i>1,c=Xg(n,a),g=d?Jg(n,i):0,f=b("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(ds,s),f.setAttribute("data-tool-call-id",s),f.setAttribute("data-message-id",n.id),f.setAttribute(_i,String(i)),f.setAttribute(Oi,String(g)),f.setAttribute($i,d?"true":"false"),f.setAttribute(lu,o),uu(f,c),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),qg(f,r);let u=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=b("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",u.appendChild(m);let v=b("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",u.appendChild(v),f.appendChild(u);let E=b("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),f.appendChild(E),o!=="rows"&&f.appendChild(pu(r,o)),qi(f,n,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},Zg=(n,e,t)=>{let{payload:r}=ps(e),o=Math.max(1,Xs(r).length);o>us(n)&&(n.setAttribute(_i,String(o)),o>1&&!bo(n)&&n.setAttribute($i,"true")),qi(n,e,t)};var qa=(n,e,t)=>{if(!t||!Fo(n)||Ui(e).enabled===!1)return;let o=n.toolCall.id;t.querySelectorAll(`[${ds}]`).forEach(c=>{c.getAttribute(ds)!==o&&c.remove()});let a=t.querySelector(`[${ds}="${cu(o)}"]`);if(a){Zg(a,n,e);return}let{payload:i}=ps(n),d=Yg(n,e,i);t.appendChild(d)},ms=(n,e)=>{if(!n)return;let t=e?`[${ds}="${cu(e)}"]`:`[${ds}]`;n.querySelectorAll(t).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},zi=n=>Array.from(n.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),vo=(n,e)=>{let t=Oo(n),r=pr(n);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete t[r]:t[r]=e,uu(n,t),mu(n),gu(n)},za=(n,e,t,r)=>{let o=us(n),s=Math.max(0,Math.min(o-1,r));Qg(n,s),qi(n,e,t)};var Gr="suggest_replies";var ef={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},fu={name:Gr,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:ef,origin:"sdk",annotations:{readOnlyHint:!0}},Vi=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),ji=n=>{var e;return n.variant==="tool"&&((e=n.toolCall)==null?void 0:e.name)===Gr},tf=n=>{let e=n;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let t=e==null?void 0:e.suggestions;if(!Array.isArray(t))return[];let r=t.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},hu=n=>{var e;for(let t=n.length-1;t>=0;t--){let r=n[t];if(r.role==="user")return null;if(!ji(r))continue;let o=tf((e=r.toolCall)==null?void 0:e.args);return o.length>0?o:null}return null},yu=n=>{var t;let e=(t=n==null?void 0:n.features)==null?void 0:t.suggestReplies;return(e==null?void 0:e.expose)===!0&&e.enabled!==!1};var nf={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Qs,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},rf={name:Fi,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:nf,origin:"sdk",annotations:{readOnlyHint:!0}},Ki=n=>{var r;let e=[],t=(r=n==null?void 0:n.features)==null?void 0:r.askUserQuestion;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1&&e.push(rf),yu(n)&&e.push(fu),e};var gs=require("partial-json"),bu=n=>n.replace(/\\n/g,`
7
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),fs=n=>{if(n===null)return"null";if(n===void 0)return"";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);try{return JSON.stringify(n,null,2)}catch{return String(n)}},of=n=>{var a,i;let e=(a=n.completedAt)!=null?a:Date.now(),t=(i=n.startedAt)!=null?i:e,o=(n.durationMs!==void 0?n.durationMs:Math.max(0,e-t))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},vu=n=>n.status==="complete"?of(n):n.status==="pending"?"Waiting":"",sf=n=>{var o,s,a;let t=(typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((o=n.completedAt)!=null?o:Date.now())-((a=(s=n.startedAt)!=null?s:n.completedAt)!=null?a:Date.now())))/1e3;return t<.1?"Used tool for <0.1 seconds":`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")} seconds`};var xu=n=>n.status==="complete"?sf(n):"Using tool...",Va=n=>{let e=n/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Ys=n=>{var t,r,o;let e=typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((t=n.completedAt)!=null?t:Date.now())-((o=(r=n.startedAt)!=null?r:n.completedAt)!=null?o:Date.now()));return Va(e)},ja=n=>{var t,r,o;let e=n.durationMs!==void 0?n.durationMs:Math.max(0,((t=n.completedAt)!=null?t:Date.now())-((o=(r=n.startedAt)!=null?r:n.completedAt)!=null?o:Date.now()));return Va(e)},Gi=(n,e,t)=>{var s;if(!e)return t;let r=((s=n.name)==null?void 0:s.trim())||"tool",o=Ys(n);return e.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},Ka=(n,e)=>{let t=n.replace(/\{toolName\}/g,e),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(t))!==null;)a.index>s&&Js(r,t.slice(s,a.index),[]),a[1]!==void 0?Js(r,a[1],["bold"]):a[2]!==void 0?Js(r,a[2],["italic"]):a[3]!==void 0&&Js(r,a[3],["dim"]),s=a.index+a[0].length;return s<t.length&&Js(r,t.slice(s),[]),r},Js=(n,e,t)=>{let r=e.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&n.push({text:r[o],styles:t}),o<r.length-1&&n.push({text:"{duration}",styles:t,isDuration:!0})},af=()=>{let n=null,e=0,t=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
8
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
9
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>n,processChunk:async r=>{if(r.length<=e)return n!==null?{text:n,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=t(r);return s!==null&&(n=s),e=r.length,n!==null?{text:n,raw:r}:null},close:async()=>{}}},_o=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},wu=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},Cu=()=>{var e;let n=af();return{processChunk:async t=>{let r=t.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:n.processChunk(t)},getExtractedText:n.getExtractedText.bind(n),close:(e=n.close)==null?void 0:e.bind(n)}},Au=()=>{let n=null,e=0;return{getExtractedText:()=>n,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=e)return n!==null||n===""?{text:n||"",raw:t}:null;try{let o=(0,gs.parse)(t,gs.STR|gs.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?bu(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=bu(o.text)))}catch{}return e=t.length,n!==null?{text:n,raw:t}:null},close:()=>{}}};var Su=()=>{let n=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let r=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(n=r[1],{text:n,raw:e}):null},getExtractedText:()=>n}};var Ga=class{constructor(e,t=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=e,this.gapTimeoutMs=t}push(e,t){var s,a,i;let r=(i=(s=t==null?void 0:t.seq)!=null?s:t==null?void 0:t.sequenceIndex)!=null?i:(a=t==null?void 0:t.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(e,t);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(e,t),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(e,t);return}let o=this.buffer.get(r);o!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${o.payloadType} vs ${e}); emitting earlier event out-of-order to avoid loss`),this.emitter(o.payloadType,o.payload)),this.buffer.set(r,{payloadType:e,payload:t,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let e=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(e.payloadType,e.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let e=[...this.buffer.entries()].sort((t,r)=>t[0]-r[0]);for(let[t,r]of e)this.buffer.delete(t),this.emitter(r.payloadType,r.payload);e.length>0&&(this.nextExpectedSeq=e[e.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var lf="https://api.runtype.com/v1/dispatch",Qa="https://api.runtype.com";function cf(n){var s,a;let e=n.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(r)return`attachment.${r}`;let o=e.indexOf("/");if(o>0){let i=(a=(s=e.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Qi=n=>!!(n.contentParts&&n.contentParts.length>0||n.llmContent&&n.llmContent.trim().length>0||n.rawContent&&n.rawContent.trim().length>0||n.content&&n.content.trim().length>0);function df(n){switch(n){case"json":return Au;case"regex-json":return Cu;case"xml":return Su;default:return wu}}var Tu=n=>n.startsWith("{")||n.startsWith("[")||n.startsWith("<");function pf(n,e){if(!n)return e;let t=n.trim(),r=e.trim();if(t.length===0)return e;if(r.length===0)return n;let o=Tu(t);if(!Tu(r))return n;if(!o||r===t||r.startsWith(t))return e;let a=_o(n);return _o(e)!==null&&a===null?e:n}var Zs=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var t,r,o,s;this.apiUrl=(t=e.apiUrl)!=null?t:lf,this.headers={"Content-Type":"application/json",...e.headers},this.debug=!!e.debug,this.createStreamParser=(r=e.streamParser)!=null?r:df(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=((s=e.webmcp)==null?void 0:s.enabled)===!0?new $a(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){var t;(t=this.webMcpBridge)==null||t.setConfirmHandler(e)}isWebMcpOperational(){var e;return((e=this.webMcpBridge)==null?void 0:e.isOperational())===!0}executeWebMcpToolCall(e,t,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,t,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(e){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Qa}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){var e,t;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(t=(e=this.config).onSessionInit)==null||t.call(e,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let e=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...e&&{sessionId:e}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let o=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Qa}/v1/client/feedback`}async sendFeedback(e){var a,i;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 o={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:e,comment:t})}async submitNPSFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:e,comment:t})}async dispatch(e,t){return this.isAgentMode()?this.dispatchAgent(e,t):this.isClientTokenMode()?this.dispatchClientToken(e,t):this.dispatchProxy(e,t)}async dispatchClientToken(e,t){var o,s,a,i;let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let I=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:I}),I}let c=await this.buildPayload(e.messages),g=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([I])=>I!=="sessionId"&&I!=="session_id")):void 0,f={sessionId:d.sessionId,messages:e.messages.filter(Qi).map(I=>{var R,A,W;return{id:I.id,role:I.role,content:(W=(A=(R=I.contentParts)!=null?R:I.llmContent)!=null?A:I.rawContent)!=null?W:I.content}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...g&&Object.keys(g).length>0&&{metadata:g},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},u=c.clientTools,m=!!(u&&u.length>0),v=m?nu(u):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,E=m&&x&&this.lastSentClientToolsFingerprint===v,k=!1,L=null,F;for(let I=0;;I++){let A={...f,...m&&(k||!E)&&u?{clientTools:u}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",A),F=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(A),signal:r.signal}),F.status===409&&I===0&&m){let W=await F.json().catch(()=>null);if((W==null?void 0:W.error)==="client_tools_resend_required"){k=!0,this.lastSentClientToolsFingerprint=null;continue}L=W!=null?W:{error:"Chat request failed"}}break}if(!F.ok){let I=L!=null?L:await F.json().catch(()=>({error:"Chat request failed"}));if(F.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let A=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:A}),A}if(F.status===429){let A=new Error(I.hint||"Message limit reached for this session.");throw t({type:"error",error:A}),A}let R=new Error(I.error||"Failed to send message");throw t({type:"error",error:R}),R}if(!F.body){let I=new Error("No response body received");throw t({type:"error",error:I}),I}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,t({type:"status",status:"connected"});try{await this.streamResponse(F.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(e,t){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(e,t){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(e,t,r){t({type:"status",status:"connected"});try{await this.streamResponse(e,t,r)}finally{t({type:"status",status:"idle"})}}async resolveApproval(e,t){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Qa}/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:t,streamResponse:!0})})}async resumeFlow(e,t,r){var c,g;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||Qa}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:e,toolOutputs:t,streamResponse:(g=r==null?void 0:r.streamResponse)!=null?g:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(e){var s,a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=e.slice().filter(Qi).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,d)=>{let c=new Date(i.createdAt).getTime(),g=new Date(d.createdAt).getTime();return c-g}).map(i=>{var d,c,g;return{role:i.role,content:(g=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?g:i.content,createdAt:i.createdAt}}),r={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},o=[...Ki(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(o.length>0&&(r.clientTools=o),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let c=await d({messages:e,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}return r}async buildPayload(e){var s,a;let r={messages:e.slice().filter(Qi).sort((i,d)=>{let c=new Date(i.createdAt).getTime(),g=new Date(d.createdAt).getTime();return c-g}).map(i=>{var d,c,g;return{role:i.role,content:(g=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?g:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},o=[...Ki(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(o.length>0&&(r.clientTools=o),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let c=await d({messages:e,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let d=i;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(e,t,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let d=g=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...g!==void 0&&{partId:g}};return r.current=f,o(f),f},c=g=>r.current?r.current:d(g);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let g=c(i.partId);i.partId!==void 0&&!g.partId&&(g.partId=i.partId),g.content+=i.text,o(g)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,t,r){var vn,Rt,pn,Cr;let o=e.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,g=U=>{let G=U.reasoning?{...U.reasoning,chunks:[...U.reasoning.chunks]}:void 0,ye=U.toolCall?{...U.toolCall,chunks:U.toolCall.chunks?[...U.toolCall.chunks]:void 0}:void 0,Qe=U.tools?U.tools.map(et=>({...et,chunks:et.chunks?[...et.chunks]:void 0})):void 0;return{...U,reasoning:G,toolCall:ye,tools:Qe}},f=U=>{if(U.role!=="assistant"||U.variant)return!0;let G=Array.isArray(U.contentParts)&&U.contentParts.length>0,ye=typeof U.rawContent=="string"&&U.rawContent.trim()!=="";return typeof U.content=="string"&&U.content.trim()!==""||G||ye||!!U.stopReason},u=U=>{f(U)&&t({type:"message",message:g(U)})},m=null,v=null,x={current:null},E={current:null},k=!1,L=new Map,F=new Map,I=new Map,R=new Map,A={lastId:null,byStep:new Map},W={lastId:null,byCall:new Map},D=(U,G,ye="")=>`${U}::${G}::${ye}`,N=(U,G)=>`${U}::${G}::`,M=(U,G,ye,Qe)=>{let et=D(U,G,ye),Ue=I.get(et);if(Ue)return Ue;let _e=ye?`-${ye}`:"",Pt={id:`nested-${U}-${G}${_e}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...ye?{partId:ye}:{},agentMetadata:{executionId:Qe,parentToolId:U,parentStepId:G}};return I.set(et,Pt),u(Pt),Pt},z=U=>{if(U==null)return null;try{return String(U)}catch{return null}},V=U=>{var G,ye,Qe,et,Ue;return z((Ue=(et=(Qe=(ye=(G=U.stepId)!=null?G:U.step_id)!=null?ye:U.step)!=null?Qe:U.parentId)!=null?et:U.flowStepId)!=null?Ue:U.flow_step_id)},oe=U=>{var G,ye,Qe,et,Ue,_e,Pt;return z((Pt=(_e=(Ue=(et=(Qe=(ye=(G=U.callId)!=null?G:U.call_id)!=null?ye:U.requestId)!=null?Qe:U.request_id)!=null?et:U.toolCallId)!=null?Ue:U.tool_call_id)!=null?_e:U.stepId)!=null?Pt:U.step_id)},Le=r,je=!1,ve=()=>{if(m)return m;let U;return!je&&Le?(U=Le,je=!0):Le&&E.current?U=`${Le}_${E.current}`:U=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:U,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},u(m),m},Be=(U,G)=>{A.lastId=G,U&&A.byStep.set(U,G)},Oe=(U,G)=>{var Ue;let ye=(Ue=U.reasoningId)!=null?Ue:U.id,Qe=V(U);if(ye){let _e=String(ye);return Be(Qe,_e),_e}if(Qe){let _e=A.byStep.get(Qe);if(_e)return A.lastId=_e,_e}if(A.lastId&&!G)return A.lastId;if(!G)return null;let et=`reason-${c()}`;return Be(Qe,et),et},Te=U=>{let G=L.get(U);if(G)return G;let ye={id:`reason-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:U,status:"streaming",chunks:[]}};return L.set(U,ye),u(ye),ye},we=(U,G)=>{W.lastId=G,U&&W.byCall.set(U,G)},se=new Set,Q=new Map,ae=new Set,fe=new Map,ue=U=>{if(!U)return!1;let G=U.replace(/_+/g,"_").replace(/^_|_$/g,"");return G==="emit_artifact_markdown"||G==="emit_artifact_component"},K=(U,G)=>{var Ue;let ye=(Ue=U.toolId)!=null?Ue:U.id,Qe=oe(U);if(ye){let _e=String(ye);return we(Qe,_e),_e}if(Qe){let _e=W.byCall.get(Qe);if(_e)return W.lastId=_e,_e}if(W.lastId&&!G)return W.lastId;if(!G)return null;let et=`tool-${c()}`;return we(Qe,et),et},ie=U=>{let G=F.get(U);if(G)return G;let ye={id:`tool-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:U,status:"pending"}};return F.set(U,ye),u(ye),ye},We=U=>{if(typeof U=="number"&&Number.isFinite(U))return U;if(typeof U=="string"){let G=Number(U);if(!Number.isNaN(G)&&Number.isFinite(G))return G;let ye=Date.parse(U);if(!Number.isNaN(ye))return ye}return Date.now()},te=U=>{if(typeof U=="string")return U;if(U==null)return"";try{return JSON.stringify(U)}catch{return String(U)}},ee=new Map,re=new Map,it=new Map,lt=new Map,st=null,Ee=(U,G,ye)=>{var Pt;let Qe=it.get(U);Qe||(Qe=[],it.set(U,Qe));let et=0,Ue=Qe.length;for(;et<Ue;){let Kt=et+Ue>>>1;Qe[Kt].seq<G?et=Kt+1:Ue=Kt}((Pt=Qe[et])==null?void 0:Pt.seq)===G?Qe[et]={seq:G,text:ye}:Qe.splice(et,0,{seq:G,text:ye});let _e="";for(let Kt=0;Kt<Qe.length;Kt++)_e+=Qe[Kt].text;return _e},he=(U,G)=>{let ye=te(G),Qe=re.get(U.id),et=pf(Qe,ye);U.rawContent=et;let Ue=ee.get(U.id),_e=j=>{var ce;let Ht=(ce=U.content)!=null?ce:"";j.trim()!==""&&(Ht.trim().length===0||j.startsWith(Ht)||j.trimStart().startsWith(Ht.trim()))&&(U.content=j)},Pt=()=>{var j;if(Ue){let Ht=(j=Ue.close)==null?void 0:j.call(Ue);Ht instanceof Promise&&Ht.catch(()=>{})}ee.delete(U.id),re.delete(U.id),U.streaming=!1,u(U)};if(!Ue){_e(ye),Pt();return}let Kt=_o(et);if(Kt!==null&&Kt.trim()!==""){_e(Kt),Pt();return}let Jt=j=>{var Ce;let Ht=typeof j=="string"?j:(Ce=j==null?void 0:j.text)!=null?Ce:null;if(Ht!==null&&Ht.trim()!=="")return Ht;let ce=Ue.getExtractedText();return ce!==null&&ce.trim()!==""?ce:ye},Ln;try{Ln=Ue.processChunk(et)}catch{_e(ye),Pt();return}if(Ln instanceof Promise){Ln.then(j=>{_e(Jt(j)),Pt()}).catch(()=>{_e(ye),Pt()});return}_e(Jt(Ln)),Pt()},Je=[],Y=!1,me,ke=()=>{Y||(Y=!0,queueMicrotask(()=>{Y=!1,me()}))},Ye=new Ga((U,G)=>{Je.push({payloadType:U,payload:G}),ke()}),Ge=null,Ie=new Map,Ke=(vn=this.config.iterationDisplay)!=null?vn:"separate";for(me=()=>{var U,G,ye,Qe,et,Ue,_e,Pt,Kt,Jt,Ln,j,Ht,ce,Ce,Fe,Tt,on,sn,xn,Nt,rt,Dt,pt,Yt,nr,Pn,an,On,Ar,xt,zn,Sr,Fr,mr,bt,Co,Tr,Ao,_n,Ko,Yr,Or,Zr,eo,So,To,to,Ct,Vn,jn,In,Mt,rr,or,Kn,no,_r,ro,Gn,Ft,Wn,sr,oo,$r,so,Mr,Qn,be,ut,tn,un,Er,Es,Ur,Mo,kr,_,Go,Lr,Pr,qr,Ir,gr,Qo,xa,Xn,Jn,fr,hr,Eo,zr,An,Wr,Xo,ko,Jo,wa,Yo,Ca,Zo,yt,ks,ar,$n,Aa,Sa,es,Vr,Ls,ao,Ps,Is,Ws,Rs,Un,ts,Rr,Hr,Hs,Ta,Bs,Ds,Lo,Ma,Ea,ka,La,Pa,io,lo,Ia,Ns,co,Wa,Fs,po,Os;for(let ns=0;ns<Je.length;ns++){let qe=Je[ns].payloadType,C=Je[ns].payload;if(qe==="reason_start"){let $=(U=Oe(C,!0))!=null?U:`reason-${c()}`,T=Te($);T.reasoning=(G=T.reasoning)!=null?G:{id:$,status:"streaming",chunks:[]},T.reasoning.startedAt=(Qe=T.reasoning.startedAt)!=null?Qe:We((ye=C.startedAt)!=null?ye:C.timestamp),T.reasoning.completedAt=void 0,T.reasoning.durationMs=void 0,T.streaming=!0,T.reasoning.status="streaming",u(T)}else if(qe==="reason_delta"||qe==="reason_chunk"){let $=(Ue=(et=Oe(C,!1))!=null?et:Oe(C,!0))!=null?Ue:`reason-${c()}`,T=Te($);T.reasoning=(_e=T.reasoning)!=null?_e:{id:$,status:"streaming",chunks:[]},T.reasoning.startedAt=(Kt=T.reasoning.startedAt)!=null?Kt:We((Pt=C.startedAt)!=null?Pt:C.timestamp);let J=(j=(Ln=(Jt=C.reasoningText)!=null?Jt:C.text)!=null?Ln:C.delta)!=null?j:"";if(J&&C.hidden!==!0){let le=typeof C.sequenceIndex=="number"?C.sequenceIndex:void 0;if(le!==void 0){let X=Ee($,le,String(J));T.reasoning.chunks=[X]}else T.reasoning.chunks.push(String(J))}if(T.reasoning.status=C.done?"complete":"streaming",C.done){T.reasoning.completedAt=We((Ht=C.completedAt)!=null?Ht:C.timestamp);let le=(ce=T.reasoning.startedAt)!=null?ce:Date.now();T.reasoning.durationMs=Math.max(0,((Ce=T.reasoning.completedAt)!=null?Ce:Date.now())-le)}T.streaming=T.reasoning.status!=="complete",u(T)}else if(qe==="reason_complete"){let $=(Tt=(Fe=Oe(C,!1))!=null?Fe:Oe(C,!0))!=null?Tt:`reason-${c()}`,T=L.get($);if(T!=null&&T.reasoning){T.reasoning.status="complete",T.reasoning.completedAt=We((on=C.completedAt)!=null?on:C.timestamp);let le=(sn=T.reasoning.startedAt)!=null?sn:Date.now();T.reasoning.durationMs=Math.max(0,((xn=T.reasoning.completedAt)!=null?xn:Date.now())-le),T.streaming=!1,u(T)}let J=V(C);J&&A.byStep.delete(J)}else if(qe==="tool_start"){let $=(Nt=K(C,!0))!=null?Nt:`tool-${c()}`,T=(rt=C.toolName)!=null?rt:C.name;if(ue(T)){se.add($);continue}let J=ie($),le=(Dt=J.toolCall)!=null?Dt:{id:$,status:"pending"};le.name=T!=null?T:le.name,le.status="running",C.args!==void 0?le.args=C.args:C.parameters!==void 0&&(le.args=C.parameters),le.startedAt=(Yt=le.startedAt)!=null?Yt:We((pt=C.startedAt)!=null?pt:C.timestamp),le.completedAt=void 0,le.durationMs=void 0,J.toolCall=le,J.streaming=!0;let X=C.agentContext;(X||C.executionId)&&(J.agentMetadata={executionId:(nr=X==null?void 0:X.executionId)!=null?nr:C.executionId,iteration:(Pn=X==null?void 0:X.iteration)!=null?Pn:C.iteration}),u(J)}else if(qe==="tool_chunk"||qe==="tool_delta"){let $=(On=(an=K(C,!1))!=null?an:K(C,!0))!=null?On:`tool-${c()}`;if(se.has($))continue;let T=ie($),J=(Ar=T.toolCall)!=null?Ar:{id:$,status:"running"};J.startedAt=(zn=J.startedAt)!=null?zn:We((xt=C.startedAt)!=null?xt:C.timestamp);let le=(mr=(Fr=(Sr=C.text)!=null?Sr:C.delta)!=null?Fr:C.message)!=null?mr:"";le&&(J.chunks=(bt=J.chunks)!=null?bt:[],J.chunks.push(String(le))),J.status="running",T.toolCall=J,T.streaming=!0;let X=C.agentContext;(X||C.executionId)&&(T.agentMetadata=(Ao=T.agentMetadata)!=null?Ao:{executionId:(Co=X==null?void 0:X.executionId)!=null?Co:C.executionId,iteration:(Tr=X==null?void 0:X.iteration)!=null?Tr:C.iteration}),u(T)}else if(qe==="tool_complete"){let $=(Ko=(_n=K(C,!1))!=null?_n:K(C,!0))!=null?Ko:`tool-${c()}`;if(se.has($)){se.delete($);continue}let T=ie($),J=(Yr=T.toolCall)!=null?Yr:{id:$,status:"running"};J.status="complete",C.result!==void 0&&(J.result=C.result),typeof C.duration=="number"&&(J.duration=C.duration),J.completedAt=We((Or=C.completedAt)!=null?Or:C.timestamp);let le=(Zr=C.duration)!=null?Zr:C.executionTime;if(typeof le=="number")J.durationMs=le;else{let $e=(eo=J.startedAt)!=null?eo:Date.now();J.durationMs=Math.max(0,((So=J.completedAt)!=null?So:Date.now())-$e)}T.toolCall=J,T.streaming=!1;let X=C.agentContext;(X||C.executionId)&&(T.agentMetadata=(Ct=T.agentMetadata)!=null?Ct:{executionId:(To=X==null?void 0:X.executionId)!=null?To:C.executionId,iteration:(to=X==null?void 0:X.iteration)!=null?to:C.iteration}),u(T);let Me=oe(C);Me&&W.byCall.delete(Me)}else if(qe==="step_await"&&C.awaitReason==="local_tool_required"&&C.toolName){let $=typeof C.toolCallId=="string"&&C.toolCallId.length>0?C.toolCallId:void 0,T=(Vn=$!=null?$:C.toolId)!=null?Vn:`local-${c()}`,J=ie(T),le=C.toolName,X=Ks(le),Me=(jn=J.toolCall)!=null?jn:{id:T,status:"pending"};Me.name=le,Me.args=C.parameters,Me.status=X?"running":"complete",Me.chunks=(In=Me.chunks)!=null?In:[],Me.startedAt=(rr=Me.startedAt)!=null?rr:We((Mt=C.startedAt)!=null?Mt:C.timestamp),X?(Me.completedAt=void 0,Me.duration=void 0,Me.durationMs=void 0):Me.completedAt=(or=Me.completedAt)!=null?or:Me.startedAt,J.toolCall=Me,J.streaming=!1,J.agentMetadata={...J.agentMetadata,executionId:(no=C.executionId)!=null?no:(Kn=J.agentMetadata)==null?void 0:Kn.executionId,awaitingLocalTool:!0,...$?{webMcpToolCallId:$}:{}},u(J)}else if(qe==="text_start"){if((_r=C.toolContext)!=null&&_r.toolId)continue;let $=C.partId;if($!==void 0&&E.current!==null&&$!==E.current){let T=m;T&&(T.streaming=!1,u(T),st=T,m=null,k=!0)}$!==void 0&&(E.current=$)}else if(qe==="text_end"){if((ro=C.toolContext)!=null&&ro.toolId)continue;let $=m;$&&($.streaming=!1,u($),st=$,m=null,k=!0)}else if(qe==="step_chunk"||qe==="step_delta"){let $=C.stepType,T=C.executionType;if($==="tool"||T==="context")continue;let J=C.toolContext;if(J!=null&&J.toolId){let $e=String((Ft=(Gn=C.id)!=null?Gn:J.stepId)!=null?Ft:`step-${c()}`),at=C.partId!==void 0&&C.partId!==null?String(C.partId):"",tt=`${J.toolId}::${$e}`,Bt=R.get(tt);if(at!==""&&Bt!==void 0&&Bt!==""&&Bt!==at){let At=I.get(D(J.toolId,$e,Bt));At&&At.streaming!==!1&&(At.streaming=!1,u(At))}at!==""&&R.set(tt,at);let zt=M(J.toolId,$e,at,J.executionId),ln=($r=(oo=(sr=(Wn=C.text)!=null?Wn:C.delta)!=null?sr:C.content)!=null?oo:C.chunk)!=null?$r:"";ln&&(zt.content+=String(ln),zt.streaming=!0,u(zt)),C.isComplete&&(zt.streaming=!1,u(zt));continue}let le=C.partId;if(le!==void 0&&E.current!==null&&le!==E.current){let $e=m;$e&&($e.streaming=!1,u($e),st=$e,m=null,k=!0)}le!==void 0&&(E.current=le);let X=le!==void 0&&(so=lt.get(le))!=null?so:ve();le!==void 0&&(X.partId||(X.partId=le),lt.set(le,X));let Me=(ut=(be=(Qn=(Mr=C.text)!=null?Mr:C.delta)!=null?Qn:C.content)!=null?be:C.chunk)!=null?ut:"";if(Me){let $e=typeof C.seq=="number"?C.seq:void 0,at=le!=null?le:X.id,tt=$e!==void 0?Ee(at,$e,String(Me)):((tn=re.get(X.id))!=null?tn:"")+Me;X.rawContent=tt,ee.has(X.id)||ee.set(X.id,this.createStreamParser());let Bt=ee.get(X.id),zt=tt.trim().startsWith("{")||tt.trim().startsWith("[");if(zt&&re.set(X.id,tt),Bt.__isPlainTextParser===!0){X.content=$e!==void 0?tt:X.content+Me,re.delete(X.id),ee.delete(X.id),X.rawContent=void 0,u(X);continue}let At=Bt.processChunk(tt);if(At instanceof Promise)At.then(Et=>{var Rn;let yn=typeof Et=="string"?Et:(Rn=Et==null?void 0:Et.text)!=null?Rn:null;if(yn!==null&&yn.trim()!=="")X.content=yn,u(X);else if(!zt&&!tt.trim().startsWith("<")){let wn=m,Zt=wn&&wn.id===X.id?wn:X;Zt.id===X.id&&(Zt.content=$e!==void 0?tt:Zt.content+Me,re.delete(Zt.id),ee.delete(Zt.id),Zt.rawContent=void 0,u(Zt))}}).catch(()=>{X.content=$e!==void 0?tt:X.content+Me,re.delete(X.id),ee.delete(X.id),X.rawContent=void 0,u(X)});else{let Et=typeof At=="string"?At:(un=At==null?void 0:At.text)!=null?un:null;Et!==null&&Et.trim()!==""?(X.content=Et,u(X)):!zt&&!tt.trim().startsWith("<")&&(X.content=$e!==void 0?tt:X.content+Me,re.delete(X.id),ee.delete(X.id),X.rawContent=void 0,u(X))}}if(C.isComplete){let $e=(Es=(Er=C.result)==null?void 0:Er.response)!=null?Es:X.content;if($e){let at=re.get(X.id),tt=at!=null?at:te($e);X.rawContent=tt;let Bt=ee.get(X.id),zt=null,ln=!1;if(Bt&&(zt=Bt.getExtractedText(),zt===null&&(zt=_o(tt)),zt===null)){let At=Bt.processChunk(tt);At instanceof Promise?(ln=!0,At.then(Et=>{var Rn;let yn=typeof Et=="string"?Et:(Rn=Et==null?void 0:Et.text)!=null?Rn:null;if(yn!==null){let wn=m;wn&&wn.id===X.id&&(wn.content=yn,wn.streaming=!1,ee.delete(wn.id),re.delete(wn.id),u(wn))}})):zt=typeof At=="string"?At:(Ur=At==null?void 0:At.text)!=null?Ur:null}if(!ln){zt!==null&&zt.trim()!==""?X.content=zt:re.has(X.id)||(X.content=te($e));let At=ee.get(X.id);if(At){let Et=(Mo=At.close)==null?void 0:Mo.call(At);Et instanceof Promise&&Et.catch(()=>{}),ee.delete(X.id)}re.delete(X.id),X.streaming=!1,u(X)}}}}else if(qe==="step_complete"){let $=C.stepType,T=C.executionType;if($==="tool"||T==="context")continue;let J=C.toolContext;if(J!=null&&J.toolId){let $e=String((_=(kr=C.id)!=null?kr:J.stepId)!=null?_:"");if($e){let at=N(J.toolId,$e);for(let[tt,Bt]of I)tt.startsWith(at)&&Bt.streaming!==!1&&(Bt.streaming=!1,u(Bt));R.delete(`${J.toolId}::${$e}`)}continue}let le=C.stopReason;if(k){if(m!==null){let tt=m;le&&(tt.stopReason=le),ee.delete(tt.id),re.delete(tt.id),tt.streaming!==!1&&(tt.streaming=!1,u(tt))}let $e=(Go=C.result)==null?void 0:Go.response,at=st;at&&(le&&(at.stopReason=le),$e!=null?he(at,$e):(ee.delete(at.id),re.delete(at.id))),st=null;continue}let X=(Lr=C.result)==null?void 0:Lr.response,Me=ve();if(le&&(Me.stopReason=le),X!=null){let $e=ee.get(Me.id),at=!1,tt=!1;if($e){let Bt=$e.getExtractedText(),zt=re.get(Me.id),ln=zt!=null?zt:te(X);if(Me.rawContent=ln,Bt!==null&&Bt.trim()!=="")Me.content=Bt,at=!0;else{let At=_o(ln);if(At!==null)Me.content=At,at=!0;else{let Et=$e.processChunk(ln);if(Et instanceof Promise)tt=!0,Et.then(yn=>{var wn;let Rn=typeof yn=="string"?yn:(wn=yn==null?void 0:yn.text)!=null?wn:null;if(Rn!==null&&Rn.trim()!==""){let Zt=m;Zt&&Zt.id===Me.id&&(Zt.content=Rn,Zt.streaming=!1,ee.delete(Zt.id),re.delete(Zt.id),u(Zt))}else{let Zt=$e.getExtractedText(),ir=m;ir&&ir.id===Me.id&&(Zt!==null&&Zt.trim()!==""?ir.content=Zt:re.has(ir.id)||(ir.content=te(X)),ir.streaming=!1,ee.delete(ir.id),re.delete(ir.id),u(ir))}});else{let yn=typeof Et=="string"?Et:(Pr=Et==null?void 0:Et.text)!=null?Pr:null;if(yn!==null&&yn.trim()!=="")Me.content=yn,at=!0;else{let Rn=$e.getExtractedText();Rn!==null&&Rn.trim()!==""&&(Me.content=Rn,at=!0)}}}}}if(!tt){if(!Me.rawContent){let Bt=re.get(Me.id);Me.rawContent=Bt!=null?Bt:te(X)}if(!at&&!re.has(Me.id)&&(Me.content=te(X)),$e){let Bt=(qr=$e.close)==null?void 0:qr.call($e);Bt instanceof Promise&&Bt.catch(()=>{})}ee.delete(Me.id),re.delete(Me.id),Me.streaming=!1,u(Me)}}else ee.delete(Me.id),re.delete(Me.id),Me.streaming=!1,u(Me)}else if(qe==="flow_complete"){let $=(Ir=C.result)==null?void 0:Ir.response;if(k){if(m!==null){let T=m;ee.delete(T.id),re.delete(T.id),T.streaming!==!1&&(T.streaming=!1,u(T))}}else if($!=null){let T=ve(),J=re.get(T.id),le=J!=null?J:te($);T.rawContent=le;let X=te($),Me=ee.get(T.id);if(Me){let tt=_o(le);if(tt!==null)X=tt;else{let Bt=Me.processChunk(le);Bt instanceof Promise&&Bt.then(ln=>{var Et;let At=typeof ln=="string"?ln:(Et=ln==null?void 0:ln.text)!=null?Et:null;At!==null&&(T.content=At,T.streaming=!1,u(T))});let zt=Me.getExtractedText();zt!==null&&(X=zt)}}ee.delete(T.id),re.delete(T.id);let $e=X!==T.content,at=T.streaming!==!1;$e&&(T.content=X),T.streaming=!1,($e||at)&&u(T)}else if(m!==null){let T=m;ee.delete(T.id),re.delete(T.id),T.streaming!==!1&&(T.streaming=!1,u(T))}t({type:"status",status:"idle"})}else if(qe==="agent_start")Ge={executionId:C.executionId,agentId:(gr=C.agentId)!=null?gr:"virtual",agentName:(Qo=C.agentName)!=null?Qo:"",status:"running",currentIteration:0,maxTurns:(xa=C.maxTurns)!=null?xa:1,startedAt:We(C.startedAt)};else if(qe==="agent_iteration_start"){if(Ge&&(Ge.currentIteration=C.iteration),Ke==="separate"&&C.iteration>1){let $=m;$&&($.streaming=!1,u($),Ie.set(C.iteration-1,$),m=null)}}else if(qe==="agent_turn_start")v=null;else if(qe==="agent_turn_delta"){if(C.contentType==="text"){let $=ve();$.content+=(Xn=C.delta)!=null?Xn:"",$.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId,agentName:Ge==null?void 0:Ge.agentName},v=$,u($)}else if(C.contentType==="thinking"){let $=(Jn=C.turnId)!=null?Jn:`agent-think-${C.iteration}`,T=Te($);T.reasoning=(fr=T.reasoning)!=null?fr:{id:$,status:"streaming",chunks:[]},T.reasoning.chunks.push((hr=C.delta)!=null?hr:""),T.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId},u(T)}else if(C.contentType==="tool_input"){let $=(Eo=C.toolCallId)!=null?Eo:W.lastId;if($){let T=F.get($);T!=null&&T.toolCall&&(T.toolCall.chunks=(zr=T.toolCall.chunks)!=null?zr:[],T.toolCall.chunks.push((An=C.delta)!=null?An:""),u(T))}}}else if(qe==="agent_turn_complete"){let $=C.turnId;if($){let le=L.get($);if(le!=null&&le.reasoning){le.reasoning.status="complete",le.reasoning.completedAt=We(C.completedAt);let X=(Wr=le.reasoning.startedAt)!=null?Wr:Date.now();le.reasoning.durationMs=Math.max(0,((Xo=le.reasoning.completedAt)!=null?Xo:Date.now())-X),le.streaming=!1,u(le)}}let T=C.stopReason,J=m!=null?m:v;if(T&&J!==null){let le=C.turnId;(!le||((ko=J.agentMetadata)==null?void 0:ko.turnId)===le)&&(J.stopReason=T,u(J))}}else if(qe==="agent_tool_start"){m&&(m.streaming=!1,u(m),m=null);let $=(Jo=C.toolCallId)!=null?Jo:`agent-tool-${c()}`;we(oe(C),$);let T=ie($),J=(wa=T.toolCall)!=null?wa:{id:$,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};J.name=(Ca=(Yo=C.toolName)!=null?Yo:C.name)!=null?Ca:J.name,J.status="running",C.parameters!==void 0&&(J.args=C.parameters),J.startedAt=We((Zo=C.startedAt)!=null?Zo:C.timestamp),T.toolCall=J,T.streaming=!0,T.agentMetadata={executionId:C.executionId,iteration:C.iteration},u(T)}else if(qe==="agent_tool_delta"){let $=(yt=C.toolCallId)!=null?yt:W.lastId;if($){let T=(ks=F.get($))!=null?ks:ie($);T.toolCall&&(T.toolCall.chunks=(ar=T.toolCall.chunks)!=null?ar:[],T.toolCall.chunks.push(($n=C.delta)!=null?$n:""),T.toolCall.status="running",T.streaming=!0,u(T))}}else if(qe==="agent_tool_complete"){let $=(Aa=C.toolCallId)!=null?Aa:W.lastId;if($){let T=(Sa=F.get($))!=null?Sa:ie($);if(T.toolCall){T.toolCall.status="complete",C.result!==void 0&&(T.toolCall.result=C.result),typeof C.executionTime=="number"&&(T.toolCall.durationMs=C.executionTime),T.toolCall.completedAt=We((es=C.completedAt)!=null?es:C.timestamp),T.streaming=!1,u(T);let J=oe(C);J&&W.byCall.delete(J)}}}else if(qe==="agent_media"){let $=Array.isArray(C.media)?C.media:[],T=[];for(let J of $){if(!J||typeof J!="object")continue;let le=J,X=typeof le.type=="string"?le.type:void 0,Me=typeof le.mediaType=="string"?le.mediaType.toLowerCase():"",$e=null,at="";if(X==="media"){let tt=typeof le.data=="string"?le.data:void 0;if(!tt)continue;at=Me.length>0?Me:"application/octet-stream",$e=`data:${at};base64,${tt}`}else if(X==="image-url"){let tt=typeof le.url=="string"?le.url:void 0;if(!tt)continue;at=Me,$e=tt}else if(X==="file-url"){let tt=typeof le.url=="string"?le.url:void 0;if(!tt)continue;at=Me,$e=tt}else continue;if($e)if(X==="image-url"||at.startsWith("image/"))T.push({type:"image",image:$e,...at?{mimeType:at}:{}});else if(at.startsWith("audio/"))T.push({type:"audio",audio:$e,mimeType:at});else if(at.startsWith("video/"))T.push({type:"video",video:$e,mimeType:at});else{let tt=at||"application/octet-stream";T.push({type:"file",data:$e,mimeType:tt,filename:cf(tt)})}}if(T.length>0){let J=c(),le=C.toolCallId,Me={id:`agent-media-${typeof le=="string"&&le.length>0?`${le}-${J}`:String(J)}`,role:"assistant",content:"",contentParts:T,createdAt:new Date().toISOString(),streaming:!1,sequence:J,agentMetadata:{executionId:C.executionId,iteration:C.iteration}};u(Me);let $e=m;$e&&($e.streaming=!1,u($e)),m=null,x.current=null}}else if(qe!=="agent_iteration_complete"){if(qe==="agent_reflection"||qe==="agent_reflect"){let $=`agent-reflection-${C.executionId}-${C.iteration}`,T={id:$,role:"assistant",content:(Vr=C.reflection)!=null?Vr:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:$,status:"complete",chunks:[(Ls=C.reflection)!=null?Ls:""]},agentMetadata:{executionId:C.executionId,iteration:C.iteration}};u(T)}else if(qe==="agent_complete"){Ge&&(Ge.status=C.success?"complete":"error",Ge.completedAt=We(C.completedAt),Ge.stopReason=C.stopReason);let $=m;$&&($.streaming=!1,u($)),t({type:"status",status:"idle"})}else if(qe==="agent_error"){let $=typeof C.error=="string"?C.error:(Ps=(ao=C.error)==null?void 0:ao.message)!=null?Ps:"Agent execution error";C.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",$):t({type:"error",error:new Error($)})}else if(qe!=="agent_ping"){if(qe==="agent_approval_start"){let $=(Is=C.approvalId)!=null?Is:`approval-${c()}`,T={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(Ws=Ge==null?void 0:Ge.agentId)!=null?Ws:"virtual",executionId:(Un=(Rs=C.executionId)!=null?Rs:Ge==null?void 0:Ge.executionId)!=null?Un:"",toolName:(ts=C.toolName)!=null?ts:"",toolType:C.toolType,description:(Hr=C.description)!=null?Hr:`Execute ${(Rr=C.toolName)!=null?Rr:"tool"}`,...typeof C.reason=="string"&&C.reason?{reason:C.reason}:{},parameters:C.parameters}};u(T)}else if(qe==="step_await"&&C.awaitReason==="approval_required"){let $=(Hs=C.approvalId)!=null?Hs:`approval-${c()}`,T={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(Ta=Ge==null?void 0:Ge.agentId)!=null?Ta:"virtual",executionId:(Ds=(Bs=C.executionId)!=null?Bs:Ge==null?void 0:Ge.executionId)!=null?Ds:"",toolName:(Lo=C.toolName)!=null?Lo:"",toolType:C.toolType,description:(Ea=C.description)!=null?Ea:`Execute ${(Ma=C.toolName)!=null?Ma:"tool"}`,...typeof C.reason=="string"&&C.reason?{reason:C.reason}:{},parameters:C.parameters}};u(T)}else if(qe==="agent_approval_complete"){let $=C.approvalId;if($){let J={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:(ka=C.decision)!=null?ka:"approved",agentId:(La=Ge==null?void 0:Ge.agentId)!=null?La:"virtual",executionId:(io=(Pa=C.executionId)!=null?Pa:Ge==null?void 0:Ge.executionId)!=null?io:"",toolName:(lo=C.toolName)!=null?lo:"",description:(Ia=C.description)!=null?Ia:"",resolvedAt:Date.now()}};u(J)}}else if(qe==="artifact_start"||qe==="artifact_delta"||qe==="artifact_update"||qe==="artifact_complete"){if(qe==="artifact_start"){let $=C.artifactType,T=String(C.id),J=typeof C.title=="string"?C.title:void 0;if(t({type:"artifact_start",id:T,artifactType:$,title:J,component:typeof C.component=="string"?C.component:void 0}),fe.set(T,{markdown:"",title:J}),!ae.has(T)){ae.add(T);let le={id:`artifact-ref-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:T,title:J,artifactType:$,status:"streaming"}})};Q.set(T,le),u(le)}}else if(qe==="artifact_delta"){let $=String(C.id),T=typeof C.delta=="string"?C.delta:String((Ns=C.delta)!=null?Ns:"");t({type:"artifact_delta",id:$,artDelta:T});let J=fe.get($);J&&(J.markdown+=T)}else if(qe==="artifact_update"){let $=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?C.props:{};t({type:"artifact_update",id:String(C.id),props:$,component:typeof C.component=="string"?C.component:void 0})}else if(qe==="artifact_complete"){let $=String(C.id);t({type:"artifact_complete",id:$});let T=Q.get($);if(T){T.streaming=!1;try{let J=JSON.parse((co=T.rawContent)!=null?co:"{}");if(J.props){J.props.status="complete";let le=fe.get($);le!=null&&le.markdown&&(J.props.markdown=le.markdown)}T.rawContent=JSON.stringify(J)}catch{}fe.delete($),u(T),Q.delete($)}}}else if(qe==="transcript_insert"){let $=C.message;if(!$||typeof $!="object")continue;let T=String((Wa=$.id)!=null?Wa:`msg-${c()}`),J=$.role,X={id:T,role:J==="user"?"user":J==="system"?"system":"assistant",content:typeof $.content=="string"?$.content:"",rawContent:typeof $.rawContent=="string"?$.rawContent:void 0,createdAt:typeof $.createdAt=="string"?$.createdAt:new Date().toISOString(),streaming:$.streaming===!0,...typeof $.variant=="string"?{variant:$.variant}:{},sequence:c()};if(u(X),X.rawContent)try{let Me=JSON.parse(X.rawContent),$e=(Fs=Me==null?void 0:Me.props)==null?void 0:Fs.artifactId;typeof $e=="string"&&ae.add($e)}catch{}m=null,x.current=null,ee.delete(T),re.delete(T)}else if(qe==="error"||qe==="step_error"||qe==="dispatch_error"||qe==="flow_error"){let $=null;if(C.error instanceof Error)$=C.error;else if(qe==="dispatch_error"){let T=(po=C.message)!=null?po:C.error;T!=null&&T!==""&&($=new Error(String(T)))}else if(qe==="step_error"||qe==="flow_error"){let T=C.error;typeof T=="string"&&T!==""?$=new Error(T):T!=null&&typeof T=="object"&&"message"in T&&($=new Error(String((Os=T.message)!=null?Os:T)))}else qe==="error"&&C.error!=null&&C.error!==""&&($=new Error(String(C.error)));if($){t({type:"error",error:$});let T=m;T&&T.streaming&&(T.streaming=!1,u(T)),t({type:"status",status:"idle"})}}}}}Je.length=0};;){let{done:U,value:G}=await o.read();if(U)break;a+=s.decode(G,{stream:!0});let ye=a.split(`
10
+
11
+ `);a=(Rt=ye.pop())!=null?Rt:"";for(let Qe of ye){let et=Qe.split(`
12
+ `),Ue="message",_e="";for(let Jt of et)Jt.startsWith("event:")?Ue=Jt.replace("event:","").trim():Jt.startsWith("data:")&&(_e+=Jt.replace("data:","").trim());if(!_e)continue;let Pt;try{Pt=JSON.parse(_e)}catch(Jt){t({type:"error",error:Jt instanceof Error?Jt:new Error("Failed to parse chat stream payload")});continue}let Kt=Ue!=="message"?Ue:(pn=Pt.type)!=null?pn:"message";if((Cr=this.onSSEEvent)==null||Cr.call(this,Kt,Pt),this.parseSSEEvent){x.current=m;let Jt=await this.handleCustomSSEEvent(Pt,t,x,u,c,E);if(x.current&&x.current!==m&&(m=x.current),Jt)continue}Ye.push(Kt,Pt),me()}}Ye.flushPending(),me(),Ye.destroy()}};function Xa(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${n}_${e}`}function ea(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${n}_${e}`}var Ja="[Image]";function Xi(n){return{type:"text",text:n}}var Mu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],uf=["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"],Qr=[...Mu,...uf];function mf(n){return Mu.includes(n)||n.startsWith("image/")}function Ya(n){return mf(n.type)}async function Eu(n){return new Promise((e,t)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ya(n)?e({type:"image",image:o,mimeType:n.type,alt:n.name}):e({type:"file",data:o,mimeType:n.type,filename:n.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(n)})}function ku(n,e=Qr,t=10*1024*1024){return e.includes(n.type)?n.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${n.type}". Accepted types: ${e.join(", ")}`}}function gf(n){let e=n.split(".");return e.length>1?e.pop().toLowerCase():""}function Lu(n,e){let t=gf(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"}[n]||t||"FILE"}Ji();var Pu=16e3,ff=24e3,hf=4096,yf=1380533830;function bf(n){return n.byteLength>=44&&new DataView(n).getUint32(0,!1)===yf?new Uint8Array(n,44):new Uint8Array(n)}function vf(n){var r;let e=n.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${e}`}var ta=class{constructor(e){this.config=e;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var s,a,i,d;if(this.callLive)return;let e=(s=this.config)==null?void 0:s.agentId,t=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!e)throw new Error("Runtype voice requires an agentId");if(!t)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let o=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Pu,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){c.getTracks().forEach(x=>x.stop());return}this.mediaStream=c;let g=window.AudioContext||window.webkitAudioContext,f=new g({sampleRate:Pu});f.state==="suspended"&&await f.resume().catch(()=>{}),this.captureContext=f;let u=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new hs(ff);if(o!==this.callGeneration){u.destroy(),c.getTracks().forEach(x=>x.stop()),f.close().catch(()=>{});return}this.playback=u,u.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let m=`${vf(r)}/ws/agents/${encodeURIComponent(e)}/voice`,v=new WebSocket(m,["runtype.bearer",t]);v.binaryType="arraybuffer",this.ws=v,v.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(f,c,v,o))},v.onmessage=x=>this.handleMessage(x,o),v.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},v.onclose=x=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(x.code!==1e3){let E=x.code?` (code ${x.code})`:"";this.emitError(new Error(`Voice connection closed${E}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(c){throw this.cleanup(),this.emitError(c),this.emitStatus("error"),c}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(e,t,r,o){let s=e.createMediaStreamSource(t);this.sourceNode=s;let a=e.createScriptProcessor(hf,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),c=new Int16Array(d.length);for(let g=0;g<d.length;g++){let f=Math.max(-1,Math.min(1,d[g]));c[g]=f<0?f*32768:f*32767}r.send(c.buffer)},s.connect(a),a.connect(e.destination)}handleMessage(e,t){var o,s;if(t!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,t);return}let r;try{r=JSON.parse(e.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(o=r.text)!=null?o:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(s=r.text)!=null?s:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(e,t){if(t!==this.callGeneration||!this.playback)return;let r=bf(e);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onTranscript(e){this.transcriptCallbacks.push(e)}onMetrics(e){this.metricsCallbacks.push(e)}emitStatus(e){this.statusCallbacks.forEach(t=>t(e))}emitError(e){this.errorCallbacks.forEach(t=>t(e))}emitTranscript(e,t,r){this.transcriptCallbacks.forEach(o=>o(e,t,r))}emitMetrics(e){this.metricsCallbacks.forEach(t=>t(e))}};var $o=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){var e,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((e=this.config)==null?void 0:e.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function ys(n){switch(n.type){case"runtype":if(!n.runtype)throw new Error("Runtype voice provider requires configuration");return new ta(n.runtype);case"browser":if(!$o.isSupported())throw new Error("Browser speech recognition not supported");return new $o(n.browser||{});case"custom":{let e=n.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let t=typeof e=="function"?e():e;if(!t||typeof t.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return t}default:throw new Error(`Unknown voice provider type: ${n.type}`)}}function Iu(n){if((n==null?void 0:n.type)==="custom"&&n.custom)return ys({type:"custom",custom:n.custom});if((n==null?void 0:n.type)==="runtype"&&n.runtype)return ys({type:"runtype",runtype:n.runtype});if($o.isSupported())return ys({type:"browser",browser:(n==null?void 0:n.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Yi(n){try{return Iu(n),!0}catch{return!1}}function Za(n){var 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 r of e){let o=n.find(s=>s.name===r);if(o)return o}return(t=n.find(r=>r.lang.startsWith("en")))!=null?t:n[0]}var bs=class n{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(e,t){var a;if(!n.isSupported()){(a=t.onError)==null||a.call(t,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(e.text),s=r.getVoices();if(e.voice){let i=s.find(d=>d.name===e.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):Za(s));e.rate!==void 0&&(o.rate=e.rate),e.pitch!==void 0&&(o.pitch=e.pitch),o.onend=()=>{var i;return(i=t.onEnd)==null?void 0:i.call(t)},o.onerror=i=>{var c,g;let d=i.error;d==="canceled"||d==="interrupted"?(c=t.onEnd)==null||c.call(t):(g=t.onError)==null||g.call(t,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=t.onStart)==null||i.call(t)},50)}pause(){n.isSupported()&&window.speechSynthesis.pause()}resume(){n.isSupported()&&window.speechSynthesis.resume()}stop(){n.isSupported()&&window.speechSynthesis.cancel()}};var na=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var e,t;return(t=(e=this.engine)==null?void 0:e.supportsPause)!=null?t:!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,t){var r,o;if(this.activeId===e){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,t)}async play(e,t){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(e,"loading");try{if(!this.engine){let s=await this.resolveEngine();if(r!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}this.engine.speak(t,{onStart:()=>{r===this.generation&&this.set(e,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){var e;this.generation++,(e=this.engine)==null||e.stop(),this.set(null,"idle")}destroy(){var e,t;this.stop(),(t=(e=this.engine)==null?void 0:e.destroy)==null||t.call(e),this.engine=null,this.listeners.clear()}set(e,t){this.activeId=t==="idle"?null:e,this.state=t;for(let r of this.listeners)r(this.activeId,this.state)}};function Zi(n){if(!n)return"";let e=xf(n);return Wu(e!==null?e:n)}function xf(n){let e=n.trim(),t=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(t&&(e=t[1].trim()),!e.startsWith("{"))return null;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function Wu(n){if(!n)return"";let e=n;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,`
13
+ `),e=e.replace(/\n{2,}/g,`
14
+ `),e.trim()}var Nu=null;var el=()=>Nu?Nu():Promise.resolve().then(()=>(Du(),Bu));var Af=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Sf(n,e){return Af.some(t=>n[t]!==e[t])}function Fu(n,e){let t=n instanceof Error?n:new Error(String(n));if(typeof e=="string")return e;if(typeof e=="function")return e(t);let r="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 t.message?`${r}
15
+
16
+ _Details: ${t.message}_`:r}var ra=n=>({isError:!0,content:[{type:"text",text:n}]}),Ou=(n,e="WebMCP tool execution failed.")=>n instanceof Error&&n.message?n.message:typeof n=="string"&&n?n:e,_u=n=>Ks(n)||n===Gr,ni=class{constructor(e={},t){this.config=e;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new na(()=>this.createSpeechEngine());this.handleEvent=e=>{var t,r,o,s,a,i,d,c,g,f;if(e.type==="message"){this.upsertMessage(e.message);let u=e.message.toolCall,m=!!(u!=null&&u.name)&&(Ks(u.name)||u.name===Gr&&((r=(t=this.config.features)==null?void 0:t.suggestReplies)==null?void 0:r.enabled)!==!1);((o=e.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&m&&this.enqueueWebMcpAwait(e.message),(s=e.message.agentMetadata)!=null&&s.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:(a=e.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=e.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(e.type==="status"){if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let u=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(e.status==="error"?this.agentExecution.status="error":u||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(f=(g=this.callbacks).onError)==null||f.call(g,e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};var r,o;this.messages=[...(r=e.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Zs(e),this.wireDefaultWebMcpConfirm();for(let s of(o=e.initialArtifacts)!=null?o:[])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()}prefetchRuntypeTts(){var o,s,a,i,d;let e=this.config.textToSpeech;if((e==null?void 0:e.provider)!=="runtype"||e.createEngine)return;let t=(o=e.host)!=null?o:this.config.apiUrl,r=(d=e.agentId)!=null?d:(i=(a=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:a.runtype)==null?void 0:i.agentId;!t||!r||!this.config.clientToken||el().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var e;return((e=this.agentExecution)==null?void 0:e.status)==="running"}isVoiceSupported(){var e;return Yi((e=this.config.voiceRecognition)==null?void 0:e.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var e;return(e=this.voiceProvider)!=null&&e.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var e;(e=this.voiceProvider)!=null&&e.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var e,t,r;return(r=(t=(e=this.voiceProvider)==null?void 0:e.isBargeInActive)==null?void 0:t.call(e))!=null?r:!1}async deactivateBargeIn(){var e;(e=this.voiceProvider)!=null&&e.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i;let e=this.config.textToSpeech;if(e!=null&&e.createEngine)return e.createEngine();let t=bs.isSupported()?new bs({pickVoice:e==null?void 0:e.pickVoice}):null;if((e==null?void 0:e.provider)==="runtype"){let d=(r=e.host)!=null?r:this.config.apiUrl,c=(i=e.agentId)!=null?i:(a=(s=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:s.runtype)==null?void 0:a.agentId,g=this.config.clientToken,f=e.browserFallback!==!1;if(d&&c&&g)return el().then(({RuntypeSpeechEngine:u,FallbackSpeechEngine:m})=>{let v=new u({host:d,agentId:c,clientToken:g,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return f&&t?new m(v,t,{onFallback:x=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${x.message}`)}):v});if(f&&t)return g&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),t}return t}setupVoice(e){var t,r;try{let o=e||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=ys(o);let a=(r=((t=this.config.voiceRecognition)!=null?t:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,c)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let g=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=g.id}if(c){this.pendingVoiceUserMessageId=null;let g=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=g.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let g=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=g.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.call(d,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var d,c;this.voiceStatus=i,this.voiceActive=i==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.call(d,i)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,o,s,a,i,d,c,g,f;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=e.runtype)==null?void 0:r.agentId)||"",clientToken:(s=(o=e.runtype)==null?void 0:o.clientToken)!=null?s:this.config.clientToken,host:(i=(a=e.runtype)==null?void 0:a.host)!=null?i:this.config.apiUrl,voiceId:(d=e.runtype)==null?void 0:d.voiceId,createPlaybackEngine:(c=e.runtype)==null?void 0:c.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((g=e.browser)==null?void 0:g.language)||"en-US",continuous:(f=e.browser)==null?void 0:f.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){var e,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(e=this.callbacks).onError)==null||t.call(e,r instanceof Error?r:new Error(String(r))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var e;return(e=this.clientSession)!=null?e: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,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}updateConfig(e){let t={...this.config,...e};if(!Sf(this.config,t)){this.config=t,this.client.updateConfig(t);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=t,this.client=new Zs(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:g,rawContent:f}=e,m={id:a!=null?a:t==="user"?Xa():t==="assistant"?ea():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...g!==void 0&&{voiceProcessing:g},...f!==void 0&&{rawContent:f}};return this.upsertMessage(m),m}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 t=[];for(let r of e){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:g,streaming:f=!1,voiceProcessing:u,rawContent:m}=r,x={id:d!=null?d:o==="user"?Xa():o==="assistant"?ea():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:g!=null?g:this.nextSequence(),streaming:f,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...u!==void 0&&{voiceProcessing:u},...m!==void 0&&{rawContent:m}};t.push(x)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=e,c={text:o,component:t,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(c),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(e,t){var c,g,f,u,m;let r=e.trim();if(!r&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves();let o=Xa(),s=ea(),a={id:o,role:"user",content:r||Ja,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!x){let E=Fu(v,this.config.errorMessage);if(E){let k={id:s,role:"assistant",createdAt:new Date().toISOString(),content:E,sequence:this.nextSequence()};this.appendMessage(k)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(f=(g=this.callbacks).onError)==null||f.call(g,v):(m=(u=this.callbacks).onError)==null||m.call(u,new Error(String(v))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let e=ea();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:e},this.handleEvent)}catch(c){let g=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!g){let f=Fu(c,this.config.errorMessage);if(f){let u={id:e,role:"assistant",createdAt:new Date().toISOString(),content:f,sequence:this.nextSequence()};this.appendMessage(u)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g||(c instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c))))}}async connectStream(e,t){var o,s,a;if(this.streaming&&!(t!=null&&t.allowReentry))return;t!=null&&t.allowReentry||(o=this.abortController)==null||o.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;(e==null?void 0:e.enabled)===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(t=>this.requestWebMcpApproval(t))}requestWebMcpApproval(e){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,e))===!0)return Promise.resolve(!0)}catch{}let t={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:(a=e.description)!=null?a:`Allow the assistant to run ${e.toolName}?`,parameters:e.args},r=`approval-${t.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:t}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(e,t){let r=this.webMcpApprovalResolvers.get(e);if(!r)return;this.webMcpApprovalResolvers.delete(e);let o=this.messages.find(s=>s.id===e);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:t,resolvedAt:Date.now()}}),r(t==="approved")}async resolveApproval(e,t,r){var g,f,u,m,v;let o=`approval-${e.id}`,s={...e,status:t,resolvedAt:Date.now()},a=this.messages.find(x=>x.id===o),i={id:o,role:"assistant",content:"",createdAt:(g=a==null?void 0:a.createdAt)!=null?g:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(f=this.abortController)==null||f.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let x;if(c?x=await c({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},t,r):x=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},t),x){let E=null;if(x instanceof Response){if(!x.ok){let k=await x.json().catch(()=>null);throw new Error((u=k==null?void 0:k.error)!=null?u:`Approval request failed: ${x.status}`)}E=x.body}else x instanceof ReadableStream&&(E=x);E?await this.connectStream(E,{allowReentry:!0}):(t==="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(x){let E=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));this.setStreaming(!1),this.abortController=null,E||(v=(m=this.callbacks).onError)==null||v.call(m,x instanceof Error?x:new Error(String(x)))}}persistAskUserQuestionProgress(e,t){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(e,t){var g,f,u,m,v,x,E,k,L,F,I,R;let r=this.messages.find(A=>A.id===e.id);if(((g=r==null?void 0:r.agentMetadata)==null?void 0:g.askUserQuestionAnswered)===!0)return;let o=(f=e.agentMetadata)==null?void 0:f.executionId,s=(u=e.toolCall)==null?void 0:u.name;if(!o||!s){(v=(m=this.callbacks).onError)==null||v.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof t=="string"?void 0:t;if(a===void 0&&typeof t=="string"){let A=(x=e.toolCall)==null?void 0:x.args,W=Array.isArray(A==null?void 0:A.questions)?A.questions:[];if(W.length===1){let D=typeof((E=W[0])==null?void 0:E.question)=="string"?W[0].question:"";D&&(a={[D]:t})}}this.markAskUserQuestionResolved(e,a),(k=this.abortController)==null||k.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=e.toolCall.id,d=(L=e.toolCall)==null?void 0:L.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let A=typeof t=="string"?t:Object.entries(t).map(([W,D])=>`${W}: ${Array.isArray(D)?D.join(", "):D}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:A,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let A=a!=null?a:{};c.forEach((W,D)=>{let N=typeof(W==null?void 0:W.question)=="string"?W.question:"";if(!N)return;let M=A[N],z=Array.isArray(M)?M.join(", "):typeof M=="string"?M:"";this.appendMessage({id:`ask-user-q-${i}-${D}`,role:"assistant",content:N,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${D}`,role:"user",content:z||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let A=await this.client.resumeFlow(o,{[s]:t});if(!A.ok){let W=await A.json().catch(()=>null);throw new Error((F=W==null?void 0:W.error)!=null?F:`Resume failed: ${A.status}`)}A.body?await this.connectStream(A.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(A){let W=A instanceof Error&&(A.name==="AbortError"||A.message.includes("aborted")||A.message.includes("abort"));this.setStreaming(!1),this.abortController=null,W||(R=(I=this.callbacks).onError)==null||R.call(I,A instanceof Error?A:new Error(String(A)))}}enqueueWebMcpAwait(e){var s,a;let t=(s=e.agentMetadata)==null?void 0:s.executionId,r=(a=e.toolCall)==null?void 0:a.id;if(!t||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let o=this.webMcpAwaitBatches.get(t);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let t of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(t)})}flushWebMcpAwaitBatch(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:r}=t;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(e,r)}resolveWebMcpToolStartedAt(e){var o,s;let t=this.messages.find(a=>a.id===e.id),r=[(o=t==null?void 0:t.toolCall)==null?void 0:o.startedAt,(s=e.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(e){var r,o;if(((r=e.toolCall)==null?void 0:r.name)!==Gr)return!1;let t=this.messages.find(s=>s.id===e.id);return((o=(t!=null?t:e).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(e){let t=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:t,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),t}markWebMcpToolComplete(e,t,r,o=Date.now(),s){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:t,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,t){var d,c,g,f;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(t.map(async u=>{var R,A,W,D,N,M,z;let m=(R=u.toolCall)==null?void 0:R.name,v=(A=u.toolCall)==null?void 0:A.id;if(!m||!v)return null;let x=`${e}:${v}`;if(this.webMcpInflightKeys.has(x)||this.webMcpResolvedKeys.has(x)||this.isSuggestRepliesAlreadyResolved(u))return null;this.webMcpInflightKeys.add(x),r.push(x);let E=this.markWebMcpToolRunning(u),k=(D=(W=u.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?D:m;if(m===Gr)return{dedupeKey:x,resumeKey:k,output:Vi(),toolMessage:u,startedAt:E,completedAt:Date.now()};let L=new AbortController;this.webMcpResolveControllers.add(L),o.push(L);let F=this.client.executeWebMcpToolCall(m,(N=u.toolCall)==null?void 0:N.args,L.signal),I;if(!F)I={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{I=await F}catch(V){let oe=V instanceof Error&&(V.name==="AbortError"||V.message.includes("aborted")||V.message.includes("abort"));return oe||(z=(M=this.callbacks).onError)==null||z.call(M,V instanceof Error?V:new Error(String(V))),this.markWebMcpToolComplete(u,ra(oe?"Aborted by cancel()":Ou(V)),E),this.webMcpInflightKeys.delete(x),null}return L.signal.aborted?(this.markWebMcpToolComplete(u,ra("Aborted by cancel()"),E),this.webMcpInflightKeys.delete(x),null):{dedupeKey:x,resumeKey:k,output:I,toolMessage:u,startedAt:E,completedAt:Date.now()}})),i=[];try{if(i=a.filter(v=>v!==null),i.length===0)return;let u={};for(let v of i)u[v.resumeKey]=v.output;let m=await this.client.resumeFlow(e,u,{signal:s.signal});if(!m.ok){let v=await m.json().catch(()=>null);throw new Error((d=v==null?void 0:v.error)!=null?d:`Resume failed: ${m.status}`)}for(let v of i)this.webMcpResolvedKeys.add(v.dedupeKey),this.markWebMcpToolComplete(v.toolMessage,v.output,v.startedAt,v.completedAt,((c=v.toolMessage.toolCall)==null?void 0:c.name)===Gr?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(u){if(!(u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))))(f=(g=this.callbacks).onError)==null||f.call(g,u instanceof Error?u:new Error(String(u)));else for(let v of i)this.markWebMcpToolComplete(v.toolMessage,ra("Aborted by cancel()"),v.startedAt)}finally{for(let u of r)this.webMcpInflightKeys.delete(u);for(let u of o)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){var v,x,E,k,L,F,I,R,A,W,D,N;let t=(v=e.agentMetadata)==null?void 0:v.executionId,r=(x=e.toolCall)==null?void 0:x.name,o=(E=e.toolCall)==null?void 0:E.id;if(!t){(L=(k=this.callbacks).onError)==null||L.call(k,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let M=`${t}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(M)||this.webMcpResolvedKeys.has(M))return;this.webMcpInflightKeys.add(M);try{await this.resumeWithToolOutput(t,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(M)}catch(z){(I=(F=this.callbacks).onError)==null||I.call(F,z instanceof Error?z:new Error(String(z)))}finally{this.webMcpInflightKeys.delete(M)}return}let s=`${t}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(e),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===Gr,g=(R=e.toolCall)==null?void 0:R.args,f=c?null:this.client.executeWebMcpToolCall(r,g,d),u="execute",m=a;try{let M;if(c?M=Vi():f?M=await f:M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),d.aborted){this.markWebMcpToolComplete(e,ra("Aborted by cancel()"),a);return}let z=(W=(A=e.agentMetadata)==null?void 0:A.webMcpToolCallId)!=null?W:r;u="resume",await this.resumeWithToolOutput(t,z,M,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,M,a,m,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(M){let z=M instanceof Error&&(M.name==="AbortError"||M.message.includes("aborted")||M.message.includes("abort"));(u==="execute"||z||d.aborted)&&this.markWebMcpToolComplete(e,ra(z||d.aborted?"Aborted by cancel()":Ou(M)),a),z||(N=(D=this.callbacks).onError)==null||N.call(D,M instanceof Error?M:new Error(String(M)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,t,r,o){var a,i;let s=await this.client.resumeFlow(e,{[t]:r},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.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(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;this.stopSpeaking(),(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){var o;let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(e.artifactType==="markdown"){let s={id:t,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content};return this.artifacts.set(t,s),this.selectedArtifactId=t,this.emitArtifactsState(),s}let r={id:t,artifactType:"component",title:e.title,status:"complete",component:e.component,props:(o=e.props)!=null?o:{}};return this.artifacts.set(t,r),this.selectedArtifactId=t,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var e,t;(t=(e=this.callbacks).onArtifactsState)==null||t.call(e,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){var t,r;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:""}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:(t=e.component)!=null?t:"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+e.artDelta);break}case"artifact_update":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...e.props},e.component&&(o.component=e.component));break}case"artifact_complete":{let o=this.artifacts.get(e.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(r=>{var o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,t=null){this.artifacts.clear();for(let r of e)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!(e!=null&&e.enabled)||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let r=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=Zi(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return Za(e)}toggleReadAloud(e){let t=this.messages.find(s=>s.id===e);if(!t||t.role!=="assistant")return;let r=Zi(t.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(e,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let t=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.ensureSequence(e),r=this.messages.findIndex(o=>o.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((o,s)=>{var g,f,u,m,v,x,E,k,L,F,I,R,A,W,D;if(s!==r)return o;let a={...o,...t};if(((g=o.agentMetadata)==null?void 0:g.askUserQuestionAnswered)===!0&&t.agentMetadata&&(a.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((f=o.agentMetadata)==null?void 0:f.suggestRepliesResolved)===!0&&t.agentMetadata&&(a.agentMetadata={...(u=a.agentMetadata)!=null?u:t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&t.approval&&o.approval.id===t.approval.id){let N=o.approval,M=t.approval;a.approval={...N,...M,executionId:M.executionId||N.executionId,toolName:M.toolName||N.toolName,description:M.description||N.description,toolType:(m=M.toolType)!=null?m:N.toolType,reason:(v=M.reason)!=null?v:N.reason,parameters:(x=M.parameters)!=null?x:N.parameters}}let i=(E=t.toolCall)==null?void 0:E.name,d=(k=t.agentMetadata)==null?void 0:k.executionId,c=(L=t.toolCall)==null?void 0:L.id;if(i&&_u(i)&&d&&c&&((F=t.agentMetadata)==null?void 0:F.awaitingLocalTool)===!0){let N=`${d}:${c}`,M=this.webMcpInflightKeys.has(N),z=this.webMcpResolvedKeys.has(N),V=(I=o.toolCall)==null?void 0:I.name,oe=((R=o.agentMetadata)==null?void 0:R.executionId)===d&&((A=o.toolCall)==null?void 0:A.id)===c&&V!==void 0&&_u(V)&&((W=o.toolCall)==null?void 0:W.status)==="complete";(M||z||oe)&&(a.agentMetadata={...(D=a.agentMetadata)!=null?D:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),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((t,r)=>{var d,c;let o=new Date(t.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=t.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(r.id)})}};var w=require("lucide"),Tf={activity:w.Activity,"arrow-down":w.ArrowDown,"arrow-up":w.ArrowUp,"arrow-up-right":w.ArrowUpRight,bot:w.Bot,"chevron-down":w.ChevronDown,"chevron-up":w.ChevronUp,"chevron-right":w.ChevronRight,"chevron-left":w.ChevronLeft,check:w.Check,clipboard:w.Clipboard,"clipboard-copy":w.ClipboardCopy,copy:w.Copy,file:w.File,"file-code":w.FileCode,"file-spreadsheet":w.FileSpreadsheet,"file-text":w.FileText,"image-plus":w.ImagePlus,loader:w.Loader,"loader-circle":w.LoaderCircle,mic:w.Mic,paperclip:w.Paperclip,"refresh-cw":w.RefreshCw,search:w.Search,send:w.Send,"shield-alert":w.ShieldAlert,"shield-check":w.ShieldCheck,"shield-x":w.ShieldX,square:w.Square,"thumbs-down":w.ThumbsDown,"thumbs-up":w.ThumbsUp,upload:w.Upload,"volume-2":w.Volume2,x:w.X,user:w.User,mail:w.Mail,phone:w.Phone,calendar:w.Calendar,clock:w.Clock,building:w.Building,"map-pin":w.MapPin,lock:w.Lock,key:w.Key,"credit-card":w.CreditCard,"at-sign":w.AtSign,hash:w.Hash,globe:w.Globe,link:w.Link,"circle-check":w.CircleCheck,"circle-x":w.CircleX,"triangle-alert":w.TriangleAlert,info:w.Info,ban:w.Ban,shield:w.Shield,"arrow-left":w.ArrowLeft,"arrow-right":w.ArrowRight,"external-link":w.ExternalLink,ellipsis:w.Ellipsis,"ellipsis-vertical":w.EllipsisVertical,menu:w.Menu,house:w.House,plus:w.Plus,minus:w.Minus,pencil:w.Pencil,trash:w.Trash,"trash-2":w.Trash2,save:w.Save,download:w.Download,share:w.Share,funnel:w.Funnel,settings:w.Settings,"rotate-cw":w.RotateCw,maximize:w.Maximize,minimize:w.Minimize,"shopping-cart":w.ShoppingCart,"shopping-bag":w.ShoppingBag,package:w.Package,truck:w.Truck,tag:w.Tag,gift:w.Gift,receipt:w.Receipt,wallet:w.Wallet,store:w.Store,"dollar-sign":w.DollarSign,percent:w.Percent,play:w.Play,pause:w.Pause,"volume-x":w.VolumeX,camera:w.Camera,image:w.Image,film:w.Film,headphones:w.Headphones,"message-circle":w.MessageCircle,"message-square":w.MessageSquare,bell:w.Bell,heart:w.Heart,star:w.Star,eye:w.Eye,"eye-off":w.EyeOff,bookmark:w.Bookmark,"calendar-days":w.CalendarDays,history:w.History,timer:w.Timer,folder:w.Folder,"folder-open":w.FolderOpen,files:w.Files,sparkles:w.Sparkles,zap:w.Zap,sun:w.Sun,moon:w.Moon,flag:w.Flag,monitor:w.Monitor,smartphone:w.Smartphone},Se=(n,e=24,t="currentColor",r=2)=>{let o=Tf[n];return o?Mf(o,e,t,r):(console.warn(`Lucide icon "${n}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Mf(n,e,t,r){if(!Array.isArray(n))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),n.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,g])=>{c!=="stroke"&&d.setAttribute(c,String(g))}),o.appendChild(d)}),o}var ri={allowedTypes:Qr,maxFileSize:10*1024*1024,maxFiles:4};function Ef(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function kf(n){return n==="application/pdf"||n.startsWith("text/")||n.includes("word")?"file-text":n.includes("excel")||n.includes("spreadsheet")?"file-spreadsheet":n==="application/json"?"file-code":"file"}var oa=class n{constructor(e={}){this.attachments=[];this.previewsContainer=null;var t,r,o;this.config={allowedTypes:(t=e.allowedTypes)!=null?t:ri.allowedTypes,maxFileSize:(r=e.maxFileSize)!=null?r:ri.maxFileSize,maxFiles:(o=e.maxFiles)!=null?o:ri.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:ri.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)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}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){var t,r,o,s,a,i,d;if(e.length){for(let c of e){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,c,"count");continue}let g=ku(c,this.config.allowedTypes,this.config.maxFileSize);if(!g.valid){let f=(o=g.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,f);continue}try{let f=await Eu(c),u=Ya(c)?URL.createObjectURL(c):null,m={id:Ef(),file:c,previewUrl:u,contentPart:f};this.attachments.push(m),this.renderPreview(m)}catch(f){console.error("[AttachmentManager] Failed to process file:",f)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(e){var s,a,i;let t=this.attachments.findIndex(d=>d.id===e);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${e}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var e,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(e=this.config).onAttachmentsChange)==null||t.call(e,this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let t=Ya(e.file),r=b("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",e.id),r.style.width="48px",r.style.height="48px",t&&e.previewUrl){let a=b("img");a.src=e.previewUrl,a.alt=e.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=b("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=kf(e.file.type),d=Se(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=b("span");c.textContent=Lu(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",a.appendChild(c),r.appendChild(a)}let o=b("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=Se("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(e.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,t){return new n({allowedTypes:e==null?void 0:e.allowedTypes,maxFileSize:e==null?void 0:e.maxFileSize,maxFiles:e==null?void 0:e.maxFiles,onFileRejected:e==null?void 0:e.onFileRejected,onAttachmentsChange:t})}};var $u=n=>typeof n=="object"&&n!==null&&!Array.isArray(n);function sa(n,e){if(!n)return e;if(!e)return n;let t={...n};for(let[r,o]of Object.entries(e)){let s=t[r];$u(s)&&$u(o)?t[r]=sa(s,o):t[r]=o}return t}var Xr="min(440px, calc(100vw - 24px))",qu="440px",Lf={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:Xr,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},_t={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Lf,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"follow",anchorTopOffset:16},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Uu(n,e){if(!(!n&&!e))return n?e?sa(n,e):n:e}function zu(n){var e,t,r,o,s,a,i,d,c,g,f,u,m,v,x,E,k,L,F,I,R;return n?{..._t,...n,theme:Uu(_t.theme,n.theme),darkTheme:Uu(_t.darkTheme,n.darkTheme),launcher:{..._t.launcher,...n.launcher,dock:{...(e=_t.launcher)==null?void 0:e.dock,...(t=n.launcher)==null?void 0:t.dock},clearChat:{...(r=_t.launcher)==null?void 0:r.clearChat,...(o=n.launcher)==null?void 0:o.clearChat}},copy:{..._t.copy,...n.copy},sendButton:{..._t.sendButton,...n.sendButton},statusIndicator:{..._t.statusIndicator,...n.statusIndicator},voiceRecognition:{..._t.voiceRecognition,...n.voiceRecognition},features:(()=>{var se,Q,ae,fe,ue,K,ie,We,te,ee;let A=(se=_t.features)==null?void 0:se.artifacts,W=(Q=n.features)==null?void 0:Q.artifacts,D=(ae=_t.features)==null?void 0:ae.scrollToBottom,N=(fe=n.features)==null?void 0:fe.scrollToBottom,M=(ue=_t.features)==null?void 0:ue.scrollBehavior,z=(K=n.features)==null?void 0:K.scrollBehavior,V=(ie=_t.features)==null?void 0:ie.streamAnimation,oe=(We=n.features)==null?void 0:We.streamAnimation,Le=(te=_t.features)==null?void 0:te.askUserQuestion,je=(ee=n.features)==null?void 0:ee.askUserQuestion,ve=A===void 0&&W===void 0?void 0:{...A,...W,layout:{...A==null?void 0:A.layout,...W==null?void 0:W.layout}},Be=D===void 0&&N===void 0?void 0:{...D,...N},Oe=M===void 0&&z===void 0?void 0:{...M,...z},Te=V===void 0&&oe===void 0?void 0:{...V,...oe},we=Le===void 0&&je===void 0?void 0:{...Le,...je,styles:{...Le==null?void 0:Le.styles,...je==null?void 0:je.styles}};return{..._t.features,...n.features,...Be!==void 0?{scrollToBottom:Be}:{},...Oe!==void 0?{scrollBehavior:Oe}:{},...ve!==void 0?{artifacts:ve}:{},...Te!==void 0?{streamAnimation:Te}:{},...we!==void 0?{askUserQuestion:we}:{}}})(),suggestionChips:(s=n.suggestionChips)!=null?s:_t.suggestionChips,suggestionChipsConfig:{..._t.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{..._t.layout,...n.layout,header:{...(a=_t.layout)==null?void 0:a.header,...(i=n.layout)==null?void 0:i.header},messages:{...(d=_t.layout)==null?void 0:d.messages,...(c=n.layout)==null?void 0:c.messages,avatar:{...(f=(g=_t.layout)==null?void 0:g.messages)==null?void 0:f.avatar,...(m=(u=n.layout)==null?void 0:u.messages)==null?void 0:m.avatar},timestamp:{...(x=(v=_t.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(k=(E=n.layout)==null?void 0:E.messages)==null?void 0:k.timestamp}},slots:{...(L=_t.layout)==null?void 0:L.slots,...(F=n.layout)==null?void 0:F.slots}},markdown:{..._t.markdown,...n.markdown,options:{...(I=_t.markdown)==null?void 0:I.options,...(R=n.markdown)==null?void 0:R.options}},messageActions:{..._t.messageActions,...n.messageActions}}:_t}var Pf={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},If={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"}},Wf={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:Xr,maxWidth:qu,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function vs(n,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let t=e.split("."),r=n;for(let o of t){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?vs(n,r):r}function Vu(n){let e={};function t(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=vs(n,a);d!==void 0&&(e[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(n.palette,"palette"),t(n.semantic,"semantic"),t(n.components,"components"),e}function Rf(n){let e=[],t=[];return n.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),n.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),n.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:t}}function ju(n,e){let t={...n};for(let[r,o]of Object.entries(e)){let s=t[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?t[r]=ju(s,o):t[r]=o}return t}function Hf(n,e){return e?ju(n,e):n}function Uo(n,e={}){var o,s,a,i,d,c,g,f,u,m,v,x,E;let t={palette:Pf,semantic:If,components:Wf},r={palette:{...t.palette,...n==null?void 0:n.palette,colors:{...t.palette.colors,...(o=n==null?void 0:n.palette)==null?void 0:o.colors},spacing:{...t.palette.spacing,...(s=n==null?void 0:n.palette)==null?void 0:s.spacing},typography:{...t.palette.typography,...(a=n==null?void 0:n.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=n==null?void 0:n.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=n==null?void 0:n.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(c=n==null?void 0:n.palette)==null?void 0:c.radius}},semantic:{...t.semantic,...n==null?void 0:n.semantic,colors:{...t.semantic.colors,...(g=n==null?void 0:n.semantic)==null?void 0:g.colors,interactive:{...t.semantic.colors.interactive,...(u=(f=n==null?void 0:n.semantic)==null?void 0:f.colors)==null?void 0:u.interactive},feedback:{...t.semantic.colors.feedback,...(v=(m=n==null?void 0:n.semantic)==null?void 0:m.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(x=n==null?void 0:n.semantic)==null?void 0:x.spacing},typography:{...t.semantic.typography,...(E=n==null?void 0:n.semantic)==null?void 0:E.typography}},components:Hf(t.components,n==null?void 0:n.components)};if(e.validate!==!1){let k=Rf(r);if(!k.valid)throw new Error(`Theme validation failed: ${k.errors.map(L=>L.message).join(", ")}`)}if(e.plugins)for(let k of e.plugins)r=k.transform(r);return r}function Ku(n){var x,E,k,L,F,I,R,A,W,D,N,M,z,V,oe,Le,je,ve,Be,Oe,Te,we,se,Q,ae,fe,ue,K,ie,We,te,ee,re,it,lt,st,Ee,he,Je,Y,me,ke,Ye,Ge,Ie,Ke,vn,Rt,pn,Cr,U,G,ye,Qe,et,Ue,_e,Pt,Kt,Jt,Ln,j,Ht,ce,Ce,Fe,Tt,on,sn,xn,Nt,rt,Dt,pt,Yt,nr,Pn,an,On,Ar,xt,zn,Sr,Fr,mr,bt,Co,Tr,Ao,_n,Ko,Yr,Or,Zr,eo,So,To,to,Ct,Vn,jn,In,Mt,rr,or,Kn,no,_r,ro,Gn,Ft,Wn,sr,oo,$r,so,Mr,Qn;let e=Vu(n),t={};for(let[be,ut]of Object.entries(e)){let tn=be.replace(/\./g,"-");t[`--persona-${tn}`]=ut.value}t["--persona-primary"]=(x=t["--persona-semantic-colors-primary"])!=null?x:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(E=t["--persona-semantic-colors-secondary"])!=null?E:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(k=t["--persona-semantic-colors-accent"])!=null?k:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(L=t["--persona-semantic-colors-surface"])!=null?L:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(F=t["--persona-semantic-colors-background"])!=null?F:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(I=t["--persona-semantic-colors-container"])!=null?I:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(R=t["--persona-semantic-colors-text"])!=null?R:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(A=t["--persona-semantic-colors-text-muted"])!=null?A:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(W=t["--persona-semantic-colors-text-inverse"])!=null?W:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(D=t["--persona-semantic-colors-border"])!=null?D:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(N=t["--persona-semantic-colors-divider"])!=null?N:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(M=t["--persona-components-voice-recording-indicator"])!=null?M:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(z=t["--persona-components-voice-recording-background"])!=null?z:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(V=t["--persona-components-voice-processing-icon"])!=null?V:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(oe=t["--persona-components-voice-speaking-icon"])!=null?oe:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Le=t["--persona-components-approval-requested-background"])!=null?Le:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(je=t["--persona-components-approval-requested-border"])!=null?je:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(ve=t["--persona-components-approval-requested-text"])!=null?ve:t["--persona-palette-colors-gray-900"],t["--persona-approval-shadow"]=(Be=t["--persona-components-approval-requested-shadow"])!=null?Be:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-approval-approve-bg"]=(Oe=t["--persona-components-approval-approve-background"])!=null?Oe:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(Te=t["--persona-components-approval-deny-background"])!=null?Te:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(we=t["--persona-components-attachment-image-background"])!=null?we:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(se=t["--persona-components-attachment-image-border"])!=null?se:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(Q=t["--persona-semantic-typography-fontFamily"])!=null?Q:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(ae=t["--persona-semantic-typography-fontSize"])!=null?ae:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(fe=t["--persona-semantic-typography-fontWeight"])!=null?fe:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(ue=t["--persona-semantic-typography-lineHeight"])!=null?ue:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(K=t["--persona-palette-radius-sm"])!=null?K:"0.125rem",t["--persona-radius-md"]=(ie=t["--persona-palette-radius-md"])!=null?ie:"0.375rem",t["--persona-radius-lg"]=(We=t["--persona-palette-radius-lg"])!=null?We:"0.5rem",t["--persona-radius-xl"]=(te=t["--persona-palette-radius-xl"])!=null?te:"0.75rem",t["--persona-radius-full"]=(ee=t["--persona-palette-radius-full"])!=null?ee:"9999px",t["--persona-launcher-radius"]=(it=(re=t["--persona-components-launcher-borderRadius"])!=null?re:t["--persona-palette-radius-full"])!=null?it:"9999px",t["--persona-launcher-bg"]=(lt=t["--persona-components-launcher-background"])!=null?lt:t["--persona-primary"],t["--persona-launcher-fg"]=(st=t["--persona-components-launcher-foreground"])!=null?st:t["--persona-text-inverse"],t["--persona-launcher-border"]=(Ee=t["--persona-components-launcher-border"])!=null?Ee:t["--persona-border"],t["--persona-button-primary-bg"]=(he=t["--persona-components-button-primary-background"])!=null?he:t["--persona-primary"],t["--persona-button-primary-fg"]=(Je=t["--persona-components-button-primary-foreground"])!=null?Je:t["--persona-text-inverse"],t["--persona-button-radius"]=(me=(Y=t["--persona-components-button-primary-borderRadius"])!=null?Y:t["--persona-palette-radius-full"])!=null?me:"9999px",t["--persona-panel-radius"]=(Ye=(ke=t["--persona-components-panel-borderRadius"])!=null?ke:t["--persona-radius-xl"])!=null?Ye:"0.75rem",t["--persona-panel-border"]=(Ge=t["--persona-components-panel-border"])!=null?Ge:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Ke=(Ie=t["--persona-components-panel-shadow"])!=null?Ie:t["--persona-palette-shadows-xl"])!=null?Ke:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-launcher-shadow"]=(vn=t["--persona-components-launcher-shadow"])!=null?vn:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",t["--persona-input-radius"]=(pn=(Rt=t["--persona-components-input-borderRadius"])!=null?Rt:t["--persona-radius-lg"])!=null?pn:"0.5rem",t["--persona-message-user-radius"]=(U=(Cr=t["--persona-components-message-user-borderRadius"])!=null?Cr:t["--persona-radius-lg"])!=null?U:"0.5rem",t["--persona-message-assistant-radius"]=(ye=(G=t["--persona-components-message-assistant-borderRadius"])!=null?G:t["--persona-radius-lg"])!=null?ye:"0.5rem",t["--persona-header-bg"]=(Qe=t["--persona-components-header-background"])!=null?Qe:t["--persona-surface"],t["--persona-header-border"]=(et=t["--persona-components-header-border"])!=null?et:t["--persona-divider"],t["--persona-header-icon-bg"]=(Ue=t["--persona-components-header-iconBackground"])!=null?Ue:t["--persona-primary"],t["--persona-header-icon-fg"]=(_e=t["--persona-components-header-iconForeground"])!=null?_e:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Pt=t["--persona-components-header-titleForeground"])!=null?Pt:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Kt=t["--persona-components-header-subtitleForeground"])!=null?Kt:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(Jt=t["--persona-components-header-actionIconForeground"])!=null?Jt:t["--persona-muted"];let r=(Ln=n.components)==null?void 0:Ln.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let o=(j=n.components)==null?void 0:j.introCard;t["--persona-intro-card-bg"]=(Ht=t["--persona-components-introCard-background"])!=null?Ht:t["--persona-surface"],t["--persona-intro-card-radius"]=(ce=t["--persona-components-introCard-borderRadius"])!=null?ce:"1rem",t["--persona-intro-card-padding"]=(Ce=t["--persona-components-introCard-padding"])!=null?Ce:"1.5rem",t["--persona-intro-card-shadow"]=(Tt=(Fe=o==null?void 0:o.shadow)!=null?Fe:t["--persona-components-introCard-shadow"])!=null?Tt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(on=t["--persona-components-input-background"])!=null?on:t["--persona-surface"],t["--persona-input-placeholder"]=(sn=t["--persona-components-input-placeholder"])!=null?sn:t["--persona-text-muted"],t["--persona-message-user-bg"]=(xn=t["--persona-components-message-user-background"])!=null?xn:t["--persona-accent"],t["--persona-message-user-text"]=(Nt=t["--persona-components-message-user-text"])!=null?Nt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(rt=t["--persona-components-message-user-shadow"])!=null?rt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(Dt=t["--persona-components-message-assistant-background"])!=null?Dt:t["--persona-surface"],t["--persona-message-assistant-text"]=(pt=t["--persona-components-message-assistant-text"])!=null?pt:t["--persona-text"],t["--persona-message-assistant-border"]=(Yt=t["--persona-components-message-assistant-border"])!=null?Yt:t["--persona-border"],t["--persona-message-assistant-shadow"]=(nr=t["--persona-components-message-assistant-shadow"])!=null?nr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(an=(Pn=t["--persona-components-scrollToBottom-background"])!=null?Pn:t["--persona-button-primary-bg"])!=null?an:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Ar=(On=t["--persona-components-scrollToBottom-foreground"])!=null?On:t["--persona-button-primary-fg"])!=null?Ar:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(xt=t["--persona-components-scrollToBottom-border"])!=null?xt:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(zn=t["--persona-components-scrollToBottom-size"])!=null?zn:"40px",t["--persona-scroll-to-bottom-radius"]=(mr=(Fr=(Sr=t["--persona-components-scrollToBottom-borderRadius"])!=null?Sr:t["--persona-button-radius"])!=null?Fr:t["--persona-radius-full"])!=null?mr:"9999px",t["--persona-scroll-to-bottom-shadow"]=(Co=(bt=t["--persona-components-scrollToBottom-shadow"])!=null?bt:t["--persona-palette-shadows-sm"])!=null?Co:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(Tr=t["--persona-components-scrollToBottom-padding"])!=null?Tr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(Ao=t["--persona-components-scrollToBottom-gap"])!=null?Ao:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(Ko=(_n=t["--persona-components-scrollToBottom-fontSize"])!=null?_n:t["--persona-palette-typography-fontSize-sm"])!=null?Ko:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(Yr=t["--persona-components-scrollToBottom-iconSize"])!=null?Yr:"14px",t["--persona-tool-bubble-shadow"]=(Or=t["--persona-components-toolBubble-shadow"])!=null?Or:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(Zr=t["--persona-components-reasoningBubble-shadow"])!=null?Zr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(eo=t["--persona-components-composer-shadow"])!=null?eo:"none",t["--persona-md-inline-code-bg"]=(So=t["--persona-components-markdown-inlineCode-background"])!=null?So:t["--persona-container"],t["--persona-md-inline-code-color"]=(To=t["--persona-components-markdown-inlineCode-foreground"])!=null?To:t["--persona-text"],t["--persona-md-link-color"]=(Ct=(to=t["--persona-components-markdown-link-foreground"])!=null?to:t["--persona-accent"])!=null?Ct:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let a=t["--persona-components-markdown-heading-h1-fontWeight"];a&&(t["--persona-md-h1-weight"]=a);let i=t["--persona-components-markdown-heading-h2-fontSize"];i&&(t["--persona-md-h2-size"]=i);let d=t["--persona-components-markdown-heading-h2-fontWeight"];d&&(t["--persona-md-h2-weight"]=d);let c=t["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(t["--persona-md-prose-font-family"]=c),t["--persona-md-code-block-bg"]=(Vn=t["--persona-components-markdown-codeBlock-background"])!=null?Vn:t["--persona-container"],t["--persona-md-code-block-border-color"]=(jn=t["--persona-components-markdown-codeBlock-borderColor"])!=null?jn:t["--persona-border"],t["--persona-md-code-block-text-color"]=(In=t["--persona-components-markdown-codeBlock-textColor"])!=null?In:"inherit",t["--persona-md-table-header-bg"]=(Mt=t["--persona-components-markdown-table-headerBackground"])!=null?Mt:t["--persona-container"],t["--persona-md-table-border-color"]=(rr=t["--persona-components-markdown-table-borderColor"])!=null?rr:t["--persona-border"],t["--persona-md-hr-color"]=(or=t["--persona-components-markdown-hr-color"])!=null?or:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(Kn=t["--persona-components-markdown-blockquote-borderColor"])!=null?Kn:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(no=t["--persona-components-markdown-blockquote-background"])!=null?no:"transparent",t["--persona-md-blockquote-text-color"]=(_r=t["--persona-components-markdown-blockquote-textColor"])!=null?_r:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(ro=t["--persona-components-collapsibleWidget-container"])!=null?ro:t["--persona-surface"],t["--cw-surface"]=(Gn=t["--persona-components-collapsibleWidget-surface"])!=null?Gn:t["--persona-surface"],t["--cw-border"]=(Ft=t["--persona-components-collapsibleWidget-border"])!=null?Ft:t["--persona-border"],t["--persona-message-border"]=(Wn=t["--persona-components-message-border"])!=null?Wn:t["--persona-border"];let g=n.components,f=g==null?void 0:g.iconButton;f&&(f.background&&(t["--persona-icon-btn-bg"]=f.background),f.border&&(t["--persona-icon-btn-border"]=f.border),f.color&&(t["--persona-icon-btn-color"]=f.color),f.padding&&(t["--persona-icon-btn-padding"]=f.padding),f.borderRadius&&(t["--persona-icon-btn-radius"]=f.borderRadius),f.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=f.hoverBackground),f.hoverColor&&(t["--persona-icon-btn-hover-color"]=f.hoverColor),f.activeBackground&&(t["--persona-icon-btn-active-bg"]=f.activeBackground),f.activeBorder&&(t["--persona-icon-btn-active-border"]=f.activeBorder));let u=g==null?void 0:g.labelButton;u&&(u.background&&(t["--persona-label-btn-bg"]=u.background),u.border&&(t["--persona-label-btn-border"]=u.border),u.color&&(t["--persona-label-btn-color"]=u.color),u.padding&&(t["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(t["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(t["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(t["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(t["--persona-label-btn-gap"]=u.gap));let m=g==null?void 0:g.toggleGroup;m&&(m.gap&&(t["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(t["--persona-toggle-group-radius"]=m.borderRadius));let v=g==null?void 0:g.artifact;if(v!=null&&v.toolbar){let be=v.toolbar;be.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=be.iconHoverColor),be.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=be.iconHoverBackground),be.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=be.iconPadding),be.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=be.iconBorderRadius),be.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=be.iconBorder),be.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=be.toggleGroupGap),be.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=be.toggleBorderRadius),be.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=be.copyBackground),be.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=be.copyBorder),be.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=be.copyColor),be.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=be.copyBorderRadius),be.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=be.copyPadding),be.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=be.copyMenuBackground,t["--persona-dropdown-bg"]=(sr=t["--persona-dropdown-bg"])!=null?sr:be.copyMenuBackground),be.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=be.copyMenuBorder,t["--persona-dropdown-border"]=(oo=t["--persona-dropdown-border"])!=null?oo:be.copyMenuBorder),be.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=be.copyMenuShadow,t["--persona-dropdown-shadow"]=($r=t["--persona-dropdown-shadow"])!=null?$r:be.copyMenuShadow),be.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=be.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(so=t["--persona-dropdown-radius"])!=null?so:be.copyMenuBorderRadius),be.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=be.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(Mr=t["--persona-dropdown-item-hover-bg"])!=null?Mr:be.copyMenuItemHoverBackground),be.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=be.iconBackground),be.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=be.toolbarBorder)}if(v!=null&&v.tab){let be=v.tab;be.background&&(t["--persona-artifact-tab-bg"]=be.background),be.activeBackground&&(t["--persona-artifact-tab-active-bg"]=be.activeBackground),be.activeBorder&&(t["--persona-artifact-tab-active-border"]=be.activeBorder),be.borderRadius&&(t["--persona-artifact-tab-radius"]=be.borderRadius),be.textColor&&(t["--persona-artifact-tab-color"]=be.textColor),be.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=be.hoverBackground),be.listBackground&&(t["--persona-artifact-tab-list-bg"]=be.listBackground),be.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=be.listBorderColor),be.listPadding&&(t["--persona-artifact-tab-list-padding"]=be.listPadding)}if(v!=null&&v.pane){let be=v.pane;if(be.toolbarBackground){let ut=(Qn=vs(n,be.toolbarBackground))!=null?Qn:be.toolbarBackground;t["--persona-artifact-toolbar-bg"]=ut}}return t}var Bf={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"}}},Gu=n=>{if(!(!n||typeof n!="object"||Array.isArray(n)))return n},tl=()=>{var n;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((n=window.matchMedia)!=null&&n.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Df=n=>{var t;let e=(t=n==null?void 0:n.colorScheme)!=null?t:"light";return e==="light"?"light":e==="dark"?"dark":tl()},Nf=n=>Df(n),Ff=n=>Uo(n),Of=n=>{var t;let e=Uo(void 0,{validate:!1});return Uo({...n,palette:{...e.palette,colors:{...Bf.colors,...(t=n==null?void 0:n.palette)==null?void 0:t.colors}}},{validate:!1})},oi=n=>{let e=Nf(n),t=Gu(n==null?void 0:n.theme),r=Gu(n==null?void 0:n.darkTheme);return e==="dark"?Of(sa(t!=null?t:{},r!=null?r:{})):Ff(t)},_f=n=>Ku(n),xs=(n,e)=>{let t=oi(e),r=_f(t);for(let[o,s]of Object.entries(r))n.style.setProperty(o,s)},Qu=n=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{n(tl())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>n(tl());t.addEventListener?(t.addEventListener("change",r),e.push(()=>t.removeEventListener("change",r))):t.addListener&&(t.addListener(r),e.push(()=>t.removeListener(r)))}return()=>{e.forEach(t=>t())}};var Xu=require("idiomorph"),si=(n,e,t={})=>{let{preserveTypingAnimation:r=!0}=t;Xu.Idiomorph.morph(n,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",c=(i=s.textContent)!=null?i:"";if(d!==c)return}return!1}}}}})};var ai={index:-1,draft:""};function Ju(n){let{direction:e,history:t,currentValue:r,atStart:o,state:s}=n,a=s.index!==-1;if(t.length===0)return{handled:!1,state:s};if(e==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=t.length-1;return{handled:!0,value:t[i],state:{index:i,draft:r}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:t[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<t.length-1){let i=s.index+1;return{handled:!0,value:t[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...ai}}}function Yu(n,e){var t,r,o,s,a,i,d,c,g,f,u,m,v,x,E,k,L,F,I,R,A,W,D,N,M,z,V,oe,Le,je,ve,Be,Oe,Te,we,se,Q,ae;return[n.id,n.role,(r=(t=n.content)==null?void 0:t.length)!=null?r:0,(s=(o=n.content)==null?void 0:o.slice(-32))!=null?s:"",n.streaming?"1":"0",n.voiceProcessing?"1":"0",(a=n.variant)!=null?a:"",(d=(i=n.rawContent)==null?void 0:i.length)!=null?d:0,(g=(c=n.llmContent)==null?void 0:c.length)!=null?g:0,(u=(f=n.approval)==null?void 0:f.status)!=null?u:"",(v=(m=n.toolCall)==null?void 0:m.status)!=null?v:"",(E=(x=n.toolCall)==null?void 0:x.name)!=null?E:"",(F=(L=(k=n.toolCall)==null?void 0:k.chunks)==null?void 0:L.length)!=null?F:0,(W=(A=(R=(I=n.toolCall)==null?void 0:I.chunks)==null?void 0:R[n.toolCall.chunks.length-1])==null?void 0:A.slice(-32))!=null?W:"",typeof((D=n.toolCall)==null?void 0:D.args)=="string"?n.toolCall.args.length:(N=n.toolCall)!=null&&N.args?JSON.stringify(n.toolCall.args).length:0,(V=(z=(M=n.reasoning)==null?void 0:M.chunks)==null?void 0:z.length)!=null?V:0,(ve=(je=(Le=(oe=n.reasoning)==null?void 0:oe.chunks)==null?void 0:Le[n.reasoning.chunks.length-1])==null?void 0:je.length)!=null?ve:0,(we=(Te=(Oe=(Be=n.reasoning)==null?void 0:Be.chunks)==null?void 0:Oe[n.reasoning.chunks.length-1])==null?void 0:Te.slice(-32))!=null?we:"",(Q=(se=n.contentParts)==null?void 0:se.length)!=null?Q:0,(ae=n.stopReason)!=null?ae:"",e].join("\0")}function Zu(){return new Map}function em(n,e,t){let r=n.get(e);return r&&r.fingerprint===t?r.wrapper:null}function tm(n,e,t,r){n.set(e,{fingerprint:t,wrapper:r})}function nm(n,e){for(let t of n.keys())e.has(t)||n.delete(t)}function ii(n=!0){let e=n;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function Jr(n){return Math.max(0,n.scrollHeight-n.clientHeight)}function qo(n,e){return Jr(n)-n.scrollTop<=e}function li(n){let{following:e,currentScrollTop:t,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=n,g=t-r;return a||Math.abs(g)<s?{action:"none",delta:g,nextLastScrollTop:t}:!e&&o&&(!c||g>0)?{action:"resume",delta:g,nextLastScrollTop:t}:e&&i&&g<0?{action:"pause",delta:g,nextLastScrollTop:t}:e&&d&&!o?{action:"pause",delta:g,nextLastScrollTop:t}:{action:"none",delta:g,nextLastScrollTop:t}}function ci(n){let{following:e,deltaY:t,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=n;return e&&t<0?"pause":!e&&o&&t>0&&r?"resume":"none"}function rm(n,e){return!n||n.isCollapsed?!1:e.contains(n.anchorNode)||e.contains(n.focusNode)}function om(n){let e=Math.max(0,n.anchorOffsetTop-n.topOffset),t=Math.max(0,e+n.viewportHeight-n.contentHeight);return{targetScrollTop:e,spacerHeight:t}}function sm(n){let e=Math.max(0,n.currentContentHeight-n.contentHeightAtAnchor);return Math.max(0,n.initialSpacerHeight-e)}var Mn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},En=1e5,xo=En+1;var aa={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},$f=["pre","code","a","script","style"],di=n=>{var e,t,r,o,s;return{type:(e=n==null?void 0:n.type)!=null?e:aa.type,placeholder:(t=n==null?void 0:n.placeholder)!=null?t:aa.placeholder,speed:(r=n==null?void 0:n.speed)!=null?r:aa.speed,duration:(o=n==null?void 0:n.duration)!=null?o:aa.duration,buffer:(s=n==null?void 0:n.buffer)!=null?s:aa.buffer}},Uf=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],im=new Map;for(let n of Uf)im.set(n.name,n);var ia=(n,e)=>{var t,r;return n==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,n)?(t=e[n])!=null?t:null:(r=im.get(n))!=null?r:null},pi=(n,e,t,r,o)=>{if(!o)return n;if(t!=null&&t.bufferContent)return t.bufferContent(n,r);if(!n)return n;if(e==="word"){let s=n.search(/\s(?=\S*$)/);return s<0?"":n.slice(0,s)}if(e==="line"){let s=n.lastIndexOf(`
17
+ `);return s<0?"":n.slice(0,s)}return n},qf=(n,e,t,r)=>{let o=n.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${t}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=e,o},zf=(n,e,t,r)=>{let o=n.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${t}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=e,o},nl=/\s/,Vf=(n,e)=>{let t=n.parentNode;for(;t;){if(t.nodeType===1){let r=t;if(e.has(r.tagName.toLowerCase()))return!0}t=t.parentNode}return!1},jf=(n,e,t)=>{var d;let r=n.ownerDocument,o=n.parentNode;if(!r||!o)return;let s=(d=n.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(nl.test(s[i])){let c=i;for(;c<s.length&&nl.test(s[c]);)c+=1;a.appendChild(r.createTextNode(s.slice(i,c))),i=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let g=i;for(;g<s.length&&!nl.test(s[g]);)c.appendChild(qf(r,s[g],e,t.value)),t.value+=1,g+=1;a.appendChild(c),i=g}o.replaceChild(a,n)},Kf=(n,e,t)=>{var d;let r=n.ownerDocument,o=n.parentNode;if(!r||!o)return;let s=(d=n.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let c of i)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(zf(r,c,e,t.value)),t.value+=1));o.replaceChild(a,n)},la=(n,e,t,r)=>{var f,u;if(!n||typeof document=="undefined")return n;let o=document.createElement("div");o.innerHTML=n;let s=new Set(((f=r==null?void 0:r.skipTags)!=null?f:$f).map(m=>m.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Vf(d,s)||i.push(d),d=a.nextNode();let c={value:(u=r==null?void 0:r.startIndex)!=null?u:0},g=e==="char"?jf:Kf;for(let m of i)g(m,t,c);return o.innerHTML},ui=(n=document)=>{let e=n.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},ca=(n=document)=>{let e=n.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let t=n.createElement("div");return t.className="persona-stream-skeleton-line",e.appendChild(t),e},am=new WeakMap,Gf=(n,e)=>{var s;if(!n.styles)return;let t=am.get(e);if(t||(t=new Set,am.set(e,t)),t.has(n.name)){let a=n.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${a}"]`))return;t.delete(n.name)}t.add(n.name);let o=(e instanceof ShadowRoot?e.ownerDocument:(s=e.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",n.name),o.textContent=n.styles,e.appendChild(o)},rl=new WeakMap,Qf=(n,e)=>{if(!n.onAttach)return;let t=rl.get(e);if(t||(t=new Map,rl.set(e,t)),t.has(n.name))return;let r=n.onAttach(e);t.set(n.name,r)},lm=n=>{let e=rl.get(n);if(e){for(let t of e.values())typeof t=="function"&&t();e.clear()}},ol=(n,e)=>{Gf(n,e),Qf(n,e)};function sl(n,e=En){let t=n.style.position,r=n.style.zIndex,o=n.style.isolation,s=getComputedStyle(n),a=s.position==="static"||s.position==="";return a&&(n.style.position="relative"),n.style.zIndex=String(e),n.style.isolation="isolate",()=>{a&&(n.style.position=t),n.style.zIndex=r,n.style.isolation=o}}var da=0,wo=null;function al(n=document){var t;if(da++,da===1){let r=n.body,s=((t=n.defaultView)!=null?t:window).scrollY||n.documentElement.scrollTop;wo={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:s},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${s}px`,r.style.width="100%"}let e=!1;return()=>{var r;if(!e&&(e=!0,da=Math.max(0,da-1),da===0&&wo)){let o=n.body,s=(r=n.defaultView)!=null?r:window;o.style.overflow=wo.originalOverflow,o.style.position=wo.originalPosition,o.style.top=wo.originalTop,o.style.width=wo.originalWidth,s.scrollTo(0,wo.scrollY),wo=null}}}var pa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Cn=n=>{var e,t;return((t=(e=n==null?void 0:n.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="docked"},ua=n=>{var e,t;return((t=(e=n==null?void 0:n.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="composer-bar"},xr=n=>{var t,r,o,s,a,i;let e=(t=n==null?void 0:n.launcher)==null?void 0:t.dock;return{side:(r=e==null?void 0:e.side)!=null?r:pa.side,width:(o=e==null?void 0:e.width)!=null?o:pa.width,animate:(s=e==null?void 0:e.animate)!=null?s:pa.animate,reveal:(a=e==null?void 0:e.reveal)!=null?a:pa.reveal,maxHeight:(i=e==null?void 0:e.maxHeight)!=null?i:pa.maxHeight}};var wr={"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 Xf="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",mi=(n,e={})=>{var E,k,L,F,I,R;let{showClose:t=!0,wrapperClassName:r=Xf,buttonSize:o,iconSize:s="28px"}=e,a=(E=n==null?void 0:n.launcher)!=null?E:{},i=(k=o!=null?o:a.closeButtonSize)!=null?k:"32px",d=b("div",r),c=(L=a.closeButtonTooltipText)!=null?L:"Close chat",g=(F=a.closeButtonShowTooltip)!=null?F:!0,f=(I=a.closeButtonIconName)!=null?I:"x",u=(R=a.closeButtonIconText)!=null?R:"\xD7",m=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=Lt("button",{className:Gs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!m&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:i,width:i,display:t?void 0:"none",color:a.closeButtonColor||Fn.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:m?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),x=Se(f,s,"currentColor",1);if(x?(x.style.display="block",v.appendChild(x)):v.textContent=u,d.appendChild(v),g&&c){let A=null,W=()=>{if(A)return;let N=v.ownerDocument,M=N.body;if(!M)return;A=Nr(N,"div","persona-clear-chat-tooltip"),A.textContent=c;let z=Nr(N,"div");z.className="persona-clear-chat-tooltip-arrow",A.appendChild(z);let V=v.getBoundingClientRect();A.style.position="fixed",A.style.zIndex=String(xo),A.style.left=`${V.left+V.width/2}px`,A.style.top=`${V.top-8}px`,A.style.transform="translate(-50%, -100%)",M.appendChild(A)},D=()=>{A&&A.parentNode&&(A.parentNode.removeChild(A),A=null)};d.addEventListener("mouseenter",W),d.addEventListener("mouseleave",D),v.addEventListener("focus",W),v.addEventListener("blur",D),d._cleanupTooltip=()=>{D(),d.removeEventListener("mouseenter",W),d.removeEventListener("mouseleave",D),v.removeEventListener("focus",W),v.removeEventListener("blur",D)}}return{button:v,wrapper:d}},Jf="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",gi=(n,e={})=>{var A,W,D,N,M,z,V,oe,Le,je,ve,Be,Oe;let{wrapperClassName:t=Jf,buttonSize:r,iconSize:o="20px"}=e,a=(W=((A=n==null?void 0:n.launcher)!=null?A:{}).clearChat)!=null?W:{},i=(D=r!=null?r:a.size)!=null?D:"32px",d=(N=a.iconName)!=null?N:"refresh-cw",c=(M=a.iconColor)!=null?M:"",g=(z=a.backgroundColor)!=null?z:"",f=(V=a.borderWidth)!=null?V:"",u=(oe=a.borderColor)!=null?oe:"",m=(Le=a.borderRadius)!=null?Le:"",v=(je=a.paddingX)!=null?je:"",x=(ve=a.paddingY)!=null?ve:"",E=(Be=a.tooltipText)!=null?Be:"Clear chat",k=(Oe=a.showTooltip)!=null?Oe:!0,L=b("div",t),F=!!(f||u),I=Lt("button",{className:Gs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!g&&"hover:persona-bg-gray-100",!F&&"persona-border-none",!m&&"persona-rounded-full"),attrs:{type:"button","aria-label":E},style:{height:i,width:i,color:c||Fn.actionIconColor,backgroundColor:g||void 0,border:F?`${f||"0px"} solid ${u||"transparent"}`:void 0,borderRadius:m||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:x||void 0,paddingBottom:x||void 0}}),R=Se(d,o,"currentColor",1);if(R&&(R.style.display="block",I.appendChild(R)),L.appendChild(I),k&&E){let Te=null,we=()=>{if(Te)return;let Q=I.ownerDocument,ae=Q.body;if(!ae)return;Te=Nr(Q,"div","persona-clear-chat-tooltip"),Te.textContent=E;let fe=Nr(Q,"div");fe.className="persona-clear-chat-tooltip-arrow",Te.appendChild(fe);let ue=I.getBoundingClientRect();Te.style.position="fixed",Te.style.zIndex=String(xo),Te.style.left=`${ue.left+ue.width/2}px`,Te.style.top=`${ue.top-8}px`,Te.style.transform="translate(-50%, -100%)",ae.appendChild(Te)},se=()=>{Te&&Te.parentNode&&(Te.parentNode.removeChild(Te),Te=null)};L.addEventListener("mouseenter",we),L.addEventListener("mouseleave",se),I.addEventListener("focus",we),I.addEventListener("blur",se),L._cleanupTooltip=()=>{se(),L.removeEventListener("mouseenter",we),L.removeEventListener("mouseleave",se),I.removeEventListener("focus",we),I.removeEventListener("blur",se)}}return{button:I,wrapper:L}};var Fn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},zo=n=>{var R,A,W,D,N,M,z,V,oe,Le,je,ve,Be,Oe,Te,we;let{config:e,showClose:t=!0}=n,r=Lt("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{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)))"}}),o=(R=e==null?void 0:e.launcher)!=null?R:{},s=(A=o.headerIconSize)!=null?A:"48px",a=(W=o.closeButtonPlacement)!=null?W:"inline",i=(D=o.headerIconHidden)!=null?D:!1,d=o.headerIconName,c=Lt("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(d){let se=parseFloat(s)||24,Q=Se(d,se*.6,"currentColor",1);Q?c.replaceChildren(Q):c.textContent=(M=(N=e==null?void 0:e.launcher)==null?void 0:N.agentIconText)!=null?M:"\u{1F4AC}"}else if((z=e==null?void 0:e.launcher)!=null&&z.iconUrl){let se=b("img");se.src=e.launcher.iconUrl,se.alt="",se.className="persona-rounded-xl persona-object-cover",se.style.height=s,se.style.width=s,c.replaceChildren(se)}else c.textContent=(oe=(V=e==null?void 0:e.launcher)==null?void 0:V.agentIconText)!=null?oe:"\u{1F4AC}";let g=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=Lt("span",{className:"persona-text-base persona-font-semibold",text:(je=(Le=e==null?void 0:e.launcher)==null?void 0:Le.title)!=null?je:"Chat Assistant",style:{color:Fn.titleColor}}),u=Lt("span",{className:"persona-text-xs",text:(Be=(ve=e==null?void 0:e.launcher)==null?void 0:ve.subtitle)!=null?Be:"Here to help you get answers fast",style:{color:Fn.subtitleColor}});g.append(f,u),i?r.append(g):r.append(c,g);let m=(Oe=o.clearChat)!=null?Oe:{},v=(Te=m.enabled)!=null?Te:!0,x=(we=m.placement)!=null?we:"inline",E=null,k=null;if(v){let Q=gi(e,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=Q.button,k=Q.wrapper,x==="top-right"&&(k.style.right="48px"),x==="inline"&&r.appendChild(k)}let L=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&x==="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:F,wrapper:I}=mi(e,{showClose:t,wrapperClassName:L});return a!=="top-right"&&r.appendChild(I),{header:r,iconHolder:c,headerTitle:f,headerSubtitle:u,closeButton:F,closeButtonWrapper:I,clearChatButton:E,clearChatButtonWrapper:k}},ma=(n,e,t)=>{var a,i,d,c;let r=(a=t==null?void 0:t.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";n.appendChild(e.header),o==="top-right"&&(n.style.position="relative",n.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(e.clearChatButtonWrapper))};function ws(n){let{items:e,onSelect:t,anchor:r,position:o="bottom-left",portal:s}=n,a=b("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(xo)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of e){if(m.dividerBefore){let E=document.createElement("hr");a.appendChild(E)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",m.id),m.destructive&&v.setAttribute("data-destructive",""),m.icon){let E=Se(m.icon,16,"currentColor",1.5);E&&v.appendChild(E)}let x=document.createElement("span");x.textContent=m.label,v.appendChild(x),v.addEventListener("click",E=>{E.stopPropagation(),g(),t(m.id)}),a.appendChild(v)}let i=null;function d(){if(!s)return;let m=r.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=v=>{!a.contains(v.target)&&!r.contains(v.target)&&g()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function g(){a.classList.add("persona-hidden"),i==null||i(),i=null}function f(){a.classList.contains("persona-hidden")?c():g()}function u(){g(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:g,toggle:f,destroy:u}}function kn(n){let{icon:e,label:t,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=n,d=b("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let c=Se(e,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[g,f]of Object.entries(i))d.setAttribute(g,f);return d}function il(n){let{icon:e,label:t,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=n,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+o,a&&(c+=" "+a);let g=b("button",c);if(g.type="button",g.setAttribute("aria-label",t),e){let u=Se(e,s!=null?s:14,"currentColor",2);u&&g.appendChild(u)}let f=b("span");if(f.textContent=t,g.appendChild(f),i&&g.addEventListener("click",i),d)for(let[u,m]of Object.entries(d))g.setAttribute(u,m);return g}function cm(n){var m,v;let{label:e,icon:t="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=n,c=b("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",e);let g=b("span","persona-combo-btn-label");g.textContent=e,c.appendChild(g);let f=Se(t,14,"currentColor",2);f&&(f.style.marginLeft="4px",f.style.opacity="0.6",c.appendChild(f)),d&&(c.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",c.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var x,E;c.style.backgroundColor=(x=d.background)!=null?x:"",c.style.borderColor=(E=d.border)!=null?E:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let u=ws({items:r,onSelect:x=>{c.setAttribute("aria-expanded","false"),o(x)},anchor:c,position:s,portal:a});return a||c.appendChild(u.element),c.addEventListener("click",x=>{x.stopPropagation();let E=!u.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",E?"false":"true"),u.toggle()}),c.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),c.click())}),{element:c,setLabel:x=>{g.textContent=x,c.setAttribute("aria-label",x)},open:()=>{c.setAttribute("aria-expanded","true"),u.show()},close:()=>{c.setAttribute("aria-expanded","false"),u.hide()},toggle:()=>{let x=!u.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",x?"false":"true"),u.toggle()},destroy:()=>{u.destroy(),c.remove()}}}var Yf=n=>{var r;let e=zo({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),t=(r=n.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(t){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>t()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),t())}))}return e};function Zf(n,e,t){var r,o,s;if(e!=null&&e.length)for(let a of e){let i=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=Se(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=b("div","persona-relative");d.appendChild(i);let c=ws({items:a.menuItems,onSelect:g=>t==null?void 0:t(g),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",g=>{g.stopPropagation(),c.toggle()}),n.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),n.appendChild(i)}}var eh=n=>{var L,F,I,R,A,W,D,N,M;let{config:e,showClose:t=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=n,a=(L=e==null?void 0:e.launcher)!=null?L:{},i=b("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,c,g;if(d)c=cm({label:(F=a.title)!=null?F:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=Fn.titleColor,g=(I=c.querySelector(".persona-combo-btn-label"))!=null?I:c;else{if(c=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),g=b("span","persona-text-base persona-font-semibold persona-truncate"),g.style.color=Fn.titleColor,g.textContent=(R=a.title)!=null?R:"Chat Assistant",c.appendChild(g),Zf(c,o==null?void 0:o.trailingActions,(A=o==null?void 0:o.onAction)!=null?A:s),o!=null&&o.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let V=o.onTitleClick;c.addEventListener("click",oe=>{oe.target.closest("button")||V()}),c.addEventListener("keydown",oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),V())})}let z=o==null?void 0:o.titleRowHover;z&&(c.style.borderRadius=(W=z.borderRadius)!=null?W:"10px",c.style.padding=(D=z.padding)!=null?D:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var V,oe;c.style.backgroundColor=(V=z.background)!=null?V:"",c.style.borderColor=(oe=z.border)!=null?oe:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let f=(N=a.closeButtonSize)!=null?N:"32px",u=b("div",""),m=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=f,m.style.width=f,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=t?"":"none",m.style.color=a.closeButtonColor||Fn.actionIconColor;let v=(M=a.closeButtonIconName)!=null?M:"x",x=Se(v,"28px","currentColor",1);x?m.appendChild(x):m.textContent="\xD7",r&&m.addEventListener("click",r),u.appendChild(m),i.appendChild(u);let E=b("div");E.style.display="none";let k=b("span");return k.style.display="none",{header:i,iconHolder:E,headerTitle:g,headerSubtitle:k,closeButton:m,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}},dm={default:Yf,minimal:eh},th=n=>{var e;return(e=dm[n])!=null?e:dm.default},fi=(n,e,t)=>{var a,i,d;if(e!=null&&e.render){let c=e.render({config:n,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),g=b("div");g.style.display="none";let f=b("span"),u=b("span"),m=b("button");m.style.display="none";let v=b("div");return v.style.display="none",{header:c,iconHolder:g,headerTitle:f,headerSubtitle:u,closeButton:m,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=e==null?void 0:e.layout)!=null?a:"default",s=th(r)({config:n,showClose:(d=(i=e==null?void 0:e.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:e,onHeaderAction:e==null?void 0:e.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var hi=n=>{var a,i;let e=b("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=(i=(a=n==null?void 0:n.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",e.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let t=3,r=20;e.style.maxHeight=`${t*r}px`,e.style.overflowY="auto";let o=()=>{let d=parseFloat(e.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*r},s=()=>{e.addEventListener("input",()=>{e.style.height="auto";let d=Math.min(e.scrollHeight,o());e.style.height=`${d}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:s}},yi=n=>{var R,A,W,D,N,M,z,V,oe,Le,je,ve;let e=(R=n==null?void 0:n.sendButton)!=null?R:{},t=(A=e.useIcon)!=null?A:!1,r=(W=e.iconText)!=null?W:"\u2191",o=e.iconName,s=(D=e.stopIconName)!=null?D:"square",a=(N=e.tooltipText)!=null?N:"Send message",i=(M=e.stopTooltipText)!=null?M:"Stop generating",d=(V=(z=n==null?void 0:n.copy)==null?void 0:z.sendButtonLabel)!=null?V:"Send",c=(Le=(oe=n==null?void 0:n.copy)==null?void 0:oe.stopButtonLabel)!=null?Le:"Stop",g=(je=e.showTooltip)!=null?je:!1,f=(ve=e.size)!=null?ve:"40px",u=e.backgroundColor,m=e.textColor,v=b("div","persona-send-button-wrapper"),x=Lt("button",{className:Gs("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",t?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",t&&!u&&"persona-bg-persona-primary",!t&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:t?f:void 0,height:t?f:void 0,minWidth:t?f:void 0,minHeight:t?f:void 0,fontSize:t?"18px":void 0,lineHeight:t?"1":void 0,color:t?m||"var(--persona-button-primary-fg, #ffffff)":m||void 0,backgroundColor:t&&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}}),E=null,k=null;if(t){let Be=parseFloat(f)||24,Oe=(m==null?void 0:m.trim())||"currentColor";o?(E=Se(o,Be,Oe,2),E?x.appendChild(E):x.textContent=r):x.textContent=r,k=Se(s,Be,Oe,2)}else x.textContent=d;let L=null;g&&a&&(L=b("div","persona-send-button-tooltip"),L.textContent=a,v.appendChild(L)),x.setAttribute("aria-label",a),v.appendChild(x);let F="send";return{button:x,wrapper:v,setMode:Be=>{if(Be===F)return;F=Be;let Oe=Be==="stop"?i:a;if(x.setAttribute("aria-label",Oe),L&&(L.textContent=Oe),t){if(E&&k){let Te=Be==="stop"?k:E;x.replaceChildren(Te)}}else x.textContent=Be==="stop"?c:d}}},bi=n=>{var L,F,I,R,A,W,D,N,M,z,V,oe;let e=(L=n==null?void 0:n.voiceRecognition)!=null?L:{};if(!(e.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((F=e.provider)==null?void 0:F.type)==="runtype";if(!(r||o))return null;let a=(R=(I=n==null?void 0:n.sendButton)==null?void 0:I.size)!=null?R:"40px",i=(A=e.iconName)!=null?A:"mic",d=(W=e.iconSize)!=null?W:a,c=parseFloat(d)||24,g=(N=e.backgroundColor)!=null?N:(D=n==null?void 0:n.sendButton)==null?void 0:D.backgroundColor,f=(z=e.iconColor)!=null?z:(M=n==null?void 0:n.sendButton)==null?void 0:M.textColor,u=b("div","persona-send-button-wrapper"),m=Lt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:f||"var(--persona-text, #111827)",backgroundColor:g||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}}),x=Se(i,c,f||"currentColor",1.5);x?m.appendChild(x):m.textContent="\u{1F3A4}",u.appendChild(m);let E=(V=e.tooltipText)!=null?V:"Start voice recognition";if(((oe=e.showTooltip)!=null?oe:!1)&&E){let Le=b("div","persona-send-button-tooltip");Le.textContent=E,u.appendChild(Le)}return{button:m,wrapper:u}},vi=n=>{var v,x,E,k,L,F,I,R;let e=(v=n==null?void 0:n.attachments)!=null?v:{};if(e.enabled!==!0)return null;let t=(E=(x=n==null?void 0:n.sendButton)==null?void 0:x.size)!=null?E:"40px",r=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let o=b("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=((k=e.allowedTypes)!=null?k:Qr).join(","),o.multiple=((L=e.maxFiles)!=null?L:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(F=e.buttonIconName)!=null?F:"paperclip",a=t,i=parseFloat(a)||40,d=Math.round(i*.6),c=b("div","persona-send-button-wrapper"),g=Lt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(I=e.buttonTooltipText)!=null?I:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});g.addEventListener("mouseenter",()=>{g.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),g.addEventListener("mouseleave",()=>{g.style.backgroundColor="transparent"});let f=Se(s,d,"currentColor",1.5);f?g.appendChild(f):g.textContent="\u{1F4CE}",g.addEventListener("click",A=>{A.preventDefault(),o.click()}),c.appendChild(g);let u=(R=e.buttonTooltipText)!=null?R:"Attach file",m=b("div","persona-send-button-tooltip");return m.textContent=u,c.appendChild(m),{button:g,wrapper:c,input:o,previewsContainer:r}},xi=n=>{var a,i,d;let e=(a=n==null?void 0:n.statusIndicator)!=null?a:{},t=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",r=b("div",`persona-mt-2 ${t} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=e.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=e.idleText)!=null?d:"Online";if(e.idleLink){let c=b("a");c.href=e.idleLink,c.target="_blank",c.rel="noopener noreferrer",c.textContent=s,c.style.color="inherit",c.style.textDecoration="none",r.appendChild(c)}else r.textContent=s;return r},wi=()=>Lt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Ci=n=>{var v,x,E,k,L,F;let{config:e}=n,t=Lt("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"}}),r=wi(),o=Lt("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=hi(e);a();let i=yi(e),d=bi(e),c=vi(e),g=xi(e);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let f=Lt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),u=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&u.append(c.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),f.append(u,m),o.append(f),o.addEventListener("click",I=>{I.target!==i.button&&I.target!==i.wrapper&&I.target!==(d==null?void 0:d.button)&&I.target!==(d==null?void 0:d.wrapper)&&I.target!==(c==null?void 0:c.button)&&I.target!==(c==null?void 0:c.wrapper)&&s.focus()}),t.append(r,o,g),{footer:t,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:g,attachmentButton:(E=c==null?void 0:c.button)!=null?E:null,attachmentButtonWrapper:(k=c==null?void 0:c.wrapper)!=null?k:null,attachmentInput:(L=c==null?void 0:c.input)!=null?L:null,attachmentPreviewsContainer:(F=c==null?void 0:c.previewsContainer)!=null?F:null,actionsRow:f,leftActions:u,rightActions:m,setSendButtonMode:i.setMode}};var pm=()=>{let n=Lt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=b("span","persona-pill-peek__icon"),t=Se("message-square",16,"currentColor",1.5);t&&e.appendChild(t);let r=b("span","persona-pill-peek__text"),o=b("span","persona-pill-peek__caret"),s=Se("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),n.append(e,r,o),{root:n,textNode:r}},um=n=>{var v,x,E,k,L,F;let{config:e}=n,t=Lt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=wi();r.style.display="none";let o=xi(e);o.style.display="none";let{textarea:s,attachAutoResize:a}=hi(e);s.style.maxHeight="100px",a();let i=yi(e),d=bi(e),c=vi(e);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let g=Lt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),f=b("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&f.append(c.wrapper);let u=b("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&u.append(d.wrapper),u.append(i.wrapper),g.addEventListener("click",I=>{I.target!==i.button&&I.target!==i.wrapper&&I.target!==(d==null?void 0:d.button)&&I.target!==(d==null?void 0:d.wrapper)&&I.target!==(c==null?void 0:c.button)&&I.target!==(c==null?void 0:c.wrapper)&&s.focus()}),c&&g.append(c.input),g.append(f,s,u),c&&t.append(c.previewsContainer),t.append(g,r,o);let m=g;return{footer:t,suggestions:r,composerForm:g,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:o,attachmentButton:(E=c==null?void 0:c.button)!=null?E:null,attachmentButtonWrapper:(k=c==null?void 0:c.wrapper)!=null?k:null,attachmentInput:(L=c==null?void 0:c.input)!=null?L:null,attachmentPreviewsContainer:(F=c==null?void 0:c.previewsContainer)!=null?F:null,actionsRow:m,leftActions:f,rightActions:u,setSendButtonMode:i.setMode}};var mm=n=>{var g,f,u,m,v,x,E,k,L,F,I,R,A,W,D,N,M;let e=(f=(g=n==null?void 0:n.launcher)==null?void 0:g.enabled)!=null?f:!0,t=Cn(n);if(ua(n)){let z=(m=(u=n==null?void 0:n.launcher)==null?void 0:u.composerBar)!=null?m:{},V=b("div","persona-widget-wrapper persona-fixed persona-transition");V.setAttribute("data-persona-composer-bar",""),V.dataset.state="collapsed",V.dataset.expandedSize=(v=z.expandedSize)!=null?v:"anchored",V.style.zIndex=String((E=(x=n==null?void 0:n.launcher)==null?void 0:x.zIndex)!=null?E:En);let oe=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");oe.style.width="100%",V.appendChild(oe);let Le=b("div","persona-widget-pill-root");return Le.setAttribute("data-persona-composer-bar",""),Le.dataset.state="collapsed",Le.dataset.expandedSize=(k=z.expandedSize)!=null?k:"anchored",Le.style.zIndex=String((F=(L=n==null?void 0:n.launcher)==null?void 0:L.zIndex)!=null?F:En),{wrapper:V,panel:oe,pillRoot:Le}}if(t){let z=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),V=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return z.appendChild(V),{wrapper:z,panel:V}}if(!e){let z=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),V=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),oe=(R=(I=n==null?void 0:n.launcher)==null?void 0:I.width)!=null?R:"100%";return z.style.width=oe,V.style.width="100%",z.appendChild(V),{wrapper:z,panel:V}}let o=(A=n==null?void 0:n.launcher)!=null?A:{},s=o.position&&wr[o.position]?wr[o.position]:wr["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((D=(W=n==null?void 0:n.launcher)==null?void 0:W.zIndex)!=null?D:En);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(M=(N=n==null?void 0:n.launcher)==null?void 0:N.width)!=null?M:n==null?void 0:n.launcherWidth,c=d!=null?d:Xr;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},nh=(n,e)=>{var I,R,A,W,D,N,M,z,V;let t=b("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");t.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:o}=mi(n,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(A=(R=(I=n==null?void 0:n.launcher)==null?void 0:I.clearChat)==null?void 0:R.enabled)!=null?A:!0,a=null,i=null;if(s){let oe=gi(n,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=oe.button,i=oe.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Lt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Lt("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"}});c.style.setProperty("scrollbar-gutter","stable");let g=Lt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(D=(W=n==null?void 0:n.copy)==null?void 0:W.welcomeTitle)!=null?D:"Hello \u{1F44B}"}),f=Lt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(M=(N=n==null?void 0:n.copy)==null?void 0:N.welcomeSubtitle)!=null?M:"Ask anything about your account or products."}),u=Lt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},g,f),m=b("div","persona-flex persona-flex-col persona-gap-3"),v=(z=n==null?void 0:n.layout)==null?void 0:z.contentMaxWidth;v&&(m.style.maxWidth=v,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((V=n==null?void 0:n.copy)==null?void 0:V.showWelcomeCard)!==!1||(u.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(u,m);let E=Lt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),k=um({config:n}),{root:L,textNode:F}=pm();return t.append(d,o,c,E),i&&t.appendChild(i),{container:t,body:c,messagesWrapper:m,composerOverlay:E,suggestions:k.suggestions,textarea:k.textarea,sendButton:k.sendButton,sendButtonWrapper:k.sendButtonWrapper,micButton:k.micButton,micButtonWrapper:k.micButtonWrapper,composerForm:k.composerForm,statusText:k.statusText,introTitle:g,introSubtitle:f,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:d,footer:k.footer,attachmentButton:k.attachmentButton,attachmentButtonWrapper:k.attachmentButtonWrapper,attachmentInput:k.attachmentInput,attachmentPreviewsContainer:k.attachmentPreviewsContainer,actionsRow:k.actionsRow,leftActions:k.leftActions,rightActions:k.rightActions,setSendButtonMode:k.setSendButtonMode,peekBanner:L,peekTextNode:F}},gm=(n,e=!0)=>{var E,k,L,F,I,R,A,W,D;if(ua(n))return nh(n,e);let t=Lt("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"}}),r=(E=n==null?void 0:n.layout)==null?void 0:E.header,o=((k=n==null?void 0:n.layout)==null?void 0:k.showHeader)!==!1,s=r?fi(n,r,{showClose:e}):zo({config:n,showClose:e}),a=Lt("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"}});a.style.setProperty("scrollbar-gutter","stable");let i=Lt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(F=(L=n==null?void 0:n.copy)==null?void 0:L.welcomeTitle)!=null?F:"Hello \u{1F44B}"}),d=Lt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(R=(I=n==null?void 0:n.copy)==null?void 0:I.welcomeSubtitle)!=null?R:"Ask anything about your account or products."}),c=Lt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:Cn(n)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),g=b("div","persona-flex persona-flex-col persona-gap-3"),f=(A=n==null?void 0:n.layout)==null?void 0:A.contentMaxWidth;f&&(g.style.maxWidth=f,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((W=n==null?void 0:n.copy)==null?void 0:W.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,g);let m=Ci({config:n}),v=((D=n==null?void 0:n.layout)==null?void 0:D.showFooter)!==!1;o?ma(t,s,n):(s.header.style.display="none",ma(t,s,n)),t.append(a);let x=Lt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return v||(m.footer.style.display="none"),t.append(m.footer),t.append(x),{container:t,body:a,messagesWrapper:g,composerOverlay:x,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:i,introSubtitle:d,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var ll=(n,e)=>{let t=b("button");t.type="button",t.innerHTML=`
18
+ <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>
19
+ <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
20
+ <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
21
+ <span class="persona-block persona-w-full persona-truncate persona-text-sm persona-font-semibold persona-text-persona-primary" data-role="launcher-title"></span>
22
+ <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
23
+ </span>
24
+ <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>
25
+ `,t.addEventListener("click",e);let r=s=>{var F,I,R,A,W,D,N,M,z,V,oe,Le,je;let a=(F=s.launcher)!=null?F:{},i=Cn(s),d=t.querySelector("[data-role='launcher-title']");if(d){let ve=(I=a.title)!=null?I:"Chat Assistant";d.textContent=ve,d.setAttribute("title",ve)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let ve=(R=a.subtitle)!=null?R:"Here to help you get answers fast";c.textContent=ve,c.setAttribute("title",ve)}let g=t.querySelector(".persona-flex-col");g&&(a.textHidden||i?g.style.display="none":g.style.display="");let f=t.querySelector("[data-role='launcher-icon']");if(f)if(a.agentIconHidden)f.style.display="none";else{let ve=(A=a.agentIconSize)!=null?A:"40px";if(f.style.height=ve,f.style.width=ve,f.innerHTML="",a.agentIconName){let Be=parseFloat(ve)||24,Oe=Se(a.agentIconName,Be*.6,"var(--persona-text-inverse, #ffffff)",2);Oe?(f.appendChild(Oe),f.style.display=""):(f.textContent=(W=a.agentIconText)!=null?W:"\u{1F4AC}",f.style.display="")}else a.iconUrl?f.style.display="none":(f.textContent=(D=a.agentIconText)!=null?D:"\u{1F4AC}",f.style.display="")}let u=t.querySelector("[data-role='launcher-image']");if(u){let ve=(N=a.agentIconSize)!=null?N:"40px";u.style.height=ve,u.style.width=ve,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(u.src=a.iconUrl,u.style.display="block"):u.style.display="none"}let m=t.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let ve=(M=a.callToActionIconSize)!=null?M:"32px";m.style.height=ve,m.style.width=ve,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let Be=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,Be=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let Oe=parseFloat(ve)||24,Te=Math.max(Oe-Be,8),we=Se(a.callToActionIconName,Te,"currentColor",2);we?m.appendChild(we):m.textContent=(z=a.callToActionIconText)!=null?z:"\u2197"}else m.textContent=(V=a.callToActionIconText)!=null?V:"\u2197"}let v=a.position&&wr[a.position]?wr[a.position]:wr["bottom-right"],x="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";t.className=i?E:`${x} ${v}`,i||(t.style.zIndex=String((oe=a.zIndex)!=null?oe:En));let k="1px solid var(--persona-border, #e5e7eb)",L="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(Le=a.border)!=null?Le:k,t.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:L,i?(t.style.width="0",t.style.minWidth="0",t.style.maxWidth="0",t.style.padding="0",t.style.overflow="hidden",t.style.border="none",t.style.boxShadow="none"):(t.style.width="",t.style.minWidth="",t.style.maxWidth=(je=a.collapsedMaxWidth)!=null?je:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},o=()=>{t.removeEventListener("click",e),t.remove()};return n&&r(n),{element:t,update:r,destroy:o}};var fm=({config:n,showClose:e})=>{let{wrapper:t,panel:r,pillRoot:o}=mm(n),s=gm(n,e),a={wrapper:t,panel:r,pillRoot:o},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},c={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:i,header:d,composer:c,replaceHeader:u=>(d.element.replaceWith(u.header),d.element=u.header,d.iconHolder=u.iconHolder,d.headerTitle=u.headerTitle,d.headerSubtitle=u.headerSubtitle,d.closeButton=u.closeButton,d.closeButtonWrapper=u.closeButtonWrapper,d.clearChatButton=u.clearChatButton,d.clearChatButtonWrapper=u.clearChatButtonWrapper,u),replaceComposer:u=>{c.footer.replaceWith(u),c.footer=u}}},cl=({config:n,plugins:e,onToggle:t})=>{let r=e.find(s=>s.renderLauncher);if(r!=null&&r.renderLauncher){let s=r.renderLauncher({config:n,defaultRenderer:()=>ll(n,t).element,onToggle:t});if(s)return{instance:null,element:s}}let o=ll(n,t);return{instance:o,element:o.element}};var rh=n=>{switch(n){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}},oh=(n,e)=>{if(!n)return null;let t=rh(n);if(t===null)return null;let r=e==null?void 0:e[n],o=r!==void 0?r:t;return o||null},sh=(n,e)=>{let t=b("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return t.setAttribute("data-stop-reason",n),t.setAttribute("role","note"),t.style.opacity="0.75",t.textContent=e,t},ah=n=>{let e=n.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(n)||e.startsWith("data:image/")||!n.includes(":"))},dl=n=>{let e=n.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(n)||e.startsWith("data:")||!n.includes(":"))},pl=320,ym=320,ih=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),lh=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),ch=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),dh=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),ph=(n,e,t)=>{if(n.length===0)return null;try{let r=b("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),e&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),t==null||t())};return n.forEach((i,d)=>{var f;let c=b("img");c.alt=((f=i.alt)==null?void 0:f.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${pl}px`,c.style.maxHeight=`${ym}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let g=!1;o+=1,c.addEventListener("error",()=>{g||(g=!0,o=Math.max(0,o-1),c.remove(),o===0&&a())}),c.addEventListener("load",()=>{g=!0}),ah(i.image)?(c.src=i.image,r.appendChild(c)):(g=!0,o=Math.max(0,o-1),c.remove())}),o===0?(a(),null):r}catch{return t==null||t(),null}},uh=n=>{if(n.length===0)return null;try{let e=b("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let t=0;return n.forEach(r=>{if(!dl(r.audio))return;let o=b("audio");o.controls=!0,o.preload="metadata",o.src=r.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${pl}px`,e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},mh=n=>{if(n.length===0)return null;try{let e=b("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let t=0;return n.forEach(r=>{if(!dl(r.video))return;let o=b("video");o.controls=!0,o.preload="metadata",o.src=r.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${pl}px`,o.style.maxHeight=`${ym}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},gh=n=>{if(n.length===0)return null;try{let e=b("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let t=0;return n.forEach(r=>{if(!dl(r.data))return;let o=b("a");o.href=r.data,o.download=r.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=r.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},ga=()=>{let n=document.createElement("div");n.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 t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",n.appendChild(e),n.appendChild(t),n.appendChild(r),n.appendChild(o),n},fh=(n,e,t)=>{let r={config:t!=null?t:{},streaming:!0,location:n,defaultRenderer:ga};if(e){let o=e(r);if(o!==null)return o}return ga()},hh=(n,e)=>{let t=b("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=e==="user"?n.userAvatar:n.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=b("img");o.src=r,o.alt=e==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(o)}else t.textContent=r,t.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=e==="user"?"U":"A",t.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},hm=(n,e,t="div")=>{let r=b(t,"persona-text-xs persona-text-persona-muted"),o=new Date(n.createdAt);return e.format?r.textContent=e.format(o):r.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},yh=(n,e="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(e){case"flat":n==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),n==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),n==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return t},bh=(n,e,t)=>{var v,x,E,k,L,F,I;let r=(v=e.showCopy)!=null?v:!0,o=(x=e.showUpvote)!=null?x:!0,s=(E=e.showDownvote)!=null?E:!0,a=(k=e.showReadAloud)!=null?k:!1;if(!r&&!o&&!s&&!a){let R=b("div");return R.style.display="none",R.id=`actions-${n.id}`,R.setAttribute("data-actions-for",n.id),R}let i=(L=e.visibility)!=null?L:"hover",d=(F=e.align)!=null?F:"right",c=(I=e.layout)!=null?I:"pill-inside",g={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],f={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],u=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${g} ${f} ${i==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${n.id}`,u.setAttribute("data-actions-for",n.id);let m=(R,A,W)=>{let D=kn({icon:R,label:A,size:14,className:"persona-message-action-btn"});return D.setAttribute("data-action",W),D};return r&&u.appendChild(m("copy","Copy message","copy")),a&&u.appendChild(m("volume-2","Read aloud","read-aloud")),o&&u.appendChild(m("thumbs-up","Upvote","upvote")),s&&u.appendChild(m("thumbs-down","Downvote","downvote")),u},ul=(n,e,t,r,o,s)=>{var se,Q,ae,fe,ue,K,ie,We,te,ee,re,it,lt,st,Ee,he,Je;let a=t!=null?t:{},i=(se=a.layout)!=null?se:"bubble",d=a.avatar,c=a.timestamp,g=(Q=d==null?void 0:d.show)!=null?Q:!1,f=(ae=c==null?void 0:c.show)!=null?ae:!1,u=(fe=d==null?void 0:d.position)!=null?fe:"left",m=(ue=c==null?void 0:c.position)!=null?ue:"below",v=yh(n.role,i),x=b("div",v.join(" "));x.id=`bubble-${n.id}`,x.setAttribute("data-message-id",n.id),x.setAttribute("data-persona-theme-zone",n.role==="user"?"user-message":"assistant-message"),n.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):n.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=ih(n),k=(ie=(K=n.content)==null?void 0:K.trim())!=null?ie:"",F=E.length>0&&k===Ja,I=di((te=(We=s==null?void 0:s.widgetConfig)==null?void 0:We.features)==null?void 0:te.streamAnimation),R=(it=(re=(ee=s==null?void 0:s.widgetConfig)==null?void 0:ee.features)==null?void 0:re.streamAnimation)==null?void 0:it.plugins,A=n.role==="assistant"&&I.type!=="none"?ia(I.type,R):null,W=n.role==="assistant"&&((lt=A==null?void 0:A.isAnimating)==null?void 0:lt.call(A,n))===!0,D=n.role==="assistant"&&A!==null&&(!!n.streaming||W);D&&(A!=null&&A.bubbleClass)&&x.classList.add(A.bubbleClass);let N=document.createElement("div");N.classList.add("persona-message-content"),D&&A&&(A.containerClass&&N.classList.add(A.containerClass),N.style.setProperty("--persona-stream-step",`${I.speed}ms`),N.style.setProperty("--persona-stream-duration",`${I.duration}ms`));let M=D?pi((st=n.content)!=null?st:"",I.buffer,A,n,!!n.streaming):(Ee=n.content)!=null?Ee:"",z=e({text:M,message:n,streaming:!!n.streaming,raw:n.rawContent}),V=z;D&&(A==null?void 0:A.wrap)==="char"?V=la(z,"char",n.id,{skipTags:A.skipTags}):D&&(A==null?void 0:A.wrap)==="word"&&(V=la(z,"word",n.id,{skipTags:A.skipTags}));let oe=null;if(F?(oe=document.createElement("div"),oe.innerHTML=V,oe.style.display="none",N.appendChild(oe)):N.innerHTML=V,D&&(A!=null&&A.useCaret)&&!F&&k){let Y=ui(),me=N.querySelectorAll(".persona-stream-char, .persona-stream-word"),ke=me[me.length-1];if(ke!=null&&ke.parentNode)ke.parentNode.insertBefore(Y,ke.nextSibling);else{let Ye=N.lastElementChild;Ye?Ye.appendChild(Y):N.appendChild(Y)}}if(f&&m==="inline"&&n.createdAt){let Y=hm(n,c,"span");Y.classList.add("persona-timestamp-inline");let me=N.lastElementChild;me?me.appendChild(Y):N.appendChild(Y)}if(E.length>0){let Y=ph(E,!F&&!!k,()=>{F&&oe&&(oe.style.display="")});Y?x.appendChild(Y):F&&oe&&(oe.style.display="")}let Le=lh(n);if(Le.length>0){let Y=uh(Le);Y&&x.appendChild(Y)}let je=ch(n);if(je.length>0){let Y=mh(je);Y&&x.appendChild(Y)}let ve=dh(n);if(ve.length>0){let Y=gh(ve);Y&&x.appendChild(Y)}if(x.appendChild(N),f&&m==="below"&&n.createdAt){let Y=hm(n,c);Y.classList.add("persona-mt-1"),x.appendChild(Y)}let Be=n.role==="assistant"?oh(n.stopReason,(Je=(he=s==null?void 0:s.widgetConfig)==null?void 0:he.copy)==null?void 0:Je.stopReasonNotice):null;if(n.streaming&&n.role==="assistant"){let Y=!!(M&&M.trim()),me=I.placeholder==="skeleton",ke=me&&I.buffer==="line"&&Y;if(Y)ke&&x.appendChild(ca());else if(me)x.appendChild(ca());else{let Ye=fh("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Ye&&x.appendChild(Ye)}}if(Be&&n.stopReason&&!n.streaming&&(k||(N.style.display="none"),x.appendChild(sh(n.stopReason,Be))),n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let Y=bh(n,r,o);x.appendChild(Y)}if(!g||n.role==="system")return x;let Te=b("div",`persona-flex persona-gap-2 ${n.role==="user"?"persona-flex-row-reverse":""}`),we=hh(d,n.role);return u==="right"||u==="left"&&n.role==="user"?Te.append(x,we):Te.append(we,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Te};var Cs=new Set,vh=(n,e)=>e==null?!1:typeof e=="string"?(n.textContent=e,!0):(n.appendChild(e),!0),xh=(n,e)=>{var r,o;let t=(o=(r=n.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return t?t.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
26
+ `):""},bm=(n,e)=>{let t=Cs.has(n),r=e.querySelector('button[data-expand-header="true"]'),o=e.querySelector(".persona-border-t"),s=e.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!o)return;r.setAttribute("aria-expanded",t?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let c=Se(t?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=t?"Hide":"Show"}o.style.display=t?"":"none",s&&(s.style.display=t?"none":s.textContent||s.childNodes.length?"":"none")},ml=(n,e)=>{var je,ve,Be,Oe,Te,we,se,Q,ae,fe,ue;let t=n.reasoning,r=b("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${n.id}`,r.setAttribute("data-message-id",n.id),!t)return r;let o=(ve=(je=e==null?void 0:e.features)==null?void 0:je.reasoningDisplay)!=null?ve:{},s=o.expandable!==!1,a=s&&Cs.has(n.id),i=t.status!=="complete",d=xh(n,(Be=o.previewMaxLines)!=null?Be:3),c=b("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");c.type="button",s&&(c.setAttribute("aria-expanded",a?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let g=b("div","persona-flex persona-flex-col persona-text-left"),f=b("span","persona-text-xs persona-text-persona-primary"),u="Thinking...",m=(Oe=e==null?void 0:e.reasoning)!=null?Oe:{},v=String((Te=t.startedAt)!=null?Te:Date.now()),x=()=>{let K=b("span","");return K.setAttribute("data-tool-elapsed",v),K.textContent=ja(t),K},E=(we=m.renderCollapsedSummary)==null?void 0:we.call(m,{message:n,reasoning:t,defaultSummary:u,previewText:d,isActive:i,config:e!=null?e:{},elapsed:ja(t),createElapsedElement:x});typeof E=="string"&&E.trim()?(f.textContent=E,g.appendChild(f)):E instanceof HTMLElement?g.appendChild(E):(f.textContent=u,g.appendChild(f));let k=b("span","persona-text-xs persona-text-persona-primary");k.textContent=vu(t),g.appendChild(k);let L=(se=o.loadingAnimation)!=null?se:"none",F=m.activeTextTemplate,I=m.completeTextTemplate,R=i?F:I,A=E instanceof HTMLElement,W=(K,ie,We)=>{let te=We;for(let ee of ie){let re=b("span","persona-tool-char");re.style.setProperty("--char-index",String(te)),re.textContent=ee===" "?"\xA0":ee,K.appendChild(re),te++}return te},D=(K,ie)=>{f.textContent="";let We=Ka(K,""),te=0;for(let ee of We){let re=ee.styles.length>0?(()=>{let it=b("span",ee.styles.map(lt=>`persona-tool-text-${lt}`).join(" "));return f.appendChild(it),it})():f;if(ee.isDuration&&i)re.appendChild(x());else{let it=ee.isDuration?ja(t):ee.text;ie?te=W(re,it,te):re.appendChild(document.createTextNode(it))}}};if(!A&&R)if(k.style.display="none",f.style.display="",i&&L!=="none"){let K=(Q=m.loadingAnimationDuration)!=null?Q:2e3;f.setAttribute("data-preserve-animation","true"),L==="pulse"?(f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`),D(R,!1)):(f.classList.add(`persona-tool-loading-${L}`),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`),L==="shimmer-color"&&(m.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),D(R,!0))}else D(R,!1);else if(!A&&i&&L!=="none"){f.style.display="";let K=(ae=m.loadingAnimationDuration)!=null?ae:2e3;if(f.setAttribute("data-preserve-animation","true"),L==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`);else{f.classList.add(`persona-tool-loading-${L}`),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`),L==="shimmer-color"&&(m.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let ie=f.textContent||u;f.textContent="",W(f,ie,0)}t.status==="complete"&&(f.style.display="none")}else A||(t.status==="complete"?f.style.display="none":f.style.display="");let N=null;if(s){N=b("div","persona-flex persona-items-center");let ie=Se(a?"chevron-up":"chevron-down",16,"currentColor",2);ie?N.appendChild(ie):N.textContent=a?"Hide":"Show";let We=b("div","persona-flex persona-items-center persona-ml-auto");We.append(N),c.append(g,We)}else c.append(g);let M=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(M.setAttribute("data-persona-collapsed-preview","reasoning"),M.style.display="none",M.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let K=(ue=(fe=e==null?void 0:e.reasoning)==null?void 0:fe.renderCollapsedPreview)==null?void 0:ue.call(fe,{message:n,reasoning:t,defaultPreview:d,isActive:i,config:e!=null?e:{}});vh(M,K)||(M.textContent=d),M.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(c,M),r;let z=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");z.style.display=a?"":"none";let V=t.chunks.join(""),oe=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return oe.textContent=V||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),z.appendChild(oe),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),N){N.innerHTML="";let ie=Se(a?"chevron-up":"chevron-down",16,"currentColor",2);ie?N.appendChild(ie):N.textContent=a?"Hide":"Show"}z.style.display=a?"":"none",M.style.display=a?"none":M.textContent||M.childNodes.length?"":"none"})(),r.append(c,M,z),r};var As=new Set,wh=(n,e)=>e==null?!1:typeof e=="string"?(n.textContent=e,!0):(n.appendChild(e),!0),Ch=(n,e)=>{var s;let t=n.toolCall;if(!t)return"";let r=((s=t.chunks)!=null?s:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-e).join(`
27
+ `);let o=fs(t.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,e).join(`
28
+ `):""},Ah=(n,e)=>{var g,f,u,m,v;let t=n.toolCall,r=(g=e==null?void 0:e.features)==null?void 0:g.toolCallDisplay,o=(f=r==null?void 0:r.collapsedMode)!=null?f:"tool-call",s=Ch(n,(u=r==null?void 0:r.previewMaxLines)!=null?u:3),a=t?xu(t):"";if(!t)return{summary:a,previewText:s,isActive:!1};let i=t.status!=="complete",d=(m=e==null?void 0:e.toolCall)!=null?m:{},c=a;return o==="tool-name"?c=((v=t.name)==null?void 0:v.trim())||a:o==="tool-preview"&&s&&(c=s),i&&d.activeTextTemplate?c=Gi(t,d.activeTextTemplate,c):!i&&d.completeTextTemplate&&(c=Gi(t,d.completeTextTemplate,c)),{summary:c,previewText:s,isActive:i}},vm=(n,e,t)=>{var g;let r=As.has(n),o=(g=t==null?void 0:t.toolCall)!=null?g:{},s=e.querySelector('button[data-expand-header="true"]'),a=e.querySelector(".persona-border-t"),i=e.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",r?"true":"false");let d=s.querySelector(".persona-ml-auto"),c=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let f=o.toggleTextColor||o.headerTextColor||"currentColor",u=Se(r?"chevron-up":"chevron-down",16,f,2);u?c.appendChild(u):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},gl=(n,e)=>{var V,oe,Le,je,ve,Be,Oe,Te,we;let t=n.toolCall,r=(V=e==null?void 0:e.toolCall)!=null?V:{},o=b("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${n.id}`,o.setAttribute("data-message-id",n.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),o.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!t)return o;let s=(Le=(oe=e==null?void 0:e.features)==null?void 0:oe.toolCallDisplay)!=null?Le:{},a=s.expandable!==!1,i=a&&As.has(n.id),{summary:d,previewText:c,isActive:g}=Ah(n,e),f=b("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");f.type="button",a&&(f.setAttribute("aria-expanded",i?"true":"false"),f.setAttribute("data-expand-header","true")),f.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(f.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(f.style.paddingLeft=r.headerPaddingX,f.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(f.style.paddingTop=r.headerPaddingY,f.style.paddingBottom=r.headerPaddingY);let u=b("div","persona-flex persona-flex-col persona-text-left"),m=b("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(m.style.color=r.headerTextColor);let v=String((je=t.startedAt)!=null?je:Date.now()),x=()=>{let se=b("span","");return se.setAttribute("data-tool-elapsed",v),se.textContent=Ys(t),se},E=(Be=r.renderCollapsedSummary)==null?void 0:Be.call(r,{message:n,toolCall:t,defaultSummary:d,previewText:c,collapsedMode:(ve=s.collapsedMode)!=null?ve:"tool-call",isActive:g,config:e!=null?e:{},elapsed:Ys(t),createElapsedElement:x});typeof E=="string"&&E.trim()?(m.textContent=E,u.appendChild(m)):E instanceof HTMLElement?u.appendChild(E):(m.textContent=d,u.appendChild(m));let k=(Oe=s.loadingAnimation)!=null?Oe:"none",L=r.activeTextTemplate,F=r.completeTextTemplate,I=g?L:F,R=E instanceof HTMLElement,A=(se,Q,ae)=>{let fe=ae;for(let ue of Q){let K=b("span","persona-tool-char");K.style.setProperty("--char-index",String(fe)),K.textContent=ue===" "?"\xA0":ue,se.appendChild(K),fe++}return fe},W=(se,Q)=>{var K;m.textContent="";let ae=((K=t.name)==null?void 0:K.trim())||"tool",fe=Ka(se,ae),ue=0;for(let ie of fe){let We=ie.styles.length>0?(()=>{let te=b("span",ie.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return m.appendChild(te),te})():m;if(ie.isDuration&&g)We.appendChild(x());else{let te=ie.isDuration?Ys(t):ie.text;Q?ue=A(We,te,ue):We.appendChild(document.createTextNode(te))}}};if(!R)if(g&&k!=="none"){let se=(Te=r.loadingAnimationDuration)!=null?Te:2e3;if(m.setAttribute("data-preserve-animation","true"),k==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${se}ms`),I&&W(I,!1);else if(m.classList.add(`persona-tool-loading-${k}`),m.style.setProperty("--persona-tool-anim-duration",`${se}ms`),k==="shimmer-color"&&(r.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),I)W(I,!0);else{let Q=m.textContent||d;m.textContent="",A(m,Q,0)}}else I&&W(I,!1);let D=null;if(a){D=b("div","persona-flex persona-items-center");let se=r.toggleTextColor||r.headerTextColor||"currentColor",Q=Se(i?"chevron-up":"chevron-down",16,se,2);Q?D.appendChild(Q):D.textContent=i?"Hide":"Show";let ae=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ae.append(D),f.append(u,ae)}else f.append(u);let N=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(N.setAttribute("data-persona-collapsed-preview","tool"),N.style.display="none",N.style.whiteSpace="pre-wrap",!i&&g&&s.activePreview&&c){let se=(we=r.renderCollapsedPreview)==null?void 0:we.call(r,{message:n,toolCall:t,defaultPreview:c,isActive:g,config:e!=null?e:{}});wh(N,se)||(N.textContent=c),N.style.display=""}if(!i&&g&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(f,N),o;let M=b("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=i?"":"none",r.contentBackgroundColor&&(M.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(M.style.color=r.contentTextColor),r.contentPaddingX&&(M.style.paddingLeft=r.contentPaddingX,M.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(M.style.paddingTop=r.contentPaddingY,M.style.paddingBottom=r.contentPaddingY),t.name){let se=b("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?se.style.color=r.contentTextColor:r.headerTextColor&&(se.style.color=r.headerTextColor),se.textContent=t.name,M.appendChild(se)}if(t.args!==void 0){let se=b("div","persona-space-y-1"),Q=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Q.style.color=r.labelTextColor),Q.textContent="Arguments";let ae=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(ae.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(ae.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(ae.style.color=r.codeBlockTextColor),ae.textContent=fs(t.args),se.append(Q,ae),M.appendChild(se)}if(t.chunks&&t.chunks.length){let se=b("div","persona-space-y-1"),Q=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Q.style.color=r.labelTextColor),Q.textContent="Activity";let ae=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(ae.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(ae.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(ae.style.color=r.codeBlockTextColor),ae.textContent=t.chunks.join(""),se.append(Q,ae),M.appendChild(se)}if(t.status==="complete"&&t.result!==void 0){let se=b("div","persona-space-y-1"),Q=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Q.style.color=r.labelTextColor),Q.textContent="Result";let ae=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(ae.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(ae.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(ae.style.color=r.codeBlockTextColor),ae.textContent=fs(t.result),se.append(Q,ae),M.appendChild(se)}if(t.status==="complete"&&typeof t.duration=="number"){let se=b("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(se.style.color=r.contentTextColor),se.textContent=`Duration: ${t.duration}ms`,M.appendChild(se)}return(()=>{if(f.setAttribute("aria-expanded",i?"true":"false"),D){D.innerHTML="";let se=r.toggleTextColor||r.headerTextColor||"currentColor",Q=Se(i?"chevron-up":"chevron-down",16,se,2);Q?D.appendChild(Q):D.textContent=i?"Hide":"Show"}M.style.display=i?"":"none",N.style.display=i?"none":N.textContent||N.childNodes.length?"":"none"})(),o.append(f,N,M),o};var Ai=new Map,Sh=n=>{let t=(n.startsWith(No)?n.slice(No.length):n).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(t.length===0)return n;let r=t.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},xm=n=>(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,wm=(n,e)=>{var r,o,s;let t=(o=(r=xm(e))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=Ai.get(n))!=null?s:t==="expanded"},Cm=(n,e,t)=>{var a,i;let r=xm(t);n.setAttribute("aria-expanded",e?"true":"false");let o=n.querySelector("[data-approval-details-label]");o&&(o.textContent=e?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let s=n.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=Se(e?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},Am=(n,e,t)=>{let r=e.querySelector('button[data-bubble-type="approval"]'),o=e.querySelector("[data-approval-details]");if(!r||!o)return;let s=wm(n,t);Cm(r,s,t),o.style.display=s?"":"none"};var Si=(n,e)=>{var W,D,N,M,z,V,oe,Le,je,ve,Be,Oe,Te,we,se;let t=n.approval,r=(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,o=(t==null?void 0:t.status)==="pending",s=b("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${n.id}`,s.setAttribute("data-message-id",n.id),s.style.backgroundColor=(W=r==null?void 0:r.backgroundColor)!=null?W:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(D=r==null?void 0:r.borderColor)!=null?D:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!t)return s;let a=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=b("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",c=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(N=r==null?void 0:r.titleColor)!=null?N:"currentColor",g=Se(d,20,c,2);g&&i.appendChild(g);let f=b("div","persona-flex-1 persona-min-w-0"),u=b("div","persona-flex persona-items-center persona-gap-2"),m=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(m.style.color=r.titleColor),m.textContent=(M=r==null?void 0:r.title)!=null?M:"Approval Required",u.appendChild(m),!o){let Q=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");Q.setAttribute("data-approval-status",t.status),t.status==="approved"?(Q.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",Q.style.color="var(--persona-palette-colors-success-700, #15803d)",Q.textContent="Approved"):t.status==="denied"?(Q.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",Q.style.color="var(--persona-palette-colors-error-700, #b91c1c)",Q.textContent="Denied"):t.status==="timeout"&&(Q.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",Q.style.color="var(--persona-palette-colors-warning-700, #b45309)",Q.textContent="Timeout"),u.appendChild(Q)}f.appendChild(u);let x=t.toolType==="webmcp"||t.toolName.startsWith(No)?Ni(t.toolName):void 0,E=(z=r==null?void 0:r.formatDescription)==null?void 0:z.call(r,{toolName:t.toolName,toolType:t.toolType,description:t.description,parameters:t.parameters,...x?{displayTitle:x}:{},...t.reason?{reason:t.reason}:{}}),k=!t.toolName,L=E||(k?t.description:`The assistant wants to use \u201C${x!=null?x:Sh(t.toolName)}\u201D.`),F=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(F.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(F.style.color=r.descriptionColor),F.textContent=L,f.appendChild(F),t.reason){let Q=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");Q.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?Q.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(Q.style.color=r.descriptionColor);let ae=b("span","persona-font-medium");ae.textContent=`${(V=r==null?void 0:r.reasonLabel)!=null?V:"Agent's stated reason:"} `,Q.appendChild(ae),Q.appendChild(document.createTextNode(t.reason)),f.appendChild(Q)}let I=(oe=r==null?void 0:r.detailsDisplay)!=null?oe:"collapsed",R=!!t.description&&!k,A=R||!!t.parameters;if(I!=="hidden"&&A){let Q=wm(n.id,e),ae=b("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");ae.type="button",ae.setAttribute("data-expand-header","true"),ae.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(ae.style.color=r.descriptionColor);let fe=b("span");fe.setAttribute("data-approval-details-label","true");let ue=b("span","persona-inline-flex persona-items-center");ue.setAttribute("data-approval-details-chevron","true"),ae.append(fe,ue),Cm(ae,Q,e),f.appendChild(ae);let K=b("div");if(K.setAttribute("data-approval-details","true"),K.style.display=Q?"":"none",R){let ie=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(ie.style.color=r.descriptionColor),ie.textContent=t.description,K.appendChild(ie)}if(t.parameters){let ie=b("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(ie.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(ie.style.color=r.parameterTextColor),ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",ie.textContent=fs(t.parameters),K.appendChild(ie)}f.appendChild(K)}if(o){let Q=b("div","persona-flex persona-gap-2 persona-mt-2");Q.setAttribute("data-approval-buttons","true");let ae=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");ae.type="button",ae.style.backgroundColor=(Le=r==null?void 0:r.approveButtonColor)!=null?Le:"var(--persona-approval-approve-bg, #22c55e)",ae.style.color=(je=r==null?void 0:r.approveButtonTextColor)!=null?je:"#ffffff",ae.setAttribute("data-approval-action","approve");let fe=Se("shield-check",14,(ve=r==null?void 0:r.approveButtonTextColor)!=null?ve:"#ffffff",2);fe&&(fe.style.marginRight="4px",ae.appendChild(fe));let ue=document.createTextNode((Be=r==null?void 0:r.approveLabel)!=null?Be:"Approve");ae.appendChild(ue);let K=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");K.type="button",K.style.backgroundColor=(Oe=r==null?void 0:r.denyButtonColor)!=null?Oe:"transparent",K.style.color=(Te=r==null?void 0:r.denyButtonTextColor)!=null?Te:"var(--persona-feedback-error, #dc2626)",K.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,K.setAttribute("data-approval-action","deny");let ie=Se("shield-x",14,(we=r==null?void 0:r.denyButtonTextColor)!=null?we:"var(--persona-feedback-error, #dc2626)",2);ie&&(ie.style.marginRight="4px",K.appendChild(ie));let We=document.createTextNode((se=r==null?void 0:r.denyLabel)!=null?se:"Deny");K.appendChild(We),Q.append(ae,K),f.appendChild(Q)}return a.append(i,f),s.appendChild(a),s};var Sm=n=>{let e=[],t=null;return{buttons:e,render:(o,s,a,i,d,c)=>{n.innerHTML="",e.length=0;let g=(c==null?void 0:c.agentPushed)===!0;if(g||(t=null),!o||!o.length||!g&&(i!=null?i:s?s.getMessages():[]).some(E=>E.role==="user"))return;let f=document.createDocumentFragment(),u=s?s.isStreaming():!1,m=v=>{switch(v){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(o.forEach(v=>{let x=b("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");x.type="button",x.textContent=v,x.disabled=u,d!=null&&d.fontFamily&&(x.style.fontFamily=m(d.fontFamily)),d!=null&&d.fontWeight&&(x.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(x.style.paddingLeft=d.paddingX,x.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(x.style.paddingTop=d.paddingY,x.style.paddingBottom=d.paddingY),x.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",g&&n.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:v},bubbles:!0,composed:!0})),s.sendMessage(v))}),f.appendChild(x),e.push(x)}),n.appendChild(f),g){let v=JSON.stringify(o);v!==t&&(t=v,n.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var fa=class{constructor(e=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=t}push(e){var t;this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),(t=this.store)==null||t.put(e)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let e=await this.store.getAll();if(e.length===0)return 0;let t=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let r of t)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=e.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let t=this.getAll();return e>=t.length?t:t.slice(t.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var e;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.clear()}destroy(){var e;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var ha=class{constructor(e="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=t}open(){return new Promise((e,t)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,e()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)r.put(o)}catch{}}getAll(){return new Promise((e,t)=>{if(!this.db){e([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{t(a.error)}}catch(r){t(r)}})}getCount(){return new Promise((e,t)=>{if(!this.db){e(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{t(s.error)}}catch(r){t(r)}})}clear(){return new Promise((e,t)=>{if(!this.db){e();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{e()},s.onerror=()=>{t(s.error)}}catch(r){t(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,t)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{e()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)r.put(o)}catch{}}};var Th=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Mh=new Set(["step_start","execution_start"]),Eh=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),kh=new Set(["step_complete","agent_turn_complete"]),Lh=new Set(["flow_complete","agent_complete"]),Tm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Em=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),tr=n=>typeof n=="number"&&Number.isFinite(n)?n:void 0,Vo=(n,e)=>{let t=n[e];return Em(t)?t:void 0};function fl(n){return n>0?Math.max(1,Math.ceil(n/4)):0}function Ti(n,e){if(!(n<=0||e===void 0||e<250))return n/(e/1e3)}function Ph(n,e){return typeof e.type=="string"?e.type:n}function Ih(n){return typeof n.text=="string"?n.text:typeof n.delta=="string"?n.delta:typeof n.content=="string"?n.content:typeof n.chunk=="string"?n.chunk:""}function Wh(n,e){return n==="step_delta"||n==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":n!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function Mm(n){var r,o,s,a,i;let e=Vo(n,"result"),t=[Vo(n,"tokens"),Vo(n,"totalTokens"),e?Vo(e,"tokens"):void 0,Vo(n,"usage"),e?Vo(e,"usage"):void 0];for(let d of t){if(!d)continue;let c=(o=(r=tr(d.output))!=null?r:tr(d.outputTokens))!=null?o:tr(d.completionTokens);if(c!==void 0)return c}return(i=(s=tr(n.outputTokens))!=null?s:tr(n.completionTokens))!=null?i:e?(a=tr(e.outputTokens))!=null?a:tr(e.completionTokens):void 0}function Rh(n){var t,r,o,s,a;let e=Vo(n,"result");return(a=(o=(r=(t=tr(n.executionTime))!=null?t:tr(n.executionTimeMs))!=null?r:tr(n.execution_time))!=null?o:tr(n.duration))!=null?a:e?(s=tr(e.executionTime))!=null?s:tr(e.executionTimeMs):void 0}function Hh(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ya=class{constructor(e=Hh){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let t=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:t,tokensPerSecond:Ti(this.metric.outputTokens,t)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,t){var s;if(!Em(t)){Tm.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=Ph(e,t),o=this.now();if(Th.has(r)){this.startRun(o);return}if(Mh.has(r)){this.run||this.startRun(o);return}if(Eh.has(r)){if(!Wh(r,t))return;let a=Ih(t);if(!a)return;this.run||this.startRun(o);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=o),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+fl(i.visibleCharCount),c=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ti(d,c),outputTokens:d,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(kh.has(r)){if(!this.run)return;let a=this.run,i=Mm(t);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+fl(a.visibleCharCount),g=this.resolveDuration(a,t,o);this.metric={status:"running",tokensPerSecond:Ti(c,g),outputTokens:c,durationMs:g,source:d?"usage":"estimate"};return}if(Lh.has(r)){if(!this.run)return;let a=this.run,i=Mm(t),d=i!=null?i:a.exactOutputTokens+fl(a.visibleCharCount),c=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",g=this.resolveDuration(a,t,o);this.metric={status:"complete",tokensPerSecond:Ti(d,g),outputTokens:d,durationMs:g,source:c},this.run=null;return}if(Tm.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,t,r){let o=e.firstDeltaAt!==void 0?r-e.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=Rh(t);return s!=null?s:r-e.startedAt}};function Ss(n,e){e&&e.split(/\s+/).forEach(t=>t&&n.classList.add(t))}var Bh={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},Dh={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Nh=["flowName","stepName","reasoningText","text","name","tool","toolName"],Fh=100;function Oh(n,e){let t={...Bh,...e};if(t[n])return t[n];for(let r of Object.keys(t))if(r.endsWith("_")&&n.startsWith(r))return t[r];return Dh}function _h(n,e){return`+${((n-e)/1e3).toFixed(3)}s`}function $h(n){let e=new Date(n),t=String(e.getHours()).padStart(2,"0"),r=String(e.getMinutes()).padStart(2,"0"),o=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${t}:${r}:${o}.${s}`}function Uh(n,e){try{let t=JSON.parse(n);if(typeof t!="object"||t===null)return null;for(let r of e){let o=r.split("."),s=t;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function qh(n){var e;return(e=navigator.clipboard)!=null&&e.writeText?navigator.clipboard.writeText(n):new Promise(t=>{let r=document.createElement("textarea");r.value=n,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),t()})}function zh(n){let e;try{e=JSON.parse(n.payload)}catch{e=n.payload}return JSON.stringify({type:n.type,timestamp:new Date(n.timestamp).toISOString(),payload:e},null,2)}function Vh(n){return n.tokensPerSecond===void 0||!Number.isFinite(n.tokensPerSecond)?"-- tok/s":`${n.tokensPerSecond.toFixed(1)} tok/s`}function jh(n){let e=[];return n.outputTokens!==void 0&&e.push(`${n.outputTokens.toLocaleString()} tok`),n.durationMs!==void 0&&e.push(`${(n.durationMs/1e3).toFixed(2)}s`),n.source&&e.push(n.source),e.join(" \xB7 ")}function Kh(n,e,t){let r,o;try{o=JSON.parse(n.payload),r=JSON.stringify(o,null,2)}catch{o=n.payload,r=n.payload}let s=e.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&t){let i=s.renderEventStreamPayload({event:n,config:t,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=b("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=b("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function hl(n,e,t,r,o,s,a,i){var u;let d=o.has(n.id),c=b("div","persona-border-b persona-border-persona-divider persona-text-xs");Ss(c,(u=r.classNames)==null?void 0:u.eventRow);let g=a.find(m=>m.renderEventStreamRow);if(g!=null&&g.renderEventStreamRow&&i){let m=g.renderEventStreamRow({event:n,index:e,config:i,defaultRenderer:()=>f(),isExpanded:d,onToggleExpand:()=>s(n.id)});if(m)return c.appendChild(m),c}return c.appendChild(f()),c;function f(){var V,oe;let m=b("div",""),v=b("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");v.setAttribute("data-event-id",n.id);let x=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),E=Se(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&x.appendChild(E);let k=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=(V=r.timestampFormat)!=null?V:"relative";k.textContent=L==="relative"?_h(n.timestamp,t):$h(n.timestamp);let F=null;r.showSequenceNumbers!==!1&&(F=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),F.textContent=String(e+1));let I=Oh(n.type,r.badgeColors),R=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");R.style.backgroundColor=I.bg,R.style.color=I.text,R.style.borderColor=I.text+"50",R.textContent=n.type;let A=(oe=r.descriptionFields)!=null?oe:Nh,W=Uh(n.payload,A),D=null;W&&(D=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),D.textContent=W);let N=b("div","persona-flex-1 persona-min-w-0"),M=b("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),z=Se("clipboard","12px","currentColor",1.5);return z&&M.appendChild(z),M.addEventListener("click",async Le=>{Le.stopPropagation(),await qh(zh(n)),M.innerHTML="";let je=Se("check","12px","currentColor",1.5);je&&M.appendChild(je),setTimeout(()=>{M.innerHTML="";let ve=Se("clipboard","12px","currentColor",1.5);ve&&M.appendChild(ve)},1500)}),v.appendChild(x),v.appendChild(k),F&&v.appendChild(F),v.appendChild(R),D&&v.appendChild(D),v.appendChild(N),v.appendChild(M),m.appendChild(v),d&&m.appendChild(Kh(n,a,i)),m}}function km(n){var v,x,E,k,L;let{buffer:e,getFullHistory:t,onClose:r,config:o,plugins:s=[],getThroughput:a}=n,i=(v=o==null?void 0:o.features)==null?void 0:v.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,c=(x=i==null?void 0:i.iconName)!=null?x:"arrow-down",g=(E=i==null?void 0:i.label)!=null?E:"",f=(L=(k=o==null?void 0:o.features)==null?void 0:k.eventStream)!=null?L:{},u=s.find(F=>F.renderEventStreamView);if(u!=null&&u.renderEventStreamView&&o){let F=u.renderEventStreamView({config:o,events:e.getAll(),defaultRenderer:()=>m().element,onClose:r});if(F)return{element:F,update:()=>{},destroy:()=>{}}}return m();function m(){let F=f.classNames,I=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ss(I,F==null?void 0:F.panel);let R=[],A="",W="",D=null,N=[],M={},z=0,V=ii(),oe=0,Le=0,je=!1,ve=null,Be=!1,Oe=0,Te=new Set,we=new Map,se="",Q="",ae=null,fe,ue,K,ie,We,te=null,ee=null,re=null;function it(){let ce=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),Ce=b("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");Ss(Ce,F==null?void 0:F.headerBar);let Fe=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Fe.textContent="Events",fe=b("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),fe.textContent="0",a){ee=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ee.style.cursor="help";let nr=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");nr.textContent="Throughput",te=b("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),te.textContent="-- tok/s",re=b("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),re.style.display="none",re.style.pointerEvents="none";let Pn=ee,an=re,On=()=>{if(!an.textContent)return;let xt=Pn.getBoundingClientRect(),zn=ce.getBoundingClientRect();an.style.left=`${xt.left-zn.left}px`,an.style.top=`${xt.bottom-zn.top+4}px`,an.style.display="block"},Ar=()=>{an.style.display="none"};ee.addEventListener("mouseenter",On),ee.addEventListener("mouseleave",Ar),ee.appendChild(nr),ee.appendChild(te)}let Tt=b("div","persona-flex-1");ue=b("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let on=b("option","");on.value="",on.textContent="All events",ue.appendChild(on),K=b("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),K.type="button",K.title="Copy All";let xn=Se("clipboard-copy","12px","currentColor",1.5);xn&&K.appendChild(xn);let Nt=b("span","persona-text-xs");Nt.textContent="Copy All",K.appendChild(Nt),Ce.appendChild(Fe),Ce.appendChild(fe),ee&&Ce.appendChild(ee),Ce.appendChild(Tt),Ce.appendChild(ue),Ce.appendChild(K);let rt=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ss(rt,F==null?void 0:F.searchBar);let Dt=Se("search","14px","var(--persona-muted, #9ca3af)",1.5),pt=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Dt&&pt.appendChild(Dt),ie=b("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Ss(ie,F==null?void 0:F.searchInput),ie.type="text",ie.placeholder="Search event payloads...",We=b("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),We.type="button",We.style.display="none";let Yt=Se("x","12px","currentColor",2);return Yt&&We.appendChild(Yt),rt.appendChild(pt),rt.appendChild(ie),rt.appendChild(We),ce.appendChild(Ce),ce.appendChild(rt),re&&ce.appendChild(re),ce}let lt,st=s.find(ce=>ce.renderEventStreamToolbar);if(st!=null&&st.renderEventStreamToolbar&&o){let ce=st.renderEventStreamToolbar({config:o,defaultRenderer:()=>it(),eventCount:e.getSize(),filteredCount:0,onFilterChange:Ce=>{A=Ce,Rt(),U()},onSearchChange:Ce=>{W=Ce,Rt(),U()}});lt=ce!=null?ce:it()}else lt=it();let Ee=b("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Ee.style.display="none";function he(){if(!a||!te||!ee)return;let ce=a();te.textContent=Vh(ce);let Ce=jh(ce);re&&(re.textContent=Ce,Ce||(re.style.display="none")),Ce?ee.setAttribute("aria-label",Ce):ee.removeAttribute("aria-label")}let Je=b("div","persona-flex-1 persona-min-h-0 persona-relative"),Y=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Y.style.height="100%";let me=b("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Ss(me,F==null?void 0:F.scrollIndicator),me.style.display="none",me.setAttribute("data-persona-scroll-to-bottom-has-label",g?"true":"false");let ke=Se(c,"14px","currentColor",2);ke&&me.appendChild(ke);let Ye=b("span","");Ye.textContent=g,me.appendChild(Ye);let Ge=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Ge.style.display="none",Je.appendChild(Y),Je.appendChild(Ge),Je.appendChild(me),I.setAttribute("tabindex","0"),I.appendChild(lt),I.appendChild(Ee),I.appendChild(Je);function Ie(){let ce=e.getAll(),Ce={};for(let Nt of ce)Ce[Nt.type]=(Ce[Nt.type]||0)+1;let Fe=Object.keys(Ce).sort(),Tt=Fe.length!==N.length||!Fe.every((Nt,rt)=>Nt===N[rt]),on=!Tt&&Fe.some(Nt=>Ce[Nt]!==M[Nt]),sn=ce.length!==Object.values(M).reduce((Nt,rt)=>Nt+rt,0);if(!Tt&&!on&&!sn||(N=Fe,M=Ce,!ue))return;let xn=ue.value;if(ue.options[0].textContent="All events",Tt){for(;ue.options.length>1;)ue.remove(1);for(let Nt of Fe){let rt=b("option","");rt.value=Nt,rt.textContent=`${Nt} (${Ce[Nt]||0})`,ue.appendChild(rt)}xn&&Fe.includes(xn)?ue.value=xn:xn&&(ue.value="",A="")}else for(let Nt=1;Nt<ue.options.length;Nt++){let rt=ue.options[Nt];rt.textContent=`${rt.value} (${Ce[rt.value]||0})`}}function Ke(){let ce=e.getAll();if(A&&(ce=ce.filter(Ce=>Ce.type===A)),W){let Ce=W.toLowerCase();ce=ce.filter(Fe=>Fe.type.toLowerCase().includes(Ce)||Fe.payload.toLowerCase().includes(Ce))}return ce}function vn(){return A!==""||W!==""}function Rt(){z=0,oe=0,V.resume(),me.style.display="none"}function pn(ce){Te.has(ce)?Te.delete(ce):Te.add(ce),ae=ce;let Ce=Y.scrollTop,Fe=V.isFollowing();Be=!0,V.pause(),U(),Y.scrollTop=Ce,Fe&&V.resume(),Be=!1}function Cr(){return qo(Y,50)}function U(){Le=Date.now(),je=!1,he(),Ie();let ce=e.getEvictedCount();ce>0?(Ee.textContent=`${ce.toLocaleString()} older events truncated`,Ee.style.display=""):Ee.style.display="none",R=Ke();let Ce=R.length,Fe=e.getSize()>0;fe&&(fe.textContent=String(e.getSize())),Ce===0&&Fe&&vn()?(Ge.textContent=W?`No events matching '${W}'`:"No events matching filter",Ge.style.display="",Y.style.display="none"):(Ge.style.display="none",Y.style.display=""),K&&(K.title=vn()?`Copy Filtered (${Ce})`:"Copy All"),d&&!V.isFollowing()&&Ce>z&&(oe+=Ce-z,Ye.textContent=g?`${g}${oe>0?` (${oe})`:""}`:"",me.style.display=""),z=Ce;let Tt=e.getAll(),on=Tt.length>0?Tt[0].timestamp:0,sn=new Set(R.map(rt=>rt.id));for(let rt of Te)sn.has(rt)||Te.delete(rt);let xn=A!==se||W!==Q,Nt=we.size===0&&R.length>0;if(xn||Nt||R.length===0){Y.innerHTML="",we.clear();let rt=document.createDocumentFragment();for(let Dt=0;Dt<R.length;Dt++){let pt=hl(R[Dt],Dt,on,f,Te,pn,s,o);we.set(R[Dt].id,pt),rt.appendChild(pt)}Y.appendChild(rt),se=A,Q=W,ae=null}else{if(ae!==null){let Dt=we.get(ae);if(Dt&&Dt.parentNode===Y){let pt=R.findIndex(Yt=>Yt.id===ae);if(pt>=0){let Yt=hl(R[pt],pt,on,f,Te,pn,s,o);Y.insertBefore(Yt,Dt),Dt.remove(),we.set(ae,Yt)}}ae=null}let rt=new Set(R.map(Dt=>Dt.id));for(let[Dt,pt]of we)rt.has(Dt)||(pt.remove(),we.delete(Dt));for(let Dt=0;Dt<R.length;Dt++){let pt=R[Dt];if(!we.has(pt.id)){let Yt=hl(pt,Dt,on,f,Te,pn,s,o);we.set(pt.id,Yt),Y.appendChild(Yt)}}}V.isFollowing()&&(Y.scrollTop=Y.scrollHeight)}function G(){if(Date.now()-Le>=Fh){ve!==null&&(cancelAnimationFrame(ve),ve=null),U();return}je||(je=!0,ve=requestAnimationFrame(()=>{ve=null,U()}))}let ye=(ce,Ce)=>{if(!K)return;K.innerHTML="";let Fe=Se(ce,"12px","currentColor",1.5);Fe&&K.appendChild(Fe);let Tt=b("span","persona-text-xs");Tt.textContent="Copy All",K.appendChild(Tt),setTimeout(()=>{K.innerHTML="";let on=Se("clipboard-copy","12px","currentColor",1.5);on&&K.appendChild(on);let sn=b("span","persona-text-xs");sn.textContent="Copy All",K.appendChild(sn),K.disabled=!1},Ce)},Qe=async()=>{if(K){K.disabled=!0;try{let ce;vn()?ce=R:t?(ce=await t(),ce.length===0&&(ce=e.getAll())):ce=e.getAll();let Ce=ce.map(Fe=>{try{return JSON.parse(Fe.payload)}catch{return Fe.payload}});await navigator.clipboard.writeText(JSON.stringify(Ce,null,2)),ye("check",1500)}catch{ye("x",1500)}}},et=()=>{ue&&(A=ue.value,Rt(),U())},Ue=()=>{!ie||!We||(We.style.display=ie.value?"":"none",D&&clearTimeout(D),D=setTimeout(()=>{W=ie.value,Rt(),U()},150))},_e=()=>{!ie||!We||(ie.value="",W="",We.style.display="none",D&&clearTimeout(D),Rt(),U())},Pt=()=>{if(Be)return;let ce=Y.scrollTop,{action:Ce,nextLastScrollTop:Fe}=li({following:V.isFollowing(),currentScrollTop:ce,lastScrollTop:Oe,nearBottom:Cr(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Oe=Fe,Ce==="resume"?(V.resume(),oe=0,me.style.display="none"):Ce==="pause"&&(V.pause(),d&&(Ye.textContent=g,me.style.display=""))},Kt=ce=>{let Ce=ci({following:V.isFollowing(),deltaY:ce.deltaY,nearBottom:Cr(),resumeWhenNearBottom:!0});Ce==="pause"?(V.pause(),d&&(Ye.textContent=g,me.style.display="")):Ce==="resume"&&(V.resume(),oe=0,me.style.display="none")},Jt=()=>{d&&(Y.scrollTop=Y.scrollHeight,V.resume(),oe=0,me.style.display="none")},Ln=ce=>{let Ce=ce.target;if(!Ce||Ce.closest("button"))return;let Fe=Ce.closest("[data-event-id]");if(!Fe)return;let Tt=Fe.getAttribute("data-event-id");Tt&&pn(Tt)},j=ce=>{if((ce.metaKey||ce.ctrlKey)&&ce.key==="f"){ce.preventDefault(),ie==null||ie.focus(),ie==null||ie.select();return}ce.key==="Escape"&&(ie&&document.activeElement===ie?(_e(),ie.blur(),I.focus()):r&&r())};K&&K.addEventListener("click",Qe),ue&&ue.addEventListener("change",et),ie&&ie.addEventListener("input",Ue),We&&We.addEventListener("click",_e),Y.addEventListener("scroll",Pt),Y.addEventListener("wheel",Kt,{passive:!0}),Y.addEventListener("click",Ln),me.addEventListener("click",Jt),I.addEventListener("keydown",j);function Ht(){D&&clearTimeout(D),ve!==null&&(cancelAnimationFrame(ve),ve=null),je=!1,we.clear(),K&&K.removeEventListener("click",Qe),ue&&ue.removeEventListener("change",et),ie&&ie.removeEventListener("input",Ue),We&&We.removeEventListener("click",_e),Y.removeEventListener("scroll",Pt),Y.removeEventListener("wheel",Kt),Y.removeEventListener("click",Ln),me.removeEventListener("click",Jt),I.removeEventListener("keydown",j)}return{element:I,update:G,destroy:Ht}}}function Lm(n,e){let t=typeof n.title=="string"&&n.title?n.title:"Untitled artifact",r=typeof n.artifactId=="string"?n.artifactId:"",o=n.status==="streaming"?"streaming":"complete",a=(typeof n.artifactType=="string"?n.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${t} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let g=document.createElement("div");g.className="persona-truncate persona-text-sm persona-font-medium",g.style.color="var(--persona-text, #1f2937)",g.textContent=t;let f=document.createElement("div");if(f.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",f.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let u=document.createElement("span");u.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",u.style.backgroundColor="var(--persona-primary, #171717)",u.style.animation="persona-pulse 1.5s ease-in-out infinite",f.appendChild(u);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,f.appendChild(m)}else f.textContent=a;if(c.append(g,f),i.append(d,c),o==="complete"){let u=document.createElement("button");u.type="button",u.textContent="Download",u.title=`Download ${t}`,u.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-text, #1f2937)",u.style.backgroundColor="transparent",u.style.cursor="pointer",u.setAttribute("data-download-artifact",r),i.append(u)}return i}var Pm=(n,e)=>{var r,o,s;let t=(s=(o=(r=e==null?void 0:e.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(t){let a=typeof n.title=="string"&&n.title?n.title:"Untitled artifact",i=typeof n.artifactId=="string"?n.artifactId:"",d=n.status==="streaming"?"streaming":"complete",c=typeof n.artifactType=="string"?n.artifactType:"markdown",g=t({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:e.config,defaultRenderer:()=>Lm(n,e)});if(g)return g}return Lm(n,e)};var yl=class{constructor(){this.components=new Map}register(e,t){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,t)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([t,r])=>{this.register(t,r)})}},jo=new yl;jo.register("PersonaArtifactCard",Pm);function Gh(n){var o;let e=b("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=b("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=n.component?`Component: ${n.component}`:"Component";let r=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((o=n.props)!=null?o:{},null,2),e.appendChild(t),e.appendChild(r),e}function Im(n,e){var ue,K,ie,We;let t=(K=(ue=n.features)==null?void 0:ue.artifacts)==null?void 0:K.layout,o=((ie=t==null?void 0:t.toolbarPreset)!=null?ie:"default")==="document",s=(We=t==null?void 0:t.panePadding)==null?void 0:We.trim(),a=n.markdown?Fa(n.markdown):null,i=Oa(n.sanitize),d=te=>{let ee=a?a(te):ho(te);return i?i(ee):ee},c=typeof document!="undefined"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,g=()=>{c==null||c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"),z==null||z.hide()};c&&c.addEventListener("click",()=>{var te;g(),(te=e.onDismiss)==null||te.call(e)});let f=b("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");f.setAttribute("data-persona-theme-zone","artifact-pane"),o&&f.classList.add("persona-artifact-pane-document");let u=b("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");u.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&u.classList.add("persona-artifact-toolbar-document");let m=b("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let v=b("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var te;g(),(te=e.onDismiss)==null||te.call(e)});let x="rendered",E=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),k=o?kn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):kn({icon:"eye",label:"Rendered view"}),L=o?kn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):kn({icon:"code-2",label:"Source"}),F=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),I=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,R=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,A=t==null?void 0:t.documentToolbarCopyMenuItems,W=!!(R&&A&&A.length>0),D=null,N,M=null,z=null;if(o&&(I||R)&&!W){if(N=I?il({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):kn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R){let te=Se("chevron-down",14,"currentColor",2);te&&N.appendChild(te)}}else o&&W?(D=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),N=I?il({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):kn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),M=kn({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),D.append(N,M)):o?N=kn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):N=kn({icon:"copy",label:"Copy"});let V=o?kn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):kn({icon:"refresh-cw",label:"Refresh"}),oe=o?kn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):kn({icon:"x",label:"Close"}),Le=()=>{var lt,st,Ee;let te=(lt=we.find(he=>he.id===se))!=null?lt:we[we.length-1],ee=(st=te==null?void 0:te.id)!=null?st:null,re=(te==null?void 0:te.artifactType)==="markdown"&&(Ee=te.markdown)!=null?Ee:"",it=te?JSON.stringify({component:te.component,props:te.props},null,2):"";return{markdown:re,jsonPayload:it,id:ee}},je=async()=>{var lt;let{markdown:te,jsonPayload:ee}=Le(),re=(lt=we.find(st=>st.id===se))!=null?lt:we[we.length-1],it=(re==null?void 0:re.artifactType)==="markdown"?te:re?ee:"";try{await navigator.clipboard.writeText(it)}catch{}};if(N.addEventListener("click",async()=>{let te=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(te&&W){let{markdown:ee,jsonPayload:re,id:it}=Le();try{await te({actionId:"primary",artifactId:it,markdown:ee,jsonPayload:re})}catch{}return}await je()}),M&&(A!=null&&A.length)){let te=()=>{var re;return(re=f.closest("[data-persona-root]"))!=null?re:document.body},ee=()=>{z=ws({items:A.map(re=>({id:re.id,label:re.label})),onSelect:async re=>{let{markdown:it,jsonPayload:lt,id:st}=Le(),Ee=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{Ee?await Ee({actionId:re,artifactId:st,markdown:it,jsonPayload:lt}):re==="markdown"||re==="md"?await navigator.clipboard.writeText(it):re==="json"||re==="source"?await navigator.clipboard.writeText(lt):await navigator.clipboard.writeText(it||lt)}catch{}},anchor:D!=null?D:M,position:"bottom-right",portal:te()})};f.isConnected?ee():requestAnimationFrame(ee),M.addEventListener("click",re=>{re.stopPropagation(),z==null||z.toggle()})}V.addEventListener("click",async()=>{var te;try{await((te=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:te.call(t))}catch{}ae()}),oe.addEventListener("click",()=>{var te;g(),(te=e.onDismiss)==null||te.call(e)});let ve=()=>{o&&(k.setAttribute("aria-pressed",x==="rendered"?"true":"false"),L.setAttribute("aria-pressed",x==="source"?"true":"false"))};k.addEventListener("click",()=>{x="rendered",ve(),ae()}),L.addEventListener("click",()=>{x="source",ve(),ae()});let Be=b("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(u.replaceChildren(),E.append(k,L),D?F.append(D,V,oe):F.append(N,V,oe),u.append(E,Be,F),ve()):(u.appendChild(m),u.appendChild(v)),s&&(u.style.paddingLeft=s,u.style.paddingRight=s);let Oe=b("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Te=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Oe.style.paddingLeft=s,Oe.style.paddingRight=s,Te.style.padding=s),f.appendChild(u),f.appendChild(Oe),f.appendChild(Te);let we=[],se=null,Q=!1,ae=()=>{var it,lt,st,Ee;let te=o&&we.length<=1;Oe.classList.toggle("persona-hidden",te),Oe.replaceChildren();for(let he of we){let Je=b("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");Je.type="button",Je.textContent=he.title||he.id.slice(0,8),he.id===se&&Je.classList.add("persona-bg-persona-container","persona-border-persona-border"),Je.addEventListener("click",()=>e.onSelect(he.id)),Oe.appendChild(Je)}Te.replaceChildren();let ee=se&&we.find(he=>he.id===se)||we[we.length-1];if(!ee)return;if(o){let he=ee.artifactType==="markdown"?"MD":(it=ee.component)!=null?it:"Component",Y=(ee.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Be.textContent=`${Y} \xB7 ${he}`}else m.textContent="Artifacts";if(ee.artifactType==="markdown"){if(o&&x==="source"){let Je=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Je.textContent=(lt=ee.markdown)!=null?lt:"",Te.appendChild(Je);return}let he=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");he.innerHTML=d((st=ee.markdown)!=null?st:""),Te.appendChild(he);return}let re=ee.component?jo.get(ee.component):void 0;if(re){let Je={message:{id:ee.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Y=re((Ee=ee.props)!=null?Ee:{},Je);if(Y){Te.appendChild(Y);return}}catch{}}Te.appendChild(Gh(ee))},fe=()=>{var ee;let te=we.length>0;if(f.classList.toggle("persona-hidden",!te),c){let re=typeof f.closest=="function"?f.closest("[data-persona-root]"):null,lt=((ee=re==null?void 0:re.classList.contains("persona-artifact-narrow-host"))!=null?ee:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;te&&lt&&Q?(c.classList.remove("persona-hidden"),f.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"))}};return{element:f,backdrop:c,update(te){var ee,re,it;we=te.artifacts,se=(it=(re=te.selectedId)!=null?re:(ee=te.artifacts[te.artifacts.length-1])==null?void 0:ee.id)!=null?it:null,we.length>0&&(Q=!0),ae(),fe()},setMobileOpen(te){Q=te,!te&&c?(c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open")):fe()}}}function ur(n){var e,t;return((t=(e=n==null?void 0:n.features)==null?void 0:e.artifacts)==null?void 0:t.enabled)===!0}function Wm(n,e){var s,a,i,d;if(n.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),n.style.removeProperty("--persona-artifact-pane-border"),n.style.removeProperty("--persona-artifact-pane-border-left"),!ur(e))return;let t=(a=(s=e.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),o=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();r?(n.classList.add("persona-artifact-border-full"),n.style.setProperty("--persona-artifact-pane-border",r)):o&&(n.classList.add("persona-artifact-border-left"),n.style.setProperty("--persona-artifact-pane-border-left",o))}function Qh(n){n.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),n.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),n.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function Mi(n,e){var d,c,g,f,u,m,v,x,E,k;if(!ur(e)){n.style.removeProperty("--persona-artifact-split-gap"),n.style.removeProperty("--persona-artifact-pane-width"),n.style.removeProperty("--persona-artifact-pane-max-width"),n.style.removeProperty("--persona-artifact-pane-min-width"),n.style.removeProperty("--persona-artifact-pane-bg"),n.style.removeProperty("--persona-artifact-pane-padding"),Qh(n),Wm(n,e);return}let t=(c=(d=e.features)==null?void 0:d.artifacts)==null?void 0:c.layout;n.style.setProperty("--persona-artifact-split-gap",(g=t==null?void 0:t.splitGap)!=null?g:"0.5rem"),n.style.setProperty("--persona-artifact-pane-width",(f=t==null?void 0:t.paneWidth)!=null?f:"40%"),n.style.setProperty("--persona-artifact-pane-max-width",(u=t==null?void 0:t.paneMaxWidth)!=null?u:"28rem"),t!=null&&t.paneMinWidth?n.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):n.style.removeProperty("--persona-artifact-pane-min-width");let r=(m=t==null?void 0:t.paneBackground)==null?void 0:m.trim();r?n.style.setProperty("--persona-artifact-pane-bg",r):n.style.removeProperty("--persona-artifact-pane-bg");let o=(v=t==null?void 0:t.panePadding)==null?void 0:v.trim();o?n.style.setProperty("--persona-artifact-pane-padding",o):n.style.removeProperty("--persona-artifact-pane-padding");let s=(x=t==null?void 0:t.documentToolbarIconColor)==null?void 0:x.trim();s?n.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):n.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(E=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:E.trim();a?n.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):n.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(k=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:k.trim();i?n.style.setProperty("--persona-artifact-doc-toggle-active-border",i):n.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Wm(n,e)}var Rm=["panel","seamless"];function Ei(n,e){var i,d,c,g,f,u;for(let m of Rm)n.classList.remove(`persona-artifact-appearance-${m}`);if(n.classList.remove("persona-artifact-unified-split"),n.style.removeProperty("--persona-artifact-pane-radius"),n.style.removeProperty("--persona-artifact-pane-shadow"),n.style.removeProperty("--persona-artifact-unified-outer-radius"),!ur(e))return;let t=(d=(i=e.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",o=Rm.includes(r)?r:"panel";n.classList.add(`persona-artifact-appearance-${o}`);let s=(g=t==null?void 0:t.paneBorderRadius)==null?void 0:g.trim();s&&n.style.setProperty("--persona-artifact-pane-radius",s);let a=(f=t==null?void 0:t.paneShadow)==null?void 0:f.trim();if(a&&n.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){n.classList.add("persona-artifact-unified-split");let m=((u=t.unifiedSplitOuterRadius)==null?void 0:u.trim())||s;m&&n.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Hm(n,e){var t,r,o;return!e||!ur(n)?!1:((o=(r=(t=n.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function Xh(n,e){if(!(n!=null&&n.trim()))return e;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(n.trim());return t?Math.max(0,Number(t[1])):e}function Jh(n){if(!(n!=null&&n.trim()))return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(n.trim());return e?Math.max(0,Number(e[1])):null}function Yh(n,e,t){return t<e?e:Math.min(t,Math.max(e,n))}function Zh(n,e,t,r){let o=n-r-2*e-t;return Math.max(0,o)}function Bm(n,e){var a;let r=(a=(e.getComputedStyle(n).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(r);return s?Number(s[1]):8}function Dm(n,e,t,r,o,s){let a=Xh(o,200),i=Zh(e,t,r,200);i=Math.max(a,i);let d=Jh(s);return d!==null&&(i=Math.min(i,d)),Yh(n,a,i)}var Nm={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},bl=(n,e,t,r)=>{let o=n.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var v,x,E;if(s.dataset.enhanced==="true")return;let a=(v=s.dataset.tvForm)!=null?v:"init";s.dataset.enhanced="true";let i=(x=Nm[a])!=null?x:Nm.init;s.classList.add("persona-form-card","persona-space-y-4");let d=b("div","persona-space-y-1"),c=b("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let k=b("p","persona-text-sm persona-text-persona-muted");k.textContent=i.description,d.appendChild(k)}let g=document.createElement("form");g.className="persona-form-grid persona-space-y-3",i.fields.forEach(k=>{var A,W;let L=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");L.htmlFor=`${e.id}-${a}-${k.name}`;let F=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");F.textContent=k.label,L.appendChild(F);let I=(A=k.type)!=null?A:"text",R;I==="textarea"?(R=document.createElement("textarea"),R.rows=3):(R=document.createElement("input"),R.type=I),R.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",R.id=`${e.id}-${a}-${k.name}`,R.name=k.name,R.placeholder=(W=k.placeholder)!=null?W:"",k.required&&(R.required=!0),L.appendChild(R),g.appendChild(L)});let f=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),u=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=b("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(E=i.submitLabel)!=null?E:"Submit",f.appendChild(u),f.appendChild(m),g.appendChild(f),s.replaceChildren(d,g),g.addEventListener("submit",async k=>{var R,A;k.preventDefault();let L=(R=t.formEndpoint)!=null?R:"/form",F=new FormData(g),I={};F.forEach((W,D)=>{I[D]=W}),I.type=a,m.disabled=!0,u.textContent="Submitting\u2026";try{let W=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(I)});if(!W.ok)throw new Error(`Form submission failed (${W.status})`);let D=await W.json();u.textContent=(A=D.message)!=null?A:"Thanks! We'll be in touch soon.",D.success&&D.nextPrompt&&await r.sendMessage(String(D.nextPrompt))}catch(W){u.textContent=W instanceof Error?W.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var vl=class{constructor(){this.plugins=new Map}register(e){var t;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(t=e.onRegister)==null||t.call(e)}unregister(e){var r;let t=this.plugins.get(e);t&&((r=t.onUnregister)==null||r.call(t),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,t)=>{var r,o;return((r=t.priority)!=null?r:0)-((o=e.priority)!=null?o:0)})}getForInstance(e){let t=this.getAll();if(!e||e.length===0)return t;let r=new Set(e.map(s=>s.id));return[...t.filter(s=>!r.has(s.id)),...e].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(e=>{var t;return(t=e.onUnregister)==null?void 0:t.call(e)}),this.plugins.clear()}},xl=new vl;var Fm=()=>{let n=new Map,e=(o,s)=>(n.has(o)||n.set(o,new Set),n.get(o).add(s),()=>t(o,s)),t=(o,s)=>{var a;(a=n.get(o))==null||a.delete(s)};return{on:e,off:t,emit:(o,s)=>{var a;(a=n.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var ey=n=>{let e=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:n},ty=n=>{let e=n.trim(),t=e.indexOf("{");if(t===-1)return null;let r=0;for(let o=t;o<e.length;o+=1){let s=e[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return e.slice(t,o+1)}return null},Cl=({text:n})=>{if(!n||!n.includes("{"))return null;try{let e=ey(n),t=ty(e);if(!t)return null;let r=JSON.parse(t);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},wl=n=>typeof n=="string"?n:n==null?"":String(n),ba={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:wl(n.payload.text)},messageAndClick:(n,e)=>{var o;if(n.type!=="message_and_click")return;let t=n.payload,r=wl(t.element);if(r&&((o=e.document)!=null&&o.querySelector)){let s=e.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:wl(t.text)}}},Om=n=>Array.isArray(n)?n.map(e=>String(e)):[],Al=n=>{let e=new Set(Om(n.getSessionMetadata().processedActionMessageIds)),t=()=>{e=new Set(Om(n.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(e);n.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?n.parsers.reduce((c,g)=>c||(g==null?void 0:g({text:a,message:s.message}))||null,null):null;if(!i)return null;e.add(s.message.id),r();let d={action:i,message:s.message};n.emit("action:detected",d);for(let c of n.handlers)if(c)try{let g=()=>{n.emit("action:resubmit",d)},f=c(i,{message:s.message,metadata:n.getSessionMetadata(),updateMetadata:n.updateSessionMetadata,document:n.documentRef,triggerResubmit:g});if(!f)continue;if(f.handled){let u=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:u,resubmit:f.resubmit}}}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",g)}return{text:"",persist:!0}},syncFromMetadata:t}};var ny=n=>{if(!n)return null;try{return JSON.parse(n)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},ry=n=>n.map(e=>({...e,streaming:!1})),oy=n=>n.map(e=>({...e,status:"complete"})),_m=(n="persona-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=e();return t?ny(t.getItem(n)):null},save:t=>{let r=e();if(r)try{let o={...t,messages:t.messages?ry(t.messages):void 0,artifacts:t.artifacts?oy(t.artifacts):void 0};r.setItem(n,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let t=e();if(t)try{t.removeItem(n)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};var Sl=require("partial-json");function $m(n,e){let{config:t,message:r,onPropsUpdate:o}=e,s=jo.get(n.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${n.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:t,updateProps:i=>{o&&o(i)}};try{return s(n.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,i),null}}function Um(n){if(typeof n.rawContent=="string"&&n.rawContent.length>0)return n.rawContent;if(typeof n.content=="string"){let e=n.content.trim();if(e.startsWith("{")||e.startsWith("["))return n.content}return null}function qm(n){let e=Um(n);if(!e)return!1;try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function zm(n){let e=Um(n);if(!e)return null;try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"){let r=t;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:e}}}catch{}return null}var sy=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Vm(n){let{onSubmit:e,onDismiss:t,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=sy}=n,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-csat",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Customer satisfaction feedback");let f=null,u=document.createElement("div");u.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,m.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=o,m.appendChild(x),u.appendChild(m);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let k=[];for(let A=1;A<=5;A++){let W=document.createElement("button");W.type="button",W.className="persona-feedback-rating-btn persona-feedback-star-btn",W.setAttribute("role","radio"),W.setAttribute("aria-checked","false"),W.setAttribute("aria-label",`${A} star${A>1?"s":""}: ${c[A-1]}`),W.title=c[A-1],W.dataset.rating=String(A),W.innerHTML=`
29
+ <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
30
+ <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>
31
+ </svg>
32
+ `,W.addEventListener("click",()=>{f=A,k.forEach((D,N)=>{let M=N<A;D.classList.toggle("selected",M),D.setAttribute("aria-checked",N===A-1?"true":"false")})}),k.push(W),E.appendChild(W)}u.appendChild(E);let L=null;if(d){let A=document.createElement("div");A.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),A.appendChild(L),u.appendChild(A)}let F=document.createElement("div");F.className="persona-feedback-actions";let I=document.createElement("button");I.type="button",I.className="persona-feedback-btn persona-feedback-btn-skip",I.textContent=i,I.addEventListener("click",()=>{t==null||t(),g.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=a,R.addEventListener("click",async()=>{if(f===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let A=(L==null?void 0:L.value.trim())||void 0;await e(f,A),g.remove()}catch(A){R.disabled=!1,R.textContent=a,console.error("[CSAT Feedback] Failed to submit:",A)}}),F.appendChild(I),F.appendChild(R),u.appendChild(F),g.appendChild(u),g}function jm(n){let{onSubmit:e,onDismiss:t,title:r="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:g="Very likely"}=n,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-nps",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Net Promoter Score feedback");let u=null,m=document.createElement("div");m.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,v.appendChild(x);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=o,v.appendChild(E),m.appendChild(v);let k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-nps",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Likelihood rating from 0 to 10");let L=document.createElement("div");L.className="persona-feedback-labels";let F=document.createElement("span");F.className="persona-feedback-label-low",F.textContent=c;let I=document.createElement("span");I.className="persona-feedback-label-high",I.textContent=g,L.appendChild(F),L.appendChild(I);let R=document.createElement("div");R.className="persona-feedback-numbers";let A=[];for(let z=0;z<=10;z++){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 ${z} out of 10`),V.textContent=String(z),V.dataset.rating=String(z),z<=6?V.classList.add("persona-feedback-detractor"):z<=8?V.classList.add("persona-feedback-passive"):V.classList.add("persona-feedback-promoter"),V.addEventListener("click",()=>{u=z,A.forEach((oe,Le)=>{oe.classList.toggle("selected",Le===z),oe.setAttribute("aria-checked",Le===z?"true":"false")})}),A.push(V),R.appendChild(V)}k.appendChild(L),k.appendChild(R),m.appendChild(k);let W=null;if(d){let z=document.createElement("div");z.className="persona-feedback-comment-container",W=document.createElement("textarea"),W.className="persona-feedback-comment",W.placeholder=s,W.rows=3,W.setAttribute("aria-label","Additional comments"),z.appendChild(W),m.appendChild(z)}let D=document.createElement("div");D.className="persona-feedback-actions";let N=document.createElement("button");N.type="button",N.className="persona-feedback-btn persona-feedback-btn-skip",N.textContent=i,N.addEventListener("click",()=>{t==null||t(),f.remove()});let M=document.createElement("button");return M.type="button",M.className="persona-feedback-btn persona-feedback-btn-submit",M.textContent=a,M.addEventListener("click",async()=>{if(u===null){R.classList.add("persona-feedback-shake"),setTimeout(()=>R.classList.remove("persona-feedback-shake"),500);return}M.disabled=!0,M.textContent="Submitting...";try{let z=(W==null?void 0:W.value.trim())||void 0;await e(u,z),f.remove()}catch(z){M.disabled=!1,M.textContent=a,console.error("[NPS Feedback] Failed to submit:",z)}}),D.appendChild(N),D.appendChild(M),m.appendChild(D),f.appendChild(m),f}var Ts="persona-chat-history",ay=30*1e3,iy={"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 ly(n){var r,o,s;if(!n)return[];let e=[],t=Array.from((r=n.items)!=null?r:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){e.push(i);continue}let d=(o=iy[i.type])!=null?o:"png";e.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let a of Array.from((s=n.files)!=null?s:[]))a.type.startsWith("image/")&&e.push(a);return e}function ki(n){if(!n)return!1;let e=n.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function cy(n){var e,t,r,o,s,a,i,d,c;return n?n===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(e=n.storage)!=null?e:"session",keyPrefix:(t=n.keyPrefix)!=null?t:"persona-",persist:{openState:(o=(r=n.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=n.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=n.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=n.clearOnChatClear)!=null?c:!0}:null}function dy(n){try{let e=n==="local"?localStorage:sessionStorage,t="__persist_test__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}var Tl=n=>!n||typeof n!="object"?{}:{...n},Km=n=>n.map(e=>({...e,streaming:!1})),Gm=(n,e,t)=>{let r=n!=null&&n.markdown?Fa(n.markdown):null,o=Oa(n==null?void 0:n.sanitize);return n!=null&&n.postprocessMessage&&o&&(n==null?void 0:n.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var c,g,f;let a=(c=s.text)!=null?c:"",i=(g=s.message.rawContent)!=null?g:null;if(e){let u=e.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});u!==null&&(a=u.text,u.persist||(s.message.__skipPersist=!0),u.resubmit&&!s.streaming&&t&&t())}let d;return n!=null&&n.postprocessMessage?d=n.postprocessMessage({...s,text:a,raw:(f=i!=null?i:s.text)!=null?f:""}):r?d=r(a):d=ho(a),o?o(d):d}};function Qm(n){var i,d,c,g;let e=b("div","persona-attachment-drop-overlay");n!=null&&n.background&&e.style.setProperty("--persona-drop-overlay-bg",n.background),(n==null?void 0:n.backdropBlur)!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",n.backdropBlur),n!=null&&n.border&&e.style.setProperty("--persona-drop-overlay-border",n.border),n!=null&&n.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",n.borderRadius),n!=null&&n.inset&&e.style.setProperty("--persona-drop-overlay-inset",n.inset),n!=null&&n.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",n.labelSize),n!=null&&n.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",n.labelColor);let t=(i=n==null?void 0:n.iconName)!=null?i:"upload",r=(d=n==null?void 0:n.iconSize)!=null?d:"48px",o=(c=n==null?void 0:n.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",s=(g=n==null?void 0:n.iconStrokeWidth)!=null?g:.5,a=Se(t,r,o,s);if(a&&e.appendChild(a),n!=null&&n.label){let f=b("span","persona-drop-overlay-label");f.textContent=n.label,e.appendChild(f)}return e}var Xm=(n,e,t)=>{var Xl,Jl,Yl,Zl,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,vc,xc,wc,Cc,Ac,Sc,Tc,Mc,Ec,kc,Lc,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Fc,Oc,_c,$c,Uc,qc,zc,Vc;if(n==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');n.id&&!n.getAttribute("data-persona-instance")&&n.setAttribute("data-persona-instance",n.id),n.hasAttribute("data-persona-root")||n.setAttribute("data-persona-root","true");let r=zu(e),o=xl.getForInstance(r.plugins);r.components&&jo.registerAll(r.components);let s=Fm(),i=r.persistState===!1?null:(Xl=r.storageAdapter)!=null?Xl:_m(),d={},c=null,g=!1,f=l=>{if(r.onStateLoaded)try{let p=r.onStateLoaded(l);if(p&&typeof p=="object"&&"state"in p){let{state:h,open:y}=p;return y&&(g=!0),h}return p}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",p)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")c=l.then(p=>{let h=p!=null?p:{messages:[],metadata:{}};return f(h)});else{let p=l!=null?l:{messages:[],metadata:{}},h=f(p);h.metadata&&(d=Tl(h.metadata)),(Jl=h.messages)!=null&&Jl.length&&(r={...r,initialMessages:h.messages}),(Yl=h.artifacts)!=null&&Yl.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:(Zl=h.selectedArtifactId)!=null?Zl:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=f({messages:[],metadata:{}});(ec=l.messages)!=null&&ec.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let u=()=>d,m=l=>{var h;d=(h=l({...d}))!=null?h:{},es()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Cl],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ba.message,ba.messageAndClick],E=Al({parsers:v,handlers:x,getSessionMetadata:u,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null});E.syncFromMetadata();let k=(nc=(tc=r.launcher)==null?void 0:tc.enabled)!=null?nc:!0,L=(oc=(rc=r.launcher)==null?void 0:rc.autoExpand)!=null?oc:!1,F=(sc=r.autoFocusInput)!=null?sc:!1,I=L,R=k,A=(ic=(ac=r.layout)==null?void 0:ac.header)==null?void 0:ic.layout,W=!1,D=()=>ua(r),N=()=>k||D(),M=D()?!1:k?L:!0,z=!1,V=null,oe=()=>{z=!0,V&&clearTimeout(V),V=setTimeout(()=>{z&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),z=!1)},1e4)},Le=Gm(r,E,oe),je=(cc=(lc=r.features)==null?void 0:lc.showReasoning)!=null?cc:!0,ve=(pc=(dc=r.features)==null?void 0:dc.showToolCalls)!=null?pc:!0,Be=(mc=(uc=r.features)==null?void 0:uc.showEventStreamToggle)!=null?mc:!1,Oe=(fc=(gc=r.features)==null?void 0:gc.scrollToBottom)!=null?fc:{},Te=(yc=(hc=r.features)==null?void 0:hc.scrollBehavior)!=null?yc:{},se=`${(vc=typeof r.persistState=="object"?(bc=r.persistState)==null?void 0:bc.keyPrefix:void 0)!=null?vc:"persona-"}event-stream`,Q=Be?new ha(se):null,ae=(Cc=(wc=(xc=r.features)==null?void 0:xc.eventStream)==null?void 0:wc.maxEvents)!=null?Cc:2e3,fe=Be?new fa(ae,Q):null,ue=Be?new ya:null,K=null,ie=!1,We=null,te=0;Q==null||Q.open().then(()=>fe==null?void 0:fe.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let ee={onCopy:l=>{var p,h;s.emit("message:copy",l),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(l.id,"copy").catch(y=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",y)}),(h=(p=r.messageActions)==null?void 0:p.onCopy)==null||h.call(p,l)},onFeedback:l=>{var p,h;s.emit("message:feedback",l),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(l.messageId,l.type).catch(y=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",y)}),(h=(p=r.messageActions)==null?void 0:p.onFeedback)==null||h.call(p,l)}},re=(Ac=r.statusIndicator)!=null?Ac:{},it=l=>{var p,h,y,S;return l==="idle"?(p=re.idleText)!=null?p:Mn.idle:l==="connecting"?(h=re.connectingText)!=null?h:Mn.connecting:l==="connected"?(y=re.connectedText)!=null?y:Mn.connected:l==="error"?(S=re.errorText)!=null?S:Mn.error:Mn[l]};function lt(l,p,h,y){if(y==="idle"&&h.idleLink){l.textContent="";let S=document.createElement("a");S.href=h.idleLink,S.target="_blank",S.rel="noopener noreferrer",S.textContent=p,S.style.color="inherit",S.style.textDecoration="none",l.appendChild(S)}else l.textContent=p}let st=fm({config:r,showClose:N()}),{wrapper:Ee,panel:he,pillRoot:Je}=st.shell,Y=st.panelElements,{container:me,body:ke,messagesWrapper:Ye,suggestions:Ge,textarea:Ie,sendButton:Ke,sendButtonWrapper:vn,composerForm:Rt,statusText:pn,introTitle:Cr,introSubtitle:U,closeButton:G,iconHolder:ye,headerTitle:Qe,headerSubtitle:et,header:Ue,footer:_e,actionsRow:Pt,leftActions:Kt,rightActions:Jt}=Y,Ln=Y.setSendButtonMode,j=Y.micButton,Ht=Y.micButtonWrapper,ce=Y.attachmentButton,Ce=Y.attachmentButtonWrapper,Fe=Y.attachmentInput,Tt=Y.attachmentPreviewsContainer;me.classList.add("persona-relative"),ke.classList.add("persona-relative");let on=12,sn=()=>{var l;return(l=Oe.label)!=null?l:""},xn=()=>{var l;return(l=Oe.iconName)!=null?l:"arrow-down"},Nt=()=>Oe.enabled!==!1,rt=()=>{var l;return(l=Te.mode)!=null?l:"follow"},Dt=()=>{var l;return(l=Te.anchorTopOffset)!=null?l:16},pt=b("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");pt.type="button",pt.style.display="none",pt.setAttribute("data-persona-scroll-to-bottom","true");let Yt=b("span","persona-flex persona-items-center"),nr=b("span",""),Pn=b("span","");Pn.setAttribute("data-persona-scroll-to-bottom-count",""),Pn.style.display="none",pt.append(Yt,nr,Pn),me.appendChild(pt);let an=b("div","persona-stream-anchor-spacer");an.setAttribute("aria-hidden","true"),an.setAttribute("data-persona-anchor-spacer",""),an.style.flexShrink="0",an.style.pointerEvents="none",an.style.height="0px",ke.appendChild(an);let On=()=>{let p=_e.style.display==="none"?0:_e.offsetHeight;pt.style.bottom=`${p+on}px`};On();let Ar=()=>{let l=!!sn();pt.setAttribute("aria-label",sn()||"Jump to latest"),pt.title=sn(),pt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Yt.innerHTML="";let p=Se(xn(),"14px","currentColor",2);p?(Yt.appendChild(p),Yt.style.display=""):Yt.style.display="none",nr.textContent=sn(),nr.style.display=l?"":"none"};Ar();let xt=null,zn=null,Sr=o.find(l=>l.renderHeader);if(Sr!=null&&Sr.renderHeader){let l=Sr.renderHeader({config:r,defaultRenderer:()=>{let p=zo({config:r,showClose:N()});return ma(me,p,r),p.header},onClose:()=>T(!1,"user")});if(l){let p=me.querySelector(".persona-border-b-persona-divider");p&&(p.replaceWith(l),Ue=l,st.header.element=l)}}let Fr=()=>{var p,h,y,S;if(!fe)return;if(ie=!0,!K&&fe&&(K=km({buffer:fe,getFullHistory:()=>fe.getAllFromStore(),onClose:()=>mr(),config:r,plugins:o,getThroughput:()=>{var B;return(B=ue==null?void 0:ue.getMetric())!=null?B:{status:"idle"}}})),K&&(ke.style.display="none",(p=_e.parentNode)==null||p.insertBefore(K.element,_e),K.update()),bt){bt.style.boxShadow=`inset 0 0 0 1.5px ${Fn.actionIconColor}`;let B=(S=(y=(h=r.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:S.toggleButtonActive;B&&B.split(/\s+/).forEach(q=>q&&bt.classList.add(q))}let l=()=>{if(!ie)return;let B=Date.now();B-te>=200&&(K==null||K.update(),te=B),We=requestAnimationFrame(l)};te=0,We=requestAnimationFrame(l),Un(),s.emit("eventStream:opened",{timestamp:Date.now()})},mr=()=>{var l,p,h;if(ie){if(ie=!1,K&&K.element.remove(),ke.style.display="",bt){bt.style.boxShadow="";let y=(h=(p=(l=r.features)==null?void 0:l.eventStream)==null?void 0:p.classNames)==null?void 0:h.toggleButtonActive;y&&y.split(/\s+/).forEach(S=>S&&bt.classList.remove(S))}We!==null&&(cancelAnimationFrame(We),We=null),Un(),s.emit("eventStream:closed",{timestamp:Date.now()})}},bt=null;if(Be){let l=(Tc=(Sc=r.features)==null?void 0:Sc.eventStream)==null?void 0:Tc.classNames,p="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");bt=b("button",p),bt.style.width="28px",bt.style.height="28px",bt.style.color=Fn.actionIconColor,bt.type="button",bt.setAttribute("aria-label","Event Stream"),bt.title="Event Stream";let h=Se("activity","18px","currentColor",1.5);h&&bt.appendChild(h);let y=Y.clearChatButtonWrapper,S=Y.closeButtonWrapper,B=y||S;B&&B.parentNode===Ue?Ue.insertBefore(bt,B):Ue.appendChild(bt),bt.addEventListener("click",()=>{ie?mr():Fr()})}let Co=l=>{var S,B,q,O,H;let p=r.attachments;if(!(p!=null&&p.enabled))return;let h=(S=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?S:l.querySelector(".persona-attachment-previews");if(!h){h=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let de=l.querySelector("[data-persona-composer-form]");de!=null&&de.parentNode?de.parentNode.insertBefore(h,de):l.insertBefore(h,l.firstChild)}if(!((B=l.querySelector("[data-persona-composer-attachment-input]"))!=null?B:l.querySelector('input[type="file"]'))){let de=b("input");de.type="file",de.setAttribute("data-persona-composer-attachment-input",""),de.accept=((q=p.allowedTypes)!=null?q:Qr).join(","),de.multiple=((O=p.maxFiles)!=null?O:4)>1,de.style.display="none",de.setAttribute("aria-label",(H=p.buttonTooltipText)!=null?H:"Attach files"),l.appendChild(de)}},Tr=o.find(l=>l.renderComposer);if(Tr!=null&&Tr.renderComposer){let l=r.composer,p=Tr.renderComposer({config:r,defaultRenderer:()=>Ci({config:r}).footer,onSubmit:h=>{var q;if(!_||_.isStreaming())return;let y=h.trim(),S=(q=xt==null?void 0:xt.hasAttachments())!=null?q:!1;if(!y&&!S)return;tt();let B;S&&(B=[],B.push(...xt.getContentParts()),y&&B.push(Xi(y))),_.sendMessage(y,{contentParts:B}),S&&xt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Fe==null||Fe.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:h=>{r.composer={...r.composer,selectedModelId:h},r.agent&&(r.agent={...r.agent,model:h})},onVoiceToggle:((Mc=r.voiceRecognition)==null?void 0:Mc.enabled)===!0?()=>{zn==null||zn()}:void 0});p&&(st.replaceComposer(p),_e=st.composer.footer)}let Ao=l=>{let p=(...pe)=>{for(let Z of pe){let xe=l.querySelector(Z);if(xe)return xe}return null},h=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),S=l.querySelector("[data-persona-composer-submit]"),B=l.querySelector("[data-persona-composer-mic]"),q=l.querySelector("[data-persona-composer-status]");h&&(Rt=h),y&&(Ie=y),S&&(Ke=S),B&&(j=B,Ht=B.parentElement),q&&(pn=q);let O=p("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(Ge=O);let H=p("[data-persona-composer-attachment-button]",".persona-attachment-button");H&&(ce=H,Ce=H.parentElement),Fe=p("[data-persona-composer-attachment-input]",'input[type="file"]'),Tt=p("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let de=p("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");de&&(Pt=de)};Co(_e),Ao(_e);let _n=(Ic=(Ec=r.layout)==null?void 0:Ec.contentMaxWidth)!=null?Ic:D()?(Pc=(Lc=(kc=r.launcher)==null?void 0:kc.composerBar)==null?void 0:Lc.contentMaxWidth)!=null?Pc:"720px":void 0;if(_n&&(Ye.style.maxWidth=_n,Ye.style.marginLeft="auto",Ye.style.marginRight="auto",Ye.style.width="100%"),_n&&Rt&&!D()&&(Rt.style.maxWidth=_n,Rt.style.marginLeft="auto",Rt.style.marginRight="auto"),_n&&Ge&&!D()&&(Ge.style.maxWidth=_n,Ge.style.marginLeft="auto",Ge.style.marginRight="auto"),_n&&Tt&&!D()&&(Tt.style.maxWidth=_n,Tt.style.marginLeft="auto",Tt.style.marginRight="auto"),(Wc=r.attachments)!=null&&Wc.enabled&&Fe&&Tt){xt=oa.fromConfig(r.attachments),xt.setPreviewsContainer(Tt),Fe.addEventListener("change",h=>{let y=h.target;xt==null||xt.handleFileSelect(y.files),y.value=""});let l=r.attachments.dropOverlay,p=Qm(l);me.appendChild(p)}(()=>{var y,S;let l=(S=(y=r.layout)==null?void 0:y.slots)!=null?S:{},p=B=>{switch(B){case"body-top":return me.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ye;case"footer-top":return Ge;case"composer":return Rt;case"footer-bottom":return pn;default:return null}},h=(B,q)=>{var O;switch(B){case"header-left":case"header-center":case"header-right":if(B==="header-left")Ue.insertBefore(q,Ue.firstChild);else if(B==="header-right")Ue.appendChild(q);else{let H=Ue.querySelector(".persona-flex-col");H?(O=H.parentNode)==null||O.insertBefore(q,H.nextSibling):Ue.appendChild(q)}break;case"body-top":{let H=ke.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");H?H.replaceWith(q):ke.insertBefore(q,ke.firstChild);break}case"body-bottom":ke.appendChild(q);break;case"footer-top":Ge.replaceWith(q);break;case"footer-bottom":pn.replaceWith(q);break;default:break}};for(let[B,q]of Object.entries(l))if(q)try{let O=q({config:r,defaultContent:()=>p(B)});O&&h(B,O)}catch(O){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${B}":`,O)}})();let Yr=l=>{var q,O;let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let y=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!y)return;let S=y.getAttribute("data-message-id");if(!S)return;let B=h.getAttribute("data-bubble-type");if(B==="reasoning")Cs.has(S)?Cs.delete(S):Cs.add(S),bm(S,y);else if(B==="tool")As.has(S)?As.delete(S):As.add(S),vm(S,y,r);else if(B==="approval"){let H=r.approval!==!1?r.approval:void 0,de=((q=H==null?void 0:H.detailsDisplay)!=null?q:"collapsed")==="expanded",pe=(O=Ai.get(S))!=null?O:de;Ai.set(S,!pe),Am(S,y,r)}Pr.delete(S)};Ye.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Yr(l))}),Ye.addEventListener("keydown",l=>{let p=l.target;(l.key==="Enter"||l.key===" ")&&p.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Yr(l))});let Or=new Map,Zr=null,eo="idle",So={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},To=(l,p)=>{let{icon:h,label:y}=So[p];l.setAttribute("aria-label",y),l.title=y,l.setAttribute("aria-pressed",p==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",p!=="idle"),l.classList.toggle("persona-message-action-loading",p==="loading");let S=Se(h,14,"currentColor",2);S&&(l.innerHTML="",l.appendChild(S))},to=()=>{Ye.querySelectorAll('[data-action="read-aloud"]').forEach(p=>{var B;let h=p.closest("[data-actions-for]"),y=(B=h==null?void 0:h.getAttribute("data-actions-for"))!=null?B:null;To(p,y&&y===Zr?eo:"idle")})};Ye.addEventListener("click",l=>{var q;let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let y=h.closest("[data-actions-for]");if(!y)return;let S=y.getAttribute("data-actions-for");if(!S)return;let B=h.getAttribute("data-action");if(B==="copy"){let H=_.getMessages().find(de=>de.id===S);if(H&&ee.onCopy){let de=H.content||"";navigator.clipboard.writeText(de).then(()=>{h.classList.add("persona-message-action-success");let pe=Se("check",14,"currentColor",2);pe&&(h.innerHTML="",h.appendChild(pe)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Z=Se("copy",14,"currentColor",2);Z&&(h.innerHTML="",h.appendChild(Z))},2e3)}).catch(pe=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",pe)}),ee.onCopy(H)}}else if(B==="read-aloud")_.toggleReadAloud(S);else if(B==="upvote"||B==="downvote"){let H=((q=Or.get(S))!=null?q:null)===B,de=B==="upvote"?"thumbs-up":"thumbs-down";if(H){Or.delete(S),h.classList.remove("persona-message-action-active");let pe=Se(de,14,"currentColor",2);pe&&(h.innerHTML="",h.appendChild(pe))}else{let pe=B==="upvote"?"downvote":"upvote",Z=y.querySelector(`[data-action="${pe}"]`);if(Z){Z.classList.remove("persona-message-action-active");let ze=Se(pe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ze&&(Z.innerHTML="",Z.appendChild(ze))}Or.set(S,B),h.classList.add("persona-message-action-active");let xe=Se(de,14,"currentColor",2);xe&&(xe.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(xe)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ae=_.getMessages().find(ot=>ot.id===S);Ae&&ee.onFeedback&&ee.onFeedback({type:B,messageId:Ae.id,message:Ae})}}}),Ye.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let y=h.closest(".persona-approval-bubble");if(!y)return;let S=y.getAttribute("data-message-id");if(!S)return;let B=h.getAttribute("data-approval-action");if(!B)return;let q=B==="approve"?"approved":"denied",H=_.getMessages().find(pe=>pe.id===S);if(!(H!=null&&H.approval))return;let de=y.querySelector("[data-approval-buttons]");de&&de.querySelectorAll("button").forEach(Z=>{Z.disabled=!0,Z.style.opacity="0.5",Z.style.cursor="not-allowed"}),H.approval.toolType==="webmcp"?_.resolveWebMcpApproval(S,q):_.resolveApproval(H.approval,q)});let Ct=null,Vn=null,jn={artifacts:[],selectedId:null},In=!1,Mt={current:null};Ye.addEventListener("click",l=>{var Z,xe,Ne,Ae,ot;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||((Ne=(xe=(Z=r.features)==null?void 0:Z.artifacts)==null?void 0:xe.onArtifactAction)==null?void 0:Ne.call(xe,{type:"download",artifactId:y}))===!0)return;let B=_.getArtifactById(y),q=B==null?void 0:B.markdown,O=(B==null?void 0:B.title)||"artifact";if(!q){let ze=h.closest("[data-open-artifact]"),ft=ze==null?void 0:ze.closest("[data-message-id]"),ct=ft==null?void 0:ft.getAttribute("data-message-id");if(ct){let Pe=_.getMessages().find(Ve=>Ve.id===ct);if(Pe!=null&&Pe.rawContent)try{let Ve=JSON.parse(Pe.rawContent);q=(Ae=Ve==null?void 0:Ve.props)==null?void 0:Ae.markdown,O=((ot=Ve==null?void 0:Ve.props)==null?void 0:ot.title)||O}catch{}}}if(!q)return;let H=new Blob([q],{type:"text/markdown"}),de=URL.createObjectURL(H),pe=document.createElement("a");pe.href=de,pe.download=`${O}.md`,pe.click(),URL.revokeObjectURL(de)}),Ye.addEventListener("click",l=>{var B,q,O;let h=l.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||((O=(q=(B=r.features)==null?void 0:B.artifacts)==null?void 0:q.onArtifactAction)==null?void 0:O.call(q,{type:"open",artifactId:y}))===!0||(l.preventDefault(),l.stopPropagation(),In=!1,_.selectArtifact(y),Qn())}),Ye.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let p=l.target;p.hasAttribute("data-open-artifact")&&(l.preventDefault(),p.click())});let rr=Y.composerOverlay,or=(l,p,h)=>{var O,H,de,pe;let y=p.trim();if(!y||!Mt.current)return;let S=(O=l.getAttribute("data-tool-call-id"))!=null?O:"",B=h.source==="free-text";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:S,answer:y,answers:h.structured,values:(H=h.values)!=null?H:h.source==="multi"?y.split(", "):[y],isFreeText:B,source:h.source},bubbles:!0,composed:!0})),ms(rr,S);let q=Mt.current.getMessages().find(Z=>{var xe;return((xe=Z.toolCall)==null?void 0:xe.id)===S});(de=q==null?void 0:q.agentMetadata)!=null&&de.awaitingLocalTool?Mt.current.resolveAskUserQuestion(q,(pe=h.structured)!=null?pe:y):Mt.current.sendMessage(y)},Kn=l=>{var S;let p=Mt.current;if(!p)return;let h=(S=l.getAttribute("data-tool-call-id"))!=null?S:"",y=p.getMessages().find(B=>{var q;return((q=B.toolCall)==null?void 0:q.id)===h});y&&p.persistAskUserQuestionProgress(y,{answers:Ua(l,y),currentIndex:pr(l)})},no=l=>Object.entries(l).map(([p,h])=>`${p}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),_r=l=>{var S,B,q;if(((B=(S=r.features)==null?void 0:S.askUserQuestion)==null?void 0:B.groupedAutoAdvance)===!1)return;let p=pr(l),h=us(l);if(p>=h-1)return;let y=(q=Mt.current)==null?void 0:q.getMessages().find(O=>{var H;return((H=O.toolCall)==null?void 0:H.id)===l.getAttribute("data-tool-call-id")});y&&(za(l,y,r,p+1),Kn(l))};rr.addEventListener("click",l=>{var B,q,O,H,de,pe,Z,xe,Ne,Ae,ot,ze,ft,ct;let h=l.target.closest("[data-ask-user-action]");if(!h)return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;let S=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),S==="dismiss"){let Re=(B=y.getAttribute("data-tool-call-id"))!=null?B:"";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Re},bubbles:!0,composed:!0})),ms(rr,Re);let Pe=(q=Mt.current)==null?void 0:q.getMessages().find(Ve=>{var Xe;return((Xe=Ve.toolCall)==null?void 0:Xe.id)===Re});(O=Pe==null?void 0:Pe.agentMetadata)!=null&&O.awaitingLocalTool&&((H=Mt.current)==null||H.markAskUserQuestionResolved(Pe),(de=Mt.current)==null||de.resolveAskUserQuestion(Pe,"(dismissed)"));return}if(S==="pick"){let Re=h.getAttribute("data-option-label");if(!Re)return;let Pe=y.getAttribute("data-multi-select")==="true",Ve=bo(y);if(Ve&&Pe){let Xe=Oo(y)[pr(y)],vt=new Set(Array.isArray(Xe)?Xe:[]);vt.has(Re)?vt.delete(Re):vt.add(Re),vo(y,Array.from(vt)),Kn(y);return}if(Ve){vo(y,Re),Kn(y),_r(y);return}if(Pe){let Xe=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Xe?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Xe);let vt=y.querySelector('[data-ask-user-action="submit-multi"]');vt&&(vt.disabled=zi(y).length===0);return}or(y,Re,{source:"pick",values:[Re]});return}if(S==="submit-multi"){let Re=zi(y);if(Re.length===0)return;or(y,Re.join(", "),{source:"multi",values:Re});return}if(S==="open-free-text"){let Re=y.querySelector('[data-ask-free-text-row="true"]');if(Re){Re.classList.remove("persona-hidden");let Pe=Re.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus()}return}if(S==="focus-free-text"){let Re=y.querySelector('[data-ask-free-text-input="true"]');Re==null||Re.focus();return}if(S==="submit-free-text"){let Re=y.querySelector('[data-ask-free-text-input="true"]'),Pe=(pe=Re==null?void 0:Re.value)!=null?pe:"";if(!Pe.trim())return;if(bo(y)){vo(y,Pe.trim()),Kn(y),_r(y);return}or(y,Pe,{source:"free-text"});return}if(S==="next"||S==="back"){if(!Mt.current)return;let Re=(Z=y.getAttribute("data-tool-call-id"))!=null?Z:"",Pe=Mt.current.getMessages().find(De=>{var He;return((He=De.toolCall)==null?void 0:He.id)===Re});if(!Pe)return;let Ve=y.querySelector('[data-ask-free-text-input="true"]'),Xe=(Ne=(xe=Ve==null?void 0:Ve.value)==null?void 0:xe.trim())!=null?Ne:"";if(Xe){let De=Oo(y)[pr(y)];(typeof De!="string"||De!==Xe)&&vo(y,Xe)}let vt=S==="next"?1:-1,P=pr(y)+vt;za(y,Pe,r,P),Kn(y);return}if(S==="submit-all"){if(!Mt.current)return;let Re=(Ae=y.getAttribute("data-tool-call-id"))!=null?Ae:"",Pe=Mt.current.getMessages().find(De=>{var He;return((He=De.toolCall)==null?void 0:He.id)===Re});if(!Pe)return;let Ve=y.querySelector('[data-ask-free-text-input="true"]'),Xe=(ze=(ot=Ve==null?void 0:Ve.value)==null?void 0:ot.trim())!=null?ze:"";Xe&&vo(y,Xe);let vt=Ua(y,Pe);Mt.current.persistAskUserQuestionProgress(Pe,{answers:vt,currentIndex:pr(y)});let P=no(vt);or(y,P||"(submitted)",{source:"submit-all",structured:vt});return}if(S==="skip"){if(!Mt.current)return;let Re=(ft=y.getAttribute("data-tool-call-id"))!=null?ft:"",Pe=Mt.current.getMessages().find(He=>{var ge;return((ge=He.toolCall)==null?void 0:ge.id)===Re});if(!Pe)return;let Ve=bo(y),Xe=pr(y),vt=us(y),P=Xe>=vt-1;if(!Ve){n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Re},bubbles:!0,composed:!0})),ms(rr,Re),(ct=Pe.agentMetadata)!=null&&ct.awaitingLocalTool&&(Mt.current.markAskUserQuestionResolved(Pe),Mt.current.resolveAskUserQuestion(Pe,"(dismissed)"));return}vo(y,"");let De=y.querySelector('[data-ask-free-text-input="true"]');if(De&&(De.value=""),P){let He=Ua(y,Pe),ge=no(He);or(y,ge||"(skipped)",{source:"submit-all",structured:He});return}za(y,Pe,r,Xe+1),Kn(y);return}}),rr.addEventListener("keydown",l=>{var B;if(l.key!=="Enter")return;let h=l.target;if(!((B=h.matches)!=null&&B.call(h,'[data-ask-free-text-input="true"]')))return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;l.preventDefault();let S=h.value;if(S.trim()){if(bo(y)){vo(y,S.trim()),Kn(y),_r(y);return}or(y,S,{source:"free-text"})}});let ro=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let p=l.target;if((p==null?void 0:p.tagName)==="INPUT"||(p==null?void 0:p.tagName)==="TEXTAREA"||p!=null&&p.isContentEditable)return;let h=rr.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let y=Number(l.key),B=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];B&&(l.preventDefault(),B.click())};document.addEventListener("keydown",ro);let Gn=null,Ft=null,Wn=null,sr=null,oo=()=>{};function $r(){sr==null||sr(),sr=null}let so=()=>{var q;if(!Gn||!Ft)return;let l=n.classList.contains("persona-artifact-appearance-seamless"),h=((q=n.ownerDocument.defaultView)!=null?q:window).innerWidth<=640;if(!l||n.classList.contains("persona-artifact-narrow-host")||h){Ft.style.removeProperty("position"),Ft.style.removeProperty("left"),Ft.style.removeProperty("top"),Ft.style.removeProperty("bottom"),Ft.style.removeProperty("width"),Ft.style.removeProperty("z-index");return}let y=Gn.firstElementChild;if(!y||y===Ft)return;let S=10;Ft.style.position="absolute",Ft.style.top="0",Ft.style.bottom="0",Ft.style.width=`${S}px`,Ft.style.zIndex="5";let B=y.offsetWidth-S/2;Ft.style.left=`${Math.max(0,B)}px`},Mr=()=>{},Qn=()=>{var h,y,S,B,q;if(!Ct||!ur(r))return;Mi(n,r),Ei(n,r),Mr();let l=(B=(S=(y=(h=r.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:S.narrowHostMaxWidth)!=null?B:520,p=he.getBoundingClientRect().width||0;n.classList.toggle("persona-artifact-narrow-host",p>0&&p<=l),Ct.update(jn),In?(Ct.setMobileOpen(!1),Ct.element.classList.add("persona-hidden"),(q=Ct.backdrop)==null||q.classList.add("persona-hidden")):jn.artifacts.length>0&&(Ct.element.classList.remove("persona-hidden"),Ct.setMobileOpen(!0)),oo()};if(ur(r)){he.style.position="relative";let l=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),p=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(me),Ct=Im(r,{onSelect:h=>{var y;return(y=Mt.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{In=!0,Qn()}}),Ct.element.classList.add("persona-hidden"),Gn=p,p.appendChild(l),p.appendChild(Ct.element),Ct.backdrop&&he.appendChild(Ct.backdrop),he.appendChild(p),oo=()=>{var y,S,B,q;if(!Gn||!Ct)return;if(!(((B=(S=(y=r.features)==null?void 0:y.artifacts)==null?void 0:S.layout)==null?void 0:B.resizable)===!0)){Wn==null||Wn(),Wn=null,$r(),Ft&&(Ft.remove(),Ft=null),Ct.element.style.removeProperty("width"),Ct.element.style.removeProperty("maxWidth");return}if(!Ft){let O=b("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");O.setAttribute("role","separator"),O.setAttribute("aria-orientation","vertical"),O.setAttribute("aria-label","Resize artifacts panel"),O.tabIndex=0;let H=n.ownerDocument,de=(q=H.defaultView)!=null?q:window,pe=Z=>{var ft,ct;if(!Ct||Z.button!==0||n.classList.contains("persona-artifact-narrow-host")||de.innerWidth<=640)return;Z.preventDefault(),$r();let xe=Z.clientX,Ne=Ct.element.getBoundingClientRect().width,Ae=(ct=(ft=r.features)==null?void 0:ft.artifacts)==null?void 0:ct.layout,ot=Re=>{let Pe=Gn.getBoundingClientRect().width,Ve=n.classList.contains("persona-artifact-appearance-seamless"),Xe=Ve?0:Bm(Gn,de),vt=Ve?0:O.getBoundingClientRect().width||6,P=Ne-(Re.clientX-xe),De=Dm(P,Pe,Xe,vt,Ae==null?void 0:Ae.resizableMinWidth,Ae==null?void 0:Ae.resizableMaxWidth);Ct.element.style.width=`${De}px`,Ct.element.style.maxWidth="none",so()},ze=()=>{H.removeEventListener("pointermove",ot),H.removeEventListener("pointerup",ze),H.removeEventListener("pointercancel",ze),sr=null;try{O.releasePointerCapture(Z.pointerId)}catch{}};sr=ze,H.addEventListener("pointermove",ot),H.addEventListener("pointerup",ze),H.addEventListener("pointercancel",ze);try{O.setPointerCapture(Z.pointerId)}catch{}};O.addEventListener("pointerdown",pe),Ft=O,Gn.insertBefore(O,Ct.element),Wn=()=>{O.removeEventListener("pointerdown",pe)}}if(Ft){let O=jn.artifacts.length>0&&!In;Ft.classList.toggle("persona-hidden",!O),so()}},Mr=()=>{var de,pe,Z,xe,Ne,Ae,ot,ze,ft,ct,Re,Pe,Ve,Xe;if(!k||!Ct||((pe=(de=r.launcher)==null?void 0:de.sidebarMode)!=null?pe:!1)||Cn(r)&&xr(r).reveal==="emerge")return;let y=(Z=n.ownerDocument.defaultView)!=null?Z:window,S=(Ne=(xe=r.launcher)==null?void 0:xe.mobileFullscreen)!=null?Ne:!0,B=(ot=(Ae=r.launcher)==null?void 0:Ae.mobileBreakpoint)!=null?ot:640;if(S&&y.innerWidth<=B||!Hm(r,k))return;let q=(ct=(ft=(ze=r.launcher)==null?void 0:ze.width)!=null?ft:r.launcherWidth)!=null?ct:Xr,O=(Xe=(Ve=(Pe=(Re=r.features)==null?void 0:Re.artifacts)==null?void 0:Pe.layout)==null?void 0:Ve.expandedPanelWidth)!=null?Xe:"min(720px, calc(100vw - 24px))";jn.artifacts.length>0&&!In?(he.style.width=O,he.style.maxWidth=O):(he.style.width=q,he.style.maxWidth=q)},typeof ResizeObserver!="undefined"&&(Vn=new ResizeObserver(()=>{Qn()}),Vn.observe(he))}else he.appendChild(me),D()&&Je&&(Y.peekBanner&&Je.appendChild(Y.peekBanner),Je.appendChild(_e));n.appendChild(Ee),Je&&n.appendChild(Je);let be=()=>{var De,He,ge,$t,Ot,Gt,wt,Vt,Yn,rn,Ze,It,dn,dr,Zn,Po,Io,as,is,Qt,Wo,go,fo,Kr,Ro,yr,nt,gn;if(D()){he.style.width="100%",he.style.maxWidth="100%";let qt=(He=(De=r.launcher)==null?void 0:De.composerBar)!=null?He:{},Ut=Ee.dataset.state==="expanded",ht=(ge=qt.expandedSize)!=null?ge:"anchored";if(!(Ut&&ht!=="fullscreen")){me.style.background="",me.style.border="",me.style.borderRadius="",me.style.overflow="",me.style.boxShadow="";return}let St=(Ot=($t=r.theme)==null?void 0:$t.components)==null?void 0:Ot.panel,Sn=oi(r),Hn=(Dn,Ho)=>{var Us;return Dn==null||Dn===""?Ho:(Us=vs(Sn,Dn))!=null?Us:Dn},Dr="1px solid var(--persona-border)",bn="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Bn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";me.style.background="var(--persona-surface, #ffffff)",me.style.border=Hn(St==null?void 0:St.border,Dr),me.style.borderRadius=Hn(St==null?void 0:St.borderRadius,Bn),me.style.boxShadow=Hn(St==null?void 0:St.shadow,bn),me.style.overflow="hidden";return}let l=Cn(r),p=(wt=(Gt=r.launcher)==null?void 0:Gt.sidebarMode)!=null?wt:!1,h=l||p||((Yn=(Vt=r.launcher)==null?void 0:Vt.fullHeight)!=null?Yn:!1),y=((rn=r.launcher)==null?void 0:rn.enabled)===!1,S=(It=(Ze=r.theme)==null?void 0:Ze.components)==null?void 0:It.panel,B=oi(r),q=(qt,Ut)=>{var ht;return qt==null||qt===""?Ut:(ht=vs(B,qt))!=null?ht:qt},O=(dn=n.ownerDocument.defaultView)!=null?dn:window,H=(Zn=(dr=r.launcher)==null?void 0:dr.mobileFullscreen)!=null?Zn:!0,de=(Io=(Po=r.launcher)==null?void 0:Po.mobileBreakpoint)!=null?Io:640,pe=O.innerWidth<=de,Z=H&&pe&&k,xe=(is=(as=r.launcher)==null?void 0:as.position)!=null?is:"bottom-left",Ne=xe==="bottom-left"||xe==="top-left",Ae=(Wo=(Qt=r.launcher)==null?void 0:Qt.zIndex)!=null?Wo:En,ot=p||Z?"none":"1px solid var(--persona-border)",ze=Z?"none":p?Ne?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Z&&(ze="none",ot="none");let ft=p||Z?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ct=q(S==null?void 0:S.border,ot),Re=q(S==null?void 0:S.shadow,ze),Pe=q(S==null?void 0:S.borderRadius,ft),Ve=ke.scrollTop;n.style.cssText="",Ee.style.cssText="",he.style.cssText="",me.style.cssText="",ke.style.cssText="",_e.style.cssText="";let Xe=()=>{var Ut;if(Ve<=0)return;((Ut=ke.ownerDocument.defaultView)!=null?Ut:window).requestAnimationFrame(()=>{if(ke.scrollTop===Ve)return;let ht=ke.scrollHeight-ke.clientHeight;ht<=0||(ke.scrollTop=Math.min(Ve,ht))})};if(Z){Ee.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"),Ee.style.cssText=`
33
+ position: fixed !important;
34
+ inset: 0 !important;
35
+ width: 100% !important;
36
+ height: 100% !important;
37
+ max-height: 100% !important;
38
+ margin: 0 !important;
39
+ padding: 0 !important;
40
+ display: flex !important;
41
+ flex-direction: column !important;
42
+ z-index: ${Ae} !important;
43
+ background-color: var(--persona-surface, #ffffff) !important;
44
+ `,he.style.cssText=`
45
+ position: relative !important;
46
+ display: flex !important;
47
+ flex-direction: column !important;
48
+ flex: 1 1 0% !important;
49
+ width: 100% !important;
50
+ max-width: 100% !important;
51
+ height: 100% !important;
52
+ min-height: 0 !important;
53
+ margin: 0 !important;
54
+ padding: 0 !important;
55
+ box-shadow: none !important;
56
+ border-radius: 0 !important;
57
+ `,me.style.cssText=`
58
+ display: flex !important;
59
+ flex-direction: column !important;
60
+ flex: 1 1 0% !important;
61
+ width: 100% !important;
62
+ height: 100% !important;
63
+ min-height: 0 !important;
64
+ max-height: 100% !important;
65
+ overflow: hidden !important;
66
+ border-radius: 0 !important;
67
+ border: none !important;
68
+ `,ke.style.flex="1 1 0%",ke.style.minHeight="0",ke.style.overflowY="auto",_e.style.flexShrink="0",W=!0,Xe();return}let vt=(fo=(go=r==null?void 0:r.launcher)==null?void 0:go.width)!=null?fo:r==null?void 0:r.launcherWidth,P=vt!=null?vt:Xr;if(!p&&!l)y&&h?(he.style.width="100%",he.style.maxWidth="100%"):(he.style.width=P,he.style.maxWidth=P);else if(l)if(xr(r).reveal==="emerge"){let Ut=xr(r).width;he.style.width=Ut,he.style.maxWidth=Ut}else he.style.width="100%",he.style.maxWidth="100%";if(Mr(),he.style.boxShadow=Re,he.style.borderRadius=Pe,me.style.border=ct,me.style.borderRadius=Pe,l&&!Z&&(S==null?void 0:S.border)===void 0&&(me.style.border="none",xr(r).side==="right"?me.style.borderLeft="1px solid var(--persona-border)":me.style.borderRight="1px solid var(--persona-border)"),h&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",y&&(n.style.width="100%"),Ee.style.display="flex",Ee.style.flexDirection="column",Ee.style.flex="1 1 0%",Ee.style.minHeight="0",Ee.style.maxHeight="100%",Ee.style.height="100%",y&&(Ee.style.overflow="hidden"),he.style.display="flex",he.style.flexDirection="column",he.style.flex="1 1 0%",he.style.minHeight="0",he.style.maxHeight="100%",he.style.height="100%",he.style.overflow="hidden",me.style.display="flex",me.style.flexDirection="column",me.style.flex="1 1 0%",me.style.minHeight="0",me.style.maxHeight="100%",me.style.overflow="hidden",ke.style.flex="1 1 0%",ke.style.minHeight="0",ke.style.overflowY="auto",_e.style.flexShrink="0"),Ee.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!p&&!y&&!l&&((Kr=wr[xe])!=null?Kr:wr["bottom-right"]).split(" ").forEach(Ut=>Ee.classList.add(Ut)),p){let qt=(yr=(Ro=r.launcher)==null?void 0:Ro.sidebarWidth)!=null?yr:"420px";Ee.style.cssText=`
69
+ position: fixed !important;
70
+ top: 0 !important;
71
+ bottom: 0 !important;
72
+ width: ${qt} !important;
73
+ height: 100vh !important;
74
+ max-height: 100vh !important;
75
+ margin: 0 !important;
76
+ padding: 0 !important;
77
+ display: flex !important;
78
+ flex-direction: column !important;
79
+ z-index: ${Ae} !important;
80
+ ${Ne?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
81
+ `,he.style.cssText=`
82
+ position: relative !important;
83
+ display: flex !important;
84
+ flex-direction: column !important;
85
+ flex: 1 1 0% !important;
86
+ width: 100% !important;
87
+ max-width: 100% !important;
88
+ height: 100% !important;
89
+ min-height: 0 !important;
90
+ margin: 0 !important;
91
+ padding: 0 !important;
92
+ box-shadow: ${Re} !important;
93
+ border-radius: ${Pe} !important;
94
+ `,he.style.setProperty("width","100%","important"),he.style.setProperty("max-width","100%","important"),me.style.cssText=`
95
+ display: flex !important;
96
+ flex-direction: column !important;
97
+ flex: 1 1 0% !important;
98
+ width: 100% !important;
99
+ height: 100% !important;
100
+ min-height: 0 !important;
101
+ max-height: 100% !important;
102
+ overflow: hidden !important;
103
+ border-radius: ${Pe} !important;
104
+ border: ${ct} !important;
105
+ `,_e.style.cssText=`
106
+ flex-shrink: 0 !important;
107
+ border-top: none !important;
108
+ padding: 8px 16px 12px 16px !important;
109
+ `}if(!y&&!l){let qt="max-height: -moz-available !important; max-height: stretch !important;",Ut=p?"":"padding-top: 1.25em !important;",ht=p?"":`z-index: ${(gn=(nt=r.launcher)==null?void 0:nt.zIndex)!=null?gn:En} !important;`;Ee.style.cssText+=qt+Ut+ht}Xe()};be(),xs(n,r),Mi(n,r),Ei(n,r);let ut=[];ut.push(()=>{document.removeEventListener("keydown",ro)});let tn=null,un=null;ut.push(()=>{tn==null||tn(),tn=null,un==null||un(),un=null}),Vn&&ut.push(()=>{Vn==null||Vn.disconnect(),Vn=null}),ut.push(()=>{Wn==null||Wn(),Wn=null,$r(),Ft&&(Ft.remove(),Ft=null),Ct==null||Ct.element.style.removeProperty("width"),Ct==null||Ct.element.style.removeProperty("maxWidth")}),Be&&ut.push(()=>{We!==null&&(cancelAnimationFrame(We),We=null),K==null||K.destroy(),K=null,fe==null||fe.destroy(),fe=null,Q=null});let Er=null,Es=()=>{Er&&(Er(),Er=null),r.colorScheme==="auto"&&(Er=Qu(()=>{xs(n,r)}))};Es(),ut.push(()=>{Er&&(Er(),Er=null)});let Ur=(Rc=r.features)==null?void 0:Rc.streamAnimation;if(Ur!=null&&Ur.type&&Ur.type!=="none"){let l=ia(Ur.type,Ur.plugins);l&&(ol(l,n),ut.push(()=>lm(n)))}let Mo=Sm(Ge),kr=null,_,Go=l=>{var y,S;if(!_)return;let p=l!=null?l:_.getMessages(),h=((S=(y=r.features)==null?void 0:y.suggestReplies)==null?void 0:S.enabled)!==!1?hu(p):null;h?Mo.render(h,_,Ie,p,r.suggestionChipsConfig,{agentPushed:!0}):p.some(B=>B.role==="user")?Mo.render([],_,Ie,p):Mo.render(r.suggestionChips,_,Ie,p,r.suggestionChipsConfig)},Lr=!1,Pr=Zu(),qr=new Map,Ir=new Map,gr=new Map,Qo=0,xa=cs()!==null,Xn=ii(),Jn=0,fr=null,hr=!1,Eo=!1,zr=0,An=null,Wr=null,Xo=!1,ko=!1,Jo=null,wa=4,Yo=24,Ca=80,Zo=new Map,yt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ks=(Bc=(Hc=r.voiceRecognition)==null?void 0:Hc.autoResume)!=null?Bc:!1,ar=l=>{s.emit("voice:state",{active:yt.active,source:l,timestamp:Date.now()})},$n=()=>{m(l=>({...l,voiceState:{active:yt.active,timestamp:Date.now(),manuallyDeactivated:yt.manuallyDeactivated}}))},Aa=()=>{var y,S;if(((y=r.voiceRecognition)==null?void 0:y.enabled)===!1)return;let l=Tl(d.voiceState),p=!!l.active,h=Number((S=l.timestamp)!=null?S:0);yt.manuallyDeactivated=!!l.manuallyDeactivated,p&&Date.now()-h<ay&&setTimeout(()=>{var B,q;yt.active||(yt.manuallyDeactivated=!1,((q=(B=r.voiceRecognition)==null?void 0:B.provider)==null?void 0:q.type)==="runtype"?_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),ar("restore"),_.isVoiceActive()&&os()}):Ra("restore"))},1e3)},Sa=()=>_?Km(_.getMessages()).filter(l=>!l.__skipPersist):[];function es(l){if(!(i!=null&&i.save))return;let h={messages:l?Km(l):_?Sa():[],metadata:d,artifacts:jn.artifacts,selectedArtifactId:jn.selectedId};try{let y=i.save(h);y instanceof Promise&&y.catch(S=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",S)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let Vr=null,Ls=()=>Ee.querySelector("#persona-scroll-container")||ke,ao=()=>{Vr!==null&&(cancelAnimationFrame(Vr),Vr=null),hr=!1},Ps=()=>{fr!==null&&(cancelAnimationFrame(fr),fr=null),Eo=!1,ao()},Is=()=>{zr>0?(Pn.textContent=String(zr),Pn.style.display="",pt.setAttribute("aria-label",`${sn()||"Jump to latest"} (${zr} new)`)):(Pn.textContent="",Pn.style.display="none",pt.setAttribute("aria-label",sn()||"Jump to latest"))},Ws=()=>{zr!==0&&(zr=0,Is())},Rs=()=>rt()==="follow"?!Xn.isFollowing():!qo(ke,Yo),Un=()=>{if(!Nt()||ie){pt.parentNode&&pt.remove(),pt.style.display="none";return}pt.parentNode!==me&&me.appendChild(pt),On();let p=Jr(ke)>0&&Rs();p||Ws(),pt.style.display=p?"":"none"},ts=()=>{Xn.pause()&&(Ps(),Un())},Rr=()=>{Xn.resume(),Ws(),Un()},Hr=(l=!1)=>{rt()==="follow"&&Xn.isFollowing()&&(!l&&!Lr||(fr!==null&&(cancelAnimationFrame(fr),fr=null),Eo=!0,fr=requestAnimationFrame(()=>{fr=null,Eo=!1,Xn.isFollowing()&&Ta(Ls(),l?220:140)})))},Hs=(l,p,h,y=()=>!0)=>{let S=l.scrollTop,B=p(),q=B-S;ao();let O=performance.now();hr=!0;let H=pe=>1-Math.pow(1-pe,3),de=pe=>{if(!y()){ao();return}let Z=p();Z!==B&&(B=Z,q=B-S);let xe=pe-O,Ne=Math.min(xe/h,1),Ae=H(Ne),ot=S+q*Ae;l.scrollTop=ot,Jn=l.scrollTop,Ne<1?Vr=requestAnimationFrame(de):(l.scrollTop=B,Jn=l.scrollTop,Vr=null,hr=!1)};Vr=requestAnimationFrame(de)},Ta=(l,p=500)=>{let h=Jr(l)-l.scrollTop;if(Math.abs(h)<1){Jn=l.scrollTop;return}if(Math.abs(h)>=Ca){ao(),hr=!0,l.scrollTop=Jr(l),Jn=l.scrollTop,hr=!1;return}Hs(l,()=>Jr(l),p,()=>Xn.isFollowing())},Bs=()=>{let l=Ls();hr=!0,l.scrollTop=Jr(l),Jn=l.scrollTop,hr=!1,Un()},Ds=l=>{an.style.height=`${Math.max(0,Math.round(l))}px`,An&&(An.spacerHeight=Math.max(0,l))},Lo=()=>{Wr!==null&&(cancelAnimationFrame(Wr),Wr=null),ao(),An=null,an.style.height="0px"},Ma=l=>{Wr!==null&&cancelAnimationFrame(Wr),Wr=requestAnimationFrame(()=>{var de;Wr=null;let p=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/"/g,'\\"'),h=ke.querySelector(`[data-message-id="${p}"]`);if(!h)return;let y=0,S=h;for(;S&&S!==ke;)y+=S.offsetTop,S=S.offsetParent;let B=(de=An==null?void 0:An.spacerHeight)!=null?de:0,q=ke.scrollHeight-B,{targetScrollTop:O,spacerHeight:H}=om({anchorOffsetTop:y,topOffset:Dt(),viewportHeight:ke.clientHeight,contentHeight:q});An={initialSpacerHeight:H,contentHeightAtAnchor:q,spacerHeight:H},Ds(H),Hs(ke,()=>O,220)})},Ea=()=>{if(rt()==="follow"){if(!Xn.isFollowing()||qo(ke,1))return;Hr(!Lr);return}if(An&&An.initialSpacerHeight>0){let l=ke.scrollHeight-An.spacerHeight,p=sm({initialSpacerHeight:An.initialSpacerHeight,contentHeightAtAnchor:An.contentHeightAtAnchor,currentContentHeight:l});p!==An.spacerHeight&&Ds(p)}Un()},ka=l=>{let p=rt();p==="follow"?(Rr(),Hr(!0)):p==="anchor-top"&&Ma(l)},La=l=>{let p=new Map;l.forEach(h=>{let y=Zo.get(h.id);p.set(h.id,{streaming:h.streaming,role:h.role}),!y&&h.role==="assistant"&&(s.emit("assistant:message",h),!ko&&rt()!=="anchor-top"&&Rs()&&(zr+=1,Is(),Un())),h.role==="assistant"&&(y!=null&&y.streaming)&&h.streaming===!1&&s.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(y?h.approval.status!=="pending"&&s.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):s.emit("approval:requested",{approval:h.approval,message:h}))}),Zo.clear(),p.forEach((h,y)=>{Zo.set(y,h)})},Pa=(l,p,h)=>{var ct,Re,Pe,Ve,Xe,vt;let y=document.createElement("div"),B=(()=>{var De;let P=o.find(He=>He.renderLoadingIndicator);if(P!=null&&P.renderLoadingIndicator)return P.renderLoadingIndicator;if((De=r.loadingIndicator)!=null&&De.render)return r.loadingIndicator.render})(),q=(P,De)=>De==null?!1:typeof De=="string"?(P.textContent=De,!0):(P.appendChild(De),!0),O=new Set,H=new Set,de=o.some(P=>P.renderAskUserQuestion),pe=[],Z=[],xe=r.enableComponentStreaming!==!1,Ne=o.some(P=>P.renderApproval)&&r.approval!==!1,Ae=[];if(p.forEach(P=>{var Ze,It,dn,dr,Zn,Po,Io,as,is,Qt,Wo,go,fo,Kr,Ro,yr;O.add(P.id);let De=de&&Fo(P),He=Ne&&P.variant==="approval"&&!!P.approval,ge=!De&&P.role==="assistant"&&!P.variant&&xe&&qm(P);if(!He&&gr.has(P.id)){let nt=l.querySelector(`#wrapper-${P.id}`);nt==null||nt.removeAttribute("data-preserve-runtime"),gr.delete(P.id)}if(!ge&&Ir.has(P.id)){let nt=l.querySelector(`#wrapper-${P.id}`);nt==null||nt.removeAttribute("data-preserve-runtime"),Ir.delete(P.id)}let $t=Fo(P)?`:${(Ze=P.agentMetadata)!=null&&Ze.askUserQuestionAnswered?"a":"u"}:${(It=P.agentMetadata)!=null&&It.askUserQuestionAnswers?Object.keys(P.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ot=Yu(P,Qo)+$t,Gt=De||He||ge?null:em(Pr,P.id,Ot);if(Gt){y.appendChild(Gt.cloneNode(!0)),Fo(P)&&((dn=P.toolCall)!=null&&dn.id)&&((dr=P.agentMetadata)==null?void 0:dr.awaitingLocalTool)===!0&&!((Zn=P.agentMetadata)!=null&&Zn.askUserQuestionAnswered)&&(H.add(P.toolCall.id),qa(P,r,Y.composerOverlay));return}let wt=null,Vt=o.find(nt=>!!(P.variant==="reasoning"&&nt.renderReasoning||P.variant==="tool"&&nt.renderToolCall||!P.variant&&nt.renderMessage)),Yn=(Po=r.layout)==null?void 0:Po.messages;if(Fo(P)&&((Io=P.agentMetadata)==null?void 0:Io.askUserQuestionAnswered)===!0){qr.delete(P.id);let nt=l.querySelector(`#wrapper-${P.id}`);nt==null||nt.removeAttribute("data-preserve-runtime");return}if(ji(P)&&((is=(as=r.features)==null?void 0:as.suggestReplies)==null?void 0:is.enabled)!==!1)return;if(Fo(P)&&((Wo=(Qt=r.features)==null?void 0:Qt.askUserQuestion)==null?void 0:Wo.enabled)!==!1){let nt=o.find(gn=>typeof gn.renderAskUserQuestion=="function");if(nt&&Mt.current){let gn=qr.get(P.id),qt=gn!==Ot,Ut=null;if(qt){let{payload:St,complete:Sn}=ps(P),Hn=P.id,Dr=()=>{var bn;return(bn=Mt.current)==null?void 0:bn.getMessages().find(Bn=>Bn.id===Hn)};Ut=nt.renderAskUserQuestion({message:P,payload:St,complete:Sn,resolve:bn=>{var Dn;let Bn=Dr();Bn&&((Dn=Mt.current)==null||Dn.resolveAskUserQuestion(Bn,bn))},dismiss:()=>{var Bn,Dn,Ho;let bn=Dr();(Bn=bn==null?void 0:bn.agentMetadata)!=null&&Bn.awaitingLocalTool&&((Dn=Mt.current)==null||Dn.markAskUserQuestionResolved(bn),(Ho=Mt.current)==null||Ho.resolveAskUserQuestion(bn,"(dismissed)"))},config:r})}let ht=gn!=null;if(qt&&Ut===null&&!ht){((go=P.agentMetadata)==null?void 0:go.awaitingLocalTool)===!0&&!((fo=P.agentMetadata)!=null&&fo.askUserQuestionAnswered)&&(H.add(P.toolCall.id),qa(P,r,Y.composerOverlay));return}let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id=`wrapper-${P.id}`,Xt.setAttribute("data-wrapper-id",P.id),Xt.setAttribute("data-ask-plugin-stub","true"),Xt.setAttribute("data-preserve-runtime","true"),y.appendChild(Xt),pe.push({messageId:P.id,fingerprint:Ot,bubble:Ut});return}else{((Kr=P.agentMetadata)==null?void 0:Kr.awaitingLocalTool)===!0&&!((Ro=P.agentMetadata)!=null&&Ro.askUserQuestionAnswered)&&(H.add(P.toolCall.id),qa(P,r,Y.composerOverlay));return}}else if(He){let nt=o.find(ht=>typeof ht.renderApproval=="function"),qt=gr.get(P.id)!==Ot,Ut=null;if(qt&&(nt!=null&&nt.renderApproval)){let ht=P.id,Xt=(St,Sn)=>{var Dr,bn,Bn;let Hn=(Dr=Mt.current)==null?void 0:Dr.getMessages().find(Dn=>Dn.id===ht);Hn!=null&&Hn.approval&&(Hn.approval.toolType==="webmcp"?(bn=Mt.current)==null||bn.resolveWebMcpApproval(Hn.id,St):(Bn=Mt.current)==null||Bn.resolveApproval(Hn.approval,St,Sn))};Ut=nt.renderApproval({message:P,defaultRenderer:()=>Si(P,r),config:r,approve:St=>Xt("approved",St),deny:St=>Xt("denied",St)})}if(qt&&Ut===null){let ht=l.querySelector(`#wrapper-${P.id}`);ht==null||ht.removeAttribute("data-preserve-runtime"),gr.delete(P.id),wt=Si(P,r)}else{let ht=document.createElement("div");ht.className="persona-flex",ht.id=`wrapper-${P.id}`,ht.setAttribute("data-wrapper-id",P.id),ht.setAttribute("data-approval-plugin-stub","true"),ht.setAttribute("data-preserve-runtime","true"),y.appendChild(ht),Ae.push({messageId:P.id,fingerprint:Ot,bubble:Ut});return}}else if(Vt)if(P.variant==="reasoning"&&P.reasoning&&Vt.renderReasoning){if(!je)return;wt=Vt.renderReasoning({message:P,defaultRenderer:()=>ml(P,r),config:r})}else if(P.variant==="tool"&&P.toolCall&&Vt.renderToolCall){if(!ve)return;wt=Vt.renderToolCall({message:P,defaultRenderer:()=>gl(P,r),config:r})}else Vt.renderMessage&&(wt=Vt.renderMessage({message:P,defaultRenderer:()=>{let nt=ul(P,h,Yn,r.messageActions,ee,{loadingIndicatorRenderer:B,widgetConfig:r});return P.role!=="user"&&bl(nt,P,r,_),nt},config:r}));if(!wt&&ge){let nt=zm(P);if(nt){let gn=Ir.get(P.id),qt=gn!==Ot,Ut=r.wrapComponentDirectiveInBubble!==!1,ht=null;if(qt){let Xt=$m(nt,{config:r,message:P,transform:h});if(Xt)if(Ut){let St=document.createElement("div");if(St.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),St.id=`bubble-${P.id}`,St.setAttribute("data-message-id",P.id),P.content&&P.content.trim()){let Sn=document.createElement("div");Sn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Sn.innerHTML=h({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),St.appendChild(Sn)}St.appendChild(Xt),ht=St}else{let St=document.createElement("div");if(St.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",St.id=`bubble-${P.id}`,St.setAttribute("data-message-id",P.id),St.setAttribute("data-persona-component-directive","true"),P.content&&P.content.trim()){let Sn=document.createElement("div");Sn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Sn.innerHTML=h({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),St.appendChild(Sn)}St.appendChild(Xt),ht=St}}if(ht||gn!=null){let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id=`wrapper-${P.id}`,Xt.setAttribute("data-wrapper-id",P.id),Xt.setAttribute("data-component-directive-stub","true"),Xt.setAttribute("data-preserve-runtime","true"),Ut||Xt.classList.add("persona-w-full"),y.appendChild(Xt),Z.push({messageId:P.id,fingerprint:Ot,bubble:ht});return}}}if(!wt)if(P.variant==="reasoning"&&P.reasoning){if(!je)return;wt=ml(P,r)}else if(P.variant==="tool"&&P.toolCall){if(!ve)return;wt=gl(P,r)}else if(P.variant==="approval"&&P.approval){if(r.approval===!1)return;wt=Si(P,r)}else{let nt=(yr=r.layout)==null?void 0:yr.messages;nt!=null&&nt.renderUserMessage&&P.role==="user"?wt=nt.renderUserMessage({message:P,config:r,streaming:!!P.streaming}):nt!=null&&nt.renderAssistantMessage&&P.role==="assistant"?wt=nt.renderAssistantMessage({message:P,config:r,streaming:!!P.streaming}):wt=ul(P,h,nt,r.messageActions,ee,{loadingIndicatorRenderer:B,widgetConfig:r}),P.role!=="user"&&wt&&bl(wt,P,r,_)}let rn=document.createElement("div");rn.className="persona-flex",rn.id=`wrapper-${P.id}`,rn.setAttribute("data-wrapper-id",P.id),P.role==="user"&&rn.classList.add("persona-justify-end"),(wt==null?void 0:wt.getAttribute("data-persona-component-directive"))==="true"&&rn.classList.add("persona-w-full"),rn.appendChild(wt),tm(Pr,P.id,Ot,rn),y.appendChild(rn)}),Y.composerOverlay&&Y.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(De=>{let He=De.getAttribute("data-persona-ask-sheet-for");He&&!H.has(He)&&ms(Y.composerOverlay,He)}),(Re=(ct=r.features)==null?void 0:ct.toolCallDisplay)!=null&&Re.grouped){let P=[],De=[];p.forEach(He=>{if(He.variant==="tool"&&He.toolCall&&ve){De.push(He);return}De.length>1&&P.push(De),De=[]}),De.length>1&&P.push(De),P.forEach((He,ge)=>{var Ze,It;let $t=He.map(dn=>Array.from(y.children).find(dr=>dr instanceof HTMLElement&&dr.getAttribute("data-wrapper-id")===dn.id)).filter(dn=>!!dn);if($t.length<2)return;let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id=`wrapper-tool-group-${ge}-${He[0].id}`,Ot.setAttribute("data-wrapper-id",`tool-group-${ge}-${He[0].id}`);let Gt=document.createElement("div");Gt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Gt.setAttribute("data-persona-tool-group","true");let wt=document.createElement("div");wt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let Vt=`Called ${He.length} tools`,Yn=(It=(Ze=r.toolCall)==null?void 0:Ze.renderGroupedSummary)==null?void 0:It.call(Ze,{messages:He,toolCalls:He.map(dn=>dn.toolCall).filter(dn=>!!dn),defaultSummary:Vt,config:r});q(wt,Yn)||(wt.textContent=Vt);let rn=document.createElement("div");rn.className="persona-tool-group-stack persona-flex persona-flex-col",Gt.append(wt,rn),Ot.appendChild(Gt),$t[0].before(Ot),$t.forEach((dn,dr)=>{let Zn=document.createElement("div");Zn.className="persona-tool-group-item persona-relative",Zn.setAttribute("data-persona-tool-group-item","true"),dr<$t.length-1&&Zn.setAttribute("data-persona-tool-group-connector","true"),Zn.appendChild(dn),rn.appendChild(Zn)})})}nm(Pr,O);let ot=p.some(P=>P.role==="assistant"&&P.streaming),ze=p[p.length-1],ft=(ze==null?void 0:ze.role)==="assistant"&&!ze.streaming&&ze.variant!=="approval";if(Lr&&p.some(P=>P.role==="user")&&!ot&&!ft){let P={config:r,streaming:!0,location:"standalone",defaultRenderer:ga},De=o.find(ge=>ge.renderLoadingIndicator),He=null;if(De!=null&&De.renderLoadingIndicator&&(He=De.renderLoadingIndicator(P)),He===null&&((Pe=r.loadingIndicator)!=null&&Pe.render)&&(He=r.loadingIndicator.render(P)),He===null&&(He=ga()),He){let ge=document.createElement("div"),$t=((Ve=r.loadingIndicator)==null?void 0:Ve.showBubble)!==!1;ge.className=$t?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),ge.setAttribute("data-typing-indicator","true"),ge.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",ge.appendChild(He);let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id="wrapper-typing-indicator",Ot.setAttribute("data-wrapper-id","typing-indicator"),Ot.appendChild(ge),y.appendChild(Ot)}}if(!Lr&&p.length>0){let P=p[p.length-1],De={config:r,lastMessage:P,messageCount:p.length},He=o.find($t=>$t.renderIdleIndicator),ge=null;if(He!=null&&He.renderIdleIndicator&&(ge=He.renderIdleIndicator(De)),ge===null&&((Xe=r.loadingIndicator)!=null&&Xe.renderIdle)&&(ge=r.loadingIndicator.renderIdle(De)),ge){let $t=document.createElement("div"),Ot=((vt=r.loadingIndicator)==null?void 0:vt.showBubble)!==!1;$t.className=Ot?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),$t.setAttribute("data-idle-indicator","true"),$t.appendChild(ge);let Gt=document.createElement("div");Gt.className="persona-flex",Gt.id="wrapper-idle-indicator",Gt.setAttribute("data-wrapper-id","idle-indicator"),Gt.appendChild($t),y.appendChild(Gt)}}if(si(l,y),pe.length>0)for(let{messageId:P,fingerprint:De,bubble:He}of pe){let ge=l.querySelector(`#wrapper-${P}`);ge&&He!==null&&(ge.replaceChildren(He),ge.setAttribute("data-bubble-fp",De),qr.set(P,De))}if(qr.size>0)for(let P of qr.keys())O.has(P)||qr.delete(P);if(Z.length>0)for(let{messageId:P,fingerprint:De,bubble:He}of Z){let ge=l.querySelector(`#wrapper-${P}`);ge&&He!==null&&(ge.replaceChildren(He),ge.setAttribute("data-bubble-fp",De),Ir.set(P,De))}if(Ir.size>0)for(let P of Ir.keys())O.has(P)||Ir.delete(P);if(Ae.length>0)for(let{messageId:P,fingerprint:De,bubble:He}of Ae){let ge=l.querySelector(`#wrapper-${P}`);ge&&He!==null&&(ge.replaceChildren(He),ge.setAttribute("data-bubble-fp",De),gr.set(P,De))}if(gr.size>0)for(let P of gr.keys())O.has(P)||gr.delete(P)},io=(l,p,h)=>{Pa(l,p,h),to()},lo=null,Ia=()=>{var h;if(lo)return;let l=y=>{let S=y.composedPath();S.includes(Ee)||Je&&S.includes(Je)||T(!1,"user")};lo=l,((h=n.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},Ns=()=>{var p;if(!lo)return;((p=n.ownerDocument)!=null?p:document).removeEventListener("pointerdown",lo,!0),lo=null};ut.push(()=>Ns());let co=null,Wa=()=>{var h;if(co)return;let l=y=>{y.key==="Escape"&&(y.isComposing||T(!1,"user"))};co=l,((h=n.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},Fs=()=>{var p;if(!co)return;((p=n.ownerDocument)!=null?p:document).removeEventListener("keydown",co,!0),co=null};ut.push(()=>Fs());let po=!1,Os=new Set,ns=()=>{var p,h,y,S;let l=(y=(h=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:h.peek)==null?void 0:y.streamAnimation;return l||((S=r.features)==null?void 0:S.streamAnimation)},qe=()=>{var ft,ct,Re,Pe;if(!D())return;let l=Y.peekBanner,p=Y.peekTextNode;if(!l||!p)return;if(M){l.classList.remove("persona-pill-peek--visible");return}let h=(ft=_==null?void 0:_.getMessages())!=null?ft:[],y;for(let Ve=h.length-1;Ve>=0;Ve--){let Xe=h[Ve];if(Xe.role==="assistant"&&Xe.content){y=Xe;break}}if(!y){l.classList.remove("persona-pill-peek--visible");return}let S=y.content,B=!!y.streaming,q=ns(),O=di(q),H=O.type!=="none"?ia(O.type,q==null?void 0:q.plugins):null,de=((ct=H==null?void 0:H.isAnimating)==null?void 0:ct.call(H,y))===!0,pe=H!==null&&(B||de);pe&&H&&!Os.has(H.name)&&(ol(H,n),Os.add(H.name));let Z=pe&&(H!=null&&H.containerClass)?H.containerClass:null,xe=(Re=p.dataset.personaPeekStreamClass)!=null?Re:null;xe&&xe!==Z&&(p.classList.remove(xe),delete p.dataset.personaPeekStreamClass),Z&&xe!==Z&&(p.classList.add(Z),p.dataset.personaPeekStreamClass=Z),pe?(p.style.setProperty("--persona-stream-step",`${O.speed}ms`),p.style.setProperty("--persona-stream-duration",`${O.duration}ms`)):(p.style.removeProperty("--persona-stream-step"),p.style.removeProperty("--persona-stream-duration"));let Ne=pe?pi(S,O.buffer,H,y,B):S;if(pe&&O.placeholder==="skeleton"&&B&&(!Ne||!Ne.trim())){let Ve=document.createElement("div"),Xe=ca();Xe.classList.add("persona-pill-peek__skeleton"),Ve.appendChild(Xe),si(p,Ve)}else{let Ve=Math.max(0,Ne.length-100),Xe=Ne.length>100?Ne.slice(-100):Ne,vt=ho(Xe);if(!pe||!H){let P=Ne.length>100?`\u2026${Xe}`:Xe;p.textContent!==P&&(p.textContent=P)}else{let P=vt;(H.wrap==="char"||H.wrap==="word")&&(P=la(vt,H.wrap,`peek-${y.id}`,{skipTags:H.skipTags,startIndex:Ve}));let De=document.createElement("div");if(De.innerHTML=P,H.useCaret&&Xe.length>0){let He=ui(),ge=De.querySelectorAll(".persona-stream-char, .persona-stream-word"),$t=ge[ge.length-1];$t!=null&&$t.parentNode?$t.parentNode.insertBefore(He,$t.nextSibling):De.appendChild(He)}si(p,De),(Pe=H.onAfterRender)==null||Pe.call(H,{container:p,bubble:l,messageId:y.id,message:y,speed:O.speed,duration:O.duration})}}let ze=Lr||po;l.classList.toggle("persona-pill-peek--visible",ze)};if(D()){let l=Y.peekBanner;if(l){let y=S=>{S.preventDefault(),S.stopPropagation(),T(!0,"user")};l.addEventListener("pointerdown",y),ut.push(()=>{l.removeEventListener("pointerdown",y)})}let p=()=>{po||(po=!0,qe())},h=()=>{po&&(po=!1,qe())};he.addEventListener("pointerenter",p),he.addEventListener("pointerleave",h),ut.push(()=>{he.removeEventListener("pointerenter",p),he.removeEventListener("pointerleave",h)}),Je&&(Je.addEventListener("pointerenter",p),Je.addEventListener("pointerleave",h),ut.push(()=>{Je.removeEventListener("pointerenter",p),Je.removeEventListener("pointerleave",h)}))}let C=l=>{var xe,Ne,Ae,ot,ze,ft,ct,Re;let p=(Ne=(xe=r.launcher)==null?void 0:xe.composerBar)!=null?Ne:{},h=(Ae=p.expandedSize)!=null?Ae:"anchored",y=(ot=p.bottomOffset)!=null?ot:"16px",S=p.collapsedMaxWidth,B=(ze=p.expandedMaxWidth)!=null?ze:"880px",q=(ft=p.expandedTopOffset)!=null?ft:"5vh",O=(ct=p.modalMaxWidth)!=null?ct:"880px",H=(Re=p.modalMaxHeight)!=null?Re:"min(90vh, 800px)",de="calc(100vw - 32px)",pe="var(--persona-pill-area-height, 80px)",Z=Ee.style;if(Z.left="",Z.right="",Z.top="",Z.bottom="",Z.transform="",Z.width="",Z.maxWidth="",Z.height="",Z.maxHeight="",Je){let Pe=Je.style;Pe.bottom=y,Pe.width=S!=null?S:""}if(l&&h!=="fullscreen"){if(h==="modal"){Z.top="50%",Z.left="50%",Z.transform="translate(-50%, -50%)",Z.bottom="auto",Z.right="auto",Z.width=O,Z.maxWidth=de,Z.maxHeight=H,Z.height=H;return}Z.left="50%",Z.transform="translateX(-50%)",Z.bottom=`calc(${y} + ${pe})`,Z.top=q,Z.width=B,Z.maxWidth=de}},$=()=>{var H,de,pe,Z,xe,Ne,Ae,ot;if(!N())return;if(D()){let ft=(pe=((de=(H=r.launcher)==null?void 0:H.composerBar)!=null?de:{}).expandedSize)!=null?pe:"anchored",ct=M?"expanded":"collapsed";Ee.dataset.state=ct,Ee.dataset.expandedSize=ft,Je&&(Je.dataset.state=ct,Je.dataset.expandedSize=ft),Ee.style.removeProperty("display"),Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),C(M),me.style.display=M?"flex":"none",be(),M?(Ia(),Wa()):(Ns(),Fs()),qe();return}let l=Cn(r),p=(Z=n.ownerDocument.defaultView)!=null?Z:window,h=(Ne=(xe=r.launcher)==null?void 0:xe.mobileBreakpoint)!=null?Ne:640,y=(ot=(Ae=r.launcher)==null?void 0:Ae.mobileFullscreen)!=null?ot:!0,S=p.innerWidth<=h,B=y&&S&&k,q=xr(r).reveal;M?(Ee.style.removeProperty("display"),Ee.style.display=l?"flex":"",Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0"),he.classList.add("persona-scale-100","persona-opacity-100"),nn?nn.element.style.display="none":mn&&(mn.style.display="none")):(l?l&&(q==="overlay"||q==="push")&&!B?(Ee.style.removeProperty("display"),Ee.style.display="flex",Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ee.style.setProperty("display","none","important"),Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ee.style.display="",Ee.classList.add("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100"),he.classList.add("persona-scale-95","persona-opacity-0")),nn?nn.element.style.display=l?"none":"":mn&&(mn.style.display=l?"none":""))},T=(l,p="user")=>{var B,q;if(!N()||M===l)return;let h=M;M=l,$();let y=(()=>{var Ae,ot,ze,ft,ct,Re,Pe,Ve,Xe,vt;let O=(ot=(Ae=r.launcher)==null?void 0:Ae.sidebarMode)!=null?ot:!1,H=(ze=n.ownerDocument.defaultView)!=null?ze:window,de=(ct=(ft=r.launcher)==null?void 0:ft.mobileFullscreen)!=null?ct:!0,pe=(Pe=(Re=r.launcher)==null?void 0:Re.mobileBreakpoint)!=null?Pe:640,Z=H.innerWidth<=pe,xe=Cn(r)&&de&&Z,Ne=D()&&((vt=(Xe=(Ve=r.launcher)==null?void 0:Ve.composerBar)==null?void 0:Xe.expandedSize)!=null?vt:"fullscreen")==="fullscreen";return O||de&&Z&&k||xe||Ne})();if(M&&y){if(!tn){let O=n.getRootNode(),H=O instanceof ShadowRoot?O.host:n.closest(".persona-host");H&&(tn=sl(H,(q=(B=r.launcher)==null?void 0:B.zIndex)!=null?q:En))}un||(un=al(n.ownerDocument))}else M||(tn==null||tn(),tn=null,un==null||un(),un=null);M&&(_s(),rt()==="follow"?Hr(!0):Bs());let S={open:M,source:p,timestamp:Date.now()};M&&!h?s.emit("widget:opened",S):!M&&h&&s.emit("widget:closed",S),s.emit("widget:state",{open:M,launcherEnabled:k,voiceActive:yt.active,streaming:_.isStreaming()})},J=l=>{Ln(l?"stop":"send"),j&&(j.disabled=l),Mo.buttons.forEach(p=>{p.disabled=l}),_e.dataset.personaComposerStreaming=l?"true":"false",_e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(p=>{(p instanceof HTMLButtonElement||p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement||p instanceof HTMLSelectElement)&&(p.disabled=l)})},le=()=>{yt.active||Ie&&Ie.focus()};s.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>le(),200)});let X=()=>{var h,y,S,B,q,O,H,de,pe,Z,xe;Cr.textContent=(y=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",U.textContent=(B=(S=r.copy)==null?void 0:S.welcomeSubtitle)!=null?B:"Ask anything about your account or products.",Ie.placeholder=(O=(q=r.copy)==null?void 0:q.inputPlaceholder)!=null?O:"How can I help...";let l=ke.querySelector("[data-persona-intro-card]");if(l){let Ne=((H=r.copy)==null?void 0:H.showWelcomeCard)!==!1;l.style.display=Ne?"":"none",Ne?(ke.classList.remove("persona-gap-3"),ke.classList.add("persona-gap-6")):(ke.classList.remove("persona-gap-6"),ke.classList.add("persona-gap-3"))}!((pe=(de=r.sendButton)==null?void 0:de.useIcon)!=null&&pe)&&!(_!=null&&_.isStreaming())&&(Ke.textContent=(xe=(Z=r.copy)==null?void 0:Z.sendButtonLabel)!=null?xe:"Send"),Ie.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Ie.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let l=d.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{m(p=>({...p,sessionId:l}))}});let Me=null,$e=()=>{Me==null&&(Me=setInterval(()=>{let l=Ye.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Me),Me=null;return}let p=Date.now();l.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=Va(p-y))})},100))};_=new ni(r,{onMessagesChanged(l){var y;io(Ye,l,Le),$e(),Go(l),Hr(!Lr),La(l);let p=[...l].reverse().find(S=>S.role==="user");l.length===0&&Lo(),!Xo||ko?(Xo=!0,Jo=(y=p==null?void 0:p.id)!=null?y:null):p&&p.id!==Jo&&(Jo=p.id,ka(p.id));let h=yt.lastUserMessageId;p&&p.id!==h&&(yt.lastUserMessageId=p.id,s.emit("user:message",p)),yt.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),es(l),qe()},onStatusChanged(l){var y;let p=(y=r.statusIndicator)!=null?y:{};lt(pn,(S=>{var B,q,O,H;return S==="idle"?(B=p.idleText)!=null?B:Mn.idle:S==="connecting"?(q=p.connectingText)!=null?q:Mn.connecting:S==="connected"?(O=p.connectedText)!=null?O:Mn.connected:S==="error"?(H=p.errorText)!=null?H:Mn.error:Mn[S]})(l),p,l)},onStreamingChanged(l){Lr=l,J(l),_&&io(Ye,_.getMessages(),Le),l||Hr(!0),qe()},onVoiceStatusChanged(l){var p,h;if(s.emit("voice:status",{status:l,timestamp:Date.now()}),((h=(p=r.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":jr(),os();break;case"processing":jr(),cg();break;case"speaking":jr(),dg();break;default:l==="idle"&&_.isBargeInActive()?(jr(),os(),j==null||j.setAttribute("aria-label","End voice session")):(yt.active=!1,jr(),ar("system"),$n());break}},onArtifactsState(l){jn=l,Qn(),es()}}),Mt.current=_;let at=null;if(_.onReadAloudChange((l,p)=>{var S;Zr=l,eo=p,to();let h=l!=null?l:at;l&&(at=l);let y=h&&(S=_.getMessages().find(B=>B.id===h))!=null?S:null;s.emit("message:read-aloud",{messageId:h,message:y,state:p,timestamp:Date.now()}),p==="idle"&&(at=null)}),Xo=!0,((Nc=(Dc=r.voiceRecognition)==null?void 0:Dc.provider)==null?void 0:Nc.type)==="runtype")try{_.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&_.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(fe||r.onSSEEvent)&&_.setSSEEventCallback((l,p)=>{var h;(h=r.onSSEEvent)==null||h.call(r,l,p),ue==null||ue.processEvent(l,p),fe==null||fe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(p)})}),c&&c.then(l=>{var p,h,y;if(l){if(l.metadata&&(d=Tl(l.metadata),E.syncFromMetadata()),(p=l.messages)!=null&&p.length){ko=!0;try{_.hydrateMessages(l.messages)}finally{ko=!1}}(h=l.artifacts)!=null&&h.length&&_.hydrateArtifacts(l.artifacts,(y=l.selectedArtifactId)!=null?y:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let tt=()=>{var p,h,y;!D()||M||!((y=(h=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||T(!0,"auto")},Bt=l=>{var S;if(l.preventDefault(),_.isStreaming()){_.cancel(),ue==null||ue.reset(),K==null||K.update();return}let p=Ie.value.trim(),h=(S=xt==null?void 0:xt.hasAttachments())!=null?S:!1;if(!p&&!h)return;tt();let y;h&&(y=[],y.push(...xt.getContentParts()),p&&y.push(Xi(p))),Ie.value="",Ie.style.height="auto",Et(),_.sendMessage(p,{contentParts:y}),h&&xt.clearAttachments()},zt=()=>{var l;return((l=r.features)==null?void 0:l.composerHistory)!==!1},ln={...ai},At=!1,Et=()=>{ln={...ai}},yn=()=>_.getMessages().filter(l=>l.role==="user").map(l=>{var p;return(p=l.content)!=null?p:""}).filter(l=>l.length>0),Rn=l=>{if(!Ie)return;At=!0,Ie.value=l,Ie.dispatchEvent(new Event("input",{bubbles:!0})),At=!1;let p=Ie.value.length;Ie.setSelectionRange(p,p)},wn=()=>{At||Et()},Zt=l=>{if(Ie){if(zt()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let p=Ie.selectionStart===0&&Ie.selectionEnd===0,h=Ju({direction:l.key==="ArrowUp"?"up":"down",history:yn(),currentValue:Ie.value,atStart:p,state:ln});if(ln=h.state,h.handled){l.preventDefault(),h.value!==void 0&&Rn(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(_.isStreaming()){l.preventDefault();return}Et(),l.preventDefault(),Ke.click()}}},ir=l=>{l.key!=="Escape"||l.isComposing||_.isStreaming()&&l.composedPath().includes(me)&&(_.cancel(),ue==null||ue.reset(),K==null||K.update(),Et(),l.preventDefault(),l.stopImmediatePropagation())},Wl=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!xt)return;let p=ly(l.clipboardData);p.length!==0&&(l.preventDefault(),await xt.handleFiles(p))},lr=null,Br=!1,rs=null,gt=null,Rl=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ra=(l="user")=>{var B,q,O,H,de,pe,Z;if(Br||_.isStreaming())return;let p=Rl();if(!p)return;lr=new p;let y=(q=((B=r.voiceRecognition)!=null?B:{}).pauseDuration)!=null?q:2e3;lr.continuous=!0,lr.interimResults=!0,lr.lang="en-US";let S=Ie.value;lr.onresult=xe=>{let Ne="",Ae="";for(let ze=0;ze<xe.results.length;ze++){let ft=xe.results[ze],ct=ft[0].transcript;ft.isFinal?Ne+=ct+" ":Ae=ct}let ot=S+Ne+Ae;Ie.value=ot,rs&&clearTimeout(rs),(Ne||Ae)&&(rs=window.setTimeout(()=>{let ze=Ie.value.trim();ze&&lr&&Br&&(uo(),Ie.value="",Ie.style.height="auto",_.sendMessage(ze,{viaVoice:!0}))},y))},lr.onerror=xe=>{xe.error!=="no-speech"&&uo()},lr.onend=()=>{if(Br){let xe=Ie.value.trim();xe&&xe!==S.trim()&&(Ie.value="",Ie.style.height="auto",_.sendMessage(xe,{viaVoice:!0})),uo()}};try{if(lr.start(),Br=!0,yt.active=!0,l!=="system"&&(yt.manuallyDeactivated=!1),ar(l),$n(),j){let xe=(O=r.voiceRecognition)!=null?O:{};gt={backgroundColor:j.style.backgroundColor,color:j.style.color,borderColor:j.style.borderColor,iconName:(H=xe.iconName)!=null?H:"mic",iconSize:parseFloat((Z=(pe=xe.iconSize)!=null?pe:(de=r.sendButton)==null?void 0:de.size)!=null?Z:"40")||24};let Ne=xe.recordingBackgroundColor,Ae=xe.recordingIconColor,ot=xe.recordingBorderColor;if(j.classList.add("persona-voice-recording"),j.style.backgroundColor=Ne!=null?Ne:"var(--persona-voice-recording-bg, #ef4444)",j.style.color=Ae!=null?Ae:"var(--persona-voice-recording-indicator, #ffffff)",Ae){let ze=j.querySelector("svg");ze&&ze.setAttribute("stroke",Ae)}ot&&(j.style.borderColor=ot),j.setAttribute("aria-label","Stop voice recognition")}}catch{uo("system")}},uo=(l="user")=>{if(Br){if(Br=!1,rs&&(clearTimeout(rs),rs=null),lr){try{lr.stop()}catch{}lr=null}if(yt.active=!1,ar(l),$n(),j){if(j.classList.remove("persona-voice-recording"),gt){j.style.backgroundColor=gt.backgroundColor,j.style.color=gt.color,j.style.borderColor=gt.borderColor;let p=j.querySelector("svg");p&&p.setAttribute("stroke",gt.color||"currentColor"),gt=null}j.setAttribute("aria-label","Start voice recognition")}}},lg=(l,p)=>{var ct,Re,Pe,Ve,Xe,vt,P,De,He;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((ct=l==null?void 0:l.provider)==null?void 0:ct.type)==="runtype",S=((Re=l==null?void 0:l.provider)==null?void 0:Re.type)==="custom";if(!(h||y||S))return null;let q=b("div","persona-send-button-wrapper"),O=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");O.type="button",O.setAttribute("aria-label","Start voice recognition");let H=(Pe=l==null?void 0:l.iconName)!=null?Pe:"mic",de=(Ve=p==null?void 0:p.size)!=null?Ve:"40px",pe=(Xe=l==null?void 0:l.iconSize)!=null?Xe:de,Z=parseFloat(pe)||24,xe=(vt=l==null?void 0:l.backgroundColor)!=null?vt:p==null?void 0:p.backgroundColor,Ne=(P=l==null?void 0:l.iconColor)!=null?P:p==null?void 0:p.textColor;O.style.width=pe,O.style.height=pe,O.style.minWidth=pe,O.style.minHeight=pe,O.style.fontSize="18px",O.style.lineHeight="1",Ne?O.style.color=Ne:O.style.color="var(--persona-text, #111827)";let ot=Se(H,Z,Ne||"currentColor",1.5);ot?O.appendChild(ot):O.textContent="\u{1F3A4}",xe?O.style.backgroundColor=xe:O.style.backgroundColor="",l!=null&&l.borderWidth&&(O.style.borderWidth=l.borderWidth,O.style.borderStyle="solid"),l!=null&&l.borderColor&&(O.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(O.style.paddingLeft=l.paddingX,O.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(O.style.paddingTop=l.paddingY,O.style.paddingBottom=l.paddingY),q.appendChild(O);let ze=(De=l==null?void 0:l.tooltipText)!=null?De:"Start voice recognition";if(((He=l==null?void 0:l.showTooltip)!=null?He:!1)&&ze){let ge=b("div","persona-send-button-tooltip");ge.textContent=ze,q.appendChild(ge)}return{micButton:O,micButtonWrapper:q}},Pi=()=>{var p,h,y,S,B;if(!j||gt)return;let l=(p=r.voiceRecognition)!=null?p:{};gt={backgroundColor:j.style.backgroundColor,color:j.style.color,borderColor:j.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((B=(S=l.iconSize)!=null?S:(y=r.sendButton)==null?void 0:y.size)!=null?B:"40")||24}},Ii=(l,p)=>{var B,q,O,H,de;if(!j)return;let h=j.querySelector("svg");h&&h.remove();let y=(de=gt==null?void 0:gt.iconSize)!=null?de:parseFloat((H=(O=(B=r.voiceRecognition)==null?void 0:B.iconSize)!=null?O:(q=r.sendButton)==null?void 0:q.size)!=null?H:"40")||24,S=Se(l,y,p,1.5);S&&j.appendChild(S)},Ha=()=>{j&&j.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},os=()=>{var S;if(!j)return;Pi();let l=(S=r.voiceRecognition)!=null?S:{},p=l.recordingBackgroundColor,h=l.recordingIconColor,y=l.recordingBorderColor;if(Ha(),j.classList.add("persona-voice-recording"),j.style.backgroundColor=p!=null?p:"var(--persona-voice-recording-bg, #ef4444)",j.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let B=j.querySelector("svg");B&&B.setAttribute("stroke",h)}y&&(j.style.borderColor=y),j.setAttribute("aria-label","Stop voice recognition")},cg=()=>{var O,H,de,pe,Z,xe,Ne,Ae;if(!j)return;Pi();let l=(O=r.voiceRecognition)!=null?O:{},p=_.getVoiceInterruptionMode(),h=(H=l.processingIconName)!=null?H:"loader",y=(pe=(de=l.processingIconColor)!=null?de:gt==null?void 0:gt.color)!=null?pe:"",S=(xe=(Z=l.processingBackgroundColor)!=null?Z:gt==null?void 0:gt.backgroundColor)!=null?xe:"",B=(Ae=(Ne=l.processingBorderColor)!=null?Ne:gt==null?void 0:gt.borderColor)!=null?Ae:"";Ha(),j.classList.add("persona-voice-processing"),j.style.backgroundColor=S,j.style.borderColor=B;let q=y||"currentColor";j.style.color=q,Ii(h,q),j.setAttribute("aria-label","Processing voice input"),p==="none"&&(j.style.cursor="default")},dg=()=>{var de,pe,Z,xe,Ne,Ae,ot,ze,ft,ct,Re,Pe;if(!j)return;Pi();let l=(de=r.voiceRecognition)!=null?de:{},p=_.getVoiceInterruptionMode(),h=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",y=(pe=l.speakingIconName)!=null?pe:h,S=(Ae=l.speakingIconColor)!=null?Ae:p==="barge-in"?(xe=(Z=l.recordingIconColor)!=null?Z:gt==null?void 0:gt.color)!=null?xe:"":(Ne=gt==null?void 0:gt.color)!=null?Ne:"",B=(ft=l.speakingBackgroundColor)!=null?ft:p==="barge-in"?(ot=l.recordingBackgroundColor)!=null?ot:"var(--persona-voice-recording-bg, #ef4444)":(ze=gt==null?void 0:gt.backgroundColor)!=null?ze:"",q=(Pe=l.speakingBorderColor)!=null?Pe:p==="barge-in"?(ct=l.recordingBorderColor)!=null?ct:"":(Re=gt==null?void 0:gt.borderColor)!=null?Re:"";Ha(),j.classList.add("persona-voice-speaking"),j.style.backgroundColor=B,j.style.borderColor=q;let O=S||"currentColor";j.style.color=O,Ii(y,O);let H=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";j.setAttribute("aria-label",H),p==="none"&&(j.style.cursor="default"),p==="barge-in"&&j.classList.add("persona-voice-recording")},jr=()=>{var l,p,h;j&&(Ha(),gt&&(j.style.backgroundColor=(l=gt.backgroundColor)!=null?l:"",j.style.color=(p=gt.color)!=null?p:"",j.style.borderColor=(h=gt.borderColor)!=null?h:"",Ii(gt.iconName,gt.color||"currentColor"),gt=null),j.style.cursor="",j.setAttribute("aria-label","Start voice recognition"))},Ba=()=>{var l,p;if(((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"){let h=_.getVoiceStatus(),y=_.getVoiceInterruptionMode();if(y==="none"&&(h==="processing"||h==="speaking"))return;if(y==="cancel"&&(h==="processing"||h==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{yt.active=!1,yt.manuallyDeactivated=!0,$n(),ar("user"),jr()});return}_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),yt.manuallyDeactivated=!_.isVoiceActive(),$n(),ar("user"),_.isVoiceActive()?os():jr()});return}if(Br){let h=Ie.value.trim();yt.manuallyDeactivated=!0,$n(),uo("user"),h&&(Ie.value="",Ie.style.height="auto",_.sendMessage(h))}else yt.manuallyDeactivated=!1,$n(),Ra("user")};zn=Ba,j&&(j.addEventListener("click",Ba),ut.push(()=>{var l,p;((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),jr()):uo("system"),j&&j.removeEventListener("click",Ba)}));let pg=s.on("assistant:complete",()=>{ks&&(yt.active||yt.manuallyDeactivated||ks==="assistant"&&!yt.lastUserMessageWasVoice||setTimeout(()=>{var l,p;!yt.active&&!yt.manuallyDeactivated&&(((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),ar("auto"),_.isVoiceActive()&&os()}):Ra("auto"))},600))});ut.push(pg);let ug=s.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});ut.push(ug);let Hl=()=>{T(!M,"user")},nn=null,mn=null;if(k&&!D()){let{instance:l,element:p}=cl({config:r,plugins:o,onToggle:Hl});nn=l,l||(mn=p)}nn?n.appendChild(nn.element):mn&&n.appendChild(mn),$(),Go(),X(),J(_.isStreaming()),rt()==="follow"?Hr(!0):Bs(),Aa(),F&&(!k||D()?setTimeout(()=>le(),0):M&&setTimeout(()=>le(),200));let _s=()=>{var H,de,pe,Z,xe,Ne,Ae,ot,ze,ft,ct,Re,Pe,Ve,Xe,vt,P,De,He,ge,$t,Ot;if(D()){On(),$();return}let l=Cn(r),p=(de=(H=r.launcher)==null?void 0:H.sidebarMode)!=null?de:!1,h=l||p||((Z=(pe=r.launcher)==null?void 0:pe.fullHeight)!=null?Z:!1),y=(xe=n.ownerDocument.defaultView)!=null?xe:window,S=(Ae=(Ne=r.launcher)==null?void 0:Ne.mobileFullscreen)!=null?Ae:!0,B=(ze=(ot=r.launcher)==null?void 0:ot.mobileBreakpoint)!=null?ze:640,q=y.innerWidth<=B,O=S&&q&&k;try{if(O){be(),xs(n,r);return}if(W&&(W=!1,be(),xs(n,r)),!k&&!l){he.style.height="",he.style.width="";return}if(!p&&!l){let Gt=(ct=(ft=r==null?void 0:r.launcher)==null?void 0:ft.width)!=null?ct:r==null?void 0:r.launcherWidth,wt=Gt!=null?Gt:Xr;he.style.width=wt,he.style.maxWidth=wt}if(Mr(),!h){let Gt=y.innerHeight,wt=64,Vt=(Pe=(Re=r.launcher)==null?void 0:Re.heightOffset)!=null?Pe:0,Yn=Math.max(200,Gt-wt),rn=Math.min(640,Yn),Ze=Math.max(200,rn-Vt);he.style.height=`${Ze}px`}}finally{if(On(),$(),M&&k){let wt=((Ve=n.ownerDocument.defaultView)!=null?Ve:window).innerWidth<=((vt=(Xe=r.launcher)==null?void 0:Xe.mobileBreakpoint)!=null?vt:640),Vt=(De=(P=r.launcher)==null?void 0:P.sidebarMode)!=null?De:!1,Yn=(ge=(He=r.launcher)==null?void 0:He.mobileFullscreen)!=null?ge:!0,rn=Cn(r)&&Yn&&wt,Ze=Vt||Yn&&wt&&k||rn;if(Ze&&!un){let It=n.getRootNode(),dn=It instanceof ShadowRoot?It.host:n.closest(".persona-host");dn&&!tn&&(tn=sl(dn,(Ot=($t=r.launcher)==null?void 0:$t.zIndex)!=null?Ot:En)),un=al(n.ownerDocument)}else Ze||(tn==null||tn(),tn=null,un==null||un(),un=null)}}};_s();let Bl=(Fc=n.ownerDocument.defaultView)!=null?Fc:window;if(Bl.addEventListener("resize",_s),ut.push(()=>Bl.removeEventListener("resize",_s)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{On()});l.observe(_e),ut.push(()=>l.disconnect())}Jn=ke.scrollTop;let Dl=Jr(ke),mg=()=>{let l=ke.getRootNode(),p=typeof l.getSelection=="function"?l.getSelection():null;return p!=null?p:ke.ownerDocument.getSelection()},Wi=()=>rm(mg(),ke),Nl=()=>{let l=ke.scrollTop,p=Jr(ke),h=p<Dl;if(Dl=p,rt()!=="follow"){Jn=l,Un();return}let{action:y,nextLastScrollTop:S}=li({following:Xn.isFollowing(),currentScrollTop:l,lastScrollTop:Jn,nearBottom:qo(ke,Yo),userScrollThreshold:wa,isAutoScrolling:hr||Eo||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Jn=S,y==="resume"){Wi()||Rr();return}y==="pause"&&ts()};if(ke.addEventListener("scroll",Nl,{passive:!0}),ut.push(()=>ke.removeEventListener("scroll",Nl)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Ea()});l.observe(Ye),l.observe(ke),ut.push(()=>l.disconnect())}let Fl=()=>{rt()==="follow"&&Xn.isFollowing()&&Wi()&&ts()},Ol=ke.ownerDocument;Ol.addEventListener("selectionchange",Fl),ut.push(()=>{Ol.removeEventListener("selectionchange",Fl)});let _l=l=>{if(rt()!=="follow")return;let p=ci({following:Xn.isFollowing(),deltaY:l.deltaY,nearBottom:qo(ke,Yo),resumeWhenNearBottom:!0});p==="pause"?ts():p==="resume"&&!Wi()&&Rr()};ke.addEventListener("wheel",_l,{passive:!0}),ut.push(()=>ke.removeEventListener("wheel",_l)),pt.addEventListener("click",()=>{Lo(),ke.scrollTop=ke.scrollHeight,Jn=ke.scrollTop,Rr(),Hr(!0),Un()}),ut.push(()=>pt.remove()),ut.push(()=>{Ps(),Lo()});let $l=()=>{G&&(kr&&(G.removeEventListener("click",kr),kr=null),N()?(G.style.display="",kr=()=>{T(!1,"user")},G.addEventListener("click",kr)):G.style.display="none")};$l(),(()=>{let{clearChatButton:l}=Y;l&&l.addEventListener("click",()=>{_.clearMessages(),Pr.clear(),Rr(),ms(Y.composerOverlay);try{localStorage.removeItem(Ts),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ts}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Ts)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let p=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}d={},E.syncFromMetadata(),fe==null||fe.clear(),ue==null||ue.reset(),K==null||K.update()})})(),Rt&&Rt.addEventListener("submit",Bt),Ie==null||Ie.addEventListener("keydown",Zt),Ie==null||Ie.addEventListener("input",wn),Ie==null||Ie.addEventListener("paste",Wl);let Ul=(Oc=n.ownerDocument)!=null?Oc:document;Ul.addEventListener("keydown",ir,!0);let ql="persona-attachment-drop-active",$s=0,Ri=()=>{$s=0,me.classList.remove(ql)},ss=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&xt!==null},zl=l=>{!ki(l.dataTransfer)||!ss()||($s++,$s===1&&me.classList.add(ql))},Vl=l=>{!ki(l.dataTransfer)||!ss()||($s--,$s<=0&&Ri())},jl=l=>{!ki(l.dataTransfer)||!ss()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Kl=l=>{var h;if(!ki(l.dataTransfer)||!ss())return;l.preventDefault(),l.stopPropagation(),Ri();let p=Array.from((h=l.dataTransfer.files)!=null?h:[]);p.length!==0&&xt.handleFiles(p)},mo=!0;me.addEventListener("dragenter",zl,mo),me.addEventListener("dragleave",Vl,mo),n.addEventListener("dragover",jl,mo),n.addEventListener("drop",Kl,mo);let Da=n.ownerDocument,Gl=l=>{ss()&&l.preventDefault()},Ql=l=>{ss()&&l.preventDefault()};Da.addEventListener("dragover",Gl),Da.addEventListener("drop",Ql),ut.push(()=>{Rt&&Rt.removeEventListener("submit",Bt),Ie==null||Ie.removeEventListener("keydown",Zt),Ie==null||Ie.removeEventListener("input",wn),Ie==null||Ie.removeEventListener("paste",Wl),Ul.removeEventListener("keydown",ir,!0)}),ut.push(()=>{me.removeEventListener("dragenter",zl,mo),me.removeEventListener("dragleave",Vl,mo),n.removeEventListener("dragover",jl,mo),n.removeEventListener("drop",Kl,mo),Da.removeEventListener("dragover",Gl),Da.removeEventListener("drop",Ql),Ri()}),ut.push(()=>{_.cancel()}),nn?ut.push(()=>{nn==null||nn.destroy()}):mn&&ut.push(()=>{mn==null||mn.remove()});let cn={update(l){var Sn,Hn,Dr,bn,Bn,Dn,Ho,Us,jc,Kc,Gc,Qc,Xc,Jc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,vd,xd,wd,Cd,Ad,Sd,Td,Md,Ed,kd,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Fd,Od,_d,$d,Ud,qd,zd,Vd,jd,Kd,Gd,Qd,Xd,Jd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,vp,xp,wp,Cp,Ap,Sp,Tp,Mp,Ep,kp,Lp,Pp,Ip,Wp,Rp,Hp,Bp,Dp,Np,Fp,Op,_p,$p,Up,qp,zp;let p=r.toolCall,h=r.messageActions,y=(Sn=r.layout)==null?void 0:Sn.messages,S=r.colorScheme,B=r.loadingIndicator,q=r.iterationDisplay,O=(Hn=r.features)==null?void 0:Hn.showReasoning,H=(Dr=r.features)==null?void 0:Dr.showToolCalls,de=(bn=r.features)==null?void 0:bn.toolCallDisplay,pe=(Bn=r.features)==null?void 0:Bn.reasoningDisplay;r={...r,...l},be(),xs(n,r),Mi(n,r),Ei(n,r),Qn(),r.colorScheme!==S&&Es();let Z=xl.getForInstance(r.plugins);o.length=0,o.push(...Z),k=(Ho=(Dn=r.launcher)==null?void 0:Dn.enabled)!=null?Ho:!0,L=(jc=(Us=r.launcher)==null?void 0:Us.autoExpand)!=null?jc:!1,je=(Gc=(Kc=r.features)==null?void 0:Kc.showReasoning)!=null?Gc:!0,ve=(Xc=(Qc=r.features)==null?void 0:Qc.showToolCalls)!=null?Xc:!0,Oe=(Yc=(Jc=r.features)==null?void 0:Jc.scrollToBottom)!=null?Yc:{};let xe=rt();Te=(ed=(Zc=r.features)==null?void 0:Zc.scrollBehavior)!=null?ed:{},xe!==rt()&&(Lo(),Rr()),Ar(),Un();let Ne=Be;if(Be=(nd=(td=r.features)==null?void 0:td.showEventStreamToggle)!=null?nd:!1,Be&&!Ne){if(fe||(Q=new ha(se),fe=new fa(ae,Q),ue=ue!=null?ue:new ya,Q.open().then(()=>fe==null?void 0:fe.restore()).catch(()=>{}),_.setSSEEventCallback((ne,kt)=>{var jt;(jt=r.onSSEEvent)==null||jt.call(r,ne,kt),ue==null||ue.processEvent(ne,kt),fe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ne,timestamp:Date.now(),payload:JSON.stringify(kt)})})),!bt&&Ue){let ne=(od=(rd=r.features)==null?void 0:rd.eventStream)==null?void 0:od.classNames,kt="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"+(ne!=null&&ne.toggleButton?" "+ne.toggleButton:"");bt=b("button",kt),bt.style.width="28px",bt.style.height="28px",bt.style.color=Fn.actionIconColor,bt.type="button",bt.setAttribute("aria-label","Event Stream"),bt.title="Event Stream";let jt=Se("activity","18px","currentColor",1.5);jt&&bt.appendChild(jt);let dt=Y.clearChatButtonWrapper,Wt=Y.closeButtonWrapper,fn=dt||Wt;fn&&fn.parentNode===Ue?Ue.insertBefore(bt,fn):Ue.appendChild(bt),bt.addEventListener("click",()=>{ie?mr():Fr()})}}else!Be&&Ne&&(mr(),bt&&(bt.remove(),bt=null),fe==null||fe.clear(),Q==null||Q.destroy(),fe=null,Q=null,ue==null||ue.reset(),ue=null);if(((sd=r.launcher)==null?void 0:sd.enabled)===!1&&nn&&(nn.destroy(),nn=null),((ad=r.launcher)==null?void 0:ad.enabled)===!1&&mn&&(mn.remove(),mn=null),((id=r.launcher)==null?void 0:id.enabled)!==!1&&!nn&&!mn){let{instance:ne,element:kt}=cl({config:r,plugins:o,onToggle:Hl});nn=ne,ne||(mn=kt),n.appendChild(kt)}nn&&nn.update(r),Qe&&((ld=r.launcher)==null?void 0:ld.title)!==void 0&&(Qe.textContent=r.launcher.title),et&&((cd=r.launcher)==null?void 0:cd.subtitle)!==void 0&&(et.textContent=r.launcher.subtitle);let Ae=(dd=r.layout)==null?void 0:dd.header;if((Ae==null?void 0:Ae.layout)!==A&&Ue){let ne=Ae?fi(r,Ae,{showClose:N(),onClose:()=>T(!1,"user")}):zo({config:r,showClose:N(),onClose:()=>T(!1,"user")});st.replaceHeader(ne),Ue=st.header.element,ye=st.header.iconHolder,Qe=st.header.headerTitle,et=st.header.headerSubtitle,G=st.header.closeButton,A=Ae==null?void 0:Ae.layout}else if(Ae&&(ye&&(ye.style.display=Ae.showIcon===!1?"none":""),Qe&&(Qe.style.display=Ae.showTitle===!1?"none":""),et&&(et.style.display=Ae.showSubtitle===!1?"none":""),G&&(G.style.display=Ae.showCloseButton===!1?"none":""),Y.clearChatButtonWrapper)){let ne=Ae.showClearChat;if(ne!==void 0){Y.clearChatButtonWrapper.style.display=ne?"":"none";let{closeButtonWrapper:kt}=Y;kt&&!kt.classList.contains("persona-absolute")&&(ne?kt.classList.remove("persona-ml-auto"):kt.classList.add("persona-ml-auto"))}}let ze=((pd=r.layout)==null?void 0:pd.showHeader)!==!1;Ue&&(Ue.style.display=ze?"":"none");let ft=((ud=r.layout)==null?void 0:ud.showFooter)!==!1;_e&&(_e.style.display=ft?"":"none"),On(),Un(),k!==R?k?T(L,"auto"):(M=!0,$()):L!==I&&T(L,"auto"),I=L,R=k,_s(),$l();let Pe=JSON.stringify(l.toolCall)!==JSON.stringify(p),Ve=JSON.stringify(r.messageActions)!==JSON.stringify(h),Xe=JSON.stringify((md=r.layout)==null?void 0:md.messages)!==JSON.stringify(y),vt=((gd=r.loadingIndicator)==null?void 0:gd.render)!==(B==null?void 0:B.render)||((fd=r.loadingIndicator)==null?void 0:fd.renderIdle)!==(B==null?void 0:B.renderIdle)||((hd=r.loadingIndicator)==null?void 0:hd.showBubble)!==(B==null?void 0:B.showBubble),P=r.iterationDisplay!==q,De=((bd=(yd=r.features)==null?void 0:yd.showReasoning)!=null?bd:!0)!==(O!=null?O:!0)||((xd=(vd=r.features)==null?void 0:vd.showToolCalls)!=null?xd:!0)!==(H!=null?H:!0)||JSON.stringify((wd=r.features)==null?void 0:wd.toolCallDisplay)!==JSON.stringify(de)||JSON.stringify((Cd=r.features)==null?void 0:Cd.reasoningDisplay)!==JSON.stringify(pe);(Pe||Ve||Xe||vt||P||De)&&_&&(Qo++,io(Ye,_.getMessages(),Le));let ge=(Ad=r.launcher)!=null?Ad:{},$t=(Sd=ge.headerIconHidden)!=null?Sd:!1,Ot=(Md=(Td=r.layout)==null?void 0:Td.header)==null?void 0:Md.showIcon,Gt=$t||Ot===!1,wt=ge.headerIconName,Vt=(Ed=ge.headerIconSize)!=null?Ed:"48px";if(ye){let ne=me.querySelector(".persona-border-b-persona-divider"),kt=ne==null?void 0:ne.querySelector(".persona-flex-col");if(Gt)ye.style.display="none",ne&&kt&&!ne.contains(kt)&&ne.insertBefore(kt,ne.firstChild);else{if(ye.style.display="",ye.style.height=Vt,ye.style.width=Vt,ne&&kt&&(ne.contains(ye)?ye.nextSibling!==kt&&(ye.remove(),ne.insertBefore(ye,kt)):ne.insertBefore(ye,kt)),wt){let dt=parseFloat(Vt)||24,Wt=Se(wt,dt*.6,"currentColor",1);Wt?ye.replaceChildren(Wt):ye.textContent=(kd=ge.agentIconText)!=null?kd:"\u{1F4AC}"}else if(ge.iconUrl){let dt=ye.querySelector("img");if(dt)dt.src=ge.iconUrl,dt.style.height=Vt,dt.style.width=Vt;else{let Wt=document.createElement("img");Wt.src=ge.iconUrl,Wt.alt="",Wt.className="persona-rounded-xl persona-object-cover",Wt.style.height=Vt,Wt.style.width=Vt,ye.replaceChildren(Wt)}}else{let dt=ye.querySelector("svg"),Wt=ye.querySelector("img");(dt||Wt)&&ye.replaceChildren(),ye.textContent=(Ld=ge.agentIconText)!=null?Ld:"\u{1F4AC}"}let jt=ye.querySelector("img");jt&&(jt.style.height=Vt,jt.style.width=Vt)}}let Yn=(Id=(Pd=r.layout)==null?void 0:Pd.header)==null?void 0:Id.showTitle,rn=(Rd=(Wd=r.layout)==null?void 0:Wd.header)==null?void 0:Rd.showSubtitle;if(Qe&&(Qe.style.display=Yn===!1?"none":""),et&&(et.style.display=rn===!1?"none":""),G){((Bd=(Hd=r.layout)==null?void 0:Hd.header)==null?void 0:Bd.showCloseButton)===!1?G.style.display="none":G.style.display="";let kt=(Dd=ge.closeButtonSize)!=null?Dd:"32px",jt=(Nd=ge.closeButtonPlacement)!=null?Nd:"inline";G.style.height=kt,G.style.width=kt;let{closeButtonWrapper:dt}=Y,Wt=jt==="top-right",fn=dt==null?void 0:dt.classList.contains("persona-absolute");if(dt&&Wt!==fn)if(dt.remove(),Wt)dt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",me.style.position="relative",me.appendChild(dt);else{let mt=(Od=(Fd=ge.clearChat)==null?void 0:Fd.placement)!=null?Od:"inline",hn=($d=(_d=ge.clearChat)==null?void 0:_d.enabled)!=null?$d:!0;dt.className=hn&&mt==="inline"?"":"persona-ml-auto";let qn=me.querySelector(".persona-border-b-persona-divider");qn&&qn.appendChild(dt)}if(G.style.color=ge.closeButtonColor||Fn.actionIconColor,ge.closeButtonBackgroundColor?(G.style.backgroundColor=ge.closeButtonBackgroundColor,G.classList.remove("hover:persona-bg-gray-100")):(G.style.backgroundColor="",G.classList.add("hover:persona-bg-gray-100")),ge.closeButtonBorderWidth||ge.closeButtonBorderColor){let mt=ge.closeButtonBorderWidth||"0px",hn=ge.closeButtonBorderColor||"transparent";G.style.border=`${mt} solid ${hn}`,G.classList.remove("persona-border-none")}else G.style.border="",G.classList.add("persona-border-none");ge.closeButtonBorderRadius?(G.style.borderRadius=ge.closeButtonBorderRadius,G.classList.remove("persona-rounded-full")):(G.style.borderRadius="",G.classList.add("persona-rounded-full")),ge.closeButtonPaddingX?(G.style.paddingLeft=ge.closeButtonPaddingX,G.style.paddingRight=ge.closeButtonPaddingX):(G.style.paddingLeft="",G.style.paddingRight=""),ge.closeButtonPaddingY?(G.style.paddingTop=ge.closeButtonPaddingY,G.style.paddingBottom=ge.closeButtonPaddingY):(G.style.paddingTop="",G.style.paddingBottom="");let Tn=(Ud=ge.closeButtonIconName)!=null?Ud:"x",br=(qd=ge.closeButtonIconText)!=null?qd:"\xD7";G.innerHTML="";let Nn=Se(Tn,"28px","currentColor",1);Nn?G.appendChild(Nn):G.textContent=br;let en=(zd=ge.closeButtonTooltipText)!=null?zd:"Close chat",er=(Vd=ge.closeButtonShowTooltip)!=null?Vd:!0;if(G.setAttribute("aria-label",en),dt&&(dt._cleanupTooltip&&(dt._cleanupTooltip(),delete dt._cleanupTooltip),er&&en)){let mt=null,hn=()=>{if(mt||!G)return;let Bo=G.ownerDocument,qs=Bo.body;if(!qs)return;mt=Nr(Bo,"div","persona-clear-chat-tooltip"),mt.textContent=en;let zs=Nr(Bo,"div");zs.className="persona-clear-chat-tooltip-arrow",mt.appendChild(zs);let Do=G.getBoundingClientRect();mt.style.position="fixed",mt.style.zIndex=String(xo),mt.style.left=`${Do.left+Do.width/2}px`,mt.style.top=`${Do.top-8}px`,mt.style.transform="translate(-50%, -100%)",qs.appendChild(mt)},qn=()=>{mt&&mt.parentNode&&(mt.parentNode.removeChild(mt),mt=null)};dt.addEventListener("mouseenter",hn),dt.addEventListener("mouseleave",qn),G.addEventListener("focus",hn),G.addEventListener("blur",qn),dt._cleanupTooltip=()=>{qn(),dt&&(dt.removeEventListener("mouseenter",hn),dt.removeEventListener("mouseleave",qn)),G&&(G.removeEventListener("focus",hn),G.removeEventListener("blur",qn))}}}let{clearChatButton:Ze,clearChatButtonWrapper:It}=Y;if(Ze){let ne=(jd=ge.clearChat)!=null?jd:{},kt=(Kd=ne.enabled)!=null?Kd:!0,jt=(Qd=(Gd=r.layout)==null?void 0:Gd.header)==null?void 0:Qd.showClearChat,dt=jt!==void 0?jt:kt,Wt=(Xd=ne.placement)!=null?Xd:"inline";if(It){It.style.display=dt?"":"none";let{closeButtonWrapper:fn}=Y;!D()&&fn&&!fn.classList.contains("persona-absolute")&&(dt?fn.classList.remove("persona-ml-auto"):fn.classList.add("persona-ml-auto"));let Tn=Wt==="top-right",br=It.classList.contains("persona-absolute");if(!D()&&Tn!==br&&dt){if(It.remove(),Tn)It.className="persona-absolute persona-top-4 persona-z-50",It.style.right="48px",me.style.position="relative",me.appendChild(It);else{It.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",It.style.right="";let en=me.querySelector(".persona-border-b-persona-divider"),er=Y.closeButtonWrapper;en&&er&&er.parentElement===en?en.insertBefore(It,er):en&&en.appendChild(It)}let Nn=Y.closeButtonWrapper;Nn&&!Nn.classList.contains("persona-absolute")&&(Tn?Nn.classList.add("persona-ml-auto"):Nn.classList.remove("persona-ml-auto"))}}if(dt){if(!D()){let mt=(Jd=ne.size)!=null?Jd:"32px";Ze.style.height=mt,Ze.style.width=mt}let fn=(Yd=ne.iconName)!=null?Yd:"refresh-cw",Tn=(Zd=ne.iconColor)!=null?Zd:"";Ze.style.color=Tn||Fn.actionIconColor,Ze.innerHTML="";let br=D()?"14px":"20px",Nn=Se(fn,br,"currentColor",2);if(Nn&&Ze.appendChild(Nn),ne.backgroundColor?(Ze.style.backgroundColor=ne.backgroundColor,Ze.classList.remove("hover:persona-bg-gray-100")):(Ze.style.backgroundColor="",Ze.classList.add("hover:persona-bg-gray-100")),ne.borderWidth||ne.borderColor){let mt=ne.borderWidth||"0px",hn=ne.borderColor||"transparent";Ze.style.border=`${mt} solid ${hn}`,Ze.classList.remove("persona-border-none")}else Ze.style.border="",Ze.classList.add("persona-border-none");ne.borderRadius?(Ze.style.borderRadius=ne.borderRadius,Ze.classList.remove("persona-rounded-full")):(Ze.style.borderRadius="",Ze.classList.add("persona-rounded-full")),ne.paddingX?(Ze.style.paddingLeft=ne.paddingX,Ze.style.paddingRight=ne.paddingX):(Ze.style.paddingLeft="",Ze.style.paddingRight=""),ne.paddingY?(Ze.style.paddingTop=ne.paddingY,Ze.style.paddingBottom=ne.paddingY):(Ze.style.paddingTop="",Ze.style.paddingBottom="");let en=(ep=ne.tooltipText)!=null?ep:"Clear chat",er=(tp=ne.showTooltip)!=null?tp:!0;if(Ze.setAttribute("aria-label",en),It&&(It._cleanupTooltip&&(It._cleanupTooltip(),delete It._cleanupTooltip),er&&en)){let mt=null,hn=()=>{if(mt||!Ze)return;let Bo=Ze.ownerDocument,qs=Bo.body;if(!qs)return;mt=Nr(Bo,"div","persona-clear-chat-tooltip"),mt.textContent=en;let zs=Nr(Bo,"div");zs.className="persona-clear-chat-tooltip-arrow",mt.appendChild(zs);let Do=Ze.getBoundingClientRect();mt.style.position="fixed",mt.style.zIndex=String(xo),mt.style.left=`${Do.left+Do.width/2}px`,mt.style.top=`${Do.top-8}px`,mt.style.transform="translate(-50%, -100%)",qs.appendChild(mt)},qn=()=>{mt&&mt.parentNode&&(mt.parentNode.removeChild(mt),mt=null)};It.addEventListener("mouseenter",hn),It.addEventListener("mouseleave",qn),Ze.addEventListener("focus",hn),Ze.addEventListener("blur",qn),It._cleanupTooltip=()=>{qn(),It&&(It.removeEventListener("mouseenter",hn),It.removeEventListener("mouseleave",qn)),Ze&&(Ze.removeEventListener("focus",hn),Ze.removeEventListener("blur",qn))}}}}let dn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Cl],dr=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ba.message,ba.messageAndClick];E=Al({parsers:dn,handlers:dr,getSessionMetadata:u,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),Le=Gm(r,E,oe),_.updateConfig(r),io(Ye,_.getMessages(),Le),Go(),X(),J(_.isStreaming());let Zn=((np=r.voiceRecognition)==null?void 0:np.enabled)===!0,Po=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Io=((op=(rp=r.voiceRecognition)==null?void 0:rp.provider)==null?void 0:op.type)==="runtype";if(Zn&&(Po||Io))if(!j||!Ht){let ne=lg(r.voiceRecognition,r.sendButton);ne&&(j=ne.micButton,Ht=ne.micButtonWrapper,Jt.insertBefore(Ht,vn),j.addEventListener("click",Ba),j.disabled=_.isStreaming())}else{let ne=(sp=r.voiceRecognition)!=null?sp:{},kt=(ap=r.sendButton)!=null?ap:{},jt=(ip=ne.iconName)!=null?ip:"mic",dt=(lp=kt.size)!=null?lp:"40px",Wt=(cp=ne.iconSize)!=null?cp:dt,fn=parseFloat(Wt)||24;j.style.width=Wt,j.style.height=Wt,j.style.minWidth=Wt,j.style.minHeight=Wt;let Tn=(pp=(dp=ne.iconColor)!=null?dp:kt.textColor)!=null?pp:"currentColor";j.innerHTML="";let br=Se(jt,fn,Tn,2);br?j.appendChild(br):j.textContent="\u{1F3A4}";let Nn=(up=ne.backgroundColor)!=null?up:kt.backgroundColor;Nn?j.style.backgroundColor=Nn:j.style.backgroundColor="",Tn?j.style.color=Tn:j.style.color="var(--persona-text, #111827)",ne.borderWidth?(j.style.borderWidth=ne.borderWidth,j.style.borderStyle="solid"):(j.style.borderWidth="",j.style.borderStyle=""),ne.borderColor?j.style.borderColor=ne.borderColor:j.style.borderColor="",ne.paddingX?(j.style.paddingLeft=ne.paddingX,j.style.paddingRight=ne.paddingX):(j.style.paddingLeft="",j.style.paddingRight=""),ne.paddingY?(j.style.paddingTop=ne.paddingY,j.style.paddingBottom=ne.paddingY):(j.style.paddingTop="",j.style.paddingBottom="");let en=Ht==null?void 0:Ht.querySelector(".persona-send-button-tooltip"),er=(mp=ne.tooltipText)!=null?mp:"Start voice recognition";if(((gp=ne.showTooltip)!=null?gp:!1)&&er)if(en)en.textContent=er,en.style.display="";else{let hn=document.createElement("div");hn.className="persona-send-button-tooltip",hn.textContent=er,Ht==null||Ht.insertBefore(hn,j)}else en&&(en.style.display="none");Ht.style.display="",j.disabled=_.isStreaming()}else j&&Ht&&(Ht.style.display="none",((hp=(fp=r.voiceRecognition)==null?void 0:fp.provider)==null?void 0:hp.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():Br&&uo());if(((yp=r.attachments)==null?void 0:yp.enabled)===!0)if(!Ce||!ce){let ne=(bp=r.attachments)!=null?bp:{},jt=(xp=((vp=r.sendButton)!=null?vp:{}).size)!=null?xp:"40px";Tt||(Tt=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Tt.style.display="none",Rt.insertBefore(Tt,Ie)),Fe||(Fe=document.createElement("input"),Fe.type="file",Fe.accept=((wp=ne.allowedTypes)!=null?wp:Qr).join(","),Fe.multiple=((Cp=ne.maxFiles)!=null?Cp:4)>1,Fe.style.display="none",Fe.setAttribute("aria-label","Attach files"),Rt.insertBefore(Fe,Ie)),Ce=b("div","persona-send-button-wrapper"),ce=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ce.type="button",ce.setAttribute("aria-label",(Ap=ne.buttonTooltipText)!=null?Ap:"Attach file");let dt=(Sp=ne.buttonIconName)!=null?Sp:"paperclip",Wt=jt,fn=parseFloat(Wt)||40,Tn=Math.round(fn*.6);ce.style.width=Wt,ce.style.height=Wt,ce.style.minWidth=Wt,ce.style.minHeight=Wt,ce.style.fontSize="18px",ce.style.lineHeight="1",ce.style.backgroundColor="transparent",ce.style.color="var(--persona-primary, #111827)",ce.style.border="none",ce.style.borderRadius="6px",ce.style.transition="background-color 0.15s ease",ce.addEventListener("mouseenter",()=>{ce.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ce.addEventListener("mouseleave",()=>{ce.style.backgroundColor="transparent"});let br=Se(dt,Tn,"currentColor",1.5);br?ce.appendChild(br):ce.textContent="\u{1F4CE}",ce.addEventListener("click",er=>{er.preventDefault(),Fe==null||Fe.click()}),Ce.appendChild(ce);let Nn=(Tp=ne.buttonTooltipText)!=null?Tp:"Attach file",en=b("div","persona-send-button-tooltip");en.textContent=Nn,Ce.appendChild(en),Kt.append(Ce),!xt&&Fe&&Tt&&(xt=oa.fromConfig(ne),xt.setPreviewsContainer(Tt),Fe.addEventListener("change",async()=>{xt&&(Fe!=null&&Fe.files)&&(await xt.handleFileSelect(Fe.files),Fe.value="")})),me.querySelector(".persona-attachment-drop-overlay")||me.appendChild(Qm(ne.dropOverlay))}else{Ce.style.display="";let ne=(Mp=r.attachments)!=null?Mp:{};Fe&&(Fe.accept=((Ep=ne.allowedTypes)!=null?Ep:Qr).join(","),Fe.multiple=((kp=ne.maxFiles)!=null?kp:4)>1),xt&&xt.updateConfig({allowedTypes:ne.allowedTypes,maxFileSize:ne.maxFileSize,maxFiles:ne.maxFiles})}else Ce&&(Ce.style.display="none"),xt&&xt.clearAttachments(),(Lp=me.querySelector(".persona-attachment-drop-overlay"))==null||Lp.remove();let Qt=(Pp=r.sendButton)!=null?Pp:{},Wo=(Ip=Qt.useIcon)!=null?Ip:!1,go=(Wp=Qt.iconText)!=null?Wp:"\u2191",fo=Qt.iconName,Kr=(Rp=Qt.tooltipText)!=null?Rp:"Send message",Ro=(Hp=Qt.showTooltip)!=null?Hp:!1,yr=(Bp=Qt.size)!=null?Bp:"40px",nt=Qt.backgroundColor,gn=Qt.textColor;if(Wo){if(Ke.style.width=yr,Ke.style.height=yr,Ke.style.minWidth=yr,Ke.style.minHeight=yr,Ke.style.fontSize="18px",Ke.style.lineHeight="1",Ke.innerHTML="",gn?Ke.style.color=gn:Ke.style.color="var(--persona-button-primary-fg, #ffffff)",fo){let ne=parseFloat(yr)||24,kt=(gn==null?void 0:gn.trim())||"currentColor",jt=Se(fo,ne,kt,2);jt?Ke.appendChild(jt):Ke.textContent=go}else Ke.textContent=go;Ke.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",nt?(Ke.style.backgroundColor=nt,Ke.classList.remove("persona-bg-persona-primary")):(Ke.style.backgroundColor="",Ke.classList.add("persona-bg-persona-primary"))}else Ke.textContent=(Np=(Dp=r.copy)==null?void 0:Dp.sendButtonLabel)!=null?Np:"Send",Ke.style.width="",Ke.style.height="",Ke.style.minWidth="",Ke.style.minHeight="",Ke.style.fontSize="",Ke.style.lineHeight="",Ke.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",nt?(Ke.style.backgroundColor=nt,Ke.classList.remove("persona-bg-persona-accent")):Ke.classList.add("persona-bg-persona-accent"),gn?Ke.style.color=gn:Ke.classList.add("persona-text-white");Qt.borderWidth?(Ke.style.borderWidth=Qt.borderWidth,Ke.style.borderStyle="solid"):(Ke.style.borderWidth="",Ke.style.borderStyle=""),Qt.borderColor?Ke.style.borderColor=Qt.borderColor:Ke.style.borderColor="",Qt.paddingX?(Ke.style.paddingLeft=Qt.paddingX,Ke.style.paddingRight=Qt.paddingX):(Ke.style.paddingLeft="",Ke.style.paddingRight=""),Qt.paddingY?(Ke.style.paddingTop=Qt.paddingY,Ke.style.paddingBottom=Qt.paddingY):(Ke.style.paddingTop="",Ke.style.paddingBottom="");let qt=vn==null?void 0:vn.querySelector(".persona-send-button-tooltip");if(Ro&&Kr)if(qt)qt.textContent=Kr,qt.style.display="";else{let ne=document.createElement("div");ne.className="persona-send-button-tooltip",ne.textContent=Kr,vn==null||vn.insertBefore(ne,Ke)}else qt&&(qt.style.display="none");let Ut=(Up=(Fp=r.layout)==null?void 0:Fp.contentMaxWidth)!=null?Up:D()?($p=(_p=(Op=r.launcher)==null?void 0:Op.composerBar)==null?void 0:_p.contentMaxWidth)!=null?$p:"720px":void 0;Ut?(Ye.style.maxWidth=Ut,Ye.style.marginLeft="auto",Ye.style.marginRight="auto",Ye.style.width="100%",Rt&&(Rt.style.maxWidth=Ut,Rt.style.marginLeft="auto",Rt.style.marginRight="auto"),Ge&&(Ge.style.maxWidth=Ut,Ge.style.marginLeft="auto",Ge.style.marginRight="auto")):(Ye.style.maxWidth="",Ye.style.marginLeft="",Ye.style.marginRight="",Ye.style.width="",Rt&&(Rt.style.maxWidth="",Rt.style.marginLeft="",Rt.style.marginRight=""),Ge&&(Ge.style.maxWidth="",Ge.style.marginLeft="",Ge.style.marginRight=""));let ht=(qp=r.statusIndicator)!=null?qp:{},Xt=(zp=ht.visible)!=null?zp:!0;if(pn.style.display=Xt?"":"none",_){let ne=_.getStatus();lt(pn,(jt=>{var dt,Wt,fn,Tn;return jt==="idle"?(dt=ht.idleText)!=null?dt:Mn.idle:jt==="connecting"?(Wt=ht.connectingText)!=null?Wt:Mn.connecting:jt==="connected"?(fn=ht.connectedText)!=null?fn:Mn.connected:jt==="error"?(Tn=ht.errorText)!=null?Tn:Mn.error:Mn[jt]})(ne),ht,ne)}pn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let St=ht.align==="left"?"persona-text-left":ht.align==="center"?"persona-text-center":"persona-text-right";pn.classList.add(St)},open(){N()&&T(!0,"api")},close(){N()&&T(!1,"api")},toggle(){N()&&T(!M,"api")},clearChat(){In=!1,_.clearMessages(),Pr.clear(),Rr();try{localStorage.removeItem(Ts),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ts}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Ts)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let p=i.clear();p instanceof Promise&&p.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}d={},E.syncFromMetadata(),fe==null||fe.clear(),ue==null||ue.reset(),K==null||K.update()},setMessage(l){return!Ie||_.isStreaming()?!1:(!M&&N()&&T(!0,"system"),Ie.value=l,Ie.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(_.isStreaming())return!1;let p=(l==null?void 0:l.trim())||Ie.value.trim();return p?(!M&&N()&&T(!0,"system"),Ie.value="",Ie.style.height="auto",_.sendMessage(p),!0):!1},startVoiceRecognition(){var p,h;return _.isStreaming()?!1:((h=(p=r.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype"?(_.isVoiceActive()||(!M&&N()&&T(!0,"system"),yt.manuallyDeactivated=!1,$n(),_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),ar("user"),_.isVoiceActive()&&os()})),!0):Br?!0:Rl()?(!M&&N()&&T(!0,"system"),yt.manuallyDeactivated=!1,$n(),Ra("user"),!0):!1},stopVoiceRecognition(){var l,p;return((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{yt.active=!1,yt.manuallyDeactivated=!0,$n(),ar("user"),jr()}),!0):!1:Br?(yt.manuallyDeactivated=!0,$n(),uo("user"),!0):!1},injectMessage(l){return!M&&N()&&T(!0,"system"),_.injectMessage(l)},injectAssistantMessage(l){!M&&N()&&T(!0,"system");let p=_.injectAssistantMessage(l);return z&&(z=!1,V&&(clearTimeout(V),V=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),p},injectUserMessage(l){return!M&&N()&&T(!0,"system"),_.injectUserMessage(l)},injectSystemMessage(l){return!M&&N()&&T(!0,"system"),_.injectSystemMessage(l)},injectMessageBatch(l){return!M&&N()&&T(!0,"system"),_.injectMessageBatch(l)},injectComponentDirective(l){return!M&&N()&&T(!0,"system"),_.injectComponentDirective(l)},injectTestMessage(l){!M&&N()&&T(!0,"system"),_.injectTestEvent(l)},async connectStream(l,p){return _.connectStream(l,p)},__pushEventStreamEvent(l){fe&&(ue==null||ue.processEvent(l.type,l.payload),fe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!Be||!fe||Fr()},hideEventStream(){ie&&mr()},isEventStreamVisible(){return ie},showArtifacts(){ur(r)&&(In=!1,Qn(),Ct==null||Ct.setMobileOpen(!0))},hideArtifacts(){ur(r)&&(In=!0,Qn())},upsertArtifact(l){return ur(r)?(In=!1,_.upsertArtifact(l)):null},selectArtifact(l){ur(r)&&_.selectArtifact(l)},clearArtifacts(){ur(r)&&_.clearArtifacts()},getArtifacts(){var l;return(l=_==null?void 0:_.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=_==null?void 0:_.getSelectedArtifactId())!=null?l:null},focusInput(){return k&&!M&&!D()||!Ie?!1:(Ie.focus(),!0)},async resolveApproval(l,p,h){let S=_.getMessages().find(B=>{var q;return B.variant==="approval"&&((q=B.approval)==null?void 0:q.id)===l});if(!(S!=null&&S.approval))throw new Error(`Approval not found: ${l}`);if(S.approval.toolType==="webmcp"){_.resolveWebMcpApproval(S.id,p);return}return _.resolveApproval(S.approval,p,h)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(l){m(l)},on(l,p){return s.on(l,p)},off(l,p){s.off(l,p)},isOpen(){return N()&&M},isVoiceActive(){return yt.active},toggleReadAloud(l){_.toggleReadAloud(l)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(l){return _.getReadAloudState(l)},onReadAloudChange(l){return _.onReadAloudChange(l)},getState(){return{open:N()&&M,launcherEnabled:k,voiceActive:yt.active,streaming:_.isStreaming()}},showCSATFeedback(l){!M&&N()&&T(!0,"system");let p=Ye.querySelector(".persona-feedback-container");p&&p.remove();let h=Vm({onSubmit:async(y,S)=>{var B;_.isClientTokenMode()&&await _.submitCSATFeedback(y,S),(B=l==null?void 0:l.onSubmit)==null||B.call(l,y,S)},onDismiss:l==null?void 0:l.onDismiss,...l});Ye.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!M&&N()&&T(!0,"system");let p=Ye.querySelector(".persona-feedback-container");p&&p.remove();let h=jm({onSubmit:async(y,S)=>{var B;_.isClientTokenMode()&&await _.submitNPSFeedback(y,S),(B=l==null?void 0:l.onSubmit)==null||B.call(l,y,S)},onDismiss:l==null?void 0:l.onDismiss,...l});Ye.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,p){return _.submitCSATFeedback(l,p)},async submitNPSFeedback(l,p){return _.submitNPSFeedback(l,p)},destroy(){Me!=null&&(clearInterval(Me),Me=null),ut.forEach(l=>l()),Ee.remove(),Je==null||Je.remove(),nn==null||nn.destroy(),mn==null||mn.remove(),kr&&G.removeEventListener("click",kr)}};if((((_c=t==null?void 0:t.debugTools)!=null?_c:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,p={controller:cn,getMessages:cn.getMessages,getStatus:cn.getStatus,getMetadata:cn.getPersistentMetadata,updateMetadata:cn.updatePersistentMetadata,clearHistory:()=>cn.clearChat(),setVoiceActive:h=>h?cn.startVoiceRecognition():cn.stopVoiceRecognition()};window.AgentWidgetBrowser=p,ut.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=n.getAttribute("data-persona-instance")||n.id||"persona-"+Math.random().toString(36).slice(2,8),p=O=>{let H=O.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&cn.focusInput()};if(window.addEventListener("persona:focusInput",p),ut.push(()=>{window.removeEventListener("persona:focusInput",p)}),Be){let O=de=>{let pe=de.detail;(!(pe!=null&&pe.instanceId)||pe.instanceId===l)&&cn.showEventStream()},H=de=>{let pe=de.detail;(!(pe!=null&&pe.instanceId)||pe.instanceId===l)&&cn.hideEventStream()};window.addEventListener("persona:showEventStream",O),window.addEventListener("persona:hideEventStream",H),ut.push(()=>{window.removeEventListener("persona:showEventStream",O),window.removeEventListener("persona:hideEventStream",H)})}let h=O=>{let H=O.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&cn.showArtifacts()},y=O=>{let H=O.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&cn.hideArtifacts()},S=O=>{let H=O.detail;H!=null&&H.instanceId&&H.instanceId!==l||H!=null&&H.artifact&&cn.upsertArtifact(H.artifact)},B=O=>{let H=O.detail;H!=null&&H.instanceId&&H.instanceId!==l||typeof(H==null?void 0:H.id)=="string"&&cn.selectArtifact(H.id)},q=O=>{let H=O.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&cn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",S),window.addEventListener("persona:selectArtifact",B),window.addEventListener("persona:clearArtifacts",q),ut.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",S),window.removeEventListener("persona:selectArtifact",B),window.removeEventListener("persona:clearArtifacts",q)})}let cr=cy(r.persistState);if(cr&&N()){let l=dy(cr.storage),p=`${cr.keyPrefix}widget-open`,h=`${cr.keyPrefix}widget-voice`,y=`${cr.keyPrefix}widget-voice-mode`;if(l){let S=(($c=cr.persist)==null?void 0:$c.openState)&&l.getItem(p)==="true",B=((Uc=cr.persist)==null?void 0:Uc.voiceState)&&l.getItem(h)==="true",q=((qc=cr.persist)==null?void 0:qc.voiceState)&&l.getItem(y)==="true";if(S&&setTimeout(()=>{cn.open(),setTimeout(()=>{var O;if(B||q)cn.startVoiceRecognition();else if((O=cr.persist)!=null&&O.focusInput){let H=n.querySelector("textarea");H&&H.focus()}},100)},0),(zc=cr.persist)!=null&&zc.openState&&(s.on("widget:opened",()=>{l.setItem(p,"true")}),s.on("widget:closed",()=>{l.setItem(p,"false")})),(Vc=cr.persist)!=null&&Vc.voiceState&&(s.on("voice:state",O=>{l.setItem(h,O.active?"true":"false")}),s.on("user:message",O=>{l.setItem(y,O.viaVoice?"true":"false")})),cr.clearOnChatClear){let O=()=>{l.removeItem(p),l.removeItem(h),l.removeItem(y)},H=()=>O();window.addEventListener("persona:clear-chat",H),ut.push(()=>{window.removeEventListener("persona:clear-chat",H)})}}}return g&&N()&&setTimeout(()=>{cn.open()},0),qe(),xa||Yp().then(()=>{_&&(Qo++,Pr.clear(),io(Ye,_.getMessages(),Le))}).catch(()=>{}),cn};var py=(n,e)=>{let t=n.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(t);return o?Math.max(0,e*parseFloat(o[1])/100):420},uy=(n,e)=>{if(e===!1){n.style.maxHeight="";return}n.style.maxHeight="100vh",n.style.maxHeight=e},my=(n,e)=>{e===!1?(n.style.position="relative",n.style.top=""):(n.style.position="sticky",n.style.top="0")},gy=(n,e)=>{let t=n.parentElement;if(!t)return;let r=n.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",t.appendChild(r);let o=r.offsetHeight>0;r.style.height="100%";let s=r.offsetHeight>0;r.remove(),!(!o||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(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.")},Jm=(n,e)=>{var r,o;let t=(o=(r=e==null?void 0:e.launcher)==null?void 0:r.enabled)!=null?o:!0;n.className="persona-host",n.style.height=t?"":"100%",n.style.display=t?"":"flex",n.style.flexDirection=t?"":"column",n.style.flex=t?"":"1 1 auto",n.style.minHeight=t?"":"0"},Ll=n=>{n.style.position="",n.style.top="",n.style.bottom="",n.style.left="",n.style.right="",n.style.zIndex="",n.style.transform="",n.style.pointerEvents=""},Ym=n=>{n.style.inset="",n.style.width="",n.style.height="",n.style.maxWidth="",n.style.maxHeight="",n.style.minWidth="",Ll(n)},Ml=n=>{n.style.transition=""},El=n=>{n.style.display="",n.style.flexDirection="",n.style.flex="",n.style.minHeight="",n.style.minWidth="",n.style.width="",n.style.height="",n.style.alignItems="",n.style.transition="",n.style.transform="",n.style.marginLeft=""},kl=n=>{n.style.width="",n.style.maxWidth="",n.style.minWidth="",n.style.flex="1 1 auto"},Li=(n,e)=>{n.style.width="",n.style.minWidth="",n.style.maxWidth="",n.style.boxSizing="",e.style.alignItems=""},fy=(n,e,t,r,o)=>{o?t.parentElement!==e&&(n.replaceChildren(),e.replaceChildren(t,r),n.appendChild(e)):t.parentElement===e&&(e.replaceChildren(),n.appendChild(t),n.appendChild(r))},hy=(n,e,t,r,o,s)=>{let a=s?e:n;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,t):a.lastElementChild!==r&&a.replaceChildren(t,r)},Zm=(n,e,t,r,o,s,a)=>{var v,x,E,k,L,F;let i=xr(s),d=i.reveal==="push";fy(n,e,t,r,d),hy(n,e,t,r,i.side,d),n.dataset.personaHostLayout="docked",n.dataset.personaDockSide=i.side,n.dataset.personaDockOpen=a?"true":"false",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.height="100%",n.style.minHeight="0",n.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let c=n.ownerDocument.defaultView,g=(x=(v=s==null?void 0:s.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,f=(k=(E=s==null?void 0:s.launcher)==null?void 0:E.mobileBreakpoint)!=null?k:640,u=c!=null?c.innerWidth<=f:!1;if(g&&u&&a){n.dataset.personaDockMobileFullscreen="true",n.removeAttribute("data-persona-dock-reveal"),El(e),Ml(r),Ym(r),kl(t),Li(o,r),n.style.display="flex",n.style.flexDirection="column",n.style.alignItems="stretch",n.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((F=(L=s==null?void 0:s.launcher)==null?void 0:L.zIndex)!=null?F:En),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(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",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(n.removeAttribute("data-persona-dock-mobile-fullscreen"),Ym(r),uy(r,i.maxHeight),i.reveal==="overlay"){n.style.display="flex",n.style.flexDirection="row",n.style.alignItems="stretch",n.style.overflow="hidden",n.dataset.personaDockReveal="overlay",El(e),Ml(r),kl(t),Li(o,r);let I=i.animate?"transform 180ms ease":"none",R=i.side==="right"?"translateX(100%)":"translateX(-100%)",A=a?"translateX(0)":R;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=I,r.style.transform=A,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){n.style.display="flex",n.style.flexDirection="row",n.style.alignItems="stretch",n.style.overflow="hidden",n.dataset.personaDockReveal="push",Ml(r),Ll(r),Li(o,r);let I=py(i.width,n.clientWidth),R=Math.max(0,n.clientWidth),A=i.animate?"margin-left 180ms ease":"none",W=i.side==="right"?a?-I:0:a?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=`${R+I}px`,e.style.transition=A,e.style.marginLeft=`${W}px`,e.style.transform="",t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${R}px`,t.style.maxWidth=`${R}px`,t.style.minWidth=`${R}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.top="",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{n.style.display="flex",n.style.flexDirection="row",n.style.alignItems="stretch",n.style.overflow="",El(e),Ll(r),kl(t),Li(o,r);let I=i.reveal==="emerge";I?n.dataset.personaDockReveal="emerge":n.removeAttribute("data-persona-dock-reveal");let R=a?i.width:"0px",A=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",W=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${R}`,r.style.width=R,r.style.maxWidth=R,r.style.minWidth=R,r.style.minHeight="0",my(r,i.maxHeight),r.style.overflow=I||W?"hidden":"visible",r.style.transition=A,I&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},yy=(n,e)=>{let t=n.ownerDocument.createElement("div");return Jm(t,e),n.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){Jm(t,r)},destroy(){t.remove()}}},by=(n,e)=>{var F,I,R,A;let{ownerDocument:t}=n,r=n.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=n.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=n.nextSibling,a=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),c=t.createElement("aside"),g=t.createElement("div"),f=(I=(F=e==null?void 0:e.launcher)==null?void 0:F.enabled)==null||I?(A=(R=e==null?void 0:e.launcher)==null?void 0:R.autoExpand)!=null?A:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",g.dataset.personaDockRole="host",c.appendChild(g),r.insertBefore(a,n),d.appendChild(n);let u=null,m=()=>{u==null||u.disconnect(),u=null},v=()=>{m(),xr(e).reveal==="push"&&typeof ResizeObserver!="undefined"&&(u=new ResizeObserver(()=>{Zm(a,i,d,c,g,e,f)}),u.observe(a))},x=!1,E=()=>{Zm(a,i,d,c,g,e,f),v(),f&&!x&&a.dataset.personaDockMobileFullscreen!=="true"&&(x=!0,gy(a,xr(e)))},k=a.ownerDocument.defaultView,L=()=>{E()};return k==null||k.addEventListener("resize",L),xr(e).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),E(),{mode:"docked",host:g,shell:a,syncWidgetState(W){let D=W.launcherEnabled?W.open:!0;f!==D&&(f=D,E())},updateConfig(W){var D,N;e=W,((N=(D=e==null?void 0:e.launcher)==null?void 0:D.enabled)!=null?N:!0)===!1&&(f=!0),E()},destroy(){k==null||k.removeEventListener("resize",L),m(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(n,s):r.appendChild(n)),a.remove()}}},eg=(n,e)=>Cn(e)?by(n,e):yy(n,e);var va={desktop:{w:1280,h:800},mobile:{w:390,h:844}},tg=.15,ng=1.5,Pl="persona-preview-shell-theme",vy={load:()=>null,save:()=>{},clear:()=>{}},xy=["How do I get started?","Pricing & plans","Talk to support"];function Il(n){return n.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function wy(n){return n==="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 rg(n){let e=wy(n);return`* { box-sizing: border-box; }
110
+ html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
111
+ html { color-scheme: ${n}; }
112
+ body { font-family: system-ui, sans-serif; background: ${e.pageBg}; }
113
+ .preview-iframe-mock { min-height: 100%; }
114
+ .preview-iframe-chrome { height: 44px; border-bottom: 1px solid ${e.chromeBorder}; background: ${e.chromeBg}; display: flex; align-items: center; gap: 8px; padding: 0 14px; }
115
+ .preview-iframe-dot { width: 10px; height: 10px; border-radius: 50%; background: ${e.dot}; }
116
+ .preview-iframe-copy { padding: 32px; }
117
+ .preview-iframe-line { border-radius: 999px; background: ${e.skeleton}; margin-bottom: 12px; }
118
+ .preview-iframe-line.hero { width: 48%; height: 16px; }
119
+ .preview-iframe-line.body { width: 72%; height: 10px; }
120
+ .preview-iframe-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; margin: 24px 0; }
121
+ .preview-iframe-card { height: 84px; border-radius: 14px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
122
+ .preview-workspace-shell { height: 100%; min-height: 100%; display: flex; flex-direction: column; }
123
+ .preview-workspace-topbar { height: 52px; flex-shrink: 0; border-bottom: 1px solid ${e.chromeBorder}; background: ${e.chromeBg}; display: flex; align-items: center; justify-content: space-between; padding: 0 18px; }
124
+ .preview-workspace-topbar-left { display: flex; align-items: center; gap: 12px; }
125
+ .preview-workspace-topbar-badge { width: 18px; height: 18px; border-radius: 6px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
126
+ .preview-workspace-topbar-line { width: 180px; height: 10px; border-radius: 999px; background: ${e.skeleton}; }
127
+ .preview-workspace-topbar-pill { width: 64px; height: 28px; border-radius: 999px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
128
+ .preview-workspace-body { flex: 1; min-height: 0; display: flex; padding: 20px; }
129
+ .preview-workspace-content { position: relative; display: flex; flex-direction: column; flex: 1; width: 100%; height: 100%; min-width: 0; min-height: 0; overflow: hidden; border-radius: 24px; background: rgba(255,255,255,0.72); box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
130
+ .preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
131
+ .preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
132
+ .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}; }
133
+ .preview-workspace-card.short { height: 96px; }`}function og(n,e){let t=n.contentDocument;if(!(t!=null&&t.documentElement))return;let r=t.getElementById(Pl);r||(r=t.createElement("style"),r.id=Pl,t.head.appendChild(r)),r.textContent=rg(e)}var Cy=`
134
+ <div class="preview-iframe-mock" aria-hidden="true">
135
+ <div class="preview-iframe-chrome">
136
+ <span class="preview-iframe-dot"></span>
137
+ <span class="preview-iframe-dot"></span>
138
+ <span class="preview-iframe-dot"></span>
139
+ </div>
140
+ <div class="preview-iframe-copy">
141
+ <div class="preview-iframe-line hero"></div>
142
+ <div class="preview-iframe-line body"></div>
143
+ <div class="preview-iframe-line body"></div>
144
+ <div class="preview-iframe-grid">
145
+ <div class="preview-iframe-card"></div>
146
+ <div class="preview-iframe-card"></div>
147
+ <div class="preview-iframe-card"></div>
148
+ </div>
149
+ <div class="preview-iframe-line body"></div>
150
+ <div class="preview-iframe-line body"></div>
151
+ </div>
152
+ </div>`,Ay=`
153
+ <div class="preview-workspace-content-shell" aria-hidden="true">
154
+ <div class="preview-iframe-line hero"></div>
155
+ <div class="preview-iframe-line body"></div>
156
+ <div class="preview-workspace-row">
157
+ <div class="preview-workspace-card"></div>
158
+ <div class="preview-workspace-card"></div>
159
+ </div>
160
+ <div class="preview-workspace-row">
161
+ <div class="preview-workspace-card short"></div>
162
+ <div class="preview-workspace-card short"></div>
163
+ <div class="preview-workspace-card short"></div>
164
+ </div>
165
+ </div>`;function sg(n,e,t,r){let o=`
166
+ ${Cy}
167
+ <div style="position:fixed;inset:0;z-index:9999;"><div id="${n}" data-mount-id="${n}"></div></div>`,s=`
168
+ <div class="preview-workspace-shell">
169
+ <div class="preview-workspace-topbar">
170
+ <div class="preview-workspace-topbar-left">
171
+ <span class="preview-workspace-topbar-badge"></span>
172
+ <span class="preview-workspace-topbar-line"></span>
173
+ </div>
174
+ <span class="preview-workspace-topbar-pill"></span>
175
+ </div>
176
+ <div class="preview-workspace-body">
177
+ <div id="preview-content-${n}" class="preview-workspace-content" data-mount-id="${n}">
178
+ ${Ay}
179
+ </div>
180
+ </div>
181
+ </div>`;return`<!DOCTYPE html>
182
+ <html lang="en">
183
+ <head>
184
+ <meta charset="UTF-8">
185
+ <meta name="viewport" content="width=device-width, initial-scale=1">
186
+ <link rel="stylesheet" href="${Il(r)}">
187
+ <style id="${Pl}">${rg(e)}</style>
188
+ </head>
189
+ <body>
190
+ ${t?s:o}
191
+ </body>
192
+ </html>`}var Sy=()=>[{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()}],Ty=n=>{var e,t,r,o,s,a,i,d;return!!((t=(e=n==null?void 0:n.features)==null?void 0:e.toolCallDisplay)!=null&&t.activePreview||(o=(r=n==null?void 0:n.features)==null?void 0:r.toolCallDisplay)!=null&&o.grouped||(a=(s=n==null?void 0:n.features)==null?void 0:s.toolCallDisplay)!=null&&a.collapsedMode&&n.features.toolCallDisplay.collapsedMode!=="tool-call"||(d=(i=n==null?void 0:n.features)==null?void 0:i.reasoningDisplay)!=null&&d.activePreview)};function My(n,e,t=[]){return n==="home"?[{id:"preview-home-1",role:"assistant",content:"Hi there! How can we help today?",createdAt:new Date().toISOString()}]:n==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:n==="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()}]:n==="conversation"&&Ty(e)?[...Sy(),...t]:[{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()},...t]}function Ey(n,e,t=[]){var s,a;let r={...n.launcher,enabled:!0,autoExpand:e!=="minimized"},o={...n,launcher:r,suggestionChips:e==="home"?(s=n.suggestionChips)!=null&&s.length?n.suggestionChips:xy:n.suggestionChips,initialMessages:My(e,n,t),storageAdapter:vy};return e==="artifact"&&(o.features={...o.features,artifacts:{...(a=o.features)==null?void 0:a.artifacts,enabled:!0}}),o}function ky(n,e){var r,o;let t=n.theme?Uo(n.theme,{validate:!1}):Uo();return{..._t,...n.config,theme:t,darkTheme:n.darkTheme,colorScheme:(o=e!=null?e:(r=n.config)==null?void 0:r.colorScheme)!=null?o:"light"}}function Ms(n,e){var r,o;let t=(r=n.scene)!=null?r:"conversation";return Ey(ky(n,e),t,(o=n.appendedMessages)!=null?o:[])}function ag(n){var r,o,s,a,i;let e=(r=n.compareMode)!=null?r:"off",t=(o=n.shellMode)!=null?o:"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:Ms(n,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Ms(n,"dark"),shellMode:"dark"}];if(e==="baseline"&&(n.baselineConfig||n.baselineTheme)){let d={...n,config:(s=n.baselineConfig)!=null?s:n.config,theme:(a=n.baselineTheme)!=null?a:n.theme,darkTheme:(i=n.baselineDarkTheme)!=null?i:n.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:Ms(d,t),shellMode:t},{mountId:"preview-current",label:"Current",config:Ms(n,t),shellMode:t}]}return[{mountId:"preview-current",label:"Current",config:Ms(n,t),shellMode:t}]}function ig(n,e){let t={...e},r=[],o=[],s=null,a=!1,i=1,d=1,c=0;function g(){var L;return(L=t.device)!=null?L:"desktop"}function f(){var L;return(L=t.zoom)!=null?L:i}function u(){var M,z;let L=getComputedStyle(n),F=parseFloat(L.paddingLeft)+parseFloat(L.paddingRight),I=parseFloat(L.paddingTop)+parseFloat(L.paddingBottom),R=40,A=((M=t.compareMode)!=null?M:"off")!=="off",W=(n.clientWidth-F-R)/(A?2:1),D=n.clientHeight-I-R;if(W<=0||D<=0)return 1;let N=(z=va[g()])!=null?z:va.desktop;return Math.min(W/N.w,D/N.h,1)}function m(){var I,R,A;i=u();let L=Math.max(tg,Math.min(ng,f()));d=L;let F=Array.from(n.querySelectorAll(".preview-iframe-wrapper"));for(let W of F){let D=(I=W.dataset.device)!=null?I:"desktop",N=(R=va[D])!=null?R:va.desktop;W.style.width=`${N.w*L}px`,W.style.height=`${N.h*L}px`,D==="mobile"&&(W.style.borderRadius=`${32*L}px`);let M=W.querySelector("iframe");M&&(M.style.width=`${N.w}px`,M.style.height=`${N.h}px`,M.style.transformOrigin="top left",M.style.transition="none",M.style.transform=`scale(${L})`)}(A=t.onScaleChange)==null||A.call(t,L)}function v(){var L;(L=t.onBeforeDestroy)==null||L.call(t);for(let F of r)F.destroy();for(let F of o)F();r=[],o=[]}function x(){return Array.from(n.querySelectorAll("iframe[data-mount-id]"))}function E(){var ve,Be,Oe,Te;if(a)return;v();let L=++c,F=ag(t),I=g(),R=((ve=t.compareMode)!=null?ve:"off")!=="off",A=((Be=t.scene)!=null?Be:"conversation")==="minimized",W=(Oe=t.widgetCssPath)!=null?Oe:"/widget-dist/widget.css",D=(Te=t.buildSrcdoc)!=null?Te:sg,N=I==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",M=we=>`<div class="${N}" data-mount-id="${we.mountId}" data-device="${I}" data-shell-mode="${we.shellMode}">
193
+ ${R?`<div class="preview-frame-meta"><span class="preview-frame-label">${Il(we.label)}</span></div>`:""}
194
+ <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${we.mountId}"></iframe>
195
+ </div>`,z=R?`<div class="preview-compare-grid">${F.map(we=>`<div class="preview-compare-cell">${M(we)}</div>`).join("")}</div>`:`<div class="preview-single">${M(F[0])}</div>`;t.morphContainer?t.morphContainer(n,z):n.innerHTML=z,m();let V=x(),oe=0,Le=V.length,je=()=>{var se,Q,ae,fe,ue;if(a||L!==c)return;for(let K of V){let ie=K.dataset.mountId;if(!ie||!K.contentDocument)continue;let We=F.find(lt=>lt.mountId===ie);if(!We)continue;let te=()=>{},ee=Cn(We.config),re=ee?(()=>{var Y;let lt=(Y=K.contentDocument)==null?void 0:Y.getElementById(`preview-content-${ie}`);if(!lt)return null;let st=eg(lt,We.config),Ee=K.contentDocument.createElement("div");Ee.id=ie,Ee.style.height="100%",Ee.style.display="flex",Ee.style.flexDirection="column",Ee.style.flex="1",Ee.style.minHeight="0",st.host.appendChild(Ee);let he=()=>st.syncWidgetState(it.getState()),Je=te;return te=()=>{st.destroy(),Je()},Ee.__syncDock=he,Ee.__hostLayout=st,Ee})():K.contentDocument.getElementById(ie);if(!re)continue;let it=Xm(re,We.config);if(r.push(it),ee&&re.__syncDock){let lt=re.__syncDock,st=it.on("widget:opened",lt),Ee=it.on("widget:closed",lt),he=te;te=()=>{st(),Ee(),he()},lt()}o.push(te),A&&it.close()}if(((se=t.scene)!=null?se:"conversation")==="artifact"||(fe=(ae=(Q=t.config)==null?void 0:Q.features)==null?void 0:ae.artifacts)!=null&&fe.enabled)for(let K of r)K.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
196
+
197
+ This is a preview of the artifact sidebar.
198
+
199
+ ## Features
200
+
201
+ - Markdown rendering
202
+ - Document toolbar
203
+ - Resizable panes`});(ue=t.onAfterMount)==null||ue.call(t,{iframes:V,controllers:[...r]})};for(let we of V){let se=we.dataset.mountId;if(!se)continue;let Q=F.find(ae=>ae.mountId===se);Q&&(we.addEventListener("load",()=>{oe++,oe>=Le&&je()},{once:!0}),we.srcdoc=D(se,Q.shellMode,Cn(Q.config),W))}Le===0&&je()}function k(){var I;if(a)return;let L=ag(t);if(r.length!==L.length){E();return}if(L.some(R=>{let A=n.querySelector(`.preview-iframe-wrapper[data-mount-id="${R.mountId}"]`);return!A||A.dataset.shellMode!==R.shellMode})){E();return}r.forEach((R,A)=>{var W;R.update(L[A].config),((W=t.scene)!=null?W:"conversation")==="minimized"&&R.close()});for(let R of L){let A=n.querySelector(`iframe[data-mount-id="${R.mountId}"]`);A&&og(A,R.shellMode)}(I=t.onAfterUpdate)==null||I.call(t,{iframes:x(),controllers:[...r]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||m()}),s.observe(n)),E(),{update(L){if(a)return;let F=L.device!==void 0&&L.device!==t.device||L.scene!==void 0&&L.scene!==t.scene||L.compareMode!==void 0&&L.compareMode!==t.compareMode||L.widgetCssPath!==void 0&&L.widgetCssPath!==t.widgetCssPath;t={...t,...L},F?E():k()},destroy(){a||(a=!0,v(),s==null||s.disconnect(),n.innerHTML="")},getControllers(){return[...r]},fitToContainer(){a||(t={...t,zoom:void 0},m())},getIframes(){return x()},getScale(){return d},setZoom(L){a||(t={...t,zoom:L},m())}}}0&&(module.exports={createThemePreview});